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

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.

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

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”).

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.