Archive for the ‘Code Snippets’ Category

Create record in MS CRM 2011 Online using C# Code

Add "Microsoft.Xrm.Sdk" reference from your sdk bin folder.

Then add the following namespaces
1) using Microsoft.Xrm.Sdk;
2) using Microsoft.Xrm.Sdk.Client;
3) using System.ServiceModel.Description;
4) using System.Web.Services.Protocols;

Finally add the below code :


try
            {
                ClientCredentials cre = new ClientCredentials();
                cre.UserName.UserName = "<username>.onmicrosoft.com";
                cre.UserName.Password = "<password>";

                Uri serviceUri = new Uri("https://<orgname>.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");

                OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, cre, null);
                proxy.EnableProxyTypes();
                IOrganizationService service = (IOrganizationService)proxy;

                Entity ent = new Entity("<entitySchemaName>");
                ent.Attributes["new_name"] = "Created from Console App4";
                service.Create(ent);
            }
            catch (SoapException ex)
            {

            }
            catch (Exception ex)
            {

            }

Happy Coding 🙂

In my example below i’m going to retrieve link entities opportunity and orders in Contact entity.

retrieve

Below is the fetch xml code:

string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                                    <entity name='contact'>
                                        <attribute name='fullname' />
                                        <attribute name='contactid' />
                                        <link-entity name='opportunity' from='customerid' to='contactid' link-type='outer'>
                                            <attribute name='name' />
                                            <attribute name='description' />
                                        </link-entity>
                                        <link-entity name='salesorder' from='customerid' to='contactid' link-type='outer'>
                                            <attribute name='name' />
                                            <attribute name='ordernumber' />
                                        </link-entity>
                                    </entity>
                                </fetch>";

            var result = service.RetrieveMultiple(new FetchExpression(fetchXml));

Hope is helps 🙂

Close Activities in CRM 2011

Posted: November 10, 2012 in Code Snippets, CRM 2011
SetStateRequest setStateRequest = new SetStateRequest();

// In my case i'm Cancelling Task Activity
setStateRequest.EntityMoniker = new EntityReference(Task.EntityLogicalName, taskId);
            
// Set the State and Status OptionSet Values to Cancelled.
setStateRequest.State = new OptionSetValue(2);
setStateRequest.Status = new OptionSetValue(6);
            
// Execute the Response
SetStateResponse setStateResponse = (SetStateResponse)service.Execute(setStateRequest);

In the same way you can “Cancel” or “Complete” any CRM 2011 Activity by passing the EntityReference accordingly.

Below are the State and Status Code OptionSet values for CRM 2011 Activities.

Task
Fax
Phone Call
Email
Letter
Appointment
Service Activity
Campaign Response
Recurring Appointment

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);
            
        }

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.

            // 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.

Display Google Maps in CRM 2011

In my example im gonna display google map in crm 2011 using a html webresource and pin the default location to Hyderabad India.
Here we need to refer google api script in the html page.

<html>
<head>
    <title>Map</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script>
    <script type="text/javascript" src="../WebResources/crm_googleMap.js"></script>
</head>
<body onload="InitializeMap()">
    <div id="map_canvas" style="width: 100%; height: 380px;">
    </div>
</body>
</html>

Here is the code for the body onload jscript

var geocoder = null;
var map = null;
function InitializeMap() {
    if (typeof google !== "undefined") {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(17.384509, 78.486156);
        var myOptions = {
            zoom: 15,
            center: latlng,
            scaleControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        codeLatLng(latlng);
    }
}

function codeLatLng(latlng) {
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (results != null && status != null) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            }
            map.setZoom(10);
        }
    });
}

Add the html webresource in your entity form. In my example i have added it in Account Form as shown below.