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

Increase Visual Studio build times

Although compiling is still the #1 programmer excuse for slacking off, you still probably don’t want to spend more time on it than you absolutely have to.

If your Visual Studio builds take longer than you would like, there are a couple of things you can do. First, if you’re still using a spinning-metal disk drive, upgrade to an SSD.

Ok, now that we’re all using an SSD, check and see if your antivirus software is slowing down your builds. If you’re using the default Windows software, you’re going to be looking for Windows Defender. Open up Task Manager and watch it while you go into your Visual Studio solution and choose “Rebuild All”. Do you see something like this?

Notice that Windows Defender, also known as Antimalware Service Executable, is taking up almost as much CPU time as Visual Studio, and quite a bit more than MSBuild.exe or the VB/C# compiler service (VBCSCompiler.exe). Assuming your build takes more than a second or two, note how long it takes to run under these conditions.

Exclude Visual Studio from Windows Defender

As a quick check, run a scan to make sure you don’t have anything currently infecting your system, and then go to Windows Defender -> Settings and disable Real-time protection:

Rebuild your solution in Visual Studio, noting the total time it takes and observing in Task Manager to see if the Antimalware Service Executable appears to be consuming significant processor time. Assuming your build is faster and your CPU less busy, congratulations, you’ve identified one cause of your performance problems. The next step is to responsibly tell Windows Defender to leave Visual Studio alone without turning it off completely.

First, turn Real-time protection back on. Then, scroll down to Exclusions and choose Add an exclusion.

We’re going to exclude the devenv.exe process and your projects folder(s). First, click Exclude a folder and choose the folder(s) where your development projects reside. Next, choose Exclude a .exe process and add devenv.exe. When you’re finished, the Add An Exclusion menu should look something like this:

Close the window and return to Visual Studio. Rebuild your solution and confirm that the build times are similar to when Real-time protection was off, and that you’re no longer seeing the Antimalware Service Executable process consuming processor time during your build.

If you’re using another antivirus tool, it should provide you with similar steps for excluding certain files and programs.

Now share this with your team – they should love you for it.

Asp.net core outperforms nodejs

https://github.com/aspnet/benchmarks

Although above links says it all, but for the lazy guys who do not want to go to that link, here are the highlights.

Tests were performed on below servers.

b0

Results are below.

b1

b2

Clearly asp.net core outshines nodeJS setup and class asp.net as well. Should be the perfect choice for asp.net fellows.

C# – Website security – Hide Connection strings from code

Your application probably needs to communicate with a database of some kind. Naturally, that database isn’t open to the world – it needs to be protected and secured. The typical solution to this is to create a username and password combination (ideally, specific to each application or user that requires access) and configure the application with these credentials. In many cases, they’re simply stored in configuration, such as the section of web.config for an ASP.NET application. By default, such settings are stored in plaintext, and are checked into source control, which can have disastrous consequences (note: if you use GitHub and accidentally expose a secret publicly, you need to change it. Just deleting it isn’t enough). There are many different kinds of secrets an application might require, from database connection strings to API keys.

Including connection strings in the code is not a very good practice as your code can be de-compiled and it will be more prone to hijacking the website as well as database server.

To protect this, a good practice would be to encrypt the connection string and decrypt it while accessing the connection string in the code.

Use below code to encrypt and decrypt connection strings using key and hash.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
namespace EncodingDecodingMain
{
    public static class EncDec
    {
        public static string Encrypt(string toEncrypt, string SecurityKey ,bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
 
            string key = SecurityKey;
 
            //If hashing use get hashcode regards to your key
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //Always release the resources and flush data
                // of the Cryptographic service provide. Best Practice
 
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
 
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes.
            //We choose ECB(Electronic code Book)
            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
 
            tdes.Padding = PaddingMode.PKCS7;
 
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            //transform the specified region of bytes array to resultArray
            byte[] resultArray =
              cTransform.TransformFinalBlock(toEncryptArray, 0,
              toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor
            tdes.Clear();
            //Return the encrypted data into unreadable string format
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
 
        public static string Decrypt(string cipherString, string SecurityKey, bool useHashing)
        {
            byte[] keyArray;
            //get the byte code of the string
 
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);
 
            string key = SecurityKey;
 
            if (useHashing)
            {
                //if hashing was used get the hash code with regards to your key
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                //release any resource held by the MD5CryptoServiceProvider
 
                hashmd5.Clear();
            }
            else
            {
                //if hashing was not implemented get the byte code of the key
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }
 
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            //set the secret key for the tripleDES algorithm
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes. 
            //We choose ECB(Electronic code Book)
 
            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;
 
            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(
                                 toEncryptArray, 0, toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor                
            tdes.Clear();
            //return the Clear decrypted TEXT
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
 
    }
}

Make a separate tool that will encode and decode a string using above code, encode your connection strings and place in the web.config file the encrypted connection strings. This way even if someone views your code, he would not be able to easily reach out to your data source without the secret key which only you have access to.

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-b – Dynamic CRM Series – Fetch some data using CRM SDK 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

In the last post we fetched some account list using FETCH XML technique, in this blog post, we will do the same but using CRM SDK, utilising this method is more familiar to C# developers.

Below is the method to fetch accounts list from dynamics CRM using CRM SDK

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
42
43
44
45
 
    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);
 
            var query = new QueryExpression("account") {ColumnSet = new ColumnSet("name", "accountid")};
 
            ConditionExpression condition = new ConditionExpression
            {
                AttributeName = "name",
                Operator = ConditionOperator.NotNull
            };
 
            FilterExpression filter = new FilterExpression();
            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(condition);
 
            query.Criteria.AddFilter(filter);
            query.Distinct = true;
 
            EntityCollection result = crmService.RetrieveMultiple(query);
            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;
        }

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

Part 2 – Dynamic CRM Series : User Authentication using 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

In our last part of series we made a connection to Dynamic CRM through the CRM SDK.

In this part, we will see how we can authenticate a user using Dynamics CRM.

The following method obtains discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.

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
 
        private TProxy GetProxy<TService, TProxy>(
            IServiceManagement<TService> serviceManagement,
            AuthenticationCredentials authCredentials)
            where TService : class
            where TProxy : ServiceProxy<TService>
        {
            Type classType = typeof(TProxy);
 
            if (serviceManagement.AuthenticationType !=
                AuthenticationProviderType.ActiveDirectory)
            {
                AuthenticationCredentials tokenCredentials =
                    serviceManagement.Authenticate(authCredentials);
                // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments. 
                // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
                return (TProxy) classType
                    .GetConstructor(new Type[] {typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse)})
                    .Invoke(new object[] {serviceManagement, tokenCredentials.SecurityTokenResponse});
            }
 
            // Obtain discovery/organization service proxy for ActiveDirectory environment.
            // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.
            return (TProxy) classType
                .GetConstructor(new Type[] {typeof(IServiceManagement<TService>), typeof(ClientCredentials)})
                .Invoke(new object[] {serviceManagement, authCredentials.ClientCredentials});
        }

Following method retrieves the Authentication Credentials from CRM SDK based on authentication provider.

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
 
	private AuthenticationCredentials GetCredentials<TService>(IServiceManagement<TService> service,
            AuthenticationProviderType endpointType, string _userName, string _password)
        {
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();
 
            switch (endpointType)
            {
                case AuthenticationProviderType.ActiveDirectory:
                    authCredentials.ClientCredentials.Windows.ClientCredential =
                        new System.Net.NetworkCredential(_userName,
                            _password,
                            _domain);
                    break;
                case AuthenticationProviderType.LiveId:
                    authCredentials.ClientCredentials.UserName.UserName = _userName;
                    authCredentials.ClientCredentials.UserName.Password = _password;
                    break;
                default: // For Federated and OnlineFederated environments.                    
                    authCredentials.ClientCredentials.UserName.UserName = _userName;
                    authCredentials.ClientCredentials.UserName.Password = _password;
                    if (endpointType == AuthenticationProviderType.OnlineFederation)
                    {
                        IdentityProvider provider =
                            service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName);
                        if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId)
                        {
                            authCredentials.SupportingCredentials = new AuthenticationCredentials();
                        }
                    }
 
                    break;
            }
 
            return authCredentials;
        }

And finally, our login method, it returns true if user is authenticated, and false if it is not.

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
42
43
44
45
46
47
48
49
50
51
 
public bool Login(string Email, string Password)
        {
            OrganizationService orgService;
            bool isValidUser=false;
            IServiceManagement<IDiscoveryService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
                    new Uri(_discoveryServiceAddress));
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;
 
            // Set the credentials.
 
            String organizationUri = String.Empty;
            // Get the discovery service proxy.
 
            bool result = false;
            try
            {
                AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType, Email,
                    Password);
                var response = GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials);
                result = response != null;
            }
            catch (Exception er)
            {
                result = false;
            }
 
            if (result)
            {
		//Although, our job is done here and we can return true, but if we need to get more user details regarding this logged in user then we can now execute the following calls. Specially the WhoAmIRequest() method of CRM SDK
                orgService = GetCRMService(Email, Password);
                Guid userid = ((WhoAmIResponse) orgService.Execute(new WhoAmIRequest())).UserId;
                dynamic systemUser = orgService.Retrieve("systemuser", userid, new ColumnSet(new string[] {"firstname", "lastname"}));
 
                string UserId = userid.ToString();
 
                string UserName = ((Microsoft.Xrm.Sdk.Entity) systemUser).Attributes["firstname"] + " " +
                                     ((Microsoft.Xrm.Sdk.Entity) systemUser).Attributes["lastname"];                
                isValidUser=true;
            }
            else
            {
                string UserId = "";
 
                string UserName = "";
            }
 
            return isValidUser;
 
        }

I really hope the code was helpful in kick starting your project in dynamics CRM, as authenticating a user from dynamics crm would be the first step if we want to start an application user dynamics CRM

Connect to Dynamics CRM through CRM SDK using C#

There are many ways to connect to and access the database of Dynamics CRM database.

a- If you are creating plug-ins, custom workflow activities, or custom XAML workflows, use Dynamics 365 SDK assemblies

https://msdn.microsoft.com/en-us/library/jj602917.aspx?f=255&MSPPError=-2147217396#SDKAssemblies

b- If you are creating Windows applications for Dynamics 365, use XRM tooling assemblies. More information: .NET Development: Use XRM Tooling assemblies

https://msdn.microsoft.com/en-us/library/jj602917.aspx?f=255&MSPPError=-2147217396#XrmTooling

c- If you are creating non-Windows applications for Dynamics 365, use Web API. More information: Use the Microsoft Dynamics 365 Web API

https://msdn.microsoft.com/en-us/library/mt593051.aspx

The way we will see in this article is to connect through CRM SDK and get the connection Service Proxy object.

In web.config file, add the following entry that carrys the connection string for CRM.

<add key=”XrmConnection” value=”Url=https://crm.domainname.com; Username={0}; password={1}” />

Add reference to following Dll’s

CRM SDK Reference

/// <summary>
/// Method globally used to return a CRM Service Proxy Object, which will be used to make futher calls to CRM.
/// </summary>
/// <param name=”userName”></param>
/// <param name=”password”></param>
/// <returns></returns>
private OrganizationService GetCRMService(string userName, string password)
{
try
{
CrmConnection connection =
CrmConnection.Parse(string.Format(ConfigurationManager.AppSettings[“XrmConnection”], userName, password));
OrganizationService orgService = new OrganizationService(connection);
return orgService;
}
catch (Exception ex)
{
return null;
}
}

This method will return the OrganizationService Proxy object that we can use later to fetch the data from Dynamics CRM Entities.

But before doing this we need to Authenticate and Authorise the user. There are two cases, one in which our application does not require the user to see his personalised content, instead the application is a reporting app, or a generic application for all the users of the organisation. In that case, we can fix the username and password for the master user account in web.config file. Make sure that user have enough previledges requried for the application to run.

In other case, if each user has to login into the application and perform his own activities, in that case above method of connection string and accessing through the metho

Productivity Tips for Visual Studio 2017

Visual Studio 2017 is a productivity powerhouse, It is loaded with tons of features that are really awesome and to talk about.

NuGet Package Suggestion for Unrecognized Types

automatically import from nuget

In my opinion, one of the most useful additions to Visual Studio 2017 was the Nuget-based Using Suggestion feature. This feature will recommend installing a specific NuGet package to handle resolving an unrecognized type that is encountered within the editor.

It can be enabled via:

  • Tools > Options > Text Editor > C# > Advanced > Suggest Usings for Types in Nuget Packages

Again – a great feature to speed up your productivity and it sure beats wandering around NuGet or running off to manually download the packages.

Query Syntax in Go To All (Ctrl+T)

filtering query syntax

Another incredibly useful tool introduced within Visual Studio 2017 was query searching within the Go To All (Ctrl+T) search area. This allows you to now quickly search for any file / type / member / or symbol by prefacing your search using the following prefixes:

  • f {file}
  • t {type}
  • m {member}
  • # {symbol}

This can allow you to easily narrow your search within your solution and find exactly what you need fast.

Full Solution Analysis

errors, messages, and warnings for the entire solution

The Full Solution Analysis feature is one that could be helpful to see every error, message, and warning throughout your entire solution (and not just the files that are currently open).

This feature can be enabled via:

  • Tools > Options > Text Editor > C# > Advanced > Enable Full Solution Analysis

If you are a stickler that can’t stand seeing a non-empty Error List, then this is for you.

Lightweight Solution Load

loading projects on demand

Another great feature that can add quite a bit of zing to Visual Studio 2017 is Lightweight Solution Load. This feature will initially load the minimal amount necessary for each project to have them functional within Visual Studio. Individual project files and dependencies will not be loaded or expanded until requested, so you only load what you will need.

This feature can be enabled in two ways; locally:

  • Right-click Project > Enable Lightweight Solution Load

Or globally (for all projects):

  • Tools > Options > Projects and Solutions > General > Lightweight Solution Load

It’s great for large solutions with multiple projects that maybe aren’t all going to be touched for most scenarios or just if you just want Visual Studio to open up a project faster than normal.

Live Unit Testing

Live Unit Testing was one of the features that was touted during the release of Visual Studio 2017, but it isn’t actually enabled by default. This feature will figure out which unit tests are affected by any code changes and the tests will be automatically run. Additionally, it will decorate your code using icons to indicate which code is covered and the status of the test covering that code.

This feature can be enabled in two ways; locally:

  • Test > Live Unit Testing > Start

Or globally (for all projects):

  • Options > Live Unit Testing

Live Unit Testing is super handy for not only seeing what tests are passing and failing, but for examining code coverage as well. This feature is also highly configurable and will allow you to include / exclude specific tests, define the number of threads you want to dedicate to it, configure when the tests are run, and much more.

EditorConfig Style Enforcement

update-editor-styles

Visual Studio 2017 adds support for .editorconfig files within projects to help provide coding style recommendations, which can be useful for large development teams looking to maintain a consistent style across their code base.

You may notice that the ellipses can be incredibly difficult to notice, especially if you are on the dark side. This can easily be adjusted within the IDE to make them far more visible from:

  • Tools > Options > Environment > Fonts and Colors > Suggestion Ellipsis

You can then configure the color to make it “pop” out a bit more :

styled suggestions

While this feature is enabled by default (if an .editorconfig file is present), you can make the process of editing it much easier through Mads Kristensen’s EditorConfig extension, which can be downloaded and will provide full autocompletion, syntax highlighting, and much more.

Keyboard Shortcuts

With many of the new additions and features that were added to Visual Studio 2017, you might be inclined to consider dropping support for the heavyweight Resharper extension to see how vanilla Visual Studio works at this point. Or if you are a developer coming from another editor such as IntelliJ, Eclipse, you are probably pretty accustomed to the keyboard shortcuts from those tools. Well, there’s an extension that has you covered.

Justin Clarebert, a member of the Visual Studio team released the HotKeys Keyboard Shortcuts extension, which allows you to easily configure Visual Studio 2017 to use the keyboard shortcuts from those other popular editors and tools, giving you the productivity you are accustomed to within a new environment.

Okay. So this is another feature that isn’t directly built in to Visual Studio 2017, but it’s too big of a productivity enhancer to leave off this list (and since it’s not built it, I suppose it still qualifies as a “secret”).

ASP.NET Core 2 Preview 1

ASP.NET Core 2.0.0-preview1

The next full version of ASP.NET Core is on its way, and developers who have been following along on the ASP.NET GitHub repositories have been very vocal about their interest in the new features in this version.  Some of these new features include:

  • A new ASP.NET Core meta-package that includes all features that you need to build an application. No longer do you need to pick and choose individual ASP.NET Core features in separate packages as all features are now included in a Microsoft.AspNetCore.All package in the default templates. If there are features you don’t need in your application, our new package trimming features will exclude those binaries in your published application output by default.
  • A new default Web Host configuration, codifying the typical defaults of the web host with the WebHost.CreateDefaultBuilder() API. This adds Kestrel, IIS configuration, default configuration sources, logging providers, and the content root.
  • Updated configuration and simplified logging. We have enhanced the LoggerFactory object to easily support a Dictionary<string, LogLevel> that defines log filters instead of a FilterLoggerSettings object, making it simpler to control the source and level of logs that get propagated from your application to your configured log providers.
  • Create pages without controllers in ASP.NET Core with the new RazorPages capabilities.  Just create a Pages folder and drop in a cshtml file with the new @page directive to get started.
  • Debugging your application in the cloud is easier than ever with integrated Azure Application Insights and diagnostics when debugging in Visual Studio and after deploying to Azure App Service.
  • A newly revamped authentication model that makes it easy to configure authentication for your application using DI.
  • New templates for configuring authentication for your web apps and web APIs using Azure AD B2C
  • New support in ASP.NET Core Identity for providing identity as a service. Updated templates decouple your apps from their identity concerns standard protocols (OpenID Connect, OAuth 2.0). Easily migrate apps using ASP.NET Core Identity for authentication to use Azure AD B2C or any other OpenID Connect compliant identity provider.
  • Build secure web APIs using ASP.NET Core Identity. Acquire access tokens for accessing your web APIs using the Microsoft Authentication Library (MSAL)
  • NET Core has always helped HTMLEncode your content by default, but with the new version we’re taking an extra step to help prevent cross-site request forgery (XSRF) attacks: ASP.NET Core will now emit anti-forgery tokens by default and validate them on form POST actions and pages without extra configuration.

For a full list of changes see the release notes.

C#- Performance of code – For loop vs For each Loop

I had a small experiment to prove the point under discussion, I have a table accounts in SQL Server database, I added  20000 rows into the table with 9 columns and approximately 1 Kilobyte of data per record. After loading into my Business layer i am converting it back to a DTO, and returning to my web service. Just to test the performance I added two performance counters, one for “for each” loop and one for “for loop”, The results are obvious, foreach loop took 107 milliseconds to execute the same process, while classic for loop took 14 milliseconds.

forloop-blog-1

Now why does this happen, lets get a bit deeper.

The for loop version uses enough stack space for only two local variables (counter and i). The Foreach version uses stack space for four locals (item, AccountList object, and two compiler-generated temporaries).

When a method is called in the CLR, all of the memory required for the locals is allocated upon the stack. As this takes place on the stack, this process is fast, but it is not free. That is why the foreach-loop will incur a small cost due to its extra two local variables.

WAIT !!!

There is something else, which changes the effect.

If we use the local variable multiple times in for loop and foreach loop, see what happens.

forloop-blog-2

The game is reversed, that means that if we have to access the local variable value multiple times in the for loop, in that case the performance will decrease.

Deductions

a- This for-each loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array.

b- The for-loop is faster than the foreach-loop if the array must only be accessed once per iteration.

CodeTrigger – One of the best .net Code generator

What is Code Trigger:

Code Trigger is a code Generation tool For C#, WPF, WCF, SQL SERVER/ORACLE/MYSQL and Visual Studio 2013-2017.

One can buy the tool from Link. 14 days Trial is also available after which one can purchase the full software.

https://www.codetrigger.com

splash_vs2013

My Experience:

Now a days life of a software engineer hangs around productivity, quality and efficiency. Delivering under tight deadlines with quality is a challenge for most of us.

Consider a client asks you to build a software under in 2 weeks, which includes web front end, backend with SQL server, and rest API’s for android and IOS platforms. It compose of let us say 4 entities, user, product, orders and sale. Sounds like a tough plan.

As a project manager one would think of following things:

a- Setup code base.
b- Graphics Design Resources availability.
c- Design and architecture.
d- Meeting deadlines.

As a developer I would think of following:

a- Which design pattern to follow.
b- 4 entities. Each entitiy should provide atleast basic CRUD (Create, read, Update and Delete) operations in Data Access Layer.
c- Performance of code
d- Bug free code
e- Web Service Layer
f- Dependency Injection in code? Ninject, Unity, Autofac?
g- Repository Pattern.
h- Writing the access layer.

Approximately i assume this should take around 4-5 days if a developer works for 40 hours a week.

A similar scenario came to me, but with a twist, i had 30+ entities, performance of code specially web services had a demand of 2-3 seconds per request, code quality should be top notch, clean code.

I was look around for difference code generator tools like LLBLgen Pro, SalarDB, and many more. But I choose code trigger for some reasons.

a- It plays directly with ado.net, and ado.net is the fastest. Clearly my choice is not Entity framework as it is slow for obvious reasons.

Dapper could be the second best choice, but it is slightly slower than core ado.net. Else i might have choose LLBLgenpro.

Few benchmark links that supports my argument.

https://www.exceptionnotfound.net/dapper-vs-entity-framework-vs-ado-net-performance-benchmarking/
http://ppanyukov.github.io/2015/05/20/entity-framework-7-performance.html

I could have gone for SalarDB generator but that was too plain simple code. Could be good for very small project.

For a medium to large scale project i must say CodeTrigger is the best code generator tool ever.

Best Features:

a- Clean & quality code
b- Bug free code
c- Performance
d- Easily manage changes during sprints, one click and you get your code changes
e- Visual Studio integration
f- Nice Criteria query API
g- Nice Repository pattern implementation
h- Generate SQL Stored procedures.
i- Support for logging
j- Exception handling support
k- Unit of work pattern
l- Dependency injection pattern using either Unity or ninject
m- Generates interface definitions.

On a recent project i did some measurements for code metrices, and they are as below:

For users who want to know more of the below stats should visit URL below:
https://msdn.microsoft.com/en-us/library/bb385914.aspx

blog-codetrigger-1

You can see the high maintainability index, low depth of inheritance and nice numbers for class coupling. And around 9000+ lines of code generated in under 15 minutes by clicks of few minutes. This is really a great tool and it increases productivity and efficiency of the developers to the highest level possible.

I would recommend this tool to all the developers fellows who are missing there deadlines, or needs to code with quality and good patterns, this is a nice tool to go for.

“Open Source PostgreSQL on Microsoft Azure” meetup in Islamabad

Microsoft has partnered up with the PostgreSQL Special Interest Group in Islamabad to bring you “Open Source PostgreSQL on the Cloud” on 23rd September, 2016! The session has been delivered by Mr. Ali Sufyan Butt, a Microsoft Most Valuable Professional on Visual Studio and Development Technologies.

Agenda

  • Introduction to Azure & its features
  • Deploy a Ubuntu Linux VM on Azure
  • Install and configure PostgreSQL on Ubuntu Linux Server hosted on Azure
  • Build a quick demo Asp.net app and connect it through the database using EF 6.0 drivers for PostgreSQL
  • Deploy the website on Azure

Extension method for IEnumerable to get a deep copy cloned object.

When we assign a List object to another it does a shallow copy, and making a change into copied object reflects in source object as well. This does not serves the purpose, thus finding a ways is through extension methods.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace Csharp
  9. {
  10.  
  11.     public static class Program
  12.     {
  13.  
  14.  
  15.         static void Main(string[] args)
  16.         {
  17.             List<string> abc = new List<string>();
  18.             abc.Add("a");
  19.  
  20.             var newList = AddAlphabet(abc);
  21.  
  22.             Console.WriteLine(abc.Count);
  23.             Console.WriteLine(newList.Count);
  24.             Console.ReadLine();
  25.         }
  26.  
  27.         private static List<string> AddAlphabet(List<string> abc)
  28.         {
  29.             List<string> _abc = abc;
  30.             _abc.Add("d");
  31.             _abc.Add("e");
  32.             return _abc;
  33.         }
  34.  
  35.  
  36.         
  37.     }
  38. }

This produces following result in output

3

3

Changing the code and added an extension method will result in proper result that I expected earlier.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace Csharp
  9. {
  10.  
  11.     public static class Program
  12.     {
  13.         public static IEnumerable<T> Clone<T>(this IEnumerable<T> collection) where T : ICloneable
  14.         {
  15.             return collection.Select(item => (T)item.Clone());
  16.         }
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             List<string> abc = new List<string>();
  21.             abc.Add("a");
  22.  
  23.             var newList = AddAlphabet(abc.Clone<string>().ToList());
  24.  
  25.             Console.WriteLine(abc.Count);
  26.             Console.WriteLine(newList.Count);
  27.             Console.ReadLine();
  28.         }
  29.  
  30.         private static List<string> AddAlphabet(List<string> abc)
  31.         {
  32.             List<string> _abc = abc;
  33.             _abc.Add("d");
  34.             _abc.Add("e");
  35.             return _abc;
  36.         }
  37.  
  38.  
  39.         
  40.     }
  41. }

This produces following result in output

1
3

We notice that it does not change the original value of source.

Mr. Corton Privacy Policy

Personal information

This application does not collect or transmit any user’s personally identifiable information. No personal information is used, stored, secured or disclosed by services this application works with.

Technical information

No technical information is sent (such as IP addresses included in the HTTP calls the application makes) neither of that is used or stored.

Communication

  • The communication made with the app in either text or voice is not stored anywhere in any form, all speech processing is done locally, only send the message to server to send back the response.

Third parties

If the app makes use of third party services, their usage of information is excluded from this privacy policy. You will be clearly made aware of the third parties involved in the app and we will ensure the very minimal set of data is set to those third parties. The third party is our AI engine which processes the sound and sends back the text.

Report violations or get more information

If you would like to report any violations of this policy or get more information on any app, please contact us by emailing at alisufyanbutt@hotmail.com.

This is just a virtual friend, any association or personal attachment to it is not our responsibility, please do not take the responses seriously, it might be not what you like, but we made sure they would be not vulgar, offensive and indecent.

NDepend is something we can depend on

Ndepend is a tool which I am really excited to review at last. I had a long time commitment with NDepend team but I for some reasons I had been too busy in other stuff that I really missed it, But I have not forgotten it at all and been using the tool and had great benefits which I want to share with you guys.

After downloading the tool, it is fairly easy to configure the extension with Visual Studio as well as we can also use Visual NDepend tool to visually analyze the solution or assemblies.

For first timers, this link can help to install and configure http://www.ndepend.com/docs/getting-started-with-ndepend

After running this tool for the first time, I scanned my project and viola, I was in deep trouble, just kidding, I mean I got a detail report of issue with my code, code metrics, dependency graphs, Dependency Matrix and a long list of rules violated in the code. This was really a great thing to see and I immediately started to work on making the mistakes right.

NDepend is giving me insights into my code that we normally ignore, but keep following through the standards and after a few iterations with NDepend, it was all sweet code. All thanks to NDepend tooling and support.