Thursday, October 21, 2010

Using XRM SDK in MSCRM 4.0 Plugins

I am back and very excited about MSCRM 5.0. But today I am putting a sample to use xrm sdk in plugins. By default there no method in XrmDataContext class to pass plugin context.
But there are ways around it. You can pass the connection as string or as crmconection as follow

Microsoft.Xrm.Client.CrmConnection.Parse(
"Authentication Type=Integrated; Server=http://localhost:" +
new Uri(Microsoft.Win32.Registry.LocalMachine.OpenSubKey ("SOFTWARE\\Microsoft\\MSCRM", false).GetValue("ServerUrl").ToString()).Port +
"/" + context.OrganizationName)

This worked for me.

Here is sample code I have used to create a note for an account



public void Execute(IPluginExecutionContext context)
{
try
{
Guid ID = new Guid();


switch (context.MessageName)
{
case "Create":
ID = new Guid(context.OutputParameters.Properties["id"].ToString());
break;
case "Update":
ID = (Guid)((Microsoft.Crm.Sdk.Key)((Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["Target"]).Properties[context.PrimaryEntityName + "id"]).Value;
break;
case "SetState":
ID = (Guid)((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["EntityMoniker"]).Id;
break;
case "SetStateDynamicEntity":
ID = (Guid)((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["EntityMoniker"]).Id;
break;
case "Delete":
ID = (Guid)((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;
break;

}


var crm = new XRM.MyDataContext(context);

var note = new XRM.annotation()
{
subject = "My XRM Note",
notetext = "This is my XRM Sample.",
Account_Annotation_id = ID,
objecttypecode = "account",

};
crm.AddToannotations(note);
crm.SaveChanges();

1 comment:

  1. Can I your email address. Its not working for me

    ReplyDelete