Monday, May 14, 2012

How to trigger a plugin for a many to many relationship

The blog will explain “ How to trigger a plugin for many to many (N:N) relationship. For this blog, I have created a new N:N relationship between account and contact entity. I am displaying this relationship just in account entity. The following screen shot is displaying the properties of the relationship.
a1
To trigger a plugin on association of 2 entities in a n:n relationship, we will use associate plugin message. I am using the developer’s toolkit for writing code from last 6 months. The problem is developer’s toolkit does not support “Associate” message. To create a plugin in developer’s toolkit, you need to choose primary entity and to use “Associate” message primary entity and secondary entity has to be “none”. There is a workaround to register  plugin step on “Associate” message. Here are the steps.
  1. Follow the steps in this blog on how to create a plugin using developer’s toolkit.
  2. In the step 12th of above-mentioned blog, replace the function “ExecutePostAccountCreate” with the following code
    protected void ExecutePostAccount(LocalPluginContext localContext)
    {
    
        if (localContext == null)
        {
            throw new ArgumentNullException("localContext");
        }
    
        // TODO: Implement your custom Plug-in business logic.
        // Obtain the execution context from the service provider.
        IPluginExecutionContext context = localContext.PluginExecutionContext;
        IOrganizationService service = localContext.OrganizationService;
        ITracingService tracingService = localContext.TracingService;
    
        try{
        // The InputParameters collection contains all the data passed in the message request.
        if (!context.InputParameters.Contains("Target")) { return; }
    
        EntityReference ef = (EntityReference)context.InputParameters["Target"];
        if (ef.LogicalName != "account") { return; }
    
        Relationship relationship = (Relationship)context.InputParameters["Relationship"];
        if (relationship.SchemaName != "new_account_contact") { return; }
    
        // Get Related Entities 
        EntityReferenceCollection re = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
    
        foreach (EntityReference rel in re)
        {
    
            Entity relatedEntity = service.Retrieve("contact", rel.Id, new ColumnSet("address1_city"));
            string city = (string)relatedEntity.Attributes["address1_city"];
            if (city=="Sydney")
            {
                //create a task
                Entity task = new Entity("task");
                task["subject"] = "A new contact from sydney is added to the account";
                task["regardingobjectid"] = ef;
                task["description"] = "A new contact from sydney is added to the account";
                // Create the task in Microsoft Dynamics CRM.
                service.Create(task);
    
            }
        }//endfor
        }
        catch (FaultException ex)
        {
            tracingService.Trace(ex.Message.ToString());
            throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
        }
    
    }//end function
    
  3. Add the following reference to your plugin class.
    using Microsoft.Xrm.Sdk.Query;
  4. The above code will create a task, when we add a contact with “address1_city” field equal to “Sydney” to an account. Just remember we are relating a contact to account using N:N relationship.
  5. Now change the RegisterFile.crmregister file  to register on an “Associate” message. Open the file and look for your plugin definition. It will look something like the following code.
    <Plugin Description="Plug-in to PostAccountCreate" FriendlyName="PostAccountCreate" Name="CRM2011PluginSeries.Plugins.PostAccountCreate" Id="420419bd-9fe7-404e-a5e3-afa582f21dd3" TypeName="CRM2011PluginSeries.Plugins.PostAccountCreate">
              <Steps>
                <clear />
                <Step CustomConfiguration="" Name="PostAccountCreate" Description="Post-Operation of Account Create" Id="b248f264-2b3f-e111-ab54-00155d32042e" MessageName="Create" Mode="Synchronous" PrimaryEntityName="account" Rank="1" SecureConfiguration="" Stage="PostOutsideTransaction" SupportedDeployment="ServerOnly">
                  <Images />
                </Step>
              </Steps>
            </Plugin>
  6. Now change the MessageName="Create" to MessageName="Associate" and PrimaryEntityName="account" to PrimaryEntityName="".
  7. Save the changes and deploy the plugin.
  8. If you get any errors during deployment, just deploy the plugin using plugin registeration tool. Don't forget to leave the "PrimaryEntityName" = none.
  9. Please provide some feedback

16 comments:

  1. what if you have two n:n relationships say account to contact and account to opportunity.. how do we specify which relationship to trigger?

    ReplyDelete
  2. It will trigger for all the relationships. You need to check the relationship name and write a code for that relationship.
    In the code above, the following line is checkingthe relationship is
    if (relationship.SchemaName != "new_account_contact") { return; }
    Change the relationship.SchemaName based on the relationship you want to run the code on.

    ReplyDelete
  3. Thanks a lot for your blog.
    I wasted 4 hours on this plugin ; trying to figure out how it would get triggered!!
    Your code makes it run perfectly!!
    Thanks :)

    ReplyDelete
  4. 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
  5. EntityReferenceCollection re = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];

    The above line of code only gets one record. So if i HAVE SELECTED MULTIPLE RECORDS TO BE ASSOCIATED The Plugin triggers for multiple times.

    Cant I have all the records in the EntityReferenceCollection and then process them.

    ReplyDelete
  6. Is triggering a plugin for a many to many relationship supported in MSCRM 2015?

    ReplyDelete
  7. Hello everyone....

    Am Mrs Barber from Scotland
    i want to testify about a great spell caster that help me cast a spell that bring my husband back to me without any delay. I broke up with him with just little misunderstanding hoping we will get back shortly,but things was growing worse until i contacted Dr.Manbela who help me with his historical powers to bring him back, i have never believed in a spell caster until i come across him, it will be of great sin if i should go out from here without dropping the contact of this great spell caster, in case you need the help of this great spell caster you can contact him through his email: once you contact him all your problems will be over ,once again i say very big thanks to you sir for helping me to recover my husband back, and please sir keep your good work because people need your help and in their lives ,once more thank you Dr Manbela

    contact him via; Manbelaspelltemple1@gmail.com or through his WhatsApp number +2348112060023

    ReplyDelete
  8. HOW TO GET BLANK ATM CARD AND WITHDRAW
    UNLIMITED CASH
    This is the happiest moment of my life having no longer to worry about paying bills as i have been settled for life. A lot has been said about atm hacking and blank card for cash withdrawal but it all seemed like a myth to me until i eventually lost my job few months back and the world seemed to be moving backwards. I went online in search of jobs and means to an end and there i found comments about blankatmdeliveryxpress and how they deliver this card in less than 7 days with no risk involved and a far much lesser price compared to what the card itself can give you, i then made contact and purchase one from them with almost my last dollars I took the risk and in exactly 6 days latter my card and a manual was delivered to my home address here in California and that same evening i used the card was able to take out $5000 for a start its been just 3 weeks and my life has taken a new shape. I simply want to say thank you to this electronic company and help spread their fame abroad. If you ever are in need of this card contact them via email :blankatmdeliveryxpress@gmail.com.
    Don't mail them if you not really ready for this card is gonna cost you money to buy the card note that,they offer card to firms, orphans,individual and business personnels mail them immediately .

    ReplyDelete
  9. INSTEAD OF GETTING A LOAN, CHECK OUT THE BLANK ATM CARD IN LESS THAN 24hours {oscarwhitehackersworld@gmail.com}


    I want to testify about OSCAR WHITE blank ATM cards which can withdraw money from any ATM machines around the world. I was very poor before and have no hope then I saw so many testimony about how OSCAR WHITE send them the blank ATM card and i use it to collect money in any ATM machine and become rich. I also email him and he sent me the blank card. I have use it to get $100,000 dollars. withdraw the maximum of $5,000 daily.OSCAR WHITE is giving out the card just to help the poor. Hack and take money directly from any ATM Machine Vault with the use of ATM Programmed Card which runs in automatic mode. email Him on how to get it now via: oscarwhitehackersworld@gmail.com or whats-app +1(323)-362-2310

    ReplyDelete
  10. Are you in a financial crisis, looking for money to start your own business or to pay your bills?
    GET YOUR BLANK ATM CREDIT CARD AT AFFORDABLE PRICE*
    We sell this cards to all our customers and interested buyers
    worldwide,Tho card has a daily withdrawal limit of $5000 and up to $50,000
    spending limit in stores and unlimited on POS.

    YOU CAN ALSO MAKE BINARY INVESTMENTS WITH LITTLE AS $500 AND GET $10,000 JUST IN SEVEN DAYS

    **WHAT WE OFFER** 

    *1)WESTERN UNION TRANSFERS/MONEY GRAM TRANSFER*
    *2)BANKS LOGINS*
    *3)BANKS TRANSFERS*
    *4)CRYPTO CURRENCY MINNING*
    *5)BUYING OF GIFT CARDS*
    *6)LOADING OF ACCOUNTS*
    *7)WALMART TRANSFERS*
    *8)BITCOIN INVESTMENTS*
    *9)REMOVING OF NAME FROM DEBIT RECORD AND CRIMINAL RECORD*
    *10)BANK HACKING*
    **email blankatmmasterusa@gmail.com
    **you can also call or whatsapp us Contact us today for more enlightenment *
    *+1(539) 888-2243*
    **BEWARE OF SCAMMERS AND FAKE HACKERS IMPERSONATING US BUT THEY ARE NOT
    FROM *
    *US CONTACT US ONLY VIA THIS CONTACT **
    *WE ARE REAL AND LEGIT...........2020 FUNDS/FORGET ABOUT GETTING A LOAN..*

    IT HAS BEEN TESTED AND TRUSTED

    ReplyDelete
  11. This card are real i got my card few hours ago and am just coming back from the ATM where i made my first withdraw of 1500$ i am going crazy this is fucking real OSCAR WHITE sorry for being so skeptical about it at first don’t blame me the street these days got fucked up lots of scammers and now i can recommend whoever needs a blank ATM card with about $50,000 on it which you can withdraw within a month because the card has a daily limit.if you are facing any financial problem contact him asap email address is oscarwhitehackersworld@gmail.com or whats-app +1(513)-299-8247 as soon as possible .

    ReplyDelete
  12. CONTACT Mr DAVID MARK IS A NICE MAN... call(+2348064080845) or add him on WhatsApp(+2348064080845) I was thinking that illuminati is not real, But today with Mr David Mark I now believe that illuminati is real, when you come across wrong person’s you will think that life is not real but when you are with the real one you will experience the goodness of your life, To Mr David Mark has made me discovered my purpose of life. Welcome to the great brotherhood of Illuminati 666: . WhatsApp mr David Mark , from , Nigeria, and every other Country’s on how to join the Illuminati brotherhood to get rich and famous, You may be a politician, business man/woman ,musical artist, student, footballer or whatever occupation you do, you want to be rich, powerful and famous in life. Illuminati can grant all your heart desires join the Illuminati to become rich and famous in life, Illuminati will make you achieve all your dream to become rich and protected all the days of your life…… BENEFIT GIVEN TO A NEW MEMBER WHO JOIN THE ILLUMINATI a cash reward of usd $2.5million USD a new sleek dream car valued at USD $70,000.00USD a dream house build in any country of your own choice one month holiday (fully paid) to your dream tourist destination.One year golf membership package a V I P treatment in all airports in the world a total lifestyle change access to bohemian grove monthly payment of $10,000USD into your bank account every month as a member, one month booked appointment with top 5 world leaders and top 5 celebrities in the world» JOIN ILLUMINATI YOUR FINANCIALDIFFICULTIES ARE BROUGHT TO AN END. WE SUPPORT YOU BOTH FINANCIALLYAND SPIRITUALLY TO ENSURE YOU LIVE A COMFORTABLE LIFE . IF YOU ARE INTERESTED CONTACT Mr David Mark on WhatsApp (+2348064080845) Or call him (+2348064080845) email him on : frankilluminateagent@gmail.com For immediately response… My Regard to mr David Mark.......

    ReplyDelete
  13. I am a widow with two kids, i want to share my testimony on how i paid all my debts and own myself a business. I went online then i came across a testimony about a blank card, i decided to give it a trial, all to my surprise it came through. i got the card, each day i withdraw $10,000 and i have withdrawn the total of $80,000. i am so thankful and grateful to Mr Rick hackers whom God used to take me out of debts and poverty i am sharing this because i know so many out there are in need do not doubt, i can guarantee you the best with Mr Rick hackers, if interested email him on rickatmcardoffer@gmail.com WhatsApp number +27783198318.

    ReplyDelete