Share via


Creating CRM Early bound entity in CRM 2011 Plugin

Hello Guys,

I’m back with exciting new topic which could be helpful when you want to understand on how to use early bound classes in CRM Plugin.

Let’s take a look at the hand-on pre-requisites

  • Visual Studio 2010 or higher
  • .NET Framework 4.0
  • LINQ
  • CRM SDK - Consuming Services
  • CRM SDK - Plugin Development

I wouldn’t touch a lot of CRM SDK basics here. I’d like to start with code generation tool directly commonly known as CrmSvcUtil. The below walkthrough will use a sample to update a contact on Post operation.

Let’s go with step-by-step approach

  • Create a new Class Library project in Visual Studio
  • Reference the below CRM SDK assemblies

  • Add the below code

namespace Apurv.CRMSdk.Samples
{
     public class UpdatePlugin : IPlugin
     {
        public void Execute(IServiceProvider serviceProvider)
        {
         // create organization service
         var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
         var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
         var Service = factory.CreateOrganizationService(context.UserId);
         using (var crm = new XrmServiceContext(Service))
         {
          //Use this variable to fetch the current target
          var target = (Entity)context.InputParameters["Target"];
          //Use this variable convert the target in current entity object
          var entity = target.ToEntity();           //Retrieving the Id value from the entity object.
          Guid id = entity.Id.Value;           //Use the XRM contact object to pass in the Early-bound context.           contact contactEntity = new contact           { contactEntity = id, contactEntity.lastname = "Last Name value" };
          //In case you want check if the entity is attached or not. The below code can be used.
          if (!crm.IsAttached(contactEntity))
          crm.Attach(contactEntity); crm.UpdateObject(contactEntity);
          crm.SaveChanges();
          }
         }
     }
}

  • Compile your code and you're assembly is ready for deployment.

Here is this example we’re getting the contact Id Guid from the Input Parameters which will help us to update the record in question. Once we save this record, the plugin will update the lastname to “developer specified value”. This example could be ideal scenario to create some auto-generated number via etc..,

Hope this was helpful.

Cheers,
Apurv

Comments

  • Anonymous
    April 04, 2013
    Thank you