Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Plug-in code

Posted on by 760

Hi,

I'm studying plug-in. I tried creating a simple code to understand it better, there's no error but is not working.

Can someone help me in understanding what;s wrong with the code.



if (entity.LogicalName != "opportunity")
return;

Entity opp = new Entity("opportunity");

opp["currentsituation"] = "testing plug-in"

*This post is locked for comments

  • ashlega Profile Picture
    ashlega 34,475 on at
    RE: Plug-in code

    There are a couple of things in your code that look suspicious(and yes, have a look at all the links above):

    1) if you are creating a new entity object in code, you have to call service.Create(entity) at some point to create it in the database.. or you have to call service.Update(entity) to update a record in the database (in which case you need to assign an id: opp.Id = entity.Id)

    2) If your intent was to call an "update", then you can use pre-operation or post-operation plugin. In the pre-operatio, you can simply update the plugin target. All those changes will go to the database - no need to create a new object. In the post operation, it's better to create a new in-memory entity, assign Id, and call service.Update.. but you'll have to make sure the plugin does not go into recursion either by specifying the right attributes on the plugin step, or by adding a condition if(context.Depth > 1) return;

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plug-in code

    Hi Arci,

    you request is not clear/complete.

    I suggest you, as Guillaume, to take a short plugin tutorial with this video:

    https://www.youtube.com/watch?v=gHk14Jbg8Ek 

    Please let us know.

    If you found the answer helpful, please mark as Verified 

    Join my network on LinkedIn      Follow me on Twitter 

    Thank You & Best Regards

    Francesco Picchi

    Microsoft Dynamics CRM Consultant, Bologna, ITALY

    Independent Contractor

    http://www.francescopicchi.com

    atch?v=gHk14Jbg8Ek

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plug-in code

    Please update complete code.. below line of code is  fine.

    if (entity.LogicalName != "opportunity")

    return;

    Entity opp = new Entity("opportunity");

    opp["currentsituation"] = "testing plug-in";

  • Suggested answer
    Kishor Kumar Profile Picture
    Kishor Kumar 3,702 on at
    RE: Plug-in code

    Hi Arci,

    Learning Plugin is very easy.

    Check this,

    msdn.microsoft.com/.../gg594416.aspx

    www.c-sharpcorner.com/.../create-plug-in-of-ms-dynamic-crm-2013-in-Asp-Net

    crmbook.powerobjects.com/.../plug-ins

    www.youtube.com/watch

    www.youtube.com/watch

    www.youtube.com/watch

  • Mahendar Pal Profile Picture
    Mahendar Pal 45,095 on at
    RE: Plug-in code

    Can you share complete code and some details about registration ?? And how you are testing it.

    Thanks

  • Suggested answer
    Iswarya Profile Picture
    Iswarya 1,345 on at
    RE: Plug-in code

    Hi,

    basic plugin code for record creation try this one

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Client;

    using System.ServiceModel;

    namespace ClassLibrary1

    {

       public class createplugin : IPlugin

       {

           #region Variable Delcaration

           EntityReference Country = new EntityReference();

           EntityReference State = new EntityReference();

           EntityReference child = new EntityReference();

           string Name;

           string des;

           #endregion

           public void Execute(IServiceProvider serviceprovider)

           {

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

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

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

               if (context.Depth > 1)

                   return;

               #region for getting values

               if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

               {

                   Entity entity = (Entity)context.InputParameters["Target"];

                   if (entity.LogicalName != "new_availability")

                       return;

                   // GETTING VALUES FOR LOOKUP FIELD

                   if (entity.Attributes.Contains("new_country"))

                   {

                       Country = (EntityReference)entity.Attributes["new_country"];

                   }

                   if (entity.Attributes.Contains("new_state"))

                   {

                       State = (EntityReference)entity.Attributes["new_state"];

                   }

                   //GETTING VALUES FOR STRING FILED

                   if (entity.Attributes.Contains("new_name"))

                   {

                       Name = ((System.String)entity.Attributes["new_name"]);

                   }

                   //GETTING VALUE FOR OPTIONSET FIELD

                   OptionSetValue lis = (OptionSetValue)entity.Attributes["new_list"];

                   //GETTING VALUE FOR DATE AND TIME

                   DateTime DATE = ((DateTime)entity.Attributes["new_date"]).Date;

                   //GETTING VALUE FOR MULTIPLE LINE TEXT

                   if(entity.Attributes.Contains("new_descript"))

                   {

                       des = ((System.String)entity.Attributes["new_descript"]);

                   }

                   //GETTING VALUE FOR CURRENCY FIELD

                       Money amount = (Money)entity.Attributes["new_amount"];

                   //GETTING VALUE FOR DECIMAL FIELD

                      Decimal Ave = (Decimal)entity.Attributes["new_average"];

                   //GETTING VALUE OF FLOATING POINT NUMBER

                      Double Rang = (Double)entity.Attributes["new_range"];

                   //GETTING WHOLE NUMBER VALUE

                      Int32 mob = (Int32)entity.Attributes["new_mobile"];

                   //GETTING VALUE OF TWO OPTION FIELD

                      Boolean Gen = (Boolean)entity.Attributes["new_gender"];

               #endregion

               #region for creation

               Entity avail = new Entity();

               avail.LogicalName = "new_product";

           //SETTING VALUE FOR LOOKUPFIELD

             if (Country != null)

               {

                   EntityReference countryvalue = new EntityReference() { Id = Country.Id, LogicalName = Country.LogicalName };

                   avail["new_country"] = countryvalue;

               }

               if (State != null)

               {

                   EntityReference statevalue = new EntityReference() { Id = State.Id, LogicalName = State.LogicalName };

                   avail["new_state"] = statevalue;

               }

               //SETTING VALUE FOR STRING FILED

                  avail["new_name"] = Name;

               //SETTING OPTIONSET VALUE

                  avail["new_list"] = lis;

               //SETTING DATE/TIME VALUE

                  avail["new_date"] = DATE;

              //SETTING MULTIPLE LINES FIELD

                  avail["new_descript"] = des;

              //SETTING CURRENCY VALUE

                  avail["new_amount"] = amount;

               //SETTING DECIMAL VALUE

                  avail["new_average"] = Ave;      

               //SETTING FLOATING POINT

                  avail["new_range"] = Rang;

               //SETING WHOLE NUMER

                  avail["new_mobile"] = mob;

               //SET TWO OPTIONS VALUE

                  avail["new_gender"] = Gen;

               Guid CreationId = service.Create(avail);

               #endregion

           }

       }

       }

    }

  • Suggested answer
    Iswarya Profile Picture
    Iswarya 1,345 on at
    RE: Plug-in code

    Hi refer this it may help u

    PLUGIN FOR CREATION AND UPDATION:

    Opoen visual studio ->file->new project->select Class library , give name and location for that library and save.

    Now add References->include dll file-> Microsoft.Xrm.Sdk and Runtime serialization assemblies. For inherit the Iplugin interface to the class.

     

    System.Runtime.Serialization:

    The System.Runtime.Serialization namespace contains classes that can be used for serializing and deserializing objects.

    Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location..

     

    For example ;

    For serializing the process of Updation or creation we need to include System.Runtime.Serialization.

    Entity hospital = new Entity();

    hospital.LogicalName = "new_hospital";

     

    if (Country != Guid.Empty)

         {

           hospital["new_country"] = new EntityReference("new_countries", Country);

         }

     

    service.Update(hospital);

     

     

    Now implement IPlugin Interface and you will get an Execute method with the IserviceProvider interface object as a parameter.

     

    Procedure

    Step 1

    => we need to trigger our plug-in when an event is executed, we need to get the service of IPluginExecutionContext using the IServiceProvider object.

    =>Iservice interface provides access to various service of dynamic ,this interface has a method called Getservice that allow us to get any type of service we want.

    =>And the GetService method returns an object of the specified type. We need to type caste that object.

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

     

    Step 2

    InputParameter:

    Contains all details about entity,

    We are retrieve the target entity from the input parmeter,

     

     

     

    Plugin For Creation:

    Means we need to trigger

    After creation of plugin we need to build our project.    

    Once you build your project, need to generate a key . Without this key cannot deploy a plug-in onto a server.

    To create a key, go to project property (ALT+ Enter) and go to the signing tab and check sign the assembly.

    Select new in the drop down and add a key name and your dynamic CRM Password. And select save (CTRL+ S).

    If you have done this then it will add a pfx encrypted key for your current project

    Plugin for Creation Event:

     

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

     

    namespace PluginCreationUpdation

    {

      

       public class CreationofPlugin : IPlugin

       {

           public void Execute(IServiceProvider serviceprovider)

           {

               try

               {

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

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

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

     

                   if(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)

                   {

                       if (context.Depth == 1)

                      {

     

    //Variable declaration done here. We need to declare our variable based on the Fields type

                           #region Variable Delcaration

     

                           int AddressType = 0;

     

                           string AddressId = string.Empty;

     

                           string Phone = string.Empty;

                           string Fax = string.Empty;

     

     

                           Guid Country = Guid.Empty;

                           Guid State = Guid.Empty;

                           Guid City = Guid.Empty;

                           Guid ZipCode = Guid.Empty;

     

                           Guid addressinformationId = Guid.Empty;

                           Guid hospitalId = Guid.Empty;

     

     

     

     

                           #endregion

     

    =>Input Parameter Contains all details about Target entity-> Entity Id,Logical Name and Filtering Atributes

    =>We are retrieve the target entity from the input parmeter,

     

     

                           Entity entity = (Entity)context.InputParameters["Target"];

    //entity reference variable contains our Target Entity.

    //here we check our target entity.logical name ,if it doesnot equal our target entity its return. Or satisfy means its proceeds further.

                          

    if (entity.LogicalName != "new_addressinformation")

                           {

                               return;

                           }

     

    //we are getting our target entity ID.

                           addressinformationId = entity.Id;

     

     

    //GET ALL THE ATTRIBUTE VALUES FROM TARGET ENTITY

     

                           if (entity.Attributes.Contains("new_addresstype"))

                           {

                               AddressType = ((OptionSetValue)entity.Attributes["new_addresstype"]).Value;

                           }

                           //throw new InvalidPluginExecutionException("Plugin Error- " + AddressType);

     

                           if (AddressType == 100000001)

                           {

     

                               if (entity.Attributes.Contains("new_hospitalid") && entity["new_hospitalid"] != null && ((EntityReference)entity["new_hospitalid"]).Id != Guid.Empty)

                               {

                                   hospitalId = ((EntityReference)entity.Attributes["new_hospitalid"]).Id;

     

     

                               }

                               if (entity.Attributes.Contains("new_country1") && entity["new_country1"] != null && ((EntityReference)entity["new_country1"]).Id != Guid.Empty)

                               {

                                   Country = ((EntityReference)entity.Attributes["new_country1"]).Id;

     

     

                               }

     

                               if (entity.Attributes.Contains("new_state1") && entity["new_state1"] != null && ((EntityReference)entity["new_state1"]).Id != Guid.Empty)

                               {

                                   State = ((EntityReference)entity.Attributes["new_state1"]).Id;

                               }

                               if (entity.Attributes.Contains("new_city1") && entity["new_city1"] != null && ((EntityReference)entity["new_city1"]).Id != Guid.Empty)

                               {

                                   City = ((EntityReference)entity.Attributes["new_city1"]).Id;

                               }

     

                               if (entity.Attributes.Contains("new_zipcode1") && entity["new_zipcode1"] != null && ((EntityReference)entity["new_zipcode1"]).Id != Guid.Empty)

                               {

                                   ZipCode = ((EntityReference)entity.Attributes["new_zipcode1"]).Id;

                              }

     

                               if (entity.Attributes.Contains("new_phone"))

                               {

                                   Phone = ((System.String)entity.Attributes["new_phone"]);

                               }

                                if (entity.Attributes.Contains("new_fax"))

                               {

                                   Fax = ((System.String)entity.Attributes["new_fax"]);

                               }

     

     

    //Above we are retrieving all the fields from target entity ,

    Now we are update the retrieving values into our entity

     

                               #region Update hospital Address

     

    //create object for serialization process

     

                               Entity

     

     

     

     

     

     

     

    = new Entity();

                               hospital.LogicalName = "new_hospital";

     

                               if (Country != Guid.Empty)

                               {

                                   hospital["new_country"] = new EntityReference("new_countries", Country);

                               }

                               if (State != Guid.Empty)

                               {

                                   hospital["new_state"] = new EntityReference("new_stattess", State);

                               }

                                if (City != Guid.Empty)

                               {

                                   hospital["new_city"] = new EntityReference("new_city", City);

                               }

     

                               if (ZipCode != Guid.Empty)

                               {

                                   hospital["new_zipcode"] = new EntityReference("new_zipcodess", ZipCode);

                               }

     

     

     

     

     

                               hospital["new_phone"] = Phone;

                                hospital["new_fax"] = Fax;

     

                               hospital["new_hospitalid"] = hospitalId;

                               service.Create(hospital);

     

     

     

     

     

     

     

                               #endregion

                           }

     

                       }

     

                   }

     

               }

     

     

     

     

     

     

     

     

     

     

               catch (Exception ex)

               {

                   throw new InvalidPluginExecutionException("Plugin Error- " + ex.Message.ToString());

               }

     

           }

       }

     

     

     

     

     

     

     

    Now register into PLUGIN REGISTERATION TOOL.

    Open the tool from sdk tools, now click create New Connection

    Now enter all credentials Server name and port number for connect to our sever.

    Now register the assembly that means out plugin getting register into our plugin registeration tool,

    Now add steps for our plgin .

     

     

     

     

     

     

     

    =>The plugin and steps are successfully registerd into plugin registeration tool.

    =>Open our organisation and check our plugin trigger based on the event what ever we mentioned.

    While register our step fill the following details:

    Message-For create or update or delete and so on.

    Primary Entity-We are mention our target entity.

    Filtering Attributes-we need to mention the field name for trigger plugin for onchange of the mention field

    Execution Order-we need to mention order of execution .i have two class library one is for creation and other is updation for that situation I need mention which plugin excute first and second.

    Pipeline Stage-we have 3 pipeline stage

    1.Pre-validation

    2.Pre-operation

    3.Post-operation

    Here I choose Post-operation because my event trigger after creation of record.

    Excution mode-we have 2 excution mode

    1.synchronous->Execution happen suddenly, operations don’t run in the background.

    2.asynchronous-> Execution happen slowly, operations run in the background.

     

    Now all steps are over,then we need to trigger our plugin.

     

     

     

     

     

     

  • Suggested answer
    Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Plug-in code

    Hi,

    Maybe you should start with a basic working plugin that you can find here: msdn.microsoft.com/.../gg594416.aspx.

    If you want that the community helps you. We will need more info. When did register your plugin (pre/ post operation)? When is triggered(creation/update/deletion/... of a record)?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans