Tuesday, October 26, 2010

Step by step plugin tutorial for CRM 2011

This is a step by step guide to create a plug-in in CRM 2011.

1. Create a class library project in vs2010.
2. Sign the assembly by using the Signing tab of the project's properties sheet.
3. Add references to microsoft.crm.sdk.proxy , Microsoft.xrm.sdk ,
System.ServiceModel and System.Runtime.Serialization.
4. Here is code for this tutorial. This plugin will check if the account number
field is empty, create a task for the user to fill this up.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;
using System.ServiceModel;

namespace CRMPlugin1
{
public class createNote:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{

// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));


// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];



try
{
//check if the account number exist

if (entity.Attributes.Contains("account number") == false)
{

//create a task
Entity task = new Entity("task");
task["subject"] = "Account number is missing";
task["regardingobjectid"] = new EntityReference("account",new Guid(context.OutputParameters["id"].ToString()));

//adding attribute using the add function
// task["description"] = "Account number is missng for the following account. Please enter the account number";
task.Attributes.Add("description", "Account number is missng for the following account. Please enter the account number");



// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


// Create the task in Microsoft Dynamics CRM.
service.Create(task);


}
}

catch (FaultException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
}

}

}
}//end class
}//end name space


5. Compile the code and register it on the registration tool provided with sdk.
6. Register it on the post create event of account entity.
Note :check the sdk for instructions to register a plugin

Thanks

57 comments:

  1. Hi,
    This is good example to the beginers who is learning CRM 2011.

    Keep rock!

    ReplyDelete
  2. Really interesting and useful explaination...Thanks !

    ReplyDelete
  3. Hi, my name is Priyank P. Jain
    Yes, This is a good example to start working on CRM 2011.
    But it will give unexpected error while creating new task.

    You have to add
    "using Microsoft.Xrm.Sdk.Metadata;"
    reference at the top of your code.
    Than it will work properly and creates new task.

    You can contact me on my email address:
    priyankjain1986@gmail.com

    ReplyDelete
  4. Hi Priyank,

    The posted code is a working code. I am not using metadata in this example. It's strange but you don't need to refer "Microsoft.Xrm.Sdk.Metadata" in this plugin.

    Thanks

    ReplyDelete
  5. hi Singh

    I followed the above steps but no O/P no error
    in CRM 2011 ,I have two organization and i registered plugin in default CRM 2011 and also added steps in plugin registration tool but still
    unable to show the desired output

    ReplyDelete
  6. check if there is any error in event viewer.
    Paste your code and I have a look.

    Regards,

    ReplyDelete
  7. Hi .... I Checked .. above code is working fine
    that was my mistake ... OK

    Thanks a lot

    ReplyDelete
  8. this code is working fine ...
    But there is one issue ... the scenario is that if a user edit the account record and enter account number and then save . in that situation created task will not affect . so how we can code to delete the task when user edit and enter account number and save ?

    ReplyDelete
  9. I would say after you enter the account number close the task as completed. If you want to automate it, you can write a plugin on post update, search for the task and update its status to completed.

    ReplyDelete
  10. Thanks i also created a plugin in crm 2011

    ReplyDelete
  11. Hi I am new to CRM 2011 development.
    Just tried the sample accountnumber-auto-generator plugin included in the Sample Plugins in the SDK. and now this one. they both work.
    but when i tried my own plugin on a custom entity following very similar structure, CRM gave me a Business process Error : login failed for user 'OrgName\...' ..
    Anyone can point out what i am doing wrong?

    ReplyDelete
  12. So you are saying that you can run this one but your plugin on custom entity does not work. If you can post your code. I can have a look.

    ReplyDelete
  13. When you need to define multiple plugins for a CRM solution, do you define all the plugins in the one VS2010 project? If so do you define plugins in separate folders/namespaces based on the entity that they'll relate to? Any best practice hints/tips appreciated.
    Thanks!

    ReplyDelete
  14. It's a personal choice. I generally do that.
    I create one .cs file for entity and create a seperate class for every plugin. I like evrything in one place.

    Other people might say, If you are working same solution. You may corrupt the working dll.It's a valid point.

    I never had a problem with using same dll for all the plugins.

    ReplyDelete
  15. Hi Singh

    I am new MS CRM 2011 Developer, I am not able to register the plugin -Tool which has given by MS in SDK. The plugin tool .exe has not working. If possible please tell me the steps for connecting plugins with Visual studio 2010.

    ReplyDelete
  16. i cannnot trigger the plugin when i'm tryin to sve without account name.. but it got sucessfully registered

    ReplyDelete
  17. Hi Singh,

    I want to create sales order using Plugin...
    and i have one condition that Customer filed on sales order which is related to account Entity have Blocked:(1.Yes 2.No) field
    and i have to check that Blocked customer Should not able to Create Sales order..

    If Possible tell me how to do that.....

    My tried code is as follows....

    ReplyDelete
  18. using System;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Xrm;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;

    public class Plugin : IPlugin
    {
    #region Class Level Members

    //private Guid _accountId;
    //private Guid _salesorderId;
    //private OrganizationServiceProxy _serviceProxy;
    //private IOrganizationService _service=new IOrganizationService();

    #endregion Class Level Members

    ReplyDelete
  19. public void Execute(IServiceProvider serviceProvider)
    {
    ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    // Obtain the execution context from the service provider.

    IPluginExecutionContext context = (IPluginExecutionContext)
    serviceProvider.GetService(typeof(IPluginExecutionContext));

    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

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

    //ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    // Obtain the execution context from the service provider.

    Entity entity = null;

    CreateRequiredRecords();

    // 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)
    {

    ReplyDelete
  20. // Obtain the target business entity from the input parameters.
    entity = (Entity)context.InputParameters["Target"];
    Entity account = new Entity("account");

    SalesOrder so = new SalesOrder();
    if (entity.LogicalName == "salesorder")
    {
    if (account.GetAttributeValue("new_blocked")==true)
    {
    //check if the account number exist
    string emailAddress = entity.GetAttributeValue("emailaddress1");
    EntityReference primaryContact = entity.GetAttributeValue("customerid");

    // UPDATE STEP FAILS HERE
    if (primaryContact == null)
    {
    tracingService.Trace("Primary Contact is null");
    }
    Entity contact = service.Retrieve("account", primaryContact.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "name" }));
    //string fullname = contact.GetAttributeValue("name");
    string name = entity.GetAttributeValue("name");

    //// Retrieve the account containing several of its attributes.
    //ColumnSet cols = new ColumnSet(new String[] { "name", "new_blocked" });
    //_salesorderId = so.CustomerId.Id;
    //_accountId = _salesorderId;


    //Account retrievedAccount = (Account)_service.Retrieve("account", _accountId, cols);

    //EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
    //relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _accountId));

    //// Create an object that defines the relationship between the salesorder and account.
    //Relationship relationship = new Relationship("name");

    ReplyDelete
  21. Hi Dattatray,

    I can't see anything wrong. But There are few things you can do.
    check if the property exist before you assign a value uding entity.Attributes.Contains("fieldname");

    ReplyDelete
  22. Also try plugin profiler to debug the plugin. I just tried today. it is very easy to use.

    ReplyDelete
  23. HI., I am new to CRM 2011 development.
    Thanks for posting valid discussion

    ReplyDelete
  24. Hi Singh,

    I want to create sales order using Plugin...
    and i have one condition that Customer filed on sales order which is related to account Entity have Blocked:(1.Yes 2.No) field
    and i have to check that Blocked customer Should not able to Create Sales order..

    If Possible tell me how to do that.....
    I have emailed u on amreeks@live.com
    Please check it.
    My tried code is as follows....

    ReplyDelete
  25. Hey,

    Awesome code...
    worked great and was very helpful.
    thanks!

    ReplyDelete
  26. hi i am intrested to learn MS CRM can anyone help me ....for getting tutorials......i am trying a lot..

    ReplyDelete
    Replies
    1. Hi sista,
      There are a lot of tutorials available online. I would recommend to download crm2011 sdk and go through some walkthroughs and lab excercise.

      Delete
    2. Hi,
      How can we make any field unique in any entity.. For E.g. in Account Entity I wish to make a Custom Field e.g. Unique ID.

      Any Suggestions !!!

      Abhay

      Delete
  27. Hi,
    How can we make any field unique in any entity.. For E.g. in Account Entity I wish to make a Custom Field e.g. Unique ID.

    Any Suggestions !!!

    ReplyDelete
    Replies
    1. There is a sample plugin in sdk.It generates a random aaccounter number. Have a look at that.
      Check in the following location after downloading the sdk \sdk\samplecode\cs\plug-ins.
      There is also a codeplex project on how to generate autonumbers in crm2011
      I hope this helps.

      Delete
  28. Great example for people just starting with plug-ins!!

    ReplyDelete
  29. Microsoft Dynamics CRM training will help you manage and prioritize your business goals, customize.we teach MS Dynamics CRM training and class available at Hyderabad.

    ReplyDelete
  30. Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u.


    How to Register a Business

    ReplyDelete
  31. Hi this is Venu,i have followed the above steps.
    i got installed plugin tool aswell it's working.
    and the above code i have compiled and i have taken that .dll file now what i have to do,and i want to c the proper output,sry this is the first time i am doing plugin i want to be more clear in this and anybody can explain the code above which will be helpfull ,it's urgent for me.

    ReplyDelete
    Replies
    1. Follow these steps
      http://msdn.microsoft.com/en-us/library/cc151173.aspx

      Regards,
      Amreek

      Delete
  32. is there any express editoin for MSCRM

    ReplyDelete
  33. Hi All,
    I need similar kind of Plugin/Code which can fetch some of Field values from Contact Page like Business Phone, Home Phone and Mobile Phone fields.
    How can i go about it ? Im very new to this CRM and its SDK. Can anybody pls provide sample working code so that i can test

    Thanks, Mayank

    ReplyDelete
    Replies
    1. It depends from which entity to get the values. Anyway try this blog http://mscrmshop.blogspot.com.au/2012/02/plugin-to-update-children-records-when.html

      Delete
  34. hi iam new to plugin concept so can anyone say what is the main purpose of images and where they are actually used with good example

    ReplyDelete
  35. Hi Amreek, thank's for a couple of good posts that got me started on plug-ins. I'm, working in VS 2012 (Premium, SP2) and it seems like the developer kit is still having a few bugs (can't browse the plug-in Assmeblies s from the CRM Explorer, Plug-ins are not registered at deploy). So I'm wondering if the recommendation is to use VS2010 still?

    Also, using the toolkit how do I create a plugin-class for an event that does not use an entity ("Send")? I assume I have to edit (remove entity references) manually? :)

    Thank's again
    Nicolai

    ReplyDelete
  36. hii can anyone suggest a good book/tutorial to start with Microsoft dynamics CRM 2011?

    ReplyDelete
  37. Hi Amreek

    I have finished my plugin registration it was successfully done but i am wondering there is no field (attribute) for account number in account entity.
    Please let me know how will i check weather its working or not ?

    ReplyDelete
    Replies
    1. It is a built in field in the account entity. Put that on the form and test the solution. If the field is not on the form then plugin should be firing all the times, as you are not entering anything in the field.

      Delete
  38. Wow, thank you for such a broad explanation of the matter.
    Do you think it would also work for dynamics 365 for operations, or is it limited to some other systems?

    ReplyDelete
  39. Thank you for such a smart entry. I have heard a lot of good lately microsoft ax. I think that in every company you need software that will help you grow your business.

    ReplyDelete
  40. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your blog.

    ReplyDelete
  41. Nice Article sir. Very informative. Thanks for sharing with us.

    http://www.webmaster-success.com/microsoft-india-signs-a-pact-with-niti-for-ai-tools-in-agriculture-healthcare/

    ReplyDelete
  42. Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work.
    h

    ReplyDelete
  43. Great post full of useful tips! My site is fairly new and I am also having a hard time getting my readers to leave comments. Analytics shows they are coming to the site but I have a feeling “nobody wants to be first.

    Microsoft dynamic 365

    ReplyDelete
  44. Thanks for sharing the steps to write an e-commerce blog. I think this is very useful especially for beginners.
    All those who are into e-commerce and wants to know more about it and re-commerce. thanks
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  45. Mscrm Shop: Step By Step Plugin Tutorial For Crm 2011 >>>>> Download Now

    >>>>> Download Full

    Mscrm Shop: Step By Step Plugin Tutorial For Crm 2011 >>>>> Download LINK

    >>>>> Download Now

    Mscrm Shop: Step By Step Plugin Tutorial For Crm 2011 >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete