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