It’s been a few years since I wrote anything, but this one deserves a post.
Ever wanted to have a real time communication with your connected clients on your web application? Well, Microsoft SignalR helps you achieve exactly that and more. SignalR is amazing. It’s so simple to get started with, you will wonder why you haven’t used it yet. There are a few gotchas, but once you get around them, you will know how easy it is to implement real time two-way communication in your own apps.
This tutorial shows you how to use Azure Notification Hubs to send push notifications to a specific app user on a specific device. An ASP.NET WebAPI backend is used to authenticate clients and to generate notifications, as shown in the guidance article Registering from your app backend.
There are many articles online about SignalR and almost all of them demo a live chat application. What I would like to show is another use case where you just need to send notifications from the server to your connected clients.
For the sake of this demo, we will create a ASP.NET MVC application. All that is required is the free Visual Studio Community Edition 2015 to get started.
Setup
Create a new Web Application project. Right click on the MVC project and click Manage Nuget packages. Search for SignalR and click install on the Microsoft.AspNet.SignalR package. You can also run the following command from the package manager console.
This will install SignalR and all it’s dependencies. Once installed, a readme file should open up. Do take the time to read through it.
Configuration
The next step is to enable SignalR in your application. First, check if there is a Startup.cs file in your application. If there is no Startup.cs file in your project, then right click your project, click on Add New Item and select OWIN Startup class. Leave the file name as Startup.cs. If the OWIN Startup class template is missing, you can just add a regular class and copy the code below into it.
Open the Startup class, and include the app.MapSignalR() call to the Startup.Configuration method:
At this point, we just need to make sure that SignalR is working, so hit F5 to compile and view the app in the browser. Navigate to
This should open up the JavaScript proxy that SignalR has generated automatically for us. If the proxy script is visible, then SignalR is working as it should. If not, retrace the steps.
Send Notifications
Back on Visual Studio, create a new folder called Hubs under your project, and add a new SignalR Hub Class named NotificationHub.cs with the following code:
The above piece of code:
- By inheriting from the Hub class, instructs SignalR to work its magic and generate a JavaScript proxy automatically. This will allow JavaScript clients to communicate with the server and vice versa
- Creates a server method called NofifyAll that is available for calls from client
- Calls the JavaScript method displayNotification on the connected clients
Next, we would need a form to pass the notification info and call the NotifyAll method on the server.
For simplicity sake, I am going to use the route Home -> Notification and create a new view that will contain the form. Open Controllers -> HomeController.cs and add the following code to the HomeController class:
Next, we will need an associated View for the above route under Views -> Home -> Notification.cshtml. Because the default Asp.Net template uses Bootstrap, we will use it’s inbuilt styles to format our form elements.
Next, add the JavaScript code below to communicate with the SignalR autogenerated proxy and send the notification to the server when the user clicks the Send to All button.
Let’s look at the code above:
Line 6: The SignalR hub must be started before we can send notifications. And because we will require a SignalR connection for receiving notifications too, we will start the connection in the master page (_Layout.cshtml). We will get to this in the Receive Notifications section below.
Line 15: The send-notification click handler requests the form values and calls the server method NotifyAll via the JavaScript hub proxy auto generated by SingalR. It’s important to note that the proxy automatically camelCases the hub and the server method names to conform to JavaScript conventions.
Receive Notifications
Now, we will include the html that will display the notification when the client receives it from the server. Like the form elements earlier, we will use Bootstrap’s inbuilt alert styles to display our notifications.
Here’s a sample of the notification HTML using Bootstrap alerts.
Ideally we would like the users to receive as many alerts and have them all visible until the user explicitly dismisses them. To achieve this, we will be creating the above HTML programatically and inject them into a container HTML element using a little bit of jQuery.
So open the Views->Shared->_Layout.cshtml file and add the following code where you would want the notification displayed:
I’ve used inline style to pad the container from the header, please use dedicated CSS classes for styling though. Now, add the following JavaScript below the jquery and bootstrap bundles.
Reference to the SignalR library and the auto-generated hub proxy
JavaScript to receive the notification and convert into a Bootstrap alert.
Lines 16 through 18 intiates the SignalR connection and stores the return object globally for use in child views. (Refer Send Notifications section on this)
This takes care of the code that is required to display the notification. Hit F5 to compile the application and view in browser. To test, leave multiple tabs/windows of your application in your browser open. Open a new tab and navigate to:
Fill the form fields and hit Send to All. You should see the notification displayed on all open tabs/windows. Try sending another notification and check the behavior.
Next Steps
It’s important to understand that this article is just an introduction into the fascinating world of real time communications using SignalR. I would highly recommend reading the reference material available as SignalR does provide a lot of customizable options.
Also the article does not deal with security. It effectively allows anyone to send a notification to all connected clients. Refer to the Introduction to SignalR Security article for information on using the Authorize attribute to secure access.
![Push notification asp.net mvc code Push notification asp.net mvc code](/uploads/1/2/4/9/124991254/128551990.png)
You can fork a copy of this project from GitHub.
Advertisements
IOS Push Notifications
![Web push notifications asp.net mvc Web push notifications asp.net mvc](/uploads/1/2/4/9/124991254/312728020.gif)
Here we learn more about sending IOS Push Notifications through PushSharp in IOS devices using C#.
PushSharp is a server-side library which can use for sending IOS Push Notifications, Android devices(using Google Cloud Messaging), Windows phones and Blackberry devices.
PushSharp is a library which you can download from below link or you can also use this through NuGet packages.
It’s very easy to use and very easy to install for IOS, Android, Windows and Blackberry devices.
To use this library to send notification in IOS devices, first of all, you need to create .p12 certificate file which is very easy to create in Mac.
Below are the steps for your reference
- Login to your IOS development center by using this address: https://developer.apple.com/devcenter/ios then click on “Certificates, Identifiers & Profiles”.
- When you click on it one IOS Apps will open, which contains four options like Certificates, Identifiers, Devices and Provisioning Profiles, So please click on Identifiers.
- When you click on Identifiers IOS App ID’s wizard will open and select your Application ID which you previously created for your application. In that screen click on edit button to make changes.
- When you click new wizard will open and that wizard has Push Notifications check box, So click on it and it will display Development SSL Certificate & Production SSL Certificate options. After this click on create certificates under Production SSL Certificate and click continue.
- After this click on “Choose File” button and select CSR (Certificate Signing Request) file and click on generate.
- Click on “Download” button to download your Push Notification Certificate and then click on done.
To follow above process you will easily create Certificate file in Mac system.
How to convert Push Notification Certificate as a .p12 File
- Go to Keychain Access and select your certificate which you have installed in Keychain Access previously then right click on it and click on “Export”.
- When you click on export wizard will open which contains four options Save As, Tags, Where and File Format, provide certificate name as per your requirement in Save As box, provide location where you want to save your file in Where box, make sure the File Format is set to “Personal Information Exchange” (.p12) click on save button to save it to your system.
- If it will ask for password leave it blank and click on Ok button.
- If it will ask for company password so enter it and click on Allow button.
- Then your .p12 file is ready and saved in the location which you specified.
If you follow above procedure correctly so your “Personal Information Exchange” (.p12) file is ready to use in our C# code.
Use below code in C# to send Push Notification in IOS devices using PushSharp library.
#put your certificate file in configuration section so it will read and create a configuration#
IOS Push Notification
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 | var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production, Server.MapPath('AppCertificate/Certificate.p12'), ', true); #Intialize ApnsServiceBroker to provide ApnsConfiguration# apnsBroker.OnNotificationFailed += (notification, aggregateEx) => aggregateEx.Handle(ex => #See what kind of exception it was to further diagnose# { var notificationException = (ApnsNotificationException)ex; Response.Write(ex.InnerException.ToString()); var apnsNotification = notificationException.Notification; var statusCode = notificationException.ErrorStatusCode; Response.Write('Apple Notification Failed: ID= ' + apnsNotification.Identifier + ', Code=' + statusCode); else { #Inner exception might hold more useful information like an ApnsConnectionException# Response.Write('Notification Failed for some unknown reason : ' + ex.InnerException); # Mark it as handled# }); apnsBroker.OnNotificationSucceeded += (notification) => Response.Write('Apple Notification Sent!'); #Start the broker# #Queue a notification to send# { Payload = JObject.Parse('{'aps':{'alert':' + Server.HtmlEncode(description) + ','badge':' + 5 + ','sound':'noti.aiff'}}') #This isn't done after every message, but after you're done with the broker } |
Here we finished it up with coding part if you follow each and every step correctly so you are able to send Push Notification in IOS devices using PushSharp.
Let us know if I miss anything above. Put your comments below related to any queries or any topic related to .Net, Android.