Sunday, April 17, 2011

Instantiating a Service Object Within a Plug-in in Microsoft Dynamics CRM 2011

I have seen people asking lately in the forums about how to instantiate a service reference from within a plug-in / plugin.  I whipped up a quick example the other day.  I will show you how to do it and work with an entity without generating early bound types or specific proxies, but I will also provide a link below to a walk-through on how to go that route also.  This example uses the Entity class from the CRM SDK.  It is the equivalent to DynamicEntity in CRM 4.0.  It is nice because you can dynamically work with entities without having generated the specific proxy information for your organization's metadata.

First, here is a simple plugin example that instantiates a service object in the simplest way.  The example then uses the exposed context UserID to perform a retrievemultiple request on a systemuser and adds the user fullname attribute to the contact entity that is the target of the plug-in execution.  Don't ask why I am putting this info into the address1_city as this is just a simple proof of concept. This example is intended to be registered pre-operation on the contact entity.

 public void Execute(IServiceProvider serviceProvider)
        {
            
            // Obtain the organization service reference.

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

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
          

            // 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"];

                if (entity.LogicalName == "contact")
                {
                    if (entity.Attributes.Contains("address1_city") == false)
                    {
                        

                        RetrieveMultipleRequest rmreq = new RetrieveMultipleRequest();
                        RetrieveMultipleResponse rmresp = new RetrieveMultipleResponse();
                        
                        
                        QueryExpression query = new QueryExpression()
                        {
                            EntityName = "systemuser",
                            ColumnSet = new ColumnSet(true),
                            Criteria = new FilterExpression
                            {
                                FilterOperator = LogicalOperator.And,
                                Conditions = 
                                {
                                    new ConditionExpression
                                    {
                                        AttributeName = "systemuserid",
                                        Operator = ConditionOperator.Equal,
                                        Values = { context.UserId.ToString() }
                                    }
                                }
                            }
                        };

                        rmreq.Query = query;
                        rmresp = (RetrieveMultipleResponse)service.Execute(rmreq);
                        Entity user = (Entity)rmresp.EntityCollection.Entities[0];

                        entity.Attributes.Add("address1_city", context.UserId.ToString() + ": " + user.Attributes["fullname"]);
                    }
                    else
                    {
                        // Throw an error, because account numbers must be system generated.
                        // Throwing an InvalidPluginExecutionException will cause the error message to be displayed in a dialog of the Web application.
                        throw new InvalidPluginExecutionException("Bad, Naughty Plug-in, Don't do that!.");
                    }
                }
            }
        }


Also, here is a walk-through on working with the early-bound entity types in a plug-in:
http://msdn.microsoft.com/en-us/library/gg695782.aspx

 

 

4 comments:

  1. Hi Jamie
    what should be the message for registering this plugin ?

    ReplyDelete
  2. You can register it on whatever message you want, the exact plugin above was meant to be registered on update of a systemuser entity.

    ReplyDelete
  3. Hi Jamie,

    In plugin registration we have GrantAccess Message. what for we will use this message and how it can be triggered ?.

    ReplyDelete
    Replies
    1. This is triggered when a record is shared. You could use it for things like notifying someone in an email that a record has been shared, and with whom.

      Delete