Dynamics CRM, set status of activity as Complete/Open using CSharp

In dynamics CRM, Task, phonecalls or any activity can be marked as complete which indicate its status as done.

To programatically, do it from C#, below code is required. Lets first make a generic entity model to be used.

1
2
3
4
5
6
7
8
9
    public class ActivityStatusInputEntity
    {
        public string Email { get; set; }
        public string Password { get; set; }
        public string ActivityId { get; set; }
        public string ActivityType{get;set;} //task, phonecall, meeting ..
        public int StatusCode { get; set; } // 5 if its a tasks, 2 if its a call, 3 if its a meeting
        public int StateCode { get; set; } // 0 to set it as open activity, 1 to make it Completed
    }

StatusCode and StateCode are the major key points here. As we cannot update these fields directly into the entity, we can do this with the SetStateRequest class.

StatusCode: 5 if its a tasks, 2 if its a call, 3 if its a meeting
StateCode: 0 to set it as open activity, 1 to make it Completed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
public Response UpdateTaskStatus(ActivityStatusInputEntity activityStatusEntity)
        {
            try
            {
                var crmService = GetCRMService(activityStatusEntity.Email, activityStatusEntity.Password);
                SetStateRequest setStateRequest = new SetStateRequest();
 
                // In my case i'm updating Task Activity
                setStateRequest.EntityMoniker = new EntityReference(activityStatusEntity.ActivityType, new Guid(activityStatusEntity.ActivityId));
 
                // Set the State and Status OptionSet Values.
                setStateRequest.State = new OptionSetValue(taskStatusEntity.StateCode);
                setStateRequest.Status = new OptionSetValue(taskStatusEntity.StatusCode);
 
                // Execute the Response
                SetStateResponse setStateResponse = (SetStateResponse) crmService.Execute(setStateRequest);
                return new Response() {Message = "success"};
            }
            catch (Exception err)
            {
                return new Response() {Message = "failure"};
            }
 
        }

This way we can set status of activities to either complete, or reopen an activity for editing programatically in C#.

Dynamics CRM, Update Task using C#

In dynamics CRM, a task, phone call, meeting are termed as activities performed on an entity. Like if there is an entity “Lead”, under a certain lead there can be multiple activities like tasks, phonecalls, appointments e.t.c

Let us update a task in dynamics CRM created in prior post.

First we will define a task DTO(Data transformation Object) or model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
public class UpdateTaskEntity
    {        
        public string Id { get; set; }
        public string RegardingObjectName { get; set; }
        public string RegardingObjectId { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string OwnerId { get; set; }
        public string Subject { get; set; }
        public string Description { get; set; }
        public DateTime ScheduledStart { get; set; }
        public DateTime ScheduledEnd { get; set; }
        public string Priority { get; set; }
        public double Duration { get; set; }
    }

GetCRMService object can be referenced from following post LINK TO PART 1

Property Id represents the Id (guid) of the task
ReferenceObjectId and ReferenceObjectName are important, as they represents the object to which this task will be added under. Like if you are to add a task under a Lead, then type referenceobjectname as “lead” and ReferenceObjectId as Id of the lead entity object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
public Response AddTask(UpdateTaskEntity task)
        {
            try
            {
                var crmService = GetCRMService(task.Email, task.Password);
                var setupTask = new Entity("task");
                setupTask.Id = new Guid(task.Id);
                setupTask.Attributes["ownerid"] = new EntityReference("systemuser", new Guid(task.OwnerId));
                setupTask.Attributes["regardingobjectid"] = new EntityReference(task.RegardingObjectName,
                    new Guid(task.RegardingObjectId));
                setupTask.Attributes["subject"] = task.Subject;
                setupTask.Attributes["description"] = task.Description;
                setupTask.Attributes["createdon"] = DateTime.Now.ToLocalTime();
 
                //setupTask.Attributes["scheduledstart"] = task.ScheduledStart;
                setupTask.Attributes["scheduledend"] = task.ScheduledEnd.AddHours(23).AddMinutes(59).AddSeconds(59);
                setupTask.Attributes["prioritycode"] =
                    new Microsoft.Xrm.Sdk.OptionSetValue(Convert.ToInt32(task.Priority));
                setupTask.Attributes["actualdurationminutes"] = Convert.ToInt32(task.Duration);
                crmService.<strong>Update</strong>(setupTask);
                return new Response() { Message = "success" };
            }
            catch (Exception err)
            {
                return new Response() { Message = "failure" };
            }
        }

Dynamics CRM, Create a task using C#

In dynamics CRM, a task, phone call, meeting are termed as activities performed on an entity. Like if there is an entity “Lead”, under a certain lead there can be multiple activities like tasks, phonecalls, appointments e.t.c

Let us create a task in dynamics CRM.

First we will define a task DTO(Data transformation Object) or model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
public class TaskEntity
    {        
        public string RegardingObjectName { get; set; }
        public string RegardingObjectId { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string OwnerId { get; set; }
        public string Subject { get; set; }
        public string Description { get; set; }
        public DateTime ScheduledStart { get; set; }
        public DateTime ScheduledEnd { get; set; }
        public string Priority { get; set; }
        public double Duration { get; set; }
    }

GetCRMService object can be referenced from following post LINK TO PART 1

ReferenceObjectId and ReferenceObjectName are important, as they represents the object to which this task will be added under. Like if you are to add a task under a Lead, then type referenceobjectname as “lead” and ReferenceObjectId as Id of the lead entity object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
public Response AddTask(TaskEntity task)
        {
            try
            {
                var crmService = GetCRMService(task.Email, task.Password);
                var setupTask = new Entity("task");
 
                setupTask.Attributes["ownerid"] = new EntityReference("systemuser", new Guid(task.OwnerId));
                setupTask.Attributes["regardingobjectid"] = new EntityReference(RegardingObjectName,
                    new Guid(task.RegardingObjectId));
                setupTask.Attributes["subject"] = task.Subject;
                setupTask.Attributes["description"] = task.Description;
                setupTask.Attributes["createdon"] = DateTime.Now.ToLocalTime();
                setupTask.Attributes["scheduledstart"] = task.ScheduledStart;
                setupTask.Attributes["scheduledend"] = task.ScheduledEnd.AddHours(23).AddMinutes(59).AddSeconds(59); // Adding end time as one day ahead of current time
                setupTask.Attributes["prioritycode"] =
                    new Microsoft.Xrm.Sdk.OptionSetValue(Convert.ToInt32(task.Priority));
                setupTask.Attributes["actualdurationminutes"] = Convert.ToInt32(task.Duration);
                crmService.Create(setupTask);
                return new Response() {Message = "success"};
            }
            catch (Exception err)
            {
                return new Response() {Message = "failure"};
            }
        }

Add note [annotation] in Dynamics CRM using Csharp

Notes in Dynamics CRM can be associated to any entity like Account, Sales Order, Order, Contact, Opportunity e.t.c; To programatically attach a note to an entity please follow the code below:

Annotation object in CRM has the following structure

Note:
has title, description and an attachment.

Following class holds an object that represents a note object in CRM.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
    public class NoteGeneric
    {
        public string ReferenceId { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public System.Web.HttpPostedFileBase file { get; set; }
        public string Description { get; set; }
        public string NoteText { get; set; }
        public string DocumentBody { get; set; }
        public string Subject { get; set; }
        public string FileName { get; set; }
        public string FileType { get; set; }
        public bool HasDocument { get; set; }
 
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
        public Response AddNotes(NoteGeneric note, string EntityName)
        {
            try
            {
                var crmService = GetCRMService(note.Email, note.Password);
 
                var annotation = new Entity("annotation");
 
                annotation.Attributes["objectid"] = new EntityReference(EntityName,
                    new Guid(note.ReferenceOpportunityId));
                annotation.Attributes["objecttypecode"] = EntityName;
                annotation.Attributes["subject"] = note.Subject;
                annotation.Attributes["notetext"] = note.NoteText;
                annotation.Attributes["createdon"] = DateTime.Now.ToLocalTime();
                if (note.HasDocument)
                {
                    annotation.Attributes["mimetype"] = note.FileType;
                    annotation.Attributes["documentbody"] = note.DocumentBody;
                    annotation.Attributes["filename"] = note.FileName;
                }
 
                crmService.Create(annotation);
                return new Response() {Message = "success"};
            }
            catch (Exception err)
            {
                return new Response() {Message = "failure"};
            }
        }

For GetCRMService method, see this post. LINK TO PART 1

Above method will attach the document only if HasDocument property is set to true, in other case, it will at a note without the attachment.

crmService.Create method saves/associated the annotation to the entity.

Part 3-a – Dynamic CRM Series – Fetch some data using FetchXML in C#

LINK TO PART 1 – Connection

LINK TO PART 2 – Authentication

LINK TO PART 3 – Fetch Data through Fetch XML

LINK TO PART 4 – Fetch Data through CRM SDK

FetchXML is a proprietary query language that is used in Microsoft Dynamics 365 (online & on-premises). It’s based on a schema that describes the capabilities of the language.

Based on our previous two posts, let us say now we have our organization service proxy, and we need to fetch the list of accounts in our CRM SDK, here is what we can do.

Below is a simple method to fetch the names of accounts from accounts entity in dynamics crm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
public class BasicAccountInfo
    {
        public string code { get; set; }
        public string name { get; set; }
    }
 
        /// <summary>
        /// Get all user accounts in CRM
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="searchphrase"></param>
        /// <returns></returns>
        public List<BasicAccountInfo> GetUserAccountsWeb(string email, string password)
        {
            var finalResult = new List<BasicAccountInfo>();
            var crmService = GetCRMService(email, password);
            string fetchXml = "";
 
 
                fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
 			<entity name='account'>
    			<attribute name='name' />
    			<attribute name='accountid' />
    			<order attribute='name' descending='false' />
  			</entity>
			</fetch>";
            }
 
            EntityCollection result = crmService.RetrieveMultiple(new FetchExpression(fetchXml));
            var finalResult = (from data in result.Entities
                                       select new
                                       {
                                           code = ((Microsoft.Xrm.Sdk.Entity)(data)).Attributes["accountid"].ToString(),
                                           name = ((Microsoft.Xrm.Sdk.Entity)(data)).Attributes["name"].ToString()
                                       }).ToList();
 
 
            return finalResult;
        }