How to obtain GUID of an LookUp

Obtain GUID of an LookUp

Guid guidLookupId = ((Microsoft.Xrm.Sdk.EntityReference)(entityUnit.Attributes[“lookupId”])).Id;

————————————————————————————————————————————————-

 From PostImage 

Guid offerGuid = ((postImageEntity.Attributes.Contains(“up_offerid”)) ? (((EntityReference)(postImageEntity.Attributes[“up_offerid”])).Id) : Guid.Empty);

 

To retreive the Guid of the Lookup entity

I have an entity which has 5 attributes. 1 of these attributes is a Lookup to another entity.

What I am trying to do with my Plugin is to retreive the Guid of the Lookup entity.

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

if (entity.LogicalName == “new_producttaxrate”)

{

if (entity.Attributes.Contains(“new_product”))

{

 EntityReference ownerLookup = (EntityReference)entity.Attributes[“new_product”]; productName = ownerLookup.Name; Guid productId = ownerLookup.Id;

}

 }                                                                     (Or)

 

EntityReference customer = (EntityReference)(postImageEntity.Attributes[“customerid”]);

                                Guid GuidCustomerId = customer.Id;

                                string strTitle = postImageEntity.Attributes[“name”].ToString();// customer.Name;

 

 

Ms CRM 2011 Custom Workflow Activity

Sample: Custom Workflow Activity

Demonstrates

This sample shows how to write a custom workflow activity that can create an account and a task for the account. This sample uses early binding.

Example

C#

 
using System;
using System.Activities;
using System.Collections.ObjectModel;

using Microsoft.Crm.Sdk.Messages;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;

namespace Microsoft.Crm.Sdk.Samples
{
 public sealed class SimpleSdkActivity : CodeActivity
 {
 protected override void Execute(CodeActivityContext executionContext)
 {
 //Create the tracing service
 ITracingService tracingService = executionContext.GetExtension<ITracingService>();

 //Create the context
 IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
 IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
 IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

 tracingService.Trace("Creating Account");

 Account entity = new Account();
 entity.Name = AccountName.Get<string>(executionContext);
 Guid entityId = service.Create(entity);

 tracingService.Trace("Account created with Id {0}", entityId.ToString());

 tracingService.Trace("Create a task for the account");
 Task newTask = new Task();
 newTask.Subject = TaskSubject.Get<string>(executionContext);
 newTask.RegardingObjectId = new EntityReference(Account.EntityLogicalName, entityId);

 Guid taskId = service.Create(newTask);

 tracingService.Trace("Task has been created");

 tracingService.Trace("Retrieve the task using QueryByAttribute");
 QueryByAttribute query = new QueryByAttribute();
 query.Attributes.AddRange(new string[] { "regardingobjectid" });
 query.ColumnSet = new ColumnSet(new string[] { "subject" });
 query.EntityName = Task.EntityLogicalName;
 query.Values.AddRange(new object[] { entityId });

 tracingService.Trace("Executing the Query for entity {0}", query.EntityName);

 //Execute using a request to test the OOB (XRM) message contracts
 RetrieveMultipleRequest request = new RetrieveMultipleRequest();
 request.Query = query;
 Collection<Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;

 //Execute a request from the CRM message assembly
 tracingService.Trace("Executing a WhoAmIRequest");
 service.Execute(new WhoAmIRequest());

 if (1 != entityList.Count)
 {
 tracingService.Trace("The entity list was too long");
 throw new InvalidPluginExecutionException("Query did not execute correctly");
 }
 else
 {
 tracingService.Trace("Casting the Task from RetrieveMultiple to strong type");
 Task retrievedTask = (Task)entityList[0];

 if (retrievedTask.ActivityId != taskId)
 {
 throw new InvalidPluginExecutionException("Incorrect task was retrieved");
 }

 tracingService.Trace("Retrieving the entity from IOrganizationService");

 //Retrieve the task using Retrieve
 retrievedTask = (Task)service.Retrieve(Task.EntityLogicalName, retrievedTask.Id, new ColumnSet("subject"));
 if (!string.Equals(newTask.Subject, retrievedTask.Subject, StringComparison.Ordinal))
 {
 throw new InvalidPluginExecutionException("Task's subject did not get retrieved correctly");
 }

 //Update the task
 retrievedTask.Subject = UpdatedTaskSubject.Get<string>(executionContext);
 service.Update(retrievedTask);
 }
 }

 [Input("Account Name")]
 [Default("Test Account: {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
 public InArgument<string> AccountName { get; set; }

 [Input("Task Subject")]
 [Default("Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
 public InArgument<string> TaskSubject { get; set; }

 [Input("Updated Task Subject")]
 [Default("UPDATED: Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
 public InArgument<string> UpdatedTaskSubject { get; set; }
 }

 public sealed class SdkWithLooselyTypesActivity : CodeActivity
 {
 protected override void Execute(CodeActivityContext executionContext)
 {
 //Create the tracing service
 ITracingService tracingService = executionContext.GetExtension<ITracingService>();

 //Create the context
 IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
 IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
 IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

 tracingService.Trace("Creating Account");

 tracingService.Trace("Creating Account");

 Entity entity = new Entity("account");
 entity.Attributes["name"] = AccountName.Get<string>(executionContext);
 Guid entityId = service.Create(entity);

 tracingService.Trace("Account created with Id {0}", entityId.ToString());

 tracingService.Trace("Create a task for the account");
 Entity newTask = new Entity("task");
 newTask["subject"] = TaskSubject.Get<string>(executionContext);
 newTask["regardingobjectid"] = new EntityReference("account", entityId);

 Guid taskId = service.Create(newTask);

 tracingService.Trace("Task has been created");

 Entity updateTask = new Entity("task");
 updateTask.Id = taskId;
 updateTask["subject"] = UpdatedTaskSubject.Get<string>(executionContext);
 service.Update(updateTask);

 tracingService.Trace("Task has been updated");
 }

 [Input("Account Name")]
 [Default("Test Account: {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
 public InArgument<string> AccountName { get; set; }

 [Input("Task Subject")]
 [Default("Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
 public InArgument<string> TaskSubject { get; set; }

 [Input("Updated Task Subject")]
 [Default("UPDATED: Task related to account {575A8B41-F8D7-4DCE-B2EA-3FFDE936AB1B}")]
 public InArgument<string> UpdatedTaskSubject { get; set; }
 }

 public sealed class SimpleSdkWithRelatedEntitiesActivity : CodeActivity
 {
 protected override void Execute(CodeActivityContext executionContext)
 {
 //Create the tracing service
 ITracingService tracingService = executionContext.GetExtension<ITracingService>();

 //Create the context
 IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
 IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
 IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

 Relationship primaryContactRelationship = new Relationship("account_primary_contact");

 Guid primaryContactId = service.Create(new Contact() { LastName = RootContactLastName.Get<string>(executionContext) });

 //tracingService.Trace("Create an Account with an existing primary contact");
 Account rootAccount = new Account() { Name = RelatedAccountName.Get<string>(executionContext) };
 Contact primaryContact = new Contact()
 {
 EntityState = EntityState.Changed,
 Id = primaryContactId,
 FirstName = RootContactFirstName.Get<string>(executionContext)
 };

 rootAccount.RelatedEntities[primaryContactRelationship] =
 new EntityCollection(new Entity[] { primaryContact }) { EntityName = Contact.EntityLogicalName };

 tracingService.Trace("Execute the Create/Update");
 rootAccount.Id = service.Create(rootAccount);

 //Create the related entities query
 RelationshipQueryCollection retrieveRelatedEntities = new RelationshipQueryCollection();
 retrieveRelatedEntities[primaryContactRelationship] = new QueryExpression(Account.EntityLogicalName)
 {
 ColumnSet = new ColumnSet("name"),
 Criteria = new FilterExpression()
 };

 //Create the request
 RetrieveResponse response = (RetrieveResponse)service.Execute(new RetrieveRequest()
 {
 ColumnSet = new ColumnSet("firstname"),
 RelatedEntitiesQuery = retrieveRelatedEntities,
 Target = new EntityReference(primaryContact.LogicalName, primaryContact.Id)
 });

 tracingService.Trace("Retrieve the record with its related entities");
 Contact retrievedContact = (Contact)response.Entity;
 Account retrievedAccount = (Account)retrievedContact.RelatedEntities[primaryContactRelationship][0];

 tracingService.Trace("Ensure the first name was updated");
 if (retrievedContact.FirstName == primaryContact.FirstName)
 {
 tracingService.Trace("Primary Contact name is correct");
 }
 else
 {
 tracingService.Trace("First Name is \"{0}\", expected \"{1}\".", retrievedContact.FirstName, primaryContact.FirstName);
 throw new InvalidPluginExecutionException("The first name was not changed");
 }
 }

 [Input("Related Account Name")]
 [Default("Related Account")]
 public InArgument<string> RelatedAccountName { get; set; }

 [Input("Root Contact First Name")]
 [Default("New FirstName")]
 public InArgument<string> RootContactFirstName { get; set; }

 [Input("Root Contact Last Name")]
 [Default("Root LastName")]
 public InArgument<string> RootContactLastName { get; set; }
 }
}

How to Create a Custom Workflow Activity in Ms CRM 2011

Custom Workflow Activity Steps:

 

This topic describes how to create a custom workflow activity, and use it in Microsoft Dynamics CRM.

Required Software and Assemblies

To develop Windows Workflow Foundation 4 custom activities, you must use Microsoft Visual Studio 2010, which requires Microsoft .NET Framework 4. If it is not available on your computer, Microsoft Visual Studio 2010 will install it.

The following assemblies must be added to your project. They can be found in the SDK\Bin folder in Microsoft Dynamics CRM SDK.

  • Microsoft.Xrm.Sdk.dll
  • Microsoft.Xrm.Sdk.Workflow.dll

Use the CodeActivity Workflow Base Class

To create a custom workflow activity, create a class that inherits from the Code Activity

workflow base class. This class is available in the System.Activities namespace. Activities that inherit from the CodeActivity class are able to override the Execute method to produce custom functionality.

To create a custom activity that inherits from CodeActivity

  1. Start Microsoft Visual Studio 2010.
  2. On the File menu, click New, and then click Project.
  3. In the New Project dialog box, select Workflow under Visual C# in the Installed Templates pane, and then select Activity Library.
  4. Specify a name and location for the solution, and click OK.
  5. Navigate to the Project menu and select Properties. On the Application tab, specify .NET Framework 4 as the target framework.
  6. Add references to the Microsoft.Xrm.Sdk.dll and Microsoft.Xrm.Workflow.dll assemblies.
  7. Delete the Activity1.xaml file in the project.
  8. Add a class file (.cs) to the project. In Solution Explorer, right-click the project, select Add, and then click Class. In the Add New Item dialog box, type a name for the class, and click Add.
  9. Open the class file, and add the following using directives:

C#

using System.Activities;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Workflow;

  1. Make the class inherit from the CodeActivity class and give it a public access modifier as shown here:

C#

public class SampleCustomActivity : CodeActivity

  1. Add functionality to the class by adding an Execute method:

C#

protected override void Execute(CodeActivityContext context)

{

    //Activity code

}

 

 .

  1. Specify input and output parameters. For more information,  
  2. Compile the project to create an assembly (.dll).

To view a code sample that demonstrates how to create a custom workflow activity,  

Specify the Name and Group Name for a Custom Workflow Activity

When you register a custom workflow activity assembly, specify the name and group name. The name property specifies the name of the workflow activity. The group name property specifies the name of the submenu added to the main menu in the Microsoft Dynamics CRM process designer. These properties link the custom workflow activity with the Microsoft Dynamics CRM process designer, so the custom activity name will appear in the user interface.

To specify the name and group name for a custom workflow activity, use the PluginType.Name and PluginType.WorkflowActivityGroupName attributes while registering the custom workflow activity assembly. For more information about registering custom workflow activities, If the PluginType.Name and PluginType.WorkflowActivityGroupName attributes are set to null, the custom activity is hidden from the Microsoft Dynamics CRM workflow designer and is only accessible from XAML workflows.

If you are using the Plug-in Registration tool to register the custom workflow activity assembly, you can specify appropriate values in the Name and WorkflowActivityGroupName boxes, under the Editable region. For more information about using the Plug-in Registration tool, see  

After this custom workflow activity is registered, you can use it from the Microsoft Dynamics CRM process designer for workflows or dialogs.  

 

 

Add Metadata to a Custom Workflow Activity

 

The assembly that contains the custom workflow activity definition is annotated using the .NET attributes to provide the metadata that Microsoft Dynamics CRM uses at runtime to link your code to the workflow engine. For more information about .NET attributes,  

Before you start adding metadata to your custom workflow activity definition, ensure that you are aware of the Microsoft Dynamics CRM types and attributes that are supported for the custom workflow activities. For more information.

 

 

Dependency Properties

The first step is to add some properties to your code as shown in the following example. Notice that the declaration is for a dependency property. This indicates that the workflow is dependent on this value. For more information about Windows Workflow Foundation dependency properties

C#

 
public static DependencyProperty aProperty =
DependencyProperty.Register("a",
typeof(CrmNumber),
typeof(MyAddActivity));
 
[CrmInput("a")]
public CrmNumber a
{
get
{
return (CrmNumber)base.GetValue(aProperty);
}
set
{
base.SetValue(aProperty, value);
}
}
 

Adding Input Parameters

While specifying the input parameter in your workflow class, you can also specify a default value for the parameter. The following sample shows the definition of an input parameter.

C#

[Input("DateTime input")]
[Default("2004-07-09T02:54:00Z")]
public InArgument<DateTime> Date { get; set; }
 

This input parameter is annotated with the .NET attribute Input. The  InputAttribute class derives from the ParameterAttribute class, which takes a parameter (ParameterAttribute.Name) to specify the name of the input attribute. This name appears in the process form assistant in the Web application. This lets you map an attribute as an input parameter to the process.

 

 

Adding Output Parameters

Output parameters are added in the same manner as the input parameters. The following sample shows the definition of an output parameter.

C#

[Output("Money output only")]
[Default("23.3")]
public OutArgument<Money> MoneyOutput { get; set; }
 
 

This output parameter is annotated with the .NET attribute Output. The OutputAttribute class derives from the ParameterAttribute class, which takes a parameter (ParameterAttribute.Name) to specify the name of the output attribute. This name appears in the process form assistant in the Web application. This lets you map an attribute as an output.

Adding Input and Output Attributes for the Same Parameter

You can use the input and output attributes for the same parameter. In the following code example, IntParameter is the input as well as the output parameter.

C#

[Input("Int input")]
[Output("Int output")]
[Default("2322")]
public InOutArgument<int> IntParameter { get; set; }
 

Additional Attributes

Some types, such as EntityReference and OptionSetValue, require additional attributes apart from the Input, Output, and Default attributes. The additional attributes are: ReferenceTarget and AttributeTarget. The following sample shows the definition of a parameter of the EntityReference type.

C#

[Input("EntityReference input")]
[Output("EntityReference output")]
[ReferenceTarget("account")]
[Default("3B036E3E-94F9-DE11-B508-00155DBA2902", "account")]
public InOutArgument<EntityReference> AccountReference { get; set; }
 

Adding the Execute Method

Your custom workflow activity must have an Execute method, as shown in the following example.

C#

protected override void Execute(CodeActivityContext context)
{
   if (AccountReference.Get(context).Id != new Guid("3B036E3E-94F9-DE11-B508-00155DBA2902"))
   {
      throw new InvalidPluginExecutionException("Unexpected default value");
   }
}
 

Use the IOrganization Web Service in a Custom Workflow Activity

 To call Microsoft Dynamics CRM organization Web service methods, you must do the following:

  1. Get a reference to IOrganizationServiceFactory.Use the IOrganizationServiceFactory.CreateOrganizationService method to create an instance of IOrganizationService.
  2. Use the IOrganizationService instance to call the supported methods.

Example

The following sample shows how to get the IOrganizationService from within the Execute method of your custom workflow activity.

C#

protected override void Execute(CodeActivityContext executionContext)

{

   // Get the context service.

   IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

   IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();

 

   // Use the context service to create an instance of IOrganizationService.

   IOrganizationService _orgService = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

  

   // Use _orgService to call methods.

}

 

Creating a Dialog in CRM 2011

 New to CRM 2011 is a process called Dialogs. Dialogs are a question and answer format that can be run on-demand or as a child to another process. As the user answers each question, the information can be stored in a record, used in a search or a number of other possibilities. Dialogs are often thought of as a solution for call centers but can be used in many other situations as well. Below we will step through setting up a dialog for the lead entity.

Example

We will create a very simple dialog with two questions that could be used by a CRM user in a call center to update a lead record. The dialog will allow the CRM user to update the First Name and Industry fields with ease. We will be using the lead entity as it is out-of-the-box.

Click Settings > Processes > New

In the window that appears:

  1. Give your dialog a name in the Process Name field.
  2. Choose Lead as the Entity.
  3. Choose Dialog as the Category.
  4. Click OK.

At this point, a window will appear where we can start the creation of our dialog. If you are familiar with creating workflows, much of this screen will look familiar.

Dialogs are a collection of “pages” in CRM so our first step is to create a page. Create a page by clicking Add Step and in the dropdown list, choose Page.

Give your page a name and then click the Select this row and click Add Step line. Make sure only that line is highlighted.

We will now add our first question to the page. In Dialogs, these questions are referred to as Prompt and Response. Click Add Step and then from the dropdown list, choose Prompt and Response.

Give your question an easy to recognize description and then click Set Properties.

The page that appears is for us to define our question. The Statement Label is pulled from your description in the previous step. The user will never see the Statement Label. The Prompt Text is the question that you want the user to see and answer. The Tip Text is a reminder for the user or clarification to make the question clear. Add your question and a tip if necessary.

Next we will choose our response type. The response types of a dialog are loosely dictated by the field in CRM that you want to populate. Since we are populating the first name, which is a single line of text, choose Single Line as the Response Type.

A few new options are available after choosing the response type. Log Response is the option of whether or not CRM will remember the answer. Data Type should match the data type of the field you are populating. Default Value will be used if there is not an answer provided when the dialog is run.

We will use Text as the Data Type and Yes to Log Response. We won’t have a Default Value in this example.

Click Save and Close and we have created our first question.

We will now setup a prompt and response to populate the Industry field on the Lead form. Follow the steps from earlier to add another prompt and response. Also fill in the Prompt Text and Tip Text.

For the Response Type choose Option Set (picklist) from the dropdown list.

We will again choose Yes for Log Response but for Data Type we will choose Integer from the dropdown list. Since Industry is an option set within CRM, we must match the values or our prompt and response in our dialog to the values of the Industry
option set. The prompt and response in the dialog does not have to contain all the options from the Industry option set so we will just use the first three. The key to making this successful is to ensure your values match. The labels don’t need to match. Notice that the Value and Label fields are reversed in the prompt and response when compared to the Industry option set.

Click Save and Close.

The last step of creating a dialog is to take an action with the information we gathered. With this dialog we will update the lead record that it is run from.

Click to the left of Page to highlight the entire area.

Click Add Step and choose Update Record. The step will default to a lead record so we will just add a description and then click Set Properties.

Click in the First Name field on the lead record and on the right pane set the Look for: values to the description of your First Name question and Response Text. Then click Add and then click OK. It should look as follows after clicking OK.

Click in the Industry field and on the right pane set the Look for: values to the description of your Industry question and Response Option Set Value.

Click Save and Close.

The dialog is now complete. To test the dialog click and then OK. From within an existing CRM lead, click and choose the dialog we just created from the list.

Sample Crm 2011 Plugin to Add note to Contact

using System;

using System.Diagnostics;

using System.Linq;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Xrm;

public classPlugin : IPlugin

{

 publicvoid Execute(IServiceProvider serviceProvider)

 {

        IPluginExecutionContext context = (IPluginExecutionContext)

serviceProvider.GetService(typeof(IPluginExecutionContext));

  Entity entity;  

 

// Check if the input parameters property bag contains a target

// of the create operation and that target is of type Entity.

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

        {       

 // Obtain the target business entity from the input parameters.

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

// Verify that the entity represents a contact.

if (entity.LogicalName != “contact”) { return; }

        }

else

        {

return;

try

        {

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)

serviceProvider.GetService(typeof(IOrganizationServiceFactory));

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

var id = (Guid)context.OutputParameters[“id”];

AddNoteToContact(service, id);

        }

catch (FaultException<OrganizationServiceFault> ex)

        {

thrownew InvalidPluginExecutionException(“An error occurred in the plug-in.”, ex);

        }

    }

privatestaticvoid AddNoteToContact(IOrganizationService service, Guid id)

    {

using (var crm = new XrmServiceContext(service))

        {

var contact = crm.ContactSet.Where(

            c => c.ContactId == id).First();

            Debug.Write(contact.FirstName);

var note = new Annotation

            {

                Subject =“Created with plugin”,

                NoteText =“This Note was created by the example plug-in”,

                ObjectId = contact.ToEntityReference(),

                ObjectTypeCode = contact.LogicalName

            };

 crm.AddObject(note);

 crm.SaveChanges();

        }

    }

}