Click Here for the Post

Thanks

To add a jscript validation for Activate or Deactivate record in CRM, everyone might probably know that we can pass the execution context as the parameter and add the validation code as below:

function OnSave(context) {
    if (context != null && context.getEventArgs() != null) {
        var saveMode = context.getEventArgs().getSaveMode();
        if (saveMode == "5") {
            // Add Deactivate validation code here
            alert("Deactivate Event");
        }
        else if (saveMode == "6") {
            // Add Activate validation code here
            alert("Activate Event");
        }
    }
}

If you observe the above two pictures, the alert message is triggered after the OOB “Confirm Contact Deactivation” message from CRM.

In one of my requirement, i need to add jscript validation before I get the OOB Confirm deactivation message. So to achieve that, first we need to know what function is called on the “Deactivate” ribbon button in CRM.

In sdk folder you can get all the CRM ribbon xml files under sdk\resources\exportedribbonxml location. In my case i need contactribbon xml file. If you open that file using visual studio, we can get the function name of deactivate button in ribbon button Command.

The command name is “Mscrm.Form.Deactivate” and jscript function name is “changeState”

Now create a new solution and add the “contact” entity to edit the ribbon customization.

Export the solution and open the customization xml file. Go to <RibbonDiffXml> and Add the following code under <CommandDefinitions> (Copy the CommandDefinition from the sdk).

Replace the function name and Library as shown above with your own file and import the solution into CRM and publish it.

Before importing the solution make sure the function and library already exists.

You can add your business required validation and call the “changeState” function to trigger OOB Deactivate record. Below is the jscript code :

function DeactivateContact(btnType, typeCode, value) {
    if (Xrm.Page.getAttribute("parentcustomerid").getValue() == null) {
        alert("Please add parent customer");
        return false;
    }
    else {
        changeState(btnType, typeCode, value);
    }
}

From now your custom validation logic will trigger first and then you can call the OOB Deactivate function method (changeState) to show the confirm message as below.

In the same way you can add the custom logic for “Activate” or for any other ribbon button by copying the CommandDefinition from sdk

Here i’m going to attach and detach files from Note and Email entities in crm programmatically.

I’m using early bound entities in my code to attach and detach files. Add the Autogenerated cs file in your solution by generating it using crmsvcutil in the sdk bin folder.

Attach Word document to Note

public static void AttachWordDocToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\TDD.docx");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\ms-word";
            note.NoteText = "Note Added with Document attached.";

            // Set the File Name
            note.FileName = "TDD.doc";
            service.Create(note);
        }

Attach Pdf file to Note

public static void AttachPDFToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\TDD1.pdf");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\pdf";
            note.NoteText = "Note Added with pdf attached.";

            // Set the File Name
            note.FileName = "TDD1.pdf";
            service.Create(note);
        }

Attach Excel file to Note

public static void AttachExcelToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\ActiveRecords.xls");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"application\ms-excel";
            note.NoteText = "Note Added with Excel attached.";

            // Set the File Name
            note.FileName = "ActiveRecords.xls";
            service.Create(note);
        }

Attach Text file to Note

public static void AttachTextToNote(EntityReference account, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\sample.txt");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);

            // Add the Note
            Annotation note = new Annotation();

            // Im going to add Note to Account entity
            note.ObjectId = account;
            note.Subject = "Note Added with attachment";

            // Set EncodedData to Document Body
            note.DocumentBody = encodedData;

            // Set the type of attachment
            note.MimeType = @"text/plain";
            note.NoteText = "Note Added with Text attached.";

            // Set the File Name
            note.FileName = "Sample.txt";
            service.Create(note);
        }

Delete attachment from Note

public static void DeleteAttachmentFromNote(Guid noteId, IOrganizationService service)
        {
            Annotation note = new Annotation();
            note.Id = noteId;

            // Set the Documentbody and other fields to null to remove the attachment
            note.DocumentBody = null;

            note.FileName = null;
            note.IsDocument = false;
            service.Update(note);
        }

Add attachment to Email

public static void AddAttachmentToEmail(EntityReference email, IOrganizationService service)
        {
            // Open a file and read the contents into a byte array
            FileStream stream = File.OpenRead(@"C:\Lakshman\sample.txt");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            // Encode the data using base64.
            string encodedData = System.Convert.ToBase64String(byteData);
            
            // Add attachment
            ActivityMimeAttachment attachment = new ActivityMimeAttachment();

            // Set the body
            attachment.Body = encodedData;

            // Set the attachment Type
            attachment.MimeType = @"text/plain";
            attachment.FileName = "Sample.txt";

            // Set the regarding object. In my case it is Email entity
            attachment.ObjectId = email;
            attachment.ObjectTypeCode = email.LogicalName;

            // Create the attachment
            service.Create(attachment);
        }

Delete attachments from Email

public static void DeleteAttachmentFromEmail(Guid emailId, IOrganizationService service, XrmDataContext context)
        {
            // Get all the attachments by passing the email guid
            List<ActivityMimeAttachment> attachments = (from at in context.ActivityMimeAttachmentSet
                                                        where at.ObjectId.Id.Equals(emailId)
                                                        select at).ToList();
            foreach (ActivityMimeAttachment attachment in attachments)
            {
                // Delete attachments
                service.Delete(ActivityMimeAttachment.EntityLogicalName, attachment.Id);    
            }
        }

Associate N:N relationship records in CRM 2011

In my example, im gonna associate and disassociate Contact record in Account entity. To perform this operation first we need to get the accout contact relationship schema name. In my case it is “contact_customer_accounts”.

Below is the code to Associate N:N relationship record.

public static void AssociateContactsToAccount(EntityReference contact, EntityReference account, IOrganizationService service)
        {

            // Creating EntityReferenceCollection for the Contact
            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();

            // Add the related entity contact
            relatedEntities.Add(contact);

            // Add the Account Contact relationship schema name
            Relationship relationship = new Relationship("contact_customer_accounts");
            
            // Associate the contact record to Account
            service.Associate(account.LogicalName, account.Id, relationship, relatedEntities);
            
        }

Disassociate N:N relationship records in CRM 2011

public static void DisassociateContactsToAccount(EntityReference contact, EntityReference account, IOrganizationService service)
        {

            // Creating EntityReferenceCollection for the Contact
            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();

            // Add the related entity contact
            relatedEntities.Add(contact);

            // Add the Account Contact relationship schema name
            Relationship relationship = new Relationship("contact_customer_accounts");

            // Disassociate the contact record to Account
            service.Disassociate(account.LogicalName, account.Id, relationship, relatedEntities);
            
        }

To Expand Tab

Xrm.Page.ui.tabs.get("<tabName>").setDisplayState("expanded");

To Collapse Tab

Xrm.Page.ui.tabs.get("<tabName>").setDisplayState("collapsed");

Share Records to User

For Sharing a record in CRM 2011 you can use GrantAccess, ModifyAccess and RevokeAccess Messages. In my example im gonna share account entity record to systemuser.

public static void ShareObject(EntityReference systemUser, EntityReference account, IOrganizationService service)
        {
            // Create the PrincipalAccess Object
            PrincipalAccess principalAccess = new PrincipalAccess
            {
                // Gives the principal read write access
                AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,

                // Set the PrincipalAccess Object's Properties
                Principal = systemUser
            };

            // Create the Request Object
            GrantAccessRequest grantAcessRequest = new GrantAccessRequest();

            // Set the Request Object's properties
            grantAcessRequest.PrincipalAccess = principalAccess;

            // Set the Target. In my case it is account record
            grantAcessRequest.Target = account;

            // Execute the Request
            service.Execute(grantAcessRequest);
        }

To Modify the shared record permissions you can use “ModifyAccess” Message

public static void ModifyObject(EntityReference systemUser, EntityReference account, IOrganizationService service)
        {
            // Create the PrincipalAccess Object
            PrincipalAccess principalAccess = new PrincipalAccess
            {
                // Gives the Full access on the record
                AccessMask = (AccessRights)852023,

                // Set the PrincipalAccess Object's Properties
                Principal = systemUser
            };

            // Create the Request Object
            ModifyAccessRequest modifyAcessRequest = new ModifyAccessRequest();

            // Set the Request Object's properties
            modifyAcessRequest.PrincipalAccess = principalAccess;

            // Set the Target. In my case it is account record
            modifyAcessRequest.Target = account;

            // Execute the Request
            service.Execute(modifyAcessRequest);
        }

To Revoke the permissions to the shared record you can use “RevokeAccess” Message

public static void RevokeObject(EntityReference systemUser, EntityReference account, IOrganizationService service)
        {
            // Create the Request Object
            RevokeAccessRequest revokeAcessRequest = new RevokeAccessRequest();

            // Set the Request Object's properties
            revokeAcessRequest.Revokee = systemUser;

            // Set the Target. In my case it is account record
            revokeAcessRequest.Target = account;

            // Execute the Request
            service.Execute(revokeAcessRequest);
        }

Share Records to Team

In the same way if you want to share or revoke permission to team, You can pass Team EntityReference instead of SystemUser.

In the Phone Call entity there is a field called “Recipent” which is a datatype of PartyList. And by default it shows Account, Contact, Lead and User entities.

If you want to show only “Contacts” in the lookup, then you can add the following jscript code in your phone call entity “onload” event.

function OnLoad() {
    document.getElementById("to").setAttribute("defaulttype", "2");
    document.getElementById("to").setAttribute("lookuptypes", "2");
    document.getElementById("to").setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif");
}

You can also achieve the same by using “crmForm.all” instead of “document.getElementById”

function OnLoad() {
    crmForm.all.to.setAttribute("defaulttype", "2");
    crmForm.all.to.setAttribute("lookuptypes", "2");
    crmForm.all.to.setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif");
}

If you want to achieve using Jquery, then you can add the following code. Dont forget to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function OnLoad() {
    $("#to").attr("defaulttype", "2");
    $("#to").attr("lookuptypes", "2");
    $("#to").attr("lookuptypeIcons", "/_imgs/ico_16_2.gif");
}

Filter 2 entities in the Recipent lookup

Now for example if you want to filter 2 entities in the Recipent lookup, you can add the following code on your onload event. Im using Account and Contact in my example.

function OnLoad() {
    document.getElementById("to").setAttribute("lookuptypenames", "contact:2:Contact,account:1:Account");
    document.getElementById("to").setAttribute("lookuptypes", "1,2");
    document.getElementById("to").setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif:/_imgs/ico_16_1.gif");
}

You can also achieve the same by using “crmForm.all” instead of “document.getElementById”

function OnLoad() {
    crmForm.all.to.setAttribute("lookuptypenames", "contact:2:Contact,account:1:Account");
    crmForm.all.to.setAttribute("lookuptypes", "1,2");
    crmForm.all.to.setAttribute("lookuptypeIcons", "/_imgs/ico_16_2.gif:/_imgs/ico_16_1.gif");
}

If you want to achieve using Jquery, then you can add the following code. Dont forget to add jquery1.4.1.min and json2 files in your Form Properties. You can get those files from sdk.
path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

function OnLoad() {
    $("#to").attr("lookuptypenames", "contact:2:Contact,account:1:Account");
    $("#to").attr("lookuptypes", "1,2");
    $("#to").attr("lookuptypeIcons", "/_imgs/ico_16_2.gif:/_imgs/ico_16_1.gif");
}
            // Get the Guid of the team
            Guid teamId = new Guid("079EE428-F515-E211-B2D9-00155D025F00");
            
            // Guid of the CRM user1
            Guid user1Id = new Guid("486FA7B3-4A6F-E111-AA15-00155D025F09");

            // // Guid of the CRM user2
            Guid user2Id = new Guid("FB9CA21D-7F72-E111-AA15-00155D025F09");

            Guid[] members = new[] { user1Id, user2Id };

            // Method to add users to team
            AddMembersToTeam(teamId, members, service);

        public static void AddMembersToTeam(Guid teamId, Guid[] membersId, IOrganizationService service)
        {
            // Create the AddMembersTeamRequest object.
            AddMembersTeamRequest addRequest = new AddMembersTeamRequest();

            // Set the AddMembersTeamRequest TeamID property to the object ID of 
            // an existing team.
            addRequest.TeamId = teamId;

            // Set the AddMembersTeamRequest MemberIds property to an 
            // array of GUIDs that contains the object IDs of one or more system users.
            addRequest.MemberIds = membersId;

            // Execute the request.
            service.Execute(addRequest);
        }

        public static void RemoveMembersFromTeam(Guid teamId, Guid[] membersId, IOrganizationService service)
        {
            // Create the AddMembersTeamRequest object.
            RemoveMembersTeamRequest addRequest = new RemoveMembersTeamRequest();

            // Set the AddMembersTeamRequest TeamID property to the object ID of 
            // an existing team.
            addRequest.TeamId = teamId;

            // Set the AddMembersTeamRequest MemberIds property to an 
            // array of GUIDs that contains the object IDs of one or more system users.
            addRequest.MemberIds = membersId;

            // Execute the request.
            service.Execute(addRequest);
        }

Import Data using C# code in CRM 2011

In my example im using XML Spreadsheet to import the data into CRM 2011.

1) Open your excel file which you need to import into CRM and save as type XML Spreadsheet 2003 format.

2) Save your xml sheet in your local drive.

3) Before importing the data into CRM, Create a DataMap so that you can use that DataMap Id to import the data.

Below is the code to import data in CRM 2011. I’m using early bound entities in my code to get the Guid of the DataMap. Add the Autogenerated cs file in your solution by generating it using crmsvcutil in the sdk bin folder.

public static void ImportToCRM(IOrganizationService service)
        {
            // Load the xml spreasheet file from your local drive using XmlDocument class
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(@"C:ActiveRecords.xml");

            // Create the Import
            Import import = new Import();
            import.ModeCode = new OptionSetValue(0);
            import.Name = "CustomEntityDataImport";
            import.SendNotification = false;
            Guid importId = service.Create(import);
            
            // Get the Guid of the DataMap by using the datamap name
            XrmDataContext context = new XrmDataContext(service);
            var importMap = (from imp in context.ImportMapSet
                     where imp.Name == "AccountDataMap"
                     select new { imp.Id }).FirstOrDefault();

            // Get the Mapping Set
            var importEntityMap = (from imp in context.ImportEntityMappingSet
                                   where imp.ImportMapId.Id.Equals(importMap.Id)
                      select new { imp.SourceEntityName }).FirstOrDefault();

            Guid importMapId = importMap.Id;

            // Create the ImportFile class
            ImportFile importFile = new ImportFile();

            // Add the xml document content
            importFile.Content = xmldoc.InnerXml;
            importFile.Name = "CustomEntityDataImport";
            importFile.FileTypeCode = new OptionSetValue(1);
            importFile.IsFirstRowHeader = true;
            importFile.Source = Path.GetFileName("CustomEntityDataImport.xml");
            importFile.SourceEntityName = importEntityMap.SourceEntityName.ToString();

            // Schema name of the Target entity
            importFile.TargetEntityName = "account";
            importFile.ImportMapId = new EntityReference(ImportMap.EntityLogicalName, importMapId);
            importFile.ImportId = new EntityReference(Import.EntityLogicalName, importId);
            importFile.Size = importFile.Content.Length.ToString();
            importFile.ProcessCode = new OptionSetValue(1);
            importFile.UseSystemMap = false;
            importFile.EnableDuplicateDetection = true;
            service.Create(importFile);

            ParseImportRequest parseRequest = new ParseImportRequest();
            parseRequest.ImportId = importId;
            service.Execute(parseRequest);

            TransformImportRequest transRequest = new TransformImportRequest();
            transRequest.ImportId = importId;
            TransformImportResponse transResponse = (TransformImportResponse)service.Execute(transRequest);

            ImportRecordsImportRequest request = new ImportRecordsImportRequest();
            request.ImportId = importId;

            ImportRecordsImportResponse response = (ImportRecordsImportResponse)service.Execute(request);

        }

In my example, i’m going to create a custom workflow activity on case create. The workflow will send an email to team members and creates a task.

When ever a case gets created in CRM, I have a default team with some users in that. My goal is to send an email to all those users in the team.

Here im using early bound entities in my code to send an email. Add the Autogenerated cs file in your solution by generating it using crmsvcutil in the sdk bin folder.

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 then 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, Microsoft.Xrm.sdk.Workflow.dll, Microsoft.Crm.Sdk.Proxy, System.Runtime.Serialization 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 then click Add.

9) Make the class inherit from the CodeActivity.

10) Add functionality to the class by adding an Execute method:

In my CRM system i have a “Case Team A” with two users added in it.

Add the below code in your cs file.

namespace Workflow
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Workflow;
    using Microsoft.Xrm.Sdk.Query;
    using System.Activities;
    using System.Web.Services.Protocols;
    using Microsoft.Crm.Sdk.Messages;
    using System.Diagnostics;

    public class CustomWorkflow : CodeActivity
    {
        [Input("Team Name")]
        [Default("Case Team")]
        public InArgument<string> CaseTeam { get; set; }

        [Output("Date time")]
        public OutArgument<DateTime> TaskDueDate { get; set; }

        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                // Create the tracing service
                ITracingService tracingService = executionContext.GetExtension<ITracingService>();

                // Create the context
                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

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

                // Create the Organiztion service
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                // Get the target entity from the context
                Entity target = (Entity)context.InputParameters["Target"];

                // Prepare DataContext by using AutoGenerated cs file
                XrmDataContext datacontext = new XrmDataContext(service);

                // Get the Team Name from the Workflow input parameter
                string teamName = CaseTeam.Get<string>(executionContext);

                // Get the Team Id from the Team Name
                var team = (from t in datacontext.TeamSet
                            where t.Name == teamName
                            select new { t.TeamId }).First();

                // Get all the members of the team to send email
                List<TeamMembership> teamMembers = (from t in datacontext.TeamMembershipSet
                                                    where t.TeamId == team.TeamId
                                                    select t).ToList();

                // Send email to memebers of the team
                CreateEmail(service, teamMembers, target, context.InitiatingUserId);

                // Set the Task DueDate to 2 days by using Output Parameter
                TaskDueDate.Set(executionContext, DateTime.Now.AddDays(2));

            }
            catch (SoapException ex)
            {
                // Add the SoapException message in event log
                EventLog.WriteEntry("code error", "Error occured in " + ex.Detail.InnerText.ToString(), EventLogEntryType.Error);
            }
            catch (Exception exe)
            {
                // Add the GeneralException message in event log
                EventLog.WriteEntry("code error", "Error occured in " + exe.InnerException.ToString(), EventLogEntryType.Error);
            }
        }

        public static void CreateEmail(IOrganizationService service, List<TeamMembership> teamMembers, Entity caseEntity, Guid loggedinUser)
        {
            // Create Email 
            Email email = new Email();

            // Set the from user of the email to Logged in user
            ActivityParty fromParty = new ActivityParty();
            fromParty.PartyId = new EntityReference(SystemUser.EntityLogicalName, loggedinUser);

            List<ActivityParty> toPartyList = new List<ActivityParty>();

            // Add the Activity party for each member in the team
            foreach (TeamMembership user in teamMembers)
            {
                ActivityParty toParty = new ActivityParty();
                toParty.PartyId = new EntityReference(SystemUser.EntityLogicalName, user.SystemUserId.Value);
                toPartyList.Add(toParty);
            }

            // Add the subject and description by concating the case ticket number
            email.Subject = "Case " + caseEntity.Attributes["ticketnumber"].ToString() + " Added. Please review";
            email.Description = "Case " + caseEntity.Attributes["ticketnumber"].ToString() + " Added. Please review";

            // Add To and From users to email
            email.To = toPartyList.ToArray();
            email.From = new[] { fromParty };

            // Set the case regarding
            email.RegardingObjectId = new EntityReference(Incident.EntityLogicalName, caseEntity.Id);

            // Create email
            Guid emailId = service.Create(email);

            SendEmailRequest sendRequest = new SendEmailRequest();
            sendRequest.EmailId = emailId;
            sendRequest.TrackingToken = string.Empty;
            sendRequest.IssueSend = true;

            // Send the email message.
            service.Execute(sendRequest);
        }
    }
}

Build the solution and Register the assembly using Plugin Registration tool

Then go to Processes under settings in crm2011 and add a workflow on case entity.

Click on Addstep and select your Workflow activity which you have previously registered using plugin tool. Remember to reset your iis or else you cant find your custom workflow activity.

Click on Set Properties and add the Input property in the textbox. In my example it
is “Case Team A”

After sending email i need to create a task. So i need to click on Add Step again and select Create Task

Here im going the set the Due Date of the Task by using Output Parameter in my Workflow
Click on Set Properties in Create Task and set the Due Date using Dynamic value as shown below

Once everything is done, Save the workflow and Activate it.

Now test your workflow by creating a case in your crm 2011. It should send an email to your case team users and create task with the due date set to 2days.