Tuesday 27 May 2014

Sending Apple Push Notifications in ASP.NET and C# (APNS Certificates Registration on Windows)

Hello Friends,

This Post will focus on How we can send an Apple Push Notification using ASP.NET and C#.

For more video tutorial You can Visit
http://YouTube.com/WebBoostings
Visit our WebSite
http://programming-guru.com

Before start, we need some certificate so please get all required certificates.
1) PushNotification.cer (Download from Apple Account)
2) PushNotification.p12 (Exported from Apple Key Chain) 

The certificates will get one from Apple Account and other from KeyChain Access of you MAC System.

Open Microsoft Management Console



To do this press Windows + R keys at the same time to open Run. Type ‘mmc’ and press enter.

This should open Following window on your screen:



Add Certificates Snap-in to your console


Click on file and select Add/Remove snap-in from menu. This will open a new window with a list of available snap-ins on the left .
Select Certificates form list on the left and hit Add button. 
Select Computer Account form the next prompt, Local computer form next one and click on finish. Your Add snap-in window should look like this:





And when you click ok button you will see :



Certificate installation


Click on Certificates(local Computer) to expand the list. Right click on personal, then select all tasks and click on import. This will open Certificate import wizard.

Click on next ,and select your .cer file in next step. In next step select second option to place all certificates in Personal store.

Press finish and you should see a confirmation message about successful installation on Certificate.

Repeat above step to import your .P12 file, now Expand Personal on left side and click on certificates. You should be able to see your certificate in right panel. If your .p12 is password protected , you need to enter the password in the wizard.

Repeat all import process to import your certificate and .p12 files to "Trusted Root Certification Authorities" Section.

Now you have imported required certificates to sign your APNS messages to Apple push notification server.




Now Import both the certification in Trusted Root Certificate Authority



That’s done for extra work Now just to Coding side.

Now, We have some Library to send Apple Push Notification on Device.
So, You can download that Library from this Link:


or You can go for Google with Mono-APN. You will get these files.




You have to please your Device Code, Message, Badge No, any Audio file name which is alredy available in iOS app.




Before build this C# Application you have to paste the Certification.p12 file in the bin/Debug directory after that you can send the Apple Push Notification to your device.


That's it. Now, you can run this application and within a movement you will get the nice Apple Push Notification on your own device.

For More video tutorial watch and subscribe

and visit our webSite



Thank You
Abhishek Bendre

Monday 19 May 2014

Push Notification With Phonegap Part - 2

Hello Friends,

For more videos please this channel
http://youtube.com/WebBoostings
Please, Find the latest details about the Programming
http://webboostings.blogspot.in/
Visit our website
http://programming-guru.com/


Generating a new phonegap project


We will start by opening a new terminal window to generate a new phonegap application. If you dont have phonegap installed just start by doing this:

For more details you can use this link to create new project: Phonegap Configuration

Open your terminal and write this command.

$ npm install -g phonegap

This will install the phongap module globally

Navigate to the folder you want to generate the project:

$ cd your/project/path

Lets generate the project:

$ phonegap create PushNotificationApp --id "com.webconnect.webboostings" --name "PushNotificationApp"

Notice that you have 4 new directories in you project folder.

!important note: Use the same bundle id you used when you
created your application in the iOS developer center in the part 1 tutorial.
These ids are tied together when you export your Xcode project.

Then go to your newly created project:

$ cd PushNotification

Build the application for iOS:

$ Phonegap build ios

Install the PushPlugin from github via the phonegap CLI:

$ phonegap local plugin add https://github.com/phonegap-build/PushPlugin

When you use the phonegap CLI to make a new
project,  it creates a kind of a dummy project for you. You can actually
export native apps to different platfoms  from this code as an example. We
don’t need this code so we are going to replace most of it.

Building our client

Replace this code with index.html

<!DOCTYPE html>
<html>
     <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width,
       initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=0" />
     <link rel="stylesheet" href="css/main.css" />
     <title>Phonegap Push Notifications</title>
     </head>
<body>
    <div id="content">
        <h1>PushNotApp</h1>
        <h2>Push Notification:</h2>
        <p id="notification"></p>
   </div>
  <script src="phonegap.js"></script>
  <script src="js/plugins/PushNotification.js"></script>
  <script src="js/main-simple.js"></script>
</body>
</html>


Next you rename the index.css

*
{
    -webkit-tap-highlight-color:rgba(0,0,0,0);
    margin:0px;
    padding:0px;
}
body {
   -webkit-touch-callout: none;
   -webkit-text-size-adjust: none;
   -webkit-user-select: none;
   background-color: #e4e4e4;
   font-family: Helvetica, Arial, sans-serif;
   font-size:100%;
   height:100%;
   width:100%;
}

#content {
   margin-left: 10px;
}

Install the other plugins which helps us to display alert, console etc

First install the console plugin
so we can print console.log messages in Xcode.
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git

Then install the device plugin so we
can get basic device information.
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git

Last we install the local notification
and vibration api so we can display nice dialog boxes.
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-dialogs.git
$ phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-vibration.git

Now, We have to paste this code in index.html page by using the script tag in the deviceready function.

var PushNotApp = PushNotApp || {};
PushNotApp.main = (function() {
var pushNotification = window.plugins.pushNotification,
showAlert = function(message, title)
  {
  if(navigator.notification) {
    navigator.notification.alert(message, null, title, 'Close');
    navigator.notification.vibrate(1000);
  }else{
    alert(title ? (title + ": " + message) : message);
  }
 },

addCallback = function(key, callback)
{
if(window.callbacks === undefined) {
    window.callbacks = {};
  }
  window.callbacks[key] = callback;
},

addNotification = function(notificationTxt) {
console.log('notification added to DOM');
  var el = document.getElementById('notification');
  el.innerHTML += notificationTxt;
},

registrationSuccessHandler = function(token) {
console.log('successful registration with token: ' + token);
addCallback('notificationHandler', notificationHandler);
},

registrationFailedHandler = function(error) {
  showAlert(error, "Error");
},

notificationHandler = function(evt) {
  console.log("received anotification: " + evt.alert);
  navigator.notification.beep(3);
  if(evt.alert) {
    addNotification(evt.alert);
  }
  if(evt.prop) {
    addNotification("received a special property: " + evt.prop);
  }
},

deviceReady = function() {
  console.log('Device is ready');
  if(parseFloat(device.version) === 7.0) {
  document.body.style.marginTop = "20px";
  }
  pushNotification.register(registrationSuccessHandler,
      registrationFailedHandler,
{
        "badge":"true",
            "sound":"true",
"alert":"true",
            "ecb":"callbacks.notificationHandler"
});
},

initialize = function() {
  document.addEventListener("deviceready",
deviceReady, false);
}
return
{
  initialize:initialize
}
}());
PushNotApp.main.initialize();


Now Build you app by Press cmd + b (window + b)

The anatomy of a Push Notification

For sending the push notification from server we have to follow the following structure.
{
"aps" : {
    "alert" : {
      "body" : "This is a push notification",
      "action-loc-key" : "Open",
      "launch-image" : "image.jpg"
    },
    "badge" : 1,
    "sound": "sound.aiff"
  },
  "key1" : "value1",
  "key2" : [ "value2", "value3" ]
}

Compiling your app in Xcode

Now it´s time to compile your application in Xcode so you can get your unique device token.

Navigate and open your exported
     Xcode project: YourAppFolder/platforms/ios/YourAppName.xcodeproj

Change the device to compile to.Chose your phone.

Run the application

Look in the output panel and you will see this:  successful registration with token: ” Your token string”

Copy your token, we are going to use it soon.


Building a simple NodeJS server

This is the last part of the tutorial and we
are going to build a simple NodeJS server that sends out a push notification to
your device. First you need to install an awesome node module that does all the
dirty work for us. I´m talking about the node-apn
module. The node-apn is basically a NodeJS module for interfacing with the
Apple Push Notification Service.  So in root of your project folder do this:

$ npm install apn
Now you have a node_modules folder that
contains the newly installed apn module. Do you remember the SSL certificate
and private key we exported form last tutorial? Well now its time to find them
and put your .pem files in a assets folder.  The last
step is to create a server.js file in root of our application:
In the Desktop folder create your new server.js file and paste this code into that file

var http = require('http');
var apn = require('apn');
var url = require('url');
var myPhone = "d2d8d2a652148a5cea89d827d23eee0d34447722a2e7defe72fe19d733697fb0";
var myDevice = new apn.Device(myPhone);
var note = new apn.Notification();
note.badge = 1;
note.sound = "notification-beep.wav";
note.alert= { "body" : "Your turn!", "action-loc-key" : "Play" , "launch-image" : "mysplash.png"};
note.payload = {'messageFrom': Webconnect};
note.device= myDevice;
var callback = function(errorNum, notification){
console.log('Error is: %s', errorNum);
console.log("Note" + notification);
}

var options = {
gateway:   'gateway.sandbox.push.apple.com', // this URL is different for Apple's
        Production Servers and changes when you go to production
    errorCallback: callback,
    cert: 'PushNotificationCer.pem',              
    key:  'PushNotificationKey.pem',              
    passphrase: ‘Certification Password',              
    port: 2195,                    
    enhanced: true,                
    cacheLength: 100              
}

var apnsConnection = new apn.Connection(options);
apnsConnection.sendNotification(note);


For sending the push notification on device please run this command
We have already compiled our
application in Xcode so all there is left to do is this to start the server:

$ node server.js
It will take some second and then you will get the owsome push


Notification on your device.



Message from Pushnotification



Push Notification With Phonegap Part - 1

Thank You
Abhishek Bendre

Sunday 11 May 2014

Push Notification with Phonegap Part - 1

Hello Friends

For more videos please follow this channels
http://www.youtube.com/WebBoostings
Please get the latest details about programming
http://webboostings.blogspot.in/
visit our website
http://programming-guru.com/

This tutorial will be based on the Phonegap tutorial. You will need a Developer Profile for Apple and Phonegap running on your computer, so I strongly recommend that you do this tutorial first. Configure Phonegap. This tutorial will give you an general overview of the Apple push notification service(APNS), It will also handle the certificate part of the application and set everything up so you can write code in a Part 2 tutorial.

Difference between Local Push Notification and Push Notification

It´s easy to be confused about push notifications and local notifications. The difference is that push notifications comes from a 3rd party server to inform users about something, but local notification only runs on the application itself without any server interaction. You can compare it with a normal javascript alert() scheduled by your application. One way to achieve native push notifications is with phonegaps official PushPlugin.

Apple Push Notification Service Work flow Overview


ASN Token Generation


  • The device connects to the APNS server, in this case with Phonegaps PushPlugin will do that.
  • The APNS generates a device token that will link your device to the APNS server.
  • The token is sent back to the device and it can be retrieved in a callback in your application.
  • At this point it´s a good idea to post the token to your server and store it in a database of your choice.


Simple diagram to understand



Creating Certificates and provisioning profiles

Generating Certificate Signing Request(CSR) and exporting a private key

You don’t need to know much about this, but its important to note that a certificate only works in combination with a private key.  The certificate is the public document and the key is your own private key. This is how your certificate and key is treated when you use Secure Socket Layer(SSL).
  1. Open Keychain Access on your mac and go to to “Certificate assistant” then to “Request a Certificate from a Certificate Authority.
  2. Enter your email address, I usually use my apple id email, but you can use whatever. Enter the app name (PushNotificationApp) in the common field, you can use any name, but a nice descriptive name is preferred so you easily can find your private key later.
  3. Check save to disk and continue. Save the file as “YourAppName.certSigningRequest” on your desktop. (PushNotificationApp.certSigningrequest)
  4. Go to the Keys section in Keychain Access and locate your new private key with the name you chose. Right click and choose export.
  5. Save the private key on your desktop with the name “YourAppName.p12″ and enter a password. (PushNotificationApp.p12)

Creating your new Application ID and SSL certificate

This part will be the same as the Phonegap Configuration tutorial except you will need an extra certificate for handling push notifications.  So I will do a recap for your convenience and myself too.
  1. Got to developer.apple.com and log in.
  2. Go to the iOS developer center.
  3. Go to “Select the Certificates, Identifiers and Profiles” from the right panel
  4.  Go to “Certificates” in the “iOS Apps” section.
  5. Got to “App IDs” in the sidebar and click the “+” button on top right corner.
Fill in these details:
  • App ID Description:  YourAppName (PushNotificationApp)
  • App Services: Tick off “Push Notifications” checkbox
  • Explicit App ID: no.apt.YourAppName (use your own bundle id) (com.webconnect.webboostings)

You will need to set this bundle id in your Xcode projects later on. Click “Continue” and verify your setup and submit.
Now we will generate a certificate for our server to handle push notifications over SSL to the APNS.
  1. Select you newly created Application for the list and you will see a dialog box. Notice the two orange lights on the “Push Notification” row that says configurable. One for “Development” and one for “Distribution”.
  2. Click “Settings” and scroll down to “Push Notifications”
  3. Select the “Create certificate” button in the “Development SSL Certificate” section.
  4. The new dialog box will ask you to generate a Certificate Signing Request(CSR), but we already did that and we have our ”YourAppName.certSigningRequest” saved on our desktop. Just click “Continue”.
  5. In the next step you will upload your CSR, upload the YourAppName.certSigningRequest” and wait a few seconds. After its done Click “Continue”
  6. Dowload your new certificate, its named  ”aps_development.cer”. Move it to the desktop along with the others.

If you been following step by step you have 3 files on your desktop:
  • YourAppName.certSigningRequest (PushNotificationApp.certSigningRequest)
  • YourAppName.p12 (PushNotificationApp.p12)
  • aps_development.cer
Take good care of them, we are going to visit them soon.

Making Provisioning Profile

The provisioning profile is the file Xcode uses to link your App iD (com.webconnect.webboostings) with developer certificates and  iOS devices. You still have work to do in the iOS developer center.
  1. Go to the sidebar and click the “Provisioning Profiles” button and then click the + button in top right corner.
  2. Tick off  ”iOS Development” and click “Continue”.
  3. Select the App ID  you created in the previous section and click “Continue”.
  4. Select the SSL Certificates you want to include in the profile and click “Continue”.
  5. Select the devices you want to include in your profile and click “Continue”.
  6. Give the profile a descriptive name such as “YourAppName Development” and click “Generate”.
  7. Download the profile and double click on it to add it to Xcode. Open Xcode and you will find your generated profile if you go to “Window” and open the “Organizer”.

Generating PEN Files (Most Important)


This the last part of this tutorial if you get this right you will be able to implement awesome push notifications in your application. In the next step we have to generate our certificate and key to .pem files which is more usable format for SSL.


  • Open a new terminal window and go to the desktop:
    • $ cd ~/Desktop
  • Convert the aps_development.cer file into a .pem file:
    • $ openssl x509 -in aps_development.cer -inform der -out YourAppNameCer.pem
  • Convert the YourAppName.p12 file into a .pem file:
    • $ openssl pkcs12 -nocerts -out YourAppNameKey.pem -in YourAppName.p12
  • After running the command you will be asked to confirm your password:
    • Enter Import Password:
    • MAC verified OK
    • Enter PEM pass phrase:
    • Verifying - Enter PEM pass phrase:
  • Now the moment of truth, does this work at all. Lets check if the certificates are OK, but first run following command to check if you don’t have an angry firewall:
    • $ telnet gateway.sandbox.push.apple.com 2195
  • If you see this response you are all good:
    • Trying 17.172.232.226...
    • Connected to gateway.sandbox.push-apple.com.akadns.net.
    • Escape character is '^]'.

If you cant connect to the APNS server then try one more time, you have to make sure port 2195 is open and try again. If you are good to go the lets try again to check if we can connect using our certificate and private key to set up a SSL connection:

  • $ openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert YourAppNameCer.pem -key YourAppNameKey.pem
  • Then enter your key password:
  • Enter pass phrase for YourAppNameKey.pem:

If the connection is successful and you get a handshake with the APNS server you are finally done with this tutorial. You can type and press enter to disconnect from the server. If you get an error, I´m truly sorry! You might have to start this tutorial over again.

There are two APNS servers: the “sandbox” server that you use in development mode, and a “live” server you use in production mode. As you might remember we set our provisioning profile to be “iOS Development” so we are using the APNS server for development.
This was the boring part! Next tutorial we are going to make a native iOS application with phonegap using the PushPlugin. Then write a nodejs server to handle our push notifications. Stay tuned for more!