AutoMapper configuration in older and newer versions

Recently when I was looking for various architecture approached and tools sets, I saw this post which is very useful. But while I was going through the post I was getting error while implementing AutoMapper. I started getting below errors when I tried to configure AutoMapper as given on the link.

  • The type or namespace name ‘Profile’ could not be found (are you missing a using directive or an assembly reference?)
  • ‘ViewModelToDomainMappingProfile.ProfileName’: no suitable method found to override
  • ‘ViewModelToDomainMappingProfile.Configure()’: no suitable method found to override
  • ‘DomainToViewModelMappingProfile.Configure()’: no suitable method found to override
  • ‘Mapper’ does not contain a definition for ‘CreateMap’
  • ‘Mapper’ does not contain a definition for ‘CreateMap’

After some time I figured out the problem. Actually while following the tutorials I installed latest version (7.0.1 at that time) of AutoMapper from nuget while this tutorial was using 3.3.1 (that article was written sometime in 2015). Keep on reading

Encryption and Decryption of content using RijndaelManaged Class in C#

If you want to encrypt and decrypt data in your .NET application then one of the most simplest and safest way is using RijndaelManaged class.

It is predecessor of Aes but still most of the new users us RijndaelManaged class because it is easy to plug and use.

First we have to generate an encryption key using a password ans salt. Password and salt could be any string (use base64 string to make your encryption stronger) which we have to convert to bytes array (byte[]) before using them for generating encryption key. Below is the complete example of generating key and encryption and decryption

public static byte[] GenerateEncryptionKey(string password, string saltString)
{
	byte[] salt = Convert.FromBase64String(saltString);
	var keyGen = new Rfc2898DeriveBytes(password, salt, 7845);
	return keyGen.GetBytes(32);
}
public static string Encrypt(object data, string password, string saltString)
{
	try
	{
		using (var aes = new RijndaelManaged())
		{
			//get some bytes
			aes.Key = GenerateEncryptionKey(password, saltString);
			aes.BlockSize = 256;
			aes.Padding = PaddingMode.PKCS7;

			//generate an IV
			aes.GenerateIV();

			//get the bytes for our message
			var plainBytes = Encoding.UTF8.GetBytes(data.ToString());

			//start up the encryption
			using (var ms = new MemoryStream())
			using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
			{
				//write the bytes to the cryptostream
				cs.Write(plainBytes, 0, plainBytes.Length);
				cs.FlushFinalBlock();

				//get message bytes
				var msgBytes = ms.ToArray();

				//create a new array big enough for the both of 'em
				var cypherBytes = new byte[aes.IV.Length + msgBytes.Length];

				//return the string with the iv as the first 32 bytes. will need this when decrypting
				System.Buffer.BlockCopy(aes.IV, 0, cypherBytes, 0, aes.IV.Length);
				System.Buffer.BlockCopy(msgBytes, 0, cypherBytes, aes.IV.Length, msgBytes.Length);

				//now convert it to base64 string
				var cypherText = System.Convert.ToBase64String(cypherBytes).TrimEnd(new char[] { '=' }).Replace('+', '-').Replace('/', '_');
				//var cypherText = Convert.ToBase64String(cypherBytes);

				//return cypher text
				return cypherText;
			}
		}
	}
	catch (Exception)
	{
		return null;
	}
}

public static string Decrypt(object cypherData, string password, string saltString)
{
	try
	{
		using (var aes = new RijndaelManaged())
		{
			//get some bytes
			aes.Key = GenerateEncryptionKey(password, saltString);
			aes.BlockSize = 256;
			aes.Padding = PaddingMode.PKCS7;

			//get the bytes for our message
			string cypherStr = cypherData.ToString();
			string incoming = cypherStr.Replace('_', '/').Replace('-', '+');
			switch (cypherStr.Length % 4)
			{
				case 2: incoming += "=="; break;
				case 3: incoming += "="; break;
			}
			
			var cypherBytes = Convert.FromBase64String(incoming);
			//var cypherBytes = Convert.FromBase64String(cypherData.ToString());
			var iv = new byte[aes.IV.Length];
			var msgBytes = new byte[cypherBytes.Length - iv.Length];

			//we use the first 32 bytes of the cypherdata for the IV
			System.Buffer.BlockCopy(cypherBytes, 0, iv, 0, iv.Length);
			System.Buffer.BlockCopy(cypherBytes, iv.Length, msgBytes, 0, msgBytes.Length);

			//set the IV for the instance
			aes.IV = iv;

			//start up the decryption
			using (var ms = new MemoryStream())
			using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
			{
				//write the bytes to the cryptostream
				cs.Write(msgBytes, 0, msgBytes.Length);
				cs.FlushFinalBlock();
					  
				//the plain text has been decrypted.
				var plainText = System.Text.Encoding.UTF8.GetString(ms.ToArray());

				//return plain text
				return plainText;
			}
		 }
	}
	catch (Exception)
	{
		return null;
	}
}

Send FCM data message & notification to Android, iOS & Web in C#

In my previous article I have explained about types of notification messages in FCM. We have already learnt how to send GCM notification using C#. Now because FCM is replacing GCM so here we are with new sample of working with FCM in C#.

public class NotificationManager
{
	private class NotificationMessage
	{
		public string Title;
		public string Message;
		public long ItemId;
	}
    
	public NotificationManager()
	{
		//
		// TODO: Add constructor logic here
		//
	}

	public string SendNotification(List deviceRegIds, string message, string title, long id)
	{
		string SERVER_API_KEY = "";
		var SENDER_ID = "";
		string regIds = string.Join("","", deviceRegIds);
		
		NotificationMessage nm = new NotificationMessage();
		nm.Title = title;
		nm.Message = message;
		nm.ItemId = id;

		var value = new JavaScriptSerializer().Serialize(nm);

		WebRequest tRequest;
		tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
		tRequest.Method = "post";
		tRequest.ContentType = "application/json";
		tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

		tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

		string postData = "{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : " + value + ","time": " + """ + System.DateTime.Now.ToString() + ""},"registration_ids":["" + regIds + ""]}";

		Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
		tRequest.ContentLength = byteArray.Length;

		Stream dataStream = tRequest.GetRequestStream();
		dataStream.Write(byteArray, 0, byteArray.Length);
		dataStream.Close();

		WebResponse tResponse = tRequest.GetResponse();

		dataStream = tResponse.GetResponseStream();

		StreamReader tReader = new StreamReader(dataStream);

		String sResponseFromServer = tReader.ReadToEnd();

		tReader.Close();
		dataStream.Close();
		tResponse.Close();
		return sResponseFromServer;
	}
}

You can see that only difference between GCM and FCM code is the request url where we have to post our data and yes this is the only difference between GCM and FCM except another notification message.

Above code is data notification message which is also called payload message. FCM provide simple notification message also which we don’t need to handle in our code in client app or we can say we can not handle because FCM will automatically catches it display on our app’s behalf. Upon clicking on this message it will open your app.

To send this kind of notification we simply need to replace data part of our message json (see string variable postData) with new notification json which should be like below:

{
	"to" : "yourclientregistrationid...",
	"notification" : {
		"body" : "notification body",
		"title" : "notification title",
		"icon" : "displayicon"
	}
}

Send notification on Android, iOS and Web using FCM

Few month before Google has launched its new cloud messaging platform Firebase Cloud messaging which will replace its current cloud messaging system Google Cloud Messaging. Gogle has not yet deprecated GCM but it has stopped support on this platform and suggested all developers to use FCM from now onward.

Although google has provided interface to send FCM notification from its console itself but there are some limitations. Actually google has divided notification system in two types:

  1. Notification message
  2. Data messages

=&0=& is simple message which contains a text which will be displayed in the notification area of the device along with some other fields like notification title and display icon. We don’t need to handle them on client app. FCM will catch and display it automatically. This type of message can be sent directly from FCM Console. Just select your project and go to notification tab.

A notification message will look like this:

{
    "to" : "yourclientregistrationid...",
    "notification" : {
      "body" : "notification body",
      "title" : "notification title",
      "icon" : "displayicon"
    }
}

=&1=& are more powerful where we can send any data we want to send in json format. Maximum payload for data messaged could be 4KB. This type of message need to be send via your own code.

A data message will look similar to this:

{
    "to" : "yourclientregistrationid...",
    "data" : {
      "field1" : "your content",
      "field2" : "your content",
      "field3" : "your content"
    }
}

You can see the notification is replaced by data and unlike notification there can be any number of field with any name which you can handle in your client app code.

In next Article we will discuss how to send data notification in C# and PHP

[SOLVED] AWS S3 – The authorization mechanism you have provided is not supported

Recently I started working on one of my project which I dropped long ago. I was using AWS SDK in this project as this was planned to deploy on AWS.

When I stopped working on this project that time there was no AWS data center in India (Amazon has launched first data center in India which is located in Mumbai). So when I resumed my project (this time I created all my resources in Mumbai region instead of Singapore) again then I get to know that my code is no more working for AWS S3 operations. Every time I tried to do any S3 operations it shows me this error:

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

From AWS documentation I get to know that this error is because of API version issue. All new data centers support only latest (v4 at that time) API version and Mumbai data center was one of them. so I download and updated AWS SDK in my project along with updating region in my web config (SDK automatically picks key, secret, region etc by using specified api settings key). But again I got same error.

After searching I get to know that I have to make changes in my code also where I was creating S3 client object because those were required as per the new version of SDK.

Old Code:

AmazonS3Client client = new AmazonS3Client("AWSAccessKey", "AWSSecretKey");

New code

IAmazonS3 client = new AmazonS3Client();

In older version I was supplying key and secret in constructor while creating S3 client object but in new version I used the approach to pick them from web.config (or in app.config if you are woking on desktop application) directly.

Here are the app settings I used in my in web.config which SDK picks automatically:

<add key="AWSRegion" value="ap-southeast-1" />
    <add key="AWSAccessKey" value="AWSAccessKey" />
    <add key="AWSSecretKey" value="AWSSecretKey" />

Visual Studio 15 Preview 3 released on 7th July 2016

Microsoft has released its preview 3 of Visual Studio 15. Yes it is Visual Studio 15 is upcoming version of Microsoft Visual Studio after Visual Studio 2015.

Being one of the most user friendly and feature rich IDE for application development Visual Studio is one of the most successful product of Microsoft. Now they are stepping to become next generation universal IDE which will be able to provide development on any platform and language. This is because in this version Microsoft has included feature to import iOS code from xcode (isn’t it a great new for all visual studio fans who want to use Visual studio as iOS development IDE?).

Here is the list of some new feature and enhancements you will get in visual studio 2015:

1. Visual Studio Tools for Apache Cordova

It will come with Apache Cordova 6.1.1 so all new projects which you will create will target Cordova 6.1.1. Apart from that you will be able any plugin using their npm package name

One thing which we should take care of is that it does not support Windows  Store 8.1 application so you have to update your  Cordova project to target Windows 10.

2. Visual Studio Tools for Universal Windows App Development

Microsoft team has done many improvements based on feedback they got from users and now there are full list of new features as well for the users. One of them is updated .NET native chain which will provide improved performance for universal windows apps.

3. Android Development Support

Now Android project support Gradle to builds .apk and .aar

4. iOS Development Support

A new entry point wizard is introduced to import existing iOS projects developed in xcode. This is not the only thing there are lot more to try and for that you have to downloadVisual Studio 15

5. Improvements in C# and Visual Basic

There is very big list specially in this category which we can not describe here. One major thing which everyone would love (atleast I am very excited after knowing this) is now you can break strings in multiple concatenated strings without manually writing + sign every time. Just put your cursor where you want to split the string and press enter it will automatically do the rest. Sounds good!!!

6. Improved Feedback Workflow

This visual studio version has better and improve feedback collaboration and followup system.

7. NuGet 3.4

Now you will get NuGet 3.4 with this version of visual studio. This version of NuGet supports Android and iOS build action in contentFile element and running NuGet in Linux and Apple environment. There are many more features and enhancements you will get.

8. Debugging and Diagnostic

Now you can condition so that debugger will break only when specified condition is true.
There is new exception introduced to see exception information in a compact dialog with instant access to inner exception.

Image Source

9. IDE Improvements

Now visual studio will load 30 to 35% faster on first launch. There is all new version control status bar to keep track of uncommitted work ad make it easier to publish local repositories.

10. And Many More

This is not all there are many more features you will get in this full bundled visual studio package. You can check complete list here
https://www.visualstudio.com/en-us/news/releasenotes/vs15-relnotes
Article Source

Transferring Cookies from WebBrowser to WebClient

I have prepared many web scrapping application and crawlers. Few of them were developed using WebClient and others were with WebBrowser control of .NET (see my previous article to Get and Set Cookies .NET WebBrowser Control). Recently I got stuck in a situation where I need features of both tools. That is WebClient and WebBrowser.

So my idea was to use WebBrowser control and pass on the session to WebClient when WebClient features are required.

For this my first task was to make WebClient aware of cookies and behave accordingly. SO After searching for few minutes I got this SO link which gave me a class to make cookie aware WebClient and after modifying it I got this final class CookieAwareWebClient

public class CookieAwareWebClient : WebClient
{
	public CookieContainer CookieContainer { get; set; }
	public Uri Uri { get; set; }
	
	public CookieAwareWebClient() : this(new CookieContainer())
	{
	
	}

	public CookieAwareWebClient(CookieContainer cookies)
	{
		this.CookieContainer = cookies;
	}

	protected override WebRequest GetWebRequest(Uri address)
	{
		WebRequest request = base.GetWebRequest(address);
		if (request is HttpWebRequest)
		{
			(request as HttpWebRequest).CookieContainer = this.CookieContainer;
		}
		
		HttpWebRequest httpRequest = (HttpWebRequest)request;
		httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
		return httpRequest;
	}

	protected override WebResponse GetWebResponse(WebRequest request)
	{
		WebResponse response = base.GetWebResponse(request);
		String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

		if (setCookieHeader != null)
		{
			//do something if needed to parse out the cookie.
			if (setCookieHeader != null)
			{
				Cookie cookie = new Cookie(); //create cookie
				this.CookieContainer.Add(cookie);
			}
		}
		return response;
	}
}

Now I have to use this class in place of WebClient because it supports cookies for by browsing.

Next thing that I have to do is pass all the cookies from my WebBrowser to this cookie aware web client. Here is how I did this:

CookieContainer cookieJar = new CookieContainer();
string[] cookies = browser.Document.Cookie.Split(new char[] { '=' });
cookieJar.Add(new Cookie(cookies[0], cookies[1], "/", "edunyte.com"));

In above code browser is my WebBrowser control object and because I have only one cookie value associated with it so I parsed (cookie key and value) it and assigned it to my cookie container. If you have multiple cookies then parse each of them and associate with cookie container.

Now because all cookies which were associated with WebBrowser browsing session is not assigned to my Cookie container so I can create CookieAwareWebClient object using this cookie container.

CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);

Now we are ready with our cookie aware client with required cookies assigned to it so we can start sending request using this object and it will behave like it is cookie owner.

Get and Set Cookies .NET WebBrowser Control

I faced this situation many times where I have to transfer cookies from one WebBrowser control to other so that I can transfer the authentication and after searching I found a simple and straight forward solution for doing this.

Get Cookies from WebBrowser Control

After doing your operation like navigating to any page and login on the site you just have to write this code in any event:

string cookies = browser.Document.Cookies;

Above line of code will return a string containing all cookies in cookies string.

Now you can use this string to set cookies of other webbrowser control. But keep in mind that cookies string is found in Document property of WebBrowser control and document is only initialised after navigating to some URL. So before assigning these cookies either navigate to that domain who generated these cookies or set cookies while navigating.

Set Cookies in WebBrowser Control

There are two methods to set cookies in web browser control

1. This is very straight forward method to assign cookies in Cookie property of your WebBrowser’s document object:

wb.Document.Cookie = cookies;

This method may not work for all sites specially on sites running on https protocol.

2. As above method doesn’t guarantee to run on all sites so here is second method which you can use to set cookies:

=&2=&

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetSetCookie(string lpszUrlName, string lpszCookieName, string lpszCookieData);

=&3=& =&4=&

Cookie ck = new Cookie("key", "value", "/folder", "/");
InternetSetCookie("https://edunyte.com/folder", null, ck.ToString());

Now you can navigate to the URL specified in InternetSetCookie to read the cookie and verify that it is working.

Send message to GCM in C#.NET for single or multiple device delivery

In previous articles we learnt about how google cloud messaging works and how to register android device on GCM for getting registration id.

Note: This post only explains how you can send same message to single or multiple devices but there is know method provided by GCM to send different message to different devices in one request.

Now we will see how we can send request to GCM server for sending notification to mobile devices. In this example we will use .NET as our server platform and C# as programming language.

For making code usable for single as well as multiple registration ids we have used list and converted it to comma separated strings. This comma separated string can be passed in our request and GCM server will relay our message to corresponding devices.

Below is the sample code:

public class NotificationManager
    {
        private class NotificationMessage
        {
            public string Title;
            public string Message;
            public long ItemId;
        }

         public NotificationManager()
        {
            //
            // TODO: Add constructor logic here
            //
        }

         public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
        {
string SERVER_API_KEY = ;
var SENDER_ID = ;
string regIds = string.Join("","", deviceRegIds);

NotificationMessage nm = new NotificationMessage();
nm.Title = title;
nm.Message = message;
nm.ItemId = id;

var value = new JavaScriptSerializer().Serialize(nm);

WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

string postData = "{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : " + value + ","time": " + """ + System.DateTime.Now.ToString() + ""},"registration_ids":["" + regIds + ""]}";

Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;

Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

WebResponse tResponse = tRequest.GetResponse();

dataStream = tResponse.GetResponseStream();

StreamReader tReader = new StreamReader(dataStream);

String sResponseFromServer = tReader.ReadToEnd();

tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
    }

In above example we have creates class named NotificationMessage for message format. We will convert object of this class to json and sent it as message.

In SendNotification method of the class, just pass list of registration ids along with message title, body and message id which we will use to show message on mobile device.

To use this code you have to create account on google developer console and generate credentials. Follow this article if you want to learn how to create account and generate credentials for GCM.

Understanding Google Cloud Messaging (GCM) process flow for mobile notifications

Today we will learn how Google Cloud Message (GCM) works. To understand complete process flow see below image

This image explains the complete process flow of how GCM works for sending notification to mobile devices. There are total 6 steps, where steps 1 to 4 are performed only once in initial and step 5 and 6 are performed for sending message each time.

  1. Register app with GCM – This step is performed on mobile device. In this step app sends a request to GCM server with needed app and device information.
  2. Receive registration id from GCM – In response to the request sent in first step GCM sends a registration id which can be used further for sending messages from server to mobile
  3. Send registration id to app server – After getting registration id from GCM, app sends this registration id to the app server from where all app notification will be sent
  4. Save Registration id – App server can store this registration id anywhere like database or file system etc.
  5. Send message to GCM with registration ids – When ever app server need to send notification to the mobile device, it send a request to GCM server with message details and registration ids where this message need to be delivered.
  6. GCM delivers message to devices related to registration ids – When GCM receives the request it sends notification to mobile device related to registration id and mobile app can catch that message and show a notification.

In next few articles we will learn how to write android and C# code to perform all above steps.

Here is the list of example of all operations explained above:

  1. Register app with GCM and receive registration id in response
  2. Send message to GCM for single or multiple device delivery
  3. Get messages on mobile app and display on notification bar