This time we are going through a process of building a custom plug-in for Microsoft Dynamics CRM and its deployment on development server.  I assume that you already downloaded and setup Development Tool Kit. And make sure CRM templates are imported in Visual Studio.

Start with creating a solution using Dynamics CRM. Navigate to Settings >> Customization >> Solution. Create a new Solution “AccountPlugin” and choose any name based on project and company requirement. In case, you are going to develop plugin for any existing solution skip this steps.

Save CRM solution and publish.

In Visual Studio, Create new project using Dynamics CRM 2013 Package template. If templates are not available, make sure that you already imported development tool kit templates in Visual Studio.

Dynamics CRM package is selected instead of Dynamics CRM 2013 plugin because it will make our process easy for plugin registration and deployment using tool kit.

 

You will be asked to connect CRM live before Visual Studio setup package solution. CRM connection screen pops up. You can also open it from Tool >> CRM connection.

Fill out required details and connect development Dynamics CRM server.

URL: CRM URL.

User Name: Domain Administrator

Password:   Domain Administrator Password

Browse all organizations and select appropriate organization and solution to hook plugin.

After a successful connection with CRM server, CRM package solution will be created in Visual Studio. Next step is to add a CRM plugin library project in solution. More plug-in projects can be added in one solution.

Now Visual Studio solution is set up and ready for plugin development. Some important file and DLLs are added in projects which are required. Let me elaborate important of these files.

RegisterFile.crmregistration is xml file contains details of all added plugins and workflows and register those in Dynamics CRM when package is deployed. Its auto created file using CRM Development Tool Kit.

Microsoft.Crm.Sdk.Proxy and Microsoft.Xrm.Sdk are two very important DLLs referenced in plugin project. These DLLs contain core classes of Microsoft dynamics CRM which are used for plugin operations.

Next step is to create strong name key for plugin project. Right click on project and select properties and create new Strong Name key (SNK). SNK is system oriented and when you move this development code on another machine, SNK needs to create again.

 

Open CRM explorer from View>>CRM explorer and expend entities. Right click on Account entity and select create plugin. It’s popping up Create Plug-in window.

Let’s go through Create Plug-in form attributes. First one “Project” is default set to “AccountPlugin” as it’s related to a single plugin project, in case we have more than one plugin projects. It will be enabled for selection.

Next is “Primary entity” is about to entity for which plugin is being created and it “Account” entity.

Next one is “Message” is about to CRM action, it’s associated with.

 

 Next important attribute is “Pipeline Stage” and it’s specifying execution time of plugin. In this example, we created “PostAccountcreate” plugin. So Pipeline Stage is to determine on which stage of “PostAccountCreate”, this plug-in will fire. 

Next one is “Class” to specify class name for plug-in. Next important attribute is “Execution order” to specify order of plugin execution. In case of many plugins are associated with an action stage, it will be used to determine the execution order of this plug-in. Click Ok and plugin will be created.

 

After successful creation of “AccountPlugin”. Open “RegisterFile.crmregister” file and a new code line is added in xml for created “AccountPlugin” plugin.

 

 

“PostAccountCreate” class is added in plug-in project, where custom code will be written for operations required under this plugin. “ExecutePostAccountCreate” method is responsible for plugin operations.

Sample code lines for update Account entity Name attribute:

// <copyright file="PostAccountCreate.cs" company="">
// Copyright (c) 2016 All Rights Reserved
// </copyright>
// <author></author>
// <date>6/4/2016 9:59:31 AM</date>
// <summary>Implements the PostAccountCreate Plugin.</summary>
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
// </auto-generated>
namespace AccountPackage.AccountPlugin
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;

    /// <summary>
    /// PostAccountCreate Plugin.
    /// </summary>    
    public class PostAccountCreate: Plugin
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PostAccountCreate"/> class.
        /// </summary>
        public PostAccountCreate()
            : base(typeof(PostAccountCreate))
        {
            base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Create", "account", new Action<LocalPluginContext>(ExecutePostAccountCreate)));

            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }

        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePostAccountCreate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.
            IPluginExecutionContext Context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            ITracingService trace = localContext.TracingService;

            
            Entity entity = null;
            EntityReference parentCustomerIdAttribRef = null;

            // If we have a target
            if (Context.InputParameters.Contains("Target") && Context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity
                entity = (Entity)Context.InputParameters["Target"];

                // Only perform this code if this is a create
                if (Context.MessageName != "Update") { return; }

                // Only perform this code for a certain entity
                if (Context.PrimaryEntityName != "account") { return; }

                // Only perform this code if this column is included in the collection of attributes 
                
                else { return; }
            }
            else { return; }
            try
            {
                

                    entity.Attributes["AttributeName"] = AttributeValue;
                   
                    //Update account entity
                    service.Update(entity);
                }
            }
            catch (FaultException<OrganizationServiceFault> e)
            { trace.Trace(string.Format("Exception: {0}", e.ToString())); }
            catch (Exception ex)
            { trace.Trace(string.Format("Exception: {0}", ex.ToString())); }
        }
    }
}

Sample code lines use to update Account attribute name value as John. So after an account is created in CRM, account name attribute is updated as “john”.

At the end build project and right click on package and select deploy.