CorrelationId Property in MS CRM

MS CRM 4.0

The CorrelationId property identifies a relationship between multiple requests. For example, a request processed by a parent pipeline can cause the platform to create and process multiple child pipeline requests in order to complete the parent request. The parent and child pipeline requests have the same CorrelationId to establish a relationship among these requests.

public Guid CorrelationId {get; set;}
Property Value

The value of this property is a Guid type.

Requirements

Web Service: CrmService

MS CRM 2011:

Guid CorrelationId {get;}

Property Value

Type: Guid
The global unique identifier for tracking plug-in or custom workflow activity execution.
Advertisements

Parent Vs Child Execution Pipeline in MS CRM 4.0

The event execution pipeline architecture provides the capability for a pipeline to initiate the execution of one or more subordinate pipelines in order to process a request. The originating pipeline is known as the “parent” while the subordinate pipeline is called the “child”. Web service method calls typically start a parent pipeline while (internal) platform calls start a child pipeline. Child pipelines only process CreateUpdate, or Delete messages as required by the platform to process the parent pipeline’s message. To determine which message is being processed by a child pipeline, you must enable tracing in Microsoft Dynamics CRM.

When a complex request is processed by a pipeline, the pipeline first executes any registered pre-event plug-ins and the core platform operation. Next, the pipeline starts a child pipeline and temporarily suspends processing until the child pipeline has finished processing its request. Once the child pipeline has completed, the parent pipeline can complete its post-event processing.

Parent and Child Context

Context plays an important role when it comes to parent-child pipeline execution. The context that is passed to plug-ins of the child pipeline will include the parent contextthat was executed immediately prior to the child pipeline’s invocation. This will enable you to track the parent and child pipeline executions and get more information about what is going on

Invocation Source

A plug-in can be registered to be executed from a parent pipeline or a child pipeline. At run time, a plug-in receives information as to how it was invoked through theInvocationSource property of the context that is passed as a parameter to the plug-in.

If you want your plug-in to run regardless of whether a Web service call or an (internal) platform call initiated the pipeline, register your plug-in in a child pipeline. However, do not use the IPluginExecutionContext.CreateCrmService or IPluginExecutionContext.CreateMetadataService methods if you are writing code for a plug-in in that is used in a child pipeline. In a child pipeline, you must instantiate the CrmService or MetadataService manually.

Example

The following code example shows how to create a CrmService proxy for plug-ins that execute in the child pipeline.

[C#]
/// <param name="context">The execution context that was passed to the plug-in's Execute method.</param>
/// <param name="flag">Set to True to use impersonation.</param>
/// <returns>A CrmServce instance.</returns>
private CrmService CreateCrmService(IPluginExecutionContext context, Boolean flag)
{
    CrmAuthenticationToken authToken = new CrmAuthenticationToken();
    authToken.AuthenticationType = 0;
    authToken.OrganizationName = context.OrganizationName;

    // Include support for impersonation.
    if (flag)
        authToken.CallerId = context.UserId;
    else
        authToken.CallerId = context.InitiatingUserId;

    CrmService service = new CrmService();
    service.CrmAuthenticationTokenValue = authToken;
    service.UseDefaultCredentials = true;

     // Include support for infinite loop detection.
    CorrelationToken corToken = new CorrelationToken();
    corToken.CorrelationId = context.CorrelationId;
    corToken.CorrelationUpdatedTime = context.CorrelationUpdatedTime;
    corToken.Depth = context.Depth;

    RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");

    service.Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx");
    service.CorrelationTokenValue = corToken;

    return service;
}

What’s the difference between FetchXML and QueryExpression? – MS CRM 2011

To Query MS CRM DB there are the two distinct ways.

  • Using QueryExpression
  • Using FetchXML

Limitation of the QueryExpression is , If you are Querying CRM DB using QueryExpression you cannot able to set Related Entity columns as filter criteria to return the Query Result.

Where as using FetchXML , you can set the Related Entity columns in filter criteria to return the Query Result.

Note: CRM also provides the following messages to convert FetchXML to QueryExpression and vice versa.

– FetchXmlToQueryExpression : Converts from FetchXML to query expression.
– QueryExpressionToFetchXml : Converts from query expression to FetchXML.

Note again, if you are to convert a FetchXML that has select columns specified from related entity, to Query Expression, the related entity columns are not included in the QueryExpression columns list.

 

Cheers,

Creating a Simple Plug-in in MS CRM 4.0

Step 1: Creating a Visual Studio Solution

First you will create a new Visual Studio project and create a Visual C# class file.

To create a Visual Studio solution

  1. In Microsoft Visual Studio, on the File menu, point to New, and then click Project to open the New Project dialog box.
  2. In the Project types pane, select Visual C#.
  3. In the Templates pane, click Class Library.
  4. Type a name for your project and then click OK. Use the name AccountCreatePlugin.
  5. In Solution Explorer, rename the Class1.cs file to Plugin.cs.
  6. When you are prompted to rename all references to this file, click Yes.

Step 2: Adding References

You need to add references to the required Microsoft Dynamics CRM assemblies.

To add the necessary assembly references

  1. In Solution Explorer, right-click the References folder and select Add Reference.
  2. Click the Browse tab and navigate to the location of your Microsoft Dynamics CRM DLLs. This may be in the SDK\Bin folder or on your server in the GAC folder. The GAC folder is located on the Microsoft Dynamics CRM server at <crm-root>\Server\i386\GAC.
  3. Select both Microsoft.Crm.Sdk.dll and Microsoft.Crm.SdkTypeProxy.dll and click OK.
  4. In Solution Explorer, right-click the References folder and select Add Reference.
  5. Click the .NET tab, select System.Web.Services, and click OK.

Step 3: Sign your Plug-in

  1. Right-click the AccountCreatePlugin project in Solution Explorer and click Properties.
  2. Create a new strong key file by clicking the Signing tab, select the Sign the assembly check box and select <New…> in the drop down list.
  3. Type AccountCreateStrongKey and clear the Protect my key file with a password check box. Click OK.
  4. Save your changes by clicking the Save All button.

Step 4: Write your Plug-in Code

This plug-in will create a new task to send an e-mail to the new customer after an account is created. It also shows you an example of throwing plug-in exceptions to the client, which displays an exception message to the user. The complete project source code can be found at SDK\Walkthroughs\Plugin\CS\AccountCreate.

To add required namespaces

  1. Open the Plugin.cs file and add Microsoft.Crm.Sdk and Microsoft.Crm.SdkTypeProxy to the imported namespaces, as shown in the following code example.
  2. Add a semicolon and the word IPlugin after the class declaration.

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

namespace Microsoft.Crm.Sdk.Walkthrough
{
    public class AccountCreateHandler : IPlugin
    {
public void Execute(IPluginExecutionContext context)
{
   DynamicEntity entity = null;

   // Check if the input parameters property bag contains a target
   // of the create operation and that target is of type DynamicEntity.
   if (context.InputParameters.Properties.Contains("Target") &&
      context.InputParameters.Properties["Target"] is DynamicEntity)
   {
      // Obtain the target business entity from the input parmameters.
      entity = (DynamicEntity)context.InputParameters.Properties["Target"];

      // Verify that the entity represents an account.
      if (entity.Name != EntityName.account.ToString()) { return; }
   }
   else
   {
      return;
   }

   try
   {
      // Create a task activity to follow up with the account customer in 7 days. 
      DynamicEntity followup = new DynamicEntity();
      followup.Name = EntityName.task.ToString();

      followup.Properties = new PropertyCollection();
      followup.Properties.Add(new StringProperty("subject", "Send e-mail to the new customer."));
      followup.Properties.Add(new StringProperty("description", 
         "Follow up with the customer. Check if there are any new issues that need resolution."));

      followup.Properties.Add(new CrmDateTimeProperty("scheduledstart", 
         CrmTypes.CreateCrmDateTimeFromUniversal(DateTime.Now.AddDays(7))));
      followup.Properties.Add(new CrmDateTimeProperty("scheduledend", 
         CrmTypes.CreateCrmDateTimeFromUniversal(DateTime.Now.AddDays(7))));

      followup.Properties.Add(new StringProperty("category",
         context.PrimaryEntityName));

      // Refer to the new account in the task activity.
      if (context.OutputParameters.Properties.Contains("id"))
      {
         Lookup lookup = new Lookup();
         lookup.Value = new Guid(context.OutputParameters.Properties["id"].ToString());
         lookup.type = EntityName.account.ToString();

         followup.Properties.Add(
            new LookupProperty("regardingobjectid", lookup));
      }

      TargetCreateDynamic targetCreate = new TargetCreateDynamic();
      targetCreate.Entity = followup;

      // Create the request object.
      CreateRequest create = new CreateRequest();
      create.Target = targetCreate;

      // Execute the request.
      ICrmService service = context.CreateCrmService(true);
      CreateResponse created = (CreateResponse)service.Execute(create);      
   }
   catch (System.Web.Services.Protocols.SoapException ex)
   {
      throw new InvalidPluginExecutionException(
         "An error occurred in the AccountCreateHandler plug-in.", ex);
   }
}

 } }
  1. Compile the project by clicking Build, and then Build Solution.

To deploy the plug-in on your server

If you intend to debug your plug-in, follow these steps to place a copy of the plug-in assembly at the correct location on the Microsoft Dynamics CRM server’s disk.

  1. On your development machine, navigate to the bin\Debug folder to find your newly compiled plug-in assembly. This may be in the bin\Release folder depending on your default project settings. Check your project’s Build Output path for the correct location.
  2. Copy the compiled plug-in assembly AccountCreatePlugin.dll to the <crmroot>\Server\bin\assembly folder of your Microsoft Dynamics CRM server.

Your plug-in code is now complete.

Step 5: Register your Online Plug-in with the PluginRegistration tool

The plug-in registration tool enables you to register your plug-in with a specific event in Microsoft Dynamics CRM. When that particular event fires, your plug-in will execute. This walkthrough uses database deployment of the plug-in for simplicity.

Note:  There is a security restriction that allows only privileged users to register plug-ins. The system user account under which the plug-in is being registered must exist in theDeployment Administrators group in Deployment Manager. The account must also have either the System Administrator or System Customizer role in Microsoft Dynamics CRM.

To register your plug-in

  1. In Visual Studio, click Tools, and then click CRM Plug-in Registration Tool to run the plug-in registration tool. If you have not added the Plug-in Registration Tool to the Visual Studio Tools menu, then manually run the tool.Plug-in Registration Tool
  2. In the Connections panel, enter a descriptive label for the connection. Fill in the other fields as appropriate for your Microsoft Dynamics CRM 4.0 server.
  3. Click Connect. A connection to the server is established and a list of available organizations for the specified system account is displayed.
  4. Double-click the desired organization in the connections list. The list of all assemblies, steps, and plug-ins currently registered for the target organization is displayed. Clicking any assembly, step, or plug-in displays a list of information about that selected item.Assemblies and plug-ins registered with an organization
  5. Select Register, and then select Register New Assembly.
  6. In the Register New Plugin form, click the ellipsis button (…) and navigate to the location of your plug-in assembly.
  7. Select the assembly.Note If an exception dialog box is displayed containing a “System.IO.FileNotFoundException: Could not load file or assembly ‘Microsoft.Crm.Sdk'” message, the plug-in registration tool cannot find the Microsoft.Crm.Sdk.dll assembly that it requires. Copy that assembly from the SDK\Bin folder to the folder containing the tool’s executable file and try again.
  8. Verify that the Select All and Database options are checked. Click Register Selected Plugins.Register New Plugin form
  9. The Registration Log will display the status of the plug-in registration process. Click OK to dismiss the Registered Plugins dialog box.

The assembly and plug-ins are now registered.

To Register a Step for your plug-in

This next procedure registers a step that defines the conditions under which the plug-in is to execute.

  1. Select the plug-in (AccountCreateHandler) in the tree view.
  2. Select Register, and then click Register New Step.
  3. In the Register New Step dialog, enter the information as shown in the figure below and select Register New Step.Registering a step

You have just created a synchronous post-event plug-in that will run when an account is created while in online mode. For further information about using the tool, press the F1 key while the tool’s window has focus to display online help. You can dismiss the plug-in registration tool at this point.

Note For this SDK release, pressing F1 in the PluginRegistration tool window displays this walkthrough in a browser window. Future SDK releases will include online Help for the PluginRegistration tool.

Test the Plug-in

To test the plug-in you can create an account. This will trigger the plug-in code to run.

  1. Open Internet Explorer, navigate to your Microsoft Dynamics CRM server, click New, and then click Account.
  2. Enter your Account Name and click Save.
  3. After Microsoft Dynamics CRM finishes saving, click the Activities link under Details.
  4. You should see the new activity created for this account with the subject Send e-mail to the new customer.

Sample Custom Workflow Activity To Create a Task

Create a Task

using System;
using System.Collections;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Reflection;

using Microsoft.Crm.Workflow;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace SampleWorkflows
{
    [CrmWorkflowActivity("Create a Task")]
    public class CustomActivity : Activity
    {
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {

            IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
            IWorkflowContext context = contextService.Context;

            ICrmService crmService = context.CreateCrmService();

            DynamicEntity entity = new DynamicEntity();
            entity.Name = EntityName.task.ToString();
            entity.Properties = new PropertyCollection();
            entity.Properties.Add(new StringProperty("subject", taskId.Value.ToString()));
            entity.Properties.Add(new KeyProperty("activityid", new Key(taskId.Value)));
            crmService.Create(entity);

            return base.Execute(executionContext);
        }

        public static DependencyProperty taskIdProperty =
           DependencyProperty.Register("taskId",
           typeof(Lookup),
           typeof(CustomActivity));

        [CrmInput("The id")]
        [CrmOutput("The output")]
        [CrmReferenceTarget("task")]
        public Lookup taskId
        {
            get
            {
                return (Lookup)base.GetValue(taskIdProperty);
            }
            set
            {
                base.SetValue(taskIdProperty, value);
            }

        }

    }
}

Diff between context.userid and context.initiatinguserid In MS CRM 2011 Plugin

Diff between context.userid and context.initiatinguserid In MS CRM 2011 Plugin

Situation: A plugin running from a impersonated context
Aim: Get the GUID of the user who has actually fired the plugin and not the GUID of the user under whose context the plugin is registered.
The context gives us both the GUIDs
  • context.initiatinguserid: gets the systemuser GUID who actually fired the plugin
  • context.userid : gets the  impersonated systemuser GUID

How to install the Microsoft Dynamics CRM server roles

Move the Microsoft Dynamics CRM Server or one of the Microsoft Dynamics CRM server roles. However, leave the SQL Server and the SQL Server Reporting Services server intact

  1. Install the Microsoft Dynamics CRM Server 2011 or server role on a new server. To do this, follow these steps:
    1. On the new computer, install Microsoft Dynamics CRM Server 2011.
    2. During the installation process, type the name of the SQL Server on which the MSCRM_CONFIG database exists in the Select Deployment Options dialog box, and then click Connect to, and if necessary, upgrade an existing deployment.
    3. Complete the installation.
  2. Uninstall the Microsoft Dynamics CRM Server 2011 or the server role from the old Microsoft Dynamics CRM Server 2011. To do this, follow these steps:
    1. In Control Panel, open the Programs and Features item.
    2. Right-click Microsoft Dynamics CRM 2011 Server, and then click Uninstall/Change.
    3. Complete the removal wizard to remove Microsoft Dynamics CRM Server 2011 or server role on the old server.

    Note

    If you cannot uninstall the old Microsoft Dynamics CRM Server 2011 or server role in step 2 because of a hardware failure, go to step 3.

  3. Remove the server from Deployment Manager. To do this, follow these steps:
    1. On the computer that is running Microsoft Dynamics CRM Server 2011, click Start, point to All Programs, point to Microsoft Dynamics CRM 2011, and then click Deployment Manager.
    2. Click Servers. A list of the servers in the Microsoft Dynamics CRM deployment appears. If no servers appear, right-click Servers, and then click Refresh.
    3. Right-click the server that is not in the deployment, click Delete, and then click Yes. The server is removed from the MSCRM_CONFIG database.

    Note

    Depending on the Microsoft Dynamics CRM roles that you move, you may have to run the Configuration Wizard for the E-mail Router to update the configuration. You may also have to run the Configuration Wizard for the Microsoft Dynamics CRM for Outlook to connect to the new Microsoft Dynamics CRM Server 2011.