Showing posts with label notification hub. Show all posts
Showing posts with label notification hub. Show all posts

Monday, October 14, 2013

Geotopia, SignalR and Notification Hub

The next extension of Geotopia is to notify users of updates. Everyone who is following 'me', should get a notification of a topic I posted. Install SignalR by using the package manager console or the Manage nuget packages screen when you right-click the asp.net project. E.g. in the package manage console, run:

Install-Package Microsoft.AspNet.SignalR -Version 1.1.3.

You can also use newer versions of SignalR.

In the webapi controller that handles the creation of Geotopics, I also update all the clients with this newly created Geotopic.

The SignalR hub is lazy loaded by the Geotopic webapi controller.

protected readonly Lazy AdminHub = 
            new Lazy(() => GlobalHost.ConnectionManager.GetHubContext());


The webapi method Post is slightly modified and calls the posted method on the clients.

[System.Web.Http.Authorize]
        public void Post(Geotopic value)
        {    

            //user must be logged in.
            var userNode = client.QueryIndex("GeotopiaUser", IndexFor.Node, String.Format("Id:{0}", User.Identity.Name));

            //now create a topic
            Geotopic newTopic = new Geotopic(value.latitude, value.longitude, value.message);

            var secondtopic = client.Create(newTopic,
                new IRelationshipAllowingParticipantNode[0],
                new[]
                            {
                                new IndexEntry("Geotopic")
                                {
                                     { "Id", newTopic.id.ToString() }
                                }
                            });
            NodeReference reference = userNode.First().Reference;

            client.CreateRelationship(secondtopic, new PostedBy(reference));
            //now SignalR it to all my followers....
            AdminHub.Value.Clients.All.posted(value);
   }

A piece of Javascript makes all of the above happen. It connects to the geotopichub and responds to the "posted" call from the webapi controller.



To show a nice popup on the Geotopiascreen I use Toastr. Get this by: install-package Toastr.

When I post a topic, the Toastr package displays a nice toast:



The SignalR addition enables webclients to be updated on the fly. For future release of mobile clients of Geotopia, I also use the Notification Hub of Windows Azure to enable notifications on mobile devices. To enable this, I create a service bus namespace and a notification hub.


Now I have a notificationhub available. A mechanism to easily update my mobile clients. On the backend side (my webrole), install the service bus package.

Install-Package WindowsAzure.ServiceBus

add use it in your designated class. In my case, I use it in my TopicsController.cs webapi module.

using Microsoft.ServiceBus.Notifications;

I add the following lines to the Post method of my TopicsController:
  NotificationHubClient myNotificationHub = NotificationHubClient.
        CreateClientFromConnectionString("Endpoint=sb://.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=;YOUR_KEY", 
            "YOUR_HUB");
 string toast = "" +
                "" +
                    "" +
                        "A toast from geotopia!" +
                    "
" +                "
";
 Task result = myNotificationHub.SendMpnsNativeNotificationAsync(toast);

In the result we can see the outcome of the notification call.

For now, everybody receives notifications of topics being posted. The next blog post will demonstrate how to make sure only my followers get my topics by using SignalR groups and adding tags for the Notification Hub.

Friday, October 11, 2013

Creating a topic on the Geotopia Canvas

Next step in realizing Geotopia is enabling logged in users to click on the map and add some information for that specific location on the map.

I enable this by:
- use jquery ui to show  a dialog on the screen that takes a piece of text
- use $.ajax to post the data to my webapi controller
- use Neo4j client to create a node containing the piece of text, the location and the user who posted it
- create a PostedBy relationship between the user and the newly created geotopic

Clicking on the map somewhere, displays this model dialog from jquery UI.




Clicking post will do the following to open mydialog and add some data to the dialog (the location as well).

  $("#MyDialog").data('location', location).dialog("open");

Here is where i get my location in the dialog function:
 var source = {
                    'latitude': location.latitude,
                    'longitude': location.longitude,
                 
                    'message': $('#topicmessage').val()
                }
This source is used to send it to my webapi controller.

 $.ajax({
            type: 'POST',
            url: '../api/Topics',
            data: source
          });

This causes my webapi controller to fire off

//user must be logged in.
//i take the username which is indexed in neo4j to get a reference to the right user node.

var userNode = client.QueryIndex("GeotopiaUser", IndexFor.Node, String.Format("Id:{0}", User.Identity.Name));

            //now create a topic
            Geotopic newTopic = new Geotopic(value.latitude, value.longitude, value.Topic);

            var secondtopic = client.Create(newTopic,
                new IRelationshipAllowingParticipantNode[0],
                new[]
                            {
                                new IndexEntry("Geotopic")
                                {
                                     { "Id", newTopic.id.ToString() }
                                }
                            });
            NodeReference reference = userNode.First().Reference;

            client.CreateRelationship(secondtopic, new PostedBy(reference));
            //now SignalR it to all my followers....

The node graph now shows up like this:

Node 163 is the newly created one.

Here are the details of node 163:



The next step will be to use SignalR and let my followers know that I posted something altogether with using the NotificationHub to notify mobile users!