Send FCM data message & notification to Android, iSO & 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, iSO & 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, iSO 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.

Morris.js donut chart examples - sample code

I love Morris charts because of its simplicity. If in any project I have to show any data in chart form then I mainly use Morris.js.

These are simple, powerful and beautiful. So here will see how to create morris donut charts.

1. First thing we have to do is include reference of Morris.js file along with jquery js and raphael js files.


<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://cdn.oesmith.co.uk/morris-0.4.1.min.js"></script>


2. Now simply create an HTML element like DIV to in which we want to show our data in donut chart form. Don't forget to give an id to this element because we will use it in js.


<div id="donut-example"></div>


3. Final step will be to add a script in the bottom of the page to create morris.js donut chart in element specified by its id.


Morris.Donut({
  element: 'donut-example',
  data: [
    {label: "Leads", value: 12},
    {label: "Sales", value: 30},
    {label: "Orders", value: 50},
    {label: "Returned", value: 5},
    {label: "Abandoned", value: 9}
  ]
});


And it will display chart similar to this one:


4. If you want to give custom colors to your chart then you can define another property named colors like we have specified data. Keep in mind that your color order should be in same order in which you have given order to data so that correct color will be displayed for corresponding data. So now your script will be like this.

Morris.Donut({
  element: 'donut-example',
  colors: ["#00a65a", "#f39c12", "#3c8dbc", "#dd4b39", "#555299"],
  data: [
    {label: "Leads", value: 12},
    {label: "Sales", value: 30},
    {label: "Orders", value: 50},
    {label: "Returned", value: 5},
    {label: "Abandoned", value: 9}
  ]
});


And it will display chart similar to this one:

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

Most of the time Microsoft release online installers for all its new visual studio releases and later after few months they publish ISO installers. I don't know why they used to follow such practices which is so annoying specially in places where internet speed is not good or consistent.

I am also among those who faced problems with these online installers every time and that is why I published an article last year to download Visual studio 2015 from its online installer exe and then install it offline anywhere. Here is that article and I am going to use same steps for Microsoft Visual Studio 15.

You can download online installer (web installer) exe of Microsoft Visual Studio 15 from here

After downloading copy download file vs_enterprise.exe, copy it to any folder on your computer like c:/VS15. Now open command prompt as administrator and move to your directory where you have copied. Type vs_enterprise.exe /Layout and press enter.

This will open a dialog to ask where you want to download installer file, so just select the folder you want and continue. It will start downloading Visual Studio 15 on your system in selected folder.

After download is complete you can use these offline installer files to install it anywhere.