CRM 2011 Code etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
CRM 2011 Code etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

CRM 2011 Code - Export Solution (.NET)


          //Export a solution
            String outputDir = @"C:\solutions\";

            ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
            exportSolutionRequest.Managed = false;

            //Specify the unique name of your solution
            exportSolutionRequest.SolutionName = "TestSolution";

            ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)crmServiceDev.Execute(exportSolutionRequest);

            byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
            string filename = "TestSolution" + ".zip";
            File.WriteAllBytes(outputDir + filename, exportXml);

            Console.WriteLine("Solution exported to {0}.", outputDir + filename);

CRM 2011 - Equipment Oluşturma (Create Equipment)


C# Code
                     
                            #region Create TesisEkipman
                            Equipment equipment = new Equipment();
                            equipment.Name ="New Created Equipment";
                            equipment.Description ="Item description";
                            equipment.CalendarId = new EntityReference("calendar", "guidvalue") ;
                            equipment.DisplayInServiceViews =true;
                            equipment.EMailAddress = "gkhnmnts@hotmail.com";
                            equipment.IsDisabled = false;
                            equipment.SiteId =new EntityReference("site", "guidvalue") ;
                            equipment.Skills =" item.Skills";
                            equipment.TimeZoneCode = 1;
                           equipment.BusinessUnitId = new EntityReference("businessunit", "guidvalue") ;

                            crmService.Create(equipment);
                            #endregion

Örnek :

 string fetchBU = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='businessunit'>
                                    <attribute name='name' />
                                    <attribute name='address1_telephone1' />
                                    <attribute name='websiteurl' />
                                    <attribute name='parentbusinessunitid' />
                                    <attribute name='businessunitid' />
                                    <order attribute='name' descending='false' />
                                  </entity>
                                </fetch>";

EntityCollection resultequipments = crmServiceDev.RetrieveMultiple(new FetchExpression(fetchBU));

            if (resultequipments.Entities.Count > 0)
            {
                Guid BuId;
                BuId = (Guid)resultequipments.Entities[0]["businessunitid"];
                Entity equipment = new Entity("equipment");
                equipment["name"] = "test";
                equipment["businessunitid"] = new EntityReference("businessunit",BuId);
                equipment["timezonecode"] = 1;
                crmServiceDev.Create(equipment);
                Console.WriteLine("Facility successfully created");

            }

CRM 2011 - Timeout Hatası (Unhandled Exception: System.TimeoutException)


Hata

System.TimeoutException: İstek kanalı, yanıt beklerken 00:02:00 sonra zaman aşımına uğradı. Request çağrısına geçirilen zaman aşımı değerini artırın ya da Binding üstündeki SendTimeout değerini artırın. Bu işlem için ayrılan süre daha uzun bir zaman aşımı değerinin bir bölümü olabilir. ---> System.TimeoutException: 'http://xxxx/xxCRM/xrmservices/2011/Organization.svc' öğesine HTTP tarafından yapılan istek, ayrılan zaman aşımı süresini (00:02:00) aştı. Bu işlem için ayrılan süre daha uzun bir zaman aşımı değerinin bir bölümü olabilir. ---> System.Net.WebException: İşlem zaman aşımına uğradı
-


Serviceproxy nin defaulttakı timeout değeri 2 dakikadır. Bu zamandan sonraki sürelerde timeout hatası verilecektir. Bunu crm le connection kurduğumuz yerde serviceproxy değeri üzerinde değiştirebiliriz.

  ClientCredentials credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = new System.Net.NetworkCredential(_settingFactory.GetUserName, _settingFactory.GetPassword, _settingFactory.GetDomainName);
                //credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                Uri organizationUri = new Uri(_settingFactory.GetOrganizationSvc);
                OrganizationServiceProxy orgService11 = new OrganizationServiceProxy(organizationUri, null, credentials, null);
                orgService11.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

                //This line is required to enable Early Bound Types
                orgService11.EnableProxyTypes();
                orgService11.Authenticate();
                orgService11.Timeout = new TimeSpan(0, 15, 0); // extends timeout to 15 minutes
                return (IOrganizationService)orgService11;

CRM Versiyon Alma ( Retrieve the current CRM version)

 public enum CRMVersion
    {
        Unknown,
        CRM2011,
        CRM2011UR12PLUS,
        CRM2013,
        CRM2013SP1,
        CRM2015
    }

 public CRMVersion GetCRMVersion(IOrganizationService service)
        {
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)service.Execute(versionRequest);

            string version = versionResponse.Version;
            if (version.StartsWith("5"))
            {
                try
                {
                    int buildNumber = Convert.ToInt32(version.Substring(version.LastIndexOf(".") + 1));
                    if (buildNumber > 3000) { return CRMVersion.CRM2011UR12PLUS; }
                }
                catch { }
                return CRMVersion.CRM2011;
            }
            if (version.StartsWith("6.0")) { return CRMVersion.CRM2013; }
            if (version.StartsWith("6.1")) { return CRMVersion.CRM2013SP1; }
            if (version.StartsWith("7")) { return CRMVersion.CRM2015; }
            return CRMVersion.Unknown;
        }

CRM 2011 - Varlığın Takımla Share İlişkisi

Aşağıdaki metot sayesinde herhangi bir kayıdın belli bir takıma share olup olmaması bulunur.

        public static bool Ishared(IOrganizationService service, string entityname, Guid entityid, string teamname)
        {
            var isReturn = false;
            var accessResponse = RetrieveAndDisplayAccess(service, entityname, entityid);
            if (accessResponse != null && accessResponse.PrincipalAccesses != null && accessResponse.PrincipalAccesses.Length != 0)
            {
                foreach (var principalAccess in accessResponse.PrincipalAccesses)
                {
                    if (principalAccess.Principal.LogicalName.ToLower().Equals("team"))
                    {
                        Team team = (Team)service.Retrieve("team", principalAccess.Principal.Id, new ColumnSet("teamid", "name"));
                        if (team != null && team.Id != Guid.Empty)
                        {
                            if (team.Name.ToLower().Equals(teamname.ToLower()))
                            {
                                isReturn = true; break;
                            }
                        }
                    }
                }
            }
            return isReturn;
        }

public static RetrieveSharedPrincipalsAndAccessResponse     RetrieveAndDisplayAccess(IOrganizationService service, string entityname, Guid entityid)
        {
            var accessRequest = new RetrieveSharedPrincipalsAndAccessRequest
            {
                Target = new EntityReference(entityname, entityid)
            };

            // The RetrieveSharedPrincipalsAndAccessResponse returns an entity reference
            // that has a LogicalName of "user" when returning access information for a
            // "team."
            return (RetrieveSharedPrincipalsAndAccessResponse)service.Execute(accessRequest);
        }


Metot Kullanımı

var isShared = Core.IsShared(serv, targetName, _targetId, team.Name);
if (!isShared)
{
 // Bu takımla paylasılmamıs
}

CRM 2011 - OptionSet Alanın Text Değerini Alma (Get Optionset Text)

Aşağıdaki metoda optionset in adını ve texti alınacak değerin value sunu göndermek yeterlidir.



 public string GetOptionsetText(Entity entity, IOrganizationService service, string optionsetName, int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;
            try
            {
                RetrieveOptionSetRequest retrieveOptionSetRequest =new RetrieveOptionSetRequest{
                        Name = optionsetName
                 };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse =(RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);

                // Access the retrieved OptionSetMetadata.
                OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                // Get the current options list for the retrieved attribute.
                OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return optionsetSelectedText;
        }

CRM 2011 - SetStateRequest Kullanımı

public static bool SetStateRequestFunc(IOrganizationService crmService, string entityname, Guid entityid, int state, int statusreason)
        {
            try
            {
                SetStateRequest open = new SetStateRequest
                {
                    EntityMoniker = new EntityReference(entityname, entityid),
                    State = new OptionSetValue(state),
                    Status = new OptionSetValue(statusreason)
                };

                SetStateResponse resp = (SetStateResponse)crmService.Execute(open);

                return true;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

CRM 2011 - Option Set İşlemleri (Ekleme,Güncelleme,Silme,Sıralama,Değerleri Alma)


Yeni Option Ekleme

Burada  InsertOptionValueRequest classından yararlanılır.

Local OptionSet



Global OptionSet




Option Güncelleme

Burada  UpdateOptionValueRequest classından yararlanılır.

Local OptionSet




Global Optionset



Option Silme

Burada  DeleteOptionValueRequest classından yararlanılır.

Local OptionSet




Global OptionSet



Option Değerlerini Alma

Burada  RetrieveAttributeRequest classından yararlanılır.



Option Değerlerini Sıralama

Burada  OrderOptionRequest classından yararlanılır.




Not : Yukarıdak metotlarda kullanılan OptionSetList Classı

















CRM 2011 - Global OptionSet Değer Ekleme, Güncelleme, Silme ve Sıralama - C#

Yeni Seçenek Ekleme

Aşagıdaki örnek kod parcacıgı InsertOptionValueRequest classı kullanılarak global option sete nasıl yeni bir secenek eklenecegini gösterir.


Örnek Kullanım:

Secenek Texti Güncelleme

Aşagıdaki örnek kod parcacıgı UpdateOptionValueRequest classı kullanılarak global option setteki bir degerin textinin güncellenmesini gösterir.

Secenek Silme

Aşagıdaki örnek kod parcacıgı DeleteOptionValueRequest classı kullanılarak global option setteki bir degerin nasıl silinecegini gösterir.

Seçenek Sıralama

Aşagıdaki örnek kod parcacıgı OrderOptionRequest classı kullanılarak global option setteki degerlerin textine göre sıralanmasını saglar.

Option Set Retrieve





CRM 2011 - Not Varlığına Word Dosyası Ekleme (Attach Word Document to Annotation)

public static void AttachWordDocToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\TDD.docx");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\ms-word";
            note.NoteText = "Note Added with Document attached.";

            // Set the File Name
            note.FileName = "TDD.doc";
            service.Create(note);
        }

CRM 2011 - Not Varlığına Text Dosya Ekleme(Attach Text to Annotation)

public static void AttachTextToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\sample.txt");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"text/plain";
            note.NoteText = "Note Added with Text attached.";

            // Set the File Name
            note.FileName = "Sample.txt";
            service.Create(note);
        }

CRM 2011 - Not Varlığına PDF Dosyası Ekleme(Attach PDF To Annotation)

public static void AttachPDFToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\TDD1.pdf");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\pdf";
            note.NoteText = "Note Added with pdf attached.";

            // Set the File Name
            note.FileName = "TDD1.pdf";
            service.Create(note);
        }

CRM 2011 - Not Varlığına Excel Dosyası Ekleme (Attach Excel to Annotation)

public static void AttachExcelToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\ActiveRecords.xls");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\ms-excel";
            note.NoteText = "Note Added with Excel attached.";

            // Set the File Name
            note.FileName = "ActiveRecords.xls";
            service.Create(note);
        }

CRM 2011-Emaile Dosya Ekleme (Add Attachment To Email )

public static void AddAttachmentToEmail(EntityReference email, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\sample.txt");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);
         
            // Add attachment
            ActivityMimeAttachment attachment = new ActivityMimeAttachment();

            // Set the body
            attachment.Body = encodedData;

            // Set the attachment Type
            attachment.MimeType = @"text/plain";
            attachment.FileName = "Sample.txt";

            // Set the regarding object. In my case it is Email entity
            attachment.ObjectId = email;
            attachment.ObjectTypeCode = email.LogicalName;

            // Create the attachment
            service.Create(attachment);
        }

CRM 2011-Not Varlığına Önceden Eklenmiş Dosyayı Silme (Delete Attachment From Annotation)

public static void DeleteAttachmentFromNote(Guid noteId, IOrganizationService service)
        {
            Annotation note = new Annotation();
            note.Id = noteId;

            // Set the Documentbody and other fields to null to remove the attachment
            note.DocumentBody = null;

            note.FileName = null;
            note.IsDocument = false;
            service.Update(note);
        }

CRM 2011- IFRAME (Custom Page) UZERINDE İŞLEM YAPILDIKTAN SONRA CRM FORMUNU REFRESHLEME


Örnegin,
Sipariş formu üzerindesiniz.
Siparişe ekli olan ürünler, kendi olusturdugumuz bir custom page i gösteren  iframe üzerinde görülür durumda olsun.
Bu iframe de ürünleri edit edebiliyor olalım.
Eğer ürünleri edit ettikten sonra formu güncellemek(refresh) istiyorsak;.

Custom Page in code behind ında crm formuna  bir message veriyor olacagız.Bu mesaji crm formu yakalayıp crm formunu refresh edecegiz.

Code Behind(Custom Page)

 protectedvoid refreshGrid()
{
    string refreshCRMGrid = "<script language='javascript'>";
    refreshCRMGrid += "parent.postMessage('RefreshJumpGrid', '*')";
    refreshCRMGrid += "</script>";
    ClientScript.RegisterStartupScript(typeof(string), "RefreshGrid", refreshCRMGrid);
}

yada

Client Side
function CrmPageRefresh(){
parent.postMessage('RefreshJumpGrid', '*');
}
Code behind()
 protectedvoid refreshGrid()
{
    string refreshCRMGrid = "<script language='javascript'>";
    refreshCRMGrid += "CrmPageRefresh()";
    refreshCRMGrid += "</script>";
    ClientScript.RegisterStartupScript(typeof(string), "RefreshGrid", refreshCRMGrid);
}

JavaScript Kod (Crm Formu için)
function Form_onload() {
    window.attachEvent('onmessage', receiveMessage);
}
function receiveMessage(e) {
    if (e.data == "RefreshJumpGrid") {
       window.location.reload();
/*Crm Formu güncellenecektir*/
    }
}



CRM 2011 - PAYLASMA (SHARING) with C#


Paylasma (Share)


public static void Share(string principalName, Guid _principalId, string targetName, Guid _targetId, IOrganizationService serv)
        {
             GrantAccessRequest grantAccessRequest = new GrantAccessRequest
                {
                    PrincipalAccess = new PrincipalAccess
                    {
                        Principal = new EntityReference(principalName, _principalId),
                        AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.ShareAccess | AccessRights.AssignAccess | AccessRights.AppendAccess | AccessRights.AppendToAccess
                    },
                    Target = new EntityReference(targetName, _targetId)
                };
                GrantAccessResponse grantAccessResponse=(GrantAccessResponse)serv.Execute(grantAccessRequest);
          
            }
        }

Paylasımı Kaldırma (UnShare)


public static Result UnShare(string principalName, Guid _principalId, string targetName, Guid _targetId, IOrganizationService serv)
        {
         
                RevokeAccessRequest revokeAccessRequest = new RevokeAccessRequest
                {
                    Revokee = new EntityReference(principalName, _principalId),

                    Target = new EntityReference(targetName, _targetId)
                };

                RevokeAccessResponse revokeaccessresponse = (RevokeAccessResponse)serv.Execute(revokeAccessRequest);
          
        }

Eski Paylasımı Guncelleme(Modify)


public static void ModifyObject(EntityReference systemUser, EntityReference account, IOrganizationService service)
        {
            PrincipalAccess principalAccess = new PrincipalAccess
            {
                AccessMask = (AccessRights)852023,

                Principal = systemUser
            };

            ModifyAccessRequest modifyAcessRequest = new ModifyAccessRequest();

            modifyAcessRequest.PrincipalAccess = principalAccess;

            modifyAcessRequest.Target = account;

            service.Execute(modifyAcessRequest);
        }

CRM 2011- KULLANICIYA TAKIM EKLEME ve KALDIRMA(C #)


       // Takımın guid id
            Guid takimId= new Guid("079EE428-F515-E211-B2D9-00155D025F00");
            
            //1.Kullanıcı guid id 
            Guid kullanici1Id= new Guid("486FA7B3-4A6F-E111-AA15-00155D025F09");

            // // 2.Kullanıcı guid id
            Guid kullanici2Id= new Guid("FB9CA21D-7F72-E111-AA15-00155D025F09");

           // kullanıcı listesi
            Guid[] kullanicilar= new[] { kullanici1Id, kullanici2Id};

            KullanicilaraTakimEkle(teamId, kullanicilar, service);
            KullanicilardanTakimKaldir(teamId, kullanicilar, service);

Takım Ekleme Metodu


        public static void KullanicilaraTakimEkle(Guid teamId, Guid[] membersId, IOrganizationService service)
        {
           //Kullanıcılara takım ekleyen nesneyi olustur.
            AddMembersTeamRequest addRequest = new AddMembersTeamRequest();
      
           // eklenecek takım id sini ver.
            addRequest.TeamId = teamId;

            // kullanıcılar listesini ver
            addRequest.MemberIds = membersId;

            // nesneyi calıstır.
            service.Execute(addRequest);
        }

Takım Kaldırma Metodu


        public static void KullanicilardanTakimKaldir(Guid teamId, Guid[] membersId, IOrganizationService service)
        {
            RemoveMembersTeamRequest addRequest = new RemoveMembersTeamRequest();

            addRequest.TeamId = teamId;
            addRequest.MemberIds = membersId;

            service.Execute(addRequest);
        }

CRM 2011- Two Options Alanın Value suna Gore Textini Alma


Herhangi bir entity deki two options fieldın text degerini field ın bulundugu entity nin adı , fieldın adı ve cekılecek textın value sunu gondererek bulabılırsınız.

C# KOD:
        public static string GetBoolText(IOrganizationService service, string entityAdi, string fieldAdi, bool fieldvalue)
        {
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest
            {
                EntityLogicalName = entityAdi,
                LogicalName = fieldAdi,
                RetrieveAsIfPublished = true
            };
            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            BooleanAttributeMetadata retrievedBooleanAttributeMetadata = (BooleanAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
            string boolText = string.Empty;
            if (fieldvalue)
            {
                boolText = retrievedBooleanAttributeMetadata.OptionSet.TrueOption.Label.UserLocalizedLabel.Label;
            }
            else
            {
                boolText = retrievedBooleanAttributeMetadata.OptionSet.FalseOption.Label.UserLocalizedLabel.Label;
            }
            return boolText;
        }