Working with organization web services

Whenever we need to interact with CRM SDK, we need to use CRM web services. Most of the time we will be working with the organization service to create and modify data. Organization services contains the following methods to interact with metadata and organization data; we will add these methods in our corresponding Earlybound.cs and Latebound.cs files in our console application.

Create

This method is used to create entity records: system or custom. We can use create method when we want to create an entity record using CRM SDK—for example, if we need to develop a utility for data importing we can use this method or if we want to create a lead record dynamically from a custom Web site. This methods takes the entity object as a parameter and returns the GUID of the record created. The following is an example of creating an account record, early and late bound, with different data types. We are setting some of the basic account entity fields in the following code:

  • Early bound:
    private void CreateAccount()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
          {
            Account accountObject = new Account
              {
                Name = "HIMBAP Early",
                Address1_City = "Delhi",
                CustomerTypeCode = new OptionSetValue(3),
                DoNotEMail = false,
                Revenue = new Money(5000),
                NumberOfEmployees = 50,
                LastUsedInCampaign = new DateTime(2015, 3, 2)
              };
            crmService.Create(accountObject);
          }
      }
  • Late bound:
    private void Create()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
          {
            Entity accountObj = new Entity("account");
            //setting string value
            accountObj["name"] = "HIMBAP";
            accountObj["address1_city"] = "Delhi";
            accountObj["accountnumber"] = "101";
            //setting optionsetvalue
            accountObj["customertypecode"] = new OptionSetValue(3);
            //setting boolean
            accountObj["donotemail"] = false;
            //setting money
            accountObj["revenue"] = new Money(5000);
            //setting entity reference/lookup
            accountObj["primarycontactid"] = new EntityReference("contact", new Guid("F6954457-6005-E511-80F4-C4346BADC5F4"));
            //setting integer
            accountObj["numberofemployees"] = 50;
            //Date Time
            accountObj["lastusedincampaign"] = new DateTime(2015, 05, 13);
            Guid AccountID = crmService.Create(accountObj);
          }
      }

Tip

You can get the GUID from CRM. Please refer to Chapter 3, Client-side Logic with Microsoft Dynamics CRM 2015, for how to get the GUID of an entity record.

We can also use the create method to create primary and related entities in a single call; for example, in the following call we are creating an account and a related contact record in a single call:

private void CreateRecordwithRelatedEntity()
  {
    using (OrganizationService crmService = new OrganizationService("OrganizationService"))
      {
        Entity accountEntity = new Entity("account");
        accountEntity["name"] = "HIMBAP Technology"; Entity relatedContact = new Entity("contact");
        relatedContact["firstname"] = "Vikram";
        relatedContact["lastname"] = "Singh";
        EntityCollection Related = new EntityCollection();
        Related.Entities.Add(relatedContact);
        Relationship accountcontactRel = new Relationship("contact_customer_accounts");
        accountEntity.RelatedEntities.Add(accountcontactRel,Related);
        crmService.Create(accountEntity);
      }
  }

In the preceding code, first we created an accountEntity object and then created an object of the relatedContact entity and added it to the Entity collection. After that we added the related entity collection to the primary entity with an entity relationship name; in this case it is contact_customer_accounts.

After that we passed our account entity object to the create method to create the account and related contact record. We will run this code to create an account as follows:

Create

relatedrecord

Update

This method is used to update existing record properties; for example we may want to change the account city or any other address information. This methods takes the entity object as a parameter, but we need to make sure to update the primary key field to update any records. The following are example of updating the account city and setting the state property:

  • Early bound:
    private void Update()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
         {
           Account accountUpdate = new Account
             {
               AccountId = new Guid("85A882EE-A500-E511-80F9-C4346BAC0E7C"),
               Address1_City = "Mandi",
               Address1_StateOrProvince = "Himachal Pradesh"
              };
            crmService.Update(accountUpdate);
         }
      }
  • Late bound:
    private void Update()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
          {
            Entity accountUpdate = new Entity("account");
            accountUpdate["accountid"] = new Guid("85A882EE-A500-E511-80F9-C4346BAC0E7C");
            accountUpdate["address1_city"] = "Mandi";
            accountUpdate["address1_stateorprovince"] = "Himachal Pradesh";
            crmService.Update(accountUpdate);
          }
      }

Similarly, to create a method, we can also use the update method to update the primary entity and the related entity in a single call, as follows:

private void Updateprimaryentitywithrelatedentity()
  {
    using (OrganizationService crmService = new OrganizationService("OrganizationService"))
      {
        Entity accountToUpdate = new Entity("account");
        accountToUpdate["name"] = "HIMBAP Technology";
        accountToUpdate["websiteurl"] = "www.himbap.com";
        accountToUpdate["accountid"] = new Guid("29FC3E74-B30B-E511-80FC-C4346BAD26CC");
        Entity relatedContact = new Entity("contact");
        relatedContact["firstname"] = "Vikram";
        relatedContact["lastname"] = "Singh";
        relatedContact["jobtitle"] = "Sr Consultant";
        relatedContact["contactid"] = new Guid("2AFC3E74-B30B-E511-80FC-C4346BAD26CC");
        EntityCollection Related = new EntityCollection();
        Related.Entities.Add(relatedContact);
        Relationship accountcontactRel = new Relationship("contact_customer_accounts");
        accountToUpdate.RelatedEntities.Add(accountcontactRel, Related);
        crmService.Update(accountToUpdate);
      }
  }

Retrieve

This method is used to get data from the CRM based on the primary field, which means this will only return one record at a time. This method takes three parameters:

  • Entity: We need to pass the logical name of the entity as the first parameter
  • ID: We need to pass the primary id of the record that we want to query
  • Columnset: We need to specify a list of the fields list that we want to fetch

The following are examples of using the Retrieve method

  • Early bound:
    private void Retrieve()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
         {
          Account retrievedAccount =
        (Account)crmService.Retrieve(Account.EntityLogicalName, new Guid("7D5E187C-9344-4267-9EAC-DD32A0AB1A30"), new ColumnSet(new string[] { "name" }));
        }
      }
  • Late bound:
    private void Retrieve()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
          {
           Entity retrievedAccount = (Entity)crmService.Retrieve ("account", new Guid("7D5E187C-9344-4267-9EAC-DD32A0AB1A30"), new ColumnSet(new string[] { "name"}));
          }
      }

RetrieveMultiple

The RetrieveMultiple method provides options to define our query object where we can define criteria to fetch records from the primary and related entity. This method takes the query object as a parameter and returns an entity collection as the response. The following are examples of using RetrieveMulitple with both early and late bound:

  • Late Bound
    private void RetrieveMultiple()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
          {
            QueryExpression query = new QueryExpression
              {
                EntityName = "account",
                ColumnSet = new ColumnSet("name", "accountnumber"),
                 Criteria =
                        {
                            FilterOperator = LogicalOperator.Or,
                            Conditions = 
                                {
                                    new ConditionExpression 
                                    {
                                        AttributeName = "address1_city",
                                        Operator = ConditionOperator.Equal,
                                        Values={"Delhi"}
                                    },
                                    new ConditionExpression
                                    {
                                        AttributeName="accountnumber",
                                        Operator=ConditionOperator.NotNull
                                    }
                                }
                        }
                    };
                    EntityCollection entityCollection = crmService.RetrieveMultiple(query);
                    foreach (Entity result in entityCollection.Entities)
                    {
                        if (result.Contains("name"))
                        {
                            Console.WriteLine("name ->" + result.GetAttributeValue<string>("name").ToString());
                        }
                    }
                }
  • Early Bound:
    private void RetrieveMultiple()
      {
        using (OrganizationService crmService = new OrganizationService("OrganizationService"))
          {
            QueryExpression RetrieveAccountsQuery = new QueryExpression
              {
                EntityName = Account.EntityLogicalName,
                ColumnSet = new ColumnSet("name", "accountnumber"),
                Criteria = new FilterExpression
                  {
                    Conditions = 
                   {
                      new ConditionExpression 
                     {
                       AttributeName = "address1_city",
                       Operator = ConditionOperator.Equal,
                         Values = { "Delhi" }
                       }
                     }
                   }
               };
           EntityCollection entityCollection = crmService.RetrieveMultiple(RetrieveAccountsQuery);
           foreach (Entity result in entityCollection.Entities)
             {
               if (result.Contains("name"))
                 {
                   Console.WriteLine("name ->" + result.GetAttributeValue<string>("name").ToString());
                  }
              }
          }
      }

Delete

This method is used to delete entity records from the CRM database. This method takes the entity name and primary ID fields as parameters:

public void Delete()
  {
    using (OrganizationService crmService = new OrganizationService("OrganizationService"))
      {
        crmService.Delete("account", new Guid("85A882EE-A500-E511-80F9-C4346BAC0E7C"));
       }
  }

Associate

This method is used to set up a link between two related entities. It takes the following parameters:

  • Entity Name: The logical name of the primary entity
  • Entity Id: This is the primary entity records ID field.
  • Relationship: Name of the relationship between two entities
  • Related Entities: This is the correction of references

The following is an example of using this method with early bound.

public void Associate()
  {
    using (OrganizationService crmService = new OrganizationService("OrganizationService"))
     {
       EntityReferenceCollection referenceEntities = new EntityReferenceCollection();
       referenceEntities.Add(new EntityReference("account", new Guid("38FC3E74-B30B-E511-80FC-C4346BAD26CC")));
       // Create an object that defines the relationship between the contact and account (we want to set up primary contact)
       Relationship relationship = new Relationship("account_primary_contact");
       //Associate the contact with the  accounts.
       crmService.Associate("contact", new Guid("38FC3E74-B30B-E511-80FC-C4346BAD26CC "), relationship,
                                               referenceEntities);
      }
  }

Disassociate

This method is the reverse of associate. It is used to remove links between two entity records. This method takes the same parameter setup as the associate method takes. The following is an example of disassociate account and contact records:

public void Disassociate()
  {
    using (OrganizationService crmService = new OrganizationService("OrganizationService"))
      {
        EntityReferenceCollection referenceEntities = new EntityReferenceCollection();
        referenceEntities.Add(new EntityReference("account", new Guid("38FC3E74-B30B-E511-80FC-C4346BAD26CC ")));
        // Create an object that defines the relationship between the contact and account.
        Relationship relationship = new Relationship("account_primary_contact");
        //Disassociate the records.
        crmService.Disassociate("contact", new Guid("15FC3E74-B30B-E511-80FC-C4346BAD26CC "), relationship,
                                 referenceEntities);
        }
  }

Execute

Apart from the common methods that we discussed, the Execute method helps to execute requests that are not available as a direct method. This method takes a request as a parameter and returns a response as result. All the common methods that we used earlier can be also used as a request with the Execute method. The following is an example of working with metadata and creating a custom event entity using the Execute method:

public void Usingmetadata()
  {
    using (OrganizationService crmService = new OrganizationService("OrganizationService"))
     {
       CreateEntityRequest createRequest = new CreateEntityRequest
         {
           Entity = new EntityMetadata
             {
               SchemaName = "him_event",
               DisplayName = new Label("Event", 1033),
               DisplayCollectionName = new Label("Events", 1033),
               Description = new Label("Custom entity demo", 1033),
               OwnershipType = OwnershipTypes.UserOwned,
               IsActivity = false,
              },
            PrimaryAttribute = new StringAttributeMetadata
              {
                SchemaName = "him_eventname",
                RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
                MaxLength = 100,
                FormatName = StringFormatName.Text,
                DisplayName = new Label("Event Name", 1033),
                Description = new Label("Primary attribute demo", 1033)
               }
           };
                crmService.Execute(createRequest);
     }
  }

In the preceding code we utilized the CreateEntityRequest class, which is used to create a custom entity. After executing the preceding code, we can check our entity and the default solution by navigating to Settings | Customizations | Customize the System.

Note

You can refer to https://msdn.microsoft.com/en-us/library/gg309553.aspx to see other requests that we can use with the Execute method.

Testing the console application

After adding the preceding methods we can test our console application by writing a simple test method where we can all our CRUD methods. For the testing we have added the following method in our Earlybound.cs file:

public void EarlyboundTesting()
        {
            Console.WriteLine("Creating Account Record.....");
            CreateAccount();
            Console.WriteLine("Updating Account Record.....");
            Update();
            Console.WriteLine("Retriving Account Record.....");
            Retrieve();
            Console.WriteLine("Deleting Account Record.....");
            Delete();
        }

After that we can call this method in the Main method of the Program.cs file as follows:

static void Main(string[] args)
        {
            Earlybound obj = new Earlybound();
            Console.WriteLine("Testing Early bound");
            obj.EarlyboundTesting();
        }

Press F5 to run our console application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.247.125