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

Sample Code - Android share action with chooser to display system default share chooser dialog

This post is for helping those you are looking to implement share feature in there android application and ending up with default ShareActionProvider which is too basic and doesn't look good at all.

Solution to this problem is "chooser". below is the sample of how you can share any data with ACTION_SEND intent by setting text and subject and at the end call start activity with createChooser.


            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);

            String text = "";
            String url = "";
            sendIntent.putExtra(Intent.EXTRA_SUBJECT, text);
            sendIntent.putExtra(Intent.EXTRA_TEXT, text + " \n\n" + url);
            sendIntent.setType("text/plain");
            context.startActivity(Intent.createChooser(sendIntent, "Share"));


There are many advantages of using chooser
  • Even if you has selected any default application of this action your application will share chooser dialog so that user can select any other application without going to settings
  • You have option to set title for your share action chooser dialog
  • If no matching application found (I don't think if this will happen to anyone in real world) then android displays a system message.

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

In our previous article we learnt how to send FCM data message notification from your server to FCM server using C#. Now for those you want to use PHP instead of C# to send FCM notification we have prepared a fairly simple class.

You just need to follow below four steps and you are done.
  1. Create an object of fcm class
  2. Call setIds method (passing array of registration ids) to set registration ids of your devices
  3. Call setData method to set your notification title, message and id.
  4. Call send method
class fcm
{
    private $url = "https://fcm.googleapis.com/fcm/send";
    private $ids = array();
    private $data = array();

    public function setIds($ids)
    {
        $this->ids = $ids;
    }

    public function send()
    {
        if (empty($this->ids)) {

            return "no id";
        }

        $post = array(
            'registration_ids'  => $this->ids,
            'data'              => $this->data,
        );
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
     
        $ch = curl_init();

        curl_setopt( $ch, CURLOPT_URL, $this->url);
        curl_setopt( $ch, CURLOPT_POST, true);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($post));

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            return $error;
        }

        curl_close($ch);

        $obj = json_decode($result, true);

        return "sent on: " . $obj['success'] . " devices";
    }

    public function setData($title, $msg, $id)
    {
        $this->data = array("title" => $$title,
                            "msg" => $msg,
                            "id" => $id);
    }
}

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<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://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

Notification Message 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"
    }
}


Data Messages 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

Adding Share Action on Android Application ActionBar (appcompat v7)

Adding share action on android application action bar is simple and straight forward.

There are mainly 3 steps that you have to follow:

1. Add Share Action Item in your menu

To add share action item in your menu simply add below item in your menu layout:

    <item
        android:id="@+id/menu_item_share"
        app:showAsAction="ifRoom"
        android:title="Share"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

And don't forget to add res-auto schema on your menu. Your final menu layout should contain below details:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <item
        android:id="@+id/menu_item_share"
        app:showAsAction="ifRoom"
        android:title="Share"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>

You can set showAsAction to any other value like always, never, withText etc

2. Create ShareActionProvider in your activity

No you have to create ShareActionProvider in your activity where you want to show and handle action share event.

For that first declare ShareActionProvider object

    private ShareActionProvider mShareActionProvider;

override onCreateOptionMenu in your activity and add below code:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate menu resource file.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // Locate MenuItem with ShareActionProvider
        MenuItem item = menu.findItem(R.id.menu_item_share);

        // Fetch and store ShareActionProvider
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

        setShareIntent();
        // Return true to display menu
        return true;
    }

Here menu_main should be your menu xml file name and menu_item_share is the id of share item added in the menu.

You many notice that we have called a method setShareIntent at the end just before returning. This is not an inbuilt method. We will define this in next step.

3. Set Share Intent

Here we will set the intent of the share action so that we can control what will be shared if user proceeds to go further with sharing.

    private void setShareIntent() {
        if (mShareActionProvider != null) {

            Intent myShareIntent = new Intent(Intent.ACTION_SEND);
            myShareIntent.setType("text/plain");

            myShareIntent.putExtra(Intent.EXTRA_SUBJECT, "");
            myShareIntent.putExtra(Intent.EXTRA_TEXT, "");

            mShareActionProvider.setShareIntent(myShareIntent);
        }
    }

You can specify different share intent type like in our case we have set text/plain because we are sharing plain text. Similarly you can set other type like view, images etc.

After that put extras based on based on your share intent type. For text/plain we have set subject and text.

Note: Whenever in your activity life cycle if your share content (subject and text in our case) is changed just call this method setShareIntent, no need to create ShareActionProvider again.

Deployment Failed: Unexpected Exception - AWS EBS deployment error

Recently I was trying to deploy my .NET project on AWS Elastic Beanstalk (EBS) using AWS Toolkit for Visual Studio.

Before this deployment attempt this same project was published on same EBS where I was just updating the project after making some changes. But unfortunately I was getting an error message (Deployment Failed: Unexpected Exception) every time I try to deploy the project on my AWS EBS instance and deployment gets failed hence EBS redeployed my previous deployed code again.

I searched for many days but none of the solution helped me resolve my issue and I started inspecting the changes I made between current and previous deployment.

After removing all the change I made in my aspx and cs paged I tried redeployment and it was really frustrating that I got same error (Deployment Failed: Unexpected Exception) and EBS again reverted my code to previous deployment.

Suddenly one thing strike in my mind that recently I updated AWS SDK in my project and after checked further I noticed that during updation process I mistakenly added an AWSRegion appSetting twice in my project web.config file.

I just removed that extra appSetting and keeping all the changes I made and tried redeployment, Voylla it was deployed successfully this time.

So this silly mistake cost my 2-3 days but all well that ends well. So never do such silly mistakes like me :)

HTML entity decode to original displayed characters in PHP

Recently I faced problem while fetching data from some websites and putting it in my database. Problem was that when I fetch data I got some special characters encoded like below
  1. character displayed was ‘ but I got &#8216; when I fetch using simplehtmldom
  2. character displayed was ’ but I got &#8217; when I fetch using simplehtmldom

After searching for more then 8 hours I got a very simple and straight forward solution to convert there characters back to the original displayed characters:

/* This is the ‘text’ I fetched*/
$input = "This is the &#8216;text&#8217; I fetched";
$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);
echo $output;


This code above converted my encoded special characters back to originally displayed characters in HTML.

Referance: http://jp2.php.net/manual/en/function.html-entity-decode.php#104617

[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" />

Microsoft Visual Studio 15 Preview 4 released - Download Offline installer ISO

Microsoft has released preview 4 of its next version of Visual Studio that is Visual Studio 15 on 22 August 2016. You can see fill list of new feature on below link:

https://www.visualstudio.com/en-us/news/releasenotes/vs15-relnotes

For downloading this preview version of Visual studio 15 you can use download option on below link:

https://go.microsoft.com/fwlink/?LinkId=733434

But main problem most of the users experience is not offline installer available there. So we have a simple set of steps you can follow and download Offline Installer ISO of any version of visual studio.

You just have to download web installer exe from link given above and then follow steps described in two of our previous. Here are those articles:

Download Visual Studio 2015 RC offline installer (ISO)
Download Visual Studio 15 ISO (Offline Installer) using web installer EXE

Only difference in steps of these articles and your steps would that you have to use web installer exe download from above link instead of web installer file described in these articles.