Sample Crm 2011 Plugin to Add note to Contact

using System;

using System.Diagnostics;

using System.Linq;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Xrm;

public classPlugin : IPlugin

{

 publicvoid Execute(IServiceProvider serviceProvider)

 {

        IPluginExecutionContext context = (IPluginExecutionContext)

serviceProvider.GetService(typeof(IPluginExecutionContext));

  Entity entity;  

 

// Check if the input parameters property bag contains a target

// of the create operation and that target is of type Entity.

 if (context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is Entity)

        {       

 // Obtain the target business entity from the input parameters.

           entity = (Entity)context.InputParameters[“Target”];

// Verify that the entity represents a contact.

if (entity.LogicalName != “contact”) { return; }

        }

else

        {

return;

try

        {

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)

serviceProvider.GetService(typeof(IOrganizationServiceFactory));

 IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

var id = (Guid)context.OutputParameters[“id”];

AddNoteToContact(service, id);

        }

catch (FaultException<OrganizationServiceFault> ex)

        {

thrownew InvalidPluginExecutionException(“An error occurred in the plug-in.”, ex);

        }

    }

privatestaticvoid AddNoteToContact(IOrganizationService service, Guid id)

    {

using (var crm = new XrmServiceContext(service))

        {

var contact = crm.ContactSet.Where(

            c => c.ContactId == id).First();

            Debug.Write(contact.FirstName);

var note = new Annotation

            {

                Subject =“Created with plugin”,

                NoteText =“This Note was created by the example plug-in”,

                ObjectId = contact.ToEntityReference(),

                ObjectTypeCode = contact.LogicalName

            };

 crm.AddObject(note);

 crm.SaveChanges();

        }

    }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s