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();

2 comments:

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

    ReplyDelete
  2. This is the first time i am visiting your site. SInce computer sciences is not my subject so i am not able to understand how ever i will suggest this site to my friend. Hope it will be useful for her.

    ReplyDelete