Task: Update Mobile Phone for Contact record where Full Name = “Arun Potti”
Solution: Follow the below steps,
Step 1: Open Visual Studio and Create Console Application Project.
Step 2: First we have to establish connection to CRM. Please follow my earlier post Connect to CRM Online or On-premise using C# SDK.
Step 3: Generate Early bound class using Crmsvcutil.exe. Please follow my earlier post Generate Early bound Class using CrmSvcUtil.Exe in CRM.
Step 4: Add EarlyBound.cs to the project.
Step 5: Include the namespace using EarlyBound.cs.
Step 6: Below method will update Contact record,
updateContactRecord("1234567890"); public static void updateContactRecord(string phoneNumber) { using (var context = new ServiceContext(_service)) { Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == "Arun Potti"); if (conRecord != null) { conRecord.MobilePhone = phoneNumber; context.UpdateObject(conRecord); if (context.SaveChanges().Count > 0) { Console.WriteLine("Record Updated Successfully"); Console.ReadKey(); } } } }
Step 7: Final Code will be like below,
using Microsoft.Crm.Sdk.Messages; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Description; using System.Text; using System.Threading.Tasks; using EarlyBound; namespace LinqToCRM { class Program { static IOrganizationService _service; static void Main(string[] args) { ConnectToMSCRM("arunpotti@MyOrg.onmicrosoft.com", "Password", "https://MyOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc"); Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId; if (userid == Guid.Empty) return; updateContactRecord("1234567890"); } public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri) { try { ClientCredentials credentials = new ClientCredentials(); credentials.UserName.UserName = UserName; credentials.UserName.Password = Password; Uri serviceUri = new Uri(SoapOrgServiceUri); OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null); proxy.EnableProxyTypes(); _service = (IOrganizationService)proxy; } catch (Exception ex) { Console.WriteLine("Error while connecting to CRM " + ex.Message); Console.ReadKey(); } } public static void updateContactRecord(string phoneNumber) { using (var context = new ServiceContext(_service)) { Contact conRecord = context.ContactSet.FirstOrDefault(c => c.FullName == "Arun Potti"); if (conRecord != null) { conRecord.MobilePhone = phoneNumber; context.UpdateObject(conRecord); if (context.SaveChanges().Count > 0) { Console.WriteLine("Record Updated Successfully"); Console.ReadKey(); } } } } } }
Step 8: Execute the project for the below output,
Please provide your valuable comments on this article.