Error: The type or namespace name ‘Xrm’ does not exist in the namespace ‘Microsoft’ using CRM 2015 SDK

Have a look by clicking the below link to resolve this Error,

http://www.syntaxwarriors.com/2015/using-crm-2015-sdk-gives-error-that-xrm-does-not-exist-in-the-namespace/

Advertisements

Create Email using CRM SDK and C#

Follow the below steps to create a simple Email record in Console application,

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 create Email record,

Create Email - Parameter Description

public static void SendEmail(Guid From, Guid To, string ToEntitySchemaName, string Subject, string Description)
{
try
{
// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, From)
};

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
{
PartyId = new EntityReference(ToEntitySchemaName, To)
};

// Create an e-mail message

Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = Subject,
Description = Description,
DirectionCode = true
};

Guid _emailId = _service.Create(email);

SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq);

if (sendEmailresp != null)
{
Console.WriteLine("Email record created successfully");
Console.ReadKey();
}
}
catch(Exception ex)
{
Console.Write("Error " + ex.Message);
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@XYZOrg.onmicrosoft.com", "password", "https://XYZOrg.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");

Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

if (userid == Guid.Empty) return;

Contact c = new Contact() //Create Contact Record
{
FirstName = "Arvind Kumar",
LastName = "Shah",
MobilePhone = "9876543210",
EMailAddress1 = "arvindshah@crm2015trial.com"
};

Guid contactGuid = _service.Create(c);

if (contactGuid != Guid.Empty)
{
SendEmail(userid, contactGuid, "contact", "Test Subject", "Test Description");
}
}

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 SendEmail(Guid From, Guid To, string ToEntitySchemaName, string Subject, string Description)
{
try
{
// Create 'From' activity party for the email

ActivityParty fromParty = new ActivityParty
{
PartyId = new EntityReference(SystemUser.EntityLogicalName, From)
};

// Create 'To' activity party for the email

ActivityParty toParty = new ActivityParty
{
PartyId = new EntityReference(ToEntitySchemaName, To)
};

// Create an e-mail message

Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = Subject,
Description = Description,
DirectionCode = true
};

Guid _emailId = _service.Create(email);

SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_service.Execute(sendEmailreq);

if (sendEmailresp != null)
{
Console.WriteLine("Email record created successfully");
Console.ReadKey();
}
}

catch(Exception ex)
{
Console.Write("Error " + ex.Message);
Console.ReadKey();
}
}
}
}

Step 8: Execute the project for the below output, Open CRM and check for the email record

Create Email - Output

Please provide your valuable comments on this article.

Retrieve records using Early Bound and LINQ in CRM

Task: Display all Contact records Full Name from Contact entity where Status = Active and Order by Full Name

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 code will retrieve records from Contact entity,

public static void retrieveContactRecords()
{
using (var context = new ServiceContext(_service))
{
var getContactRecords = from conSet in context.ContactSet
where conSet.StateCode == 0   //Check for Status == Active
orderby conSet.FullName
select conSet;

if (getContactRecords != null)
{
StringBuilder fullNameString = new StringBuilder();
Console.WriteLine("Full Name\n--------------------------");
foreach (var item in getContactRecords)
{
if (item.FullName != null)
fullNameString.AppendLine(item.FullName);
}

Console.Write(fullNameString);
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; // Check whether connection established or not

retrieveContactRecords();
}

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 retrieveContactRecords()
{
using (var context = new ServiceContext(_service))
{
var getContactRecords = from conSet in context.ContactSet
where conSet.StateCode == 0   //Check for Status == Active
orderby conSet.FullName
select conSet;

if (getContactRecords != null)
{
StringBuilder fullNameString = new StringBuilder();
Console.WriteLine("Full Name\n--------------------------");
foreach (var item in getContactRecords)
{
if (item.FullName != null)
fullNameString.AppendLine(item.FullName);
}

Console.Write(fullNameString);
Console.ReadKey();
}
}
}
}
}

Step 8: Execute the project for the below output,

Linq Retrieve Output

Please provide your valuable comments on this article.

Generate Early bound Class using CrmSvcUtil.Exe in CRM

CrmSvcUtil.exe is a command-line code generation tool for use with Microsoft Dynamics CRM. This tool generates Early bound class in C# with Custom entities and attributes. Provides Intellisense Support.

Follow the below steps to create early bound class,

Step 1: Download Latest CRM SDK.

Step 2: Open Run and type cmd.

Step 3: In SDK\bin, we can see crmsvcutil.exe. Now provide the path “CRM\SDK\bin” in command prompt.

Example: I have downloaded the CRM SDK on my desktop. So, path in command prompt will be like below,

Crmsvcutil - CMD

Step 4: Now we have to execute crmsvcutil.exe from command prompt with the following command,

CrmSvcUtil.exe
/url:<Organization Service>
out:<Class Name>.cs
/username:"<User Id>"
/password:"<Password>"
/namespace:<Namespace>
/serviceContextName:<Context Name>
Parameter Description
Organization Service Provide Organization Service. Goto Microsoft Dynamics CRM ->Settings -> Customizations -> Organization Service.
Class Name Provide Output Class Name. Ex: D:\OutputFile.cs
User Id Provide Online 365 User Id or On-Premise domain\userid .
Password Provide Password.
Namespace Provide Namespace name.
Context Name Provide Context Name.

Example:

CrmSvcUtil.exe /url:https://OrgName.api.crm5.dynamics.com/XRMServices/2011/Organization.svc /out:C:\Users\arunpotti\Desktop\EarlyBound.cs /username:"arunpotti@OrgName.onmicrosoft.com" /password:"password" /namespace:earlybound /serviceContextName:ServiceContext

Step 5: Paste the command line in command prompt and click on enter to generate class file.

Crmsvcutil - CMD line

Please provide your valuable comments on this article.

Read XML Web resource using C# & SDK in CRM

Let us see a simple example to read XML Web resource using Query Expression in Console Application,

Task: Read books.xml webresource and get all book titles.

books.xml

Solution:

Step 1: Create one Sample XML Webresource and name it as “new_books” in CRM. Click here to get XML.

Step 2: Include the below References in your visual Studio project, you can get the same from Latest SDK.

Goto the path, SDK -> Bin for the dlls

Microsoft.Crm.Sdk.Proxy
Microsoft.Xrm.Sdk

Step 3: Include the below Framework Assemblies in your project,

Reference Manager - ConnectToCRM

Step 4: Add the below namespaces in your class file,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

Step 5: First we have to connect to CRM, for details Click Here

Step 6: Next we have to use GetEntityCollection method to retrieve records, To Know more about this Click Here

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

Step 7: We are going to use GetEntityCollection method as follows,

We are going to retrieve content from webresource entity. If we write the same in SQL it will be like this,

Select name, content from FilteredWebResource where name = ‘new_books’
EntityCollection ec = GetEntityCollection(_service, "webresource", "name", "new_books", new ColumnSet("name", "content"));

Step 8: Below method is useful for converting content binary data to string. Content will be encrypted in database, so we have to convert it into String format.

Note: Include MyOrganizationCrmSdkTypes.cs file in your project for WebResource Class.

You can get the same from the path SDK\SampleCode\CS\HelperCode.

private static string ConvertContentToXMLString(EntityCollection entCol)
{
WebResource webResource = null;
string webResourceContent = string.Empty;
webResource = (WebResource)entCol.Entities[0];
if (webResource.Attributes.Contains("content"))
{
byte[] binary = Convert.FromBase64String(webResource.Attributes["content"].ToString());
webResourceContent = UnicodeEncoding.UTF8.GetString(binary);
}
return webResourceContent;
}

Step 9: Below Method is useful for converting string to XMLDocument and pointing to correct node to get the result.

Note: nodeString parameter is for pointing to XML node. For our Example, we have to get title. So, nodestring will be /catalog/book/title

private static void DisplayXmlNodes(string webResourceContent, string nodeString)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(webResourceContent);
XmlNodeList xnList = xml.SelectNodes(nodeString);
string value = string.Empty;

if (xnList.Count > 0)
{
value += "Book Title\n--------------------------------------\n";
foreach (XmlNode xn in xnList)
{
value += xn.InnerText + "\n";
}
Console.WriteLine(value);
Console.ReadKey();
}
}

Step 10: So the final code is as follows,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Xml;

namespace Read_Webresource
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
ConnectToMSCRM("arunpotti@XXXXXX.onmicrosoft.com","XXXXXX","https://XXXXXX.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
string content = string.Empty;

if (userid == Guid.Empty) return;//check for CRM Connection Establishe or not, if not return otherwise proceed to next step

EntityCollection ec = GetEntityCollection(_service, "webresource", "name", "new_sampleXMLfile", new ColumnSet("name", "content"));

if (ec.Entities[0].Attributes.Count > 0)
{
content = ConvertContentToXMLString(ec);
if (!string.IsNullOrEmpty(content))
DisplayXmlNodes(content, "/catalog/book/title");
}
}

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

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

private static string ConvertContentToXMLString(EntityCollection entCol)
{
WebResource webResource = null;
string webResourceContent = string.Empty;
webResource = (WebResource)entCol.Entities[0];
if (webResource.Attributes.Contains("content"))
{
byte[] binary = Convert.FromBase64String(webResource.Attributes["content"].ToString());
webResourceContent = UnicodeEncoding.UTF8.GetString(binary);
}
return webResourceContent;
}

private static void DisplayXmlNodes(string webResourceContent, string nodeString)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(webResourceContent);
XmlNodeList xnList = xml.SelectNodes(nodeString);
string value = string.Empty;

if (xnList.Count > 0)
{
value += "Book Title\n--------------------------------------\n";
foreach (XmlNode xn in xnList)
{
value += xn.InnerText + "\n";
}
Console.WriteLine(value);
Console.ReadKey();
}
}
}
}

Step 11: Final Output is,

Read XML Web resource-Output

Please provide your valuable feedback.

Retrieve records using Query Expression & C# SDK in CRM

Let us see a simple example to retrieve records using Query Expression,

Task: Get a Contact record with the following values, where Full Name = Arun Potti

Retrieve Multiple - FetchXML SDK

Solution: Follow the below Steps,

Step 1: Include the below References in your project, you can get the same from Latest SDK.

Goto the path, SDK -> Bin for the dlls

Microsoft.Crm.Sdk.Proxy
Microsoft.Xrm.Sdk

Step 2: Include the below Framework Assemblies in your project,

Reference Manager - ConnectToCRM

Step 3: Add the below namespaces in your class file,

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

Step 4: First we have to connect to CRM, for details Click Here

Step 5: User the below method to retrieve record, and it accepts the below parameters

Query Expression Retrieve Record Parameters

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}

Final usage of the function is as follows,

EntityCollection ec = GetEntityCollection(_service, "contact", "fullname", "Arun Potti", new ColumnSet("fullname", "parentcustomerid", "gendercode", "birthdate", "creditlimit", "donotsendmm"));

Step 6: Final Code is here,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

namespace Retrieve_Record
{
class Program
{
static IOrganizationService _service;
static void Main(string[] args)
{
EntityCollection ec = null;
ConnectToMSCRM("arunpotti@XXXXXX.onmicrosoft.com", " XXXXXX", "https:// XXXXXX.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");
Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

if (userid == Guid.Empty) return; //Check for CRM Connection Establishment. If Not return, other wise will proceed to next step

ec = GetEntityCollection(_service, "contact", "fullname", "Arun Potti", new ColumnSet("fullname", "parentcustomerid", "gendercode", "birthdate", "creditlimit", "donotsendmm"));

if(ec.Entities.Count > 0) //Check for EntityCollection count
{
string output = string.Empty;
foreach (var item in ec.Entities)
{
//String
if (item.Attributes.Contains("fullname")) //Check for fullname value exists or not in Entity Collection
output += "Full Name : " + item.Attributes["fullname"] + "\n";

//Lookup
if (item.Attributes.Contains("parentcustomerid")) //Check for parentcustomerid exists or not in Entity Collection
output += "Company : " + ((EntityReference)item.Attributes["parentcustomerid"]).Name + "\n";

//OptionSet
if (item.Attributes.Contains("gendercode")) //Check for gendercode exists or not in Entity Collection
output += "Gender : Name - " + item.FormattedValues["gendercode"] + ", Value - " + ((OptionSetValue)item.Attributes["gendercode"]).Value + "\n";

//Date
if (item.Attributes.Contains("birthdate")) //Check for birthdate exists or not in Entity Collection
output += "Birthday : " + ((DateTime)item.Attributes["birthdate"]).ToLocalTime().ToShortDateString().ToString() + "\n";

//Currency
if (item.Attributes.Contains("creditlimit")) //Check for creditlimit exists or not in Entity Collection
output += "Credit Limit : " + ((Money)item.Attributes["creditlimit"]).Value + "\n";

//Two Options
if (item.Attributes.Contains("donotsendmm")) //Check for donotsendmm exists or not in Entity Collection
output += "Send Marketing Materials : Name - " + item.FormattedValues["donotsendmm"] + ", Value - " + ((Boolean)item.Attributes["donotsendmm"]).ToString();
}
Console.WriteLine(output);
Console.ReadKey();
}
}

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

private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = cols,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = attributeName,
Operator = ConditionOperator.Equal,
Values = { attributeValue }
}
}
}
};
return service.RetrieveMultiple(query);
}
}
}

Step 7:  You can see the below output,

Retrieve Multiple - FetchXML SDK Output

Please provide your valuable feedback.

Sample Plugin using Developer Toolkit

Will see a simple example, to develop and deploy plugin in CRM Online 2013 using SDK Developer Tool Kit in Visual Studio 2012.

Task: On Post Create of Account, Task should create.

Solution:

If you do not have Developer Tool Kit on your Visual Studio, Click Here to know about Installation process.

Step 1: Open Visual Studio 2012.  Click on New Project. Goto Visual C# -> Dynamics CRM -> Dynamics CRM 2013 Package. Provide Name “CrmPackage”.

This package is helpful for Deploying Plugin from Visual Studio.

New Project

Step 2: Please follow the below steps,

  1. Provide Discovery details of your organization. (I am using CRM Online 2013)
    Get this details going to CRM Web Client,
    Microsoft Dynamics CRM -> Settings -> Customizations -> Developer Resources -> Discovery Service.
  2. Select Protocol to HTTPS and click on Connect.
  3. Provide User name & Password and click on Log on.
  4. After successful login to CRM, select Organization and Solution Name. (I have Created a Separate Solution called Plugins for demo)

Step 2

Step 3: Right Click on Solution ‘CrmPackage’ (1 project) and Select Dynamics CRM 2013 Plug-in Library. Provide Name as “PostAccountCreate” and click ok.

Step 3

Step 4: On the Left Hand Side, we can see CRM Explorer. Goto Microsoft -> Entities -> Account -> Create Plug-in.

Step 4

Step 5: Select Message, Run in Context, Pipeline Stage and Execution Mode as mentioned below. Click OK.

Step 5

Step 6: You may see the below alert, click on Yes to All

Step 6

Step 7: Have to provide Strong Key to the Plugin. For that Go to Solution Explorer on the right hand side, Right Click On “PostAccountCreate” and click on Properties .

Step 7

Step 8: Follow the below steps for Strong Key set up.

  1. Go to Signing and Select Sign the assembly.
  2. Choose a strong name key file: to <New…>.
  3. Provide Key file name: as “PostAccountCreate” and uncheck the Protect my key file with a password.
  4. Select Signature Algorithm.

Step 8

Step 9: Goto Solution Explorer, double click on “PostAccountCreate.cs” file. You can see the below code,

Step 9

Step 10: Copy and paste the below code in method ExecutePostAccountCreate after //TODO: Implement your custom Plug-in business logic.

// TODO: Implement your custom Plug-in business logic.

IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
ITracingService tracingService = localContext.TracingService;

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName == "account")
{
try
{
Entity followup = new Entity("task");

followup["subject"] = "Send e-mail to the new customer.";
followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
followup["scheduledstart"] = DateTime.Now.AddDays(7);
followup["scheduledend"] = DateTime.Now.AddDays(7);
followup["category"] = context.PrimaryEntityName;

// Refer to the account in the task activity.
if (context.OutputParameters.Contains("id"))
{
Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
string regardingobjectidType = "account";

followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
}

// Create the task in Microsoft Dynamics CRM.
tracingService.Trace("FollowupPlugin: Creating the task activity.");
service.Create(followup);
}
catch (FaultException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
}
}
}

Step 11: Finally the ExecutePostAccountCreate method looks like the below,

Step 11

Step 12: Save All. Click on F6 to build the solution.

Step 13: Goto Solution Explorer, and right Click on Solution ‘CrmPackage’ (2 projects). Click on Deploy Solution to deploy into Online CRM 2013.

Step 13

Step 14: After Successful Deployment, you can check it, whether plugin registered on Account or not, by going to Plugin Registration Tool or Go to CRM Explorer on left hand side of visual studio, you can find the below

Step 14

Step 15: Create Account record in CRM Online. After Account creation, Task is created, you can check it in under Social Pane -> Activities,

Step 15

Good Luck :):):)