Showing posts with label SignalR. Show all posts
Showing posts with label SignalR. Show all posts

Monday, June 3, 2013

What a boon. MVC 4.0 + JQuery Mobile + SignalR

MVC 4.0 + JQuery Mobile + SignalR

What a boon!

MVC 4.0 + JQuery Mobile + SignalR
Few of the best technologies when clubbed together can create a fabulous masterpiece within a time you blink your eye.

Here in this post I will brief you about how to create mobile application using MVC4.0, JQuery Mobile and SignalR.

For detail Chat application and SignalR technicalities please refer my previous posts.
http://dhavalupadhyaya.wordpress.com/2012/11/13/srchat-plug-play-enjoy/
http://dhavalupadhyaya.wordpress.com/2012/10/09/signalr-to-rescue/

Prerequisite:

MVC 4.0 ( http://www.asp.net/mvc/mvc4 )
Basic Knowledge of Razor ( http://www.w3schools.com/aspnet/razor_intro.asp )
Basic Knowledge of SignalR ( https://github.com/SignalR/SignalR/wiki )
Basic Knowledge of JQuery Mobile ( http://view.jquerymobile.com/1.3.1/dist/demos/ )

So let’s gets started

Step 1) Start visual studio and create a new Web Project with ASP.NET MVC 4 WEB Application template as shown below.

Step 1

Step 2) Select Mobile Application Project Template and click OK.

Step 2

Step 3) This will create a fresh web application with MVC 4.0 framework and some prebuild models, views and controllers for asp.net membership. We will use this as base project and add chat module to it in later steps. Change the “DefaultConnection” connectionstring into web.config file to point to your valid blank database. (Asp.Net will create the sql database to be used by membership when user registers for the first time)

Step 4) Install SignalR infrastructure. Go to Tools > Library Package Manager > Package Manager Console and Run below command as shown below

[sourcecode language="csharp"]
Install-Package Microsoft.AspNet.SignalR
[/sourcecode]

Step 4

Step 4

Step 5) Once SignalR infrastructure is added, Goto Global.asax.cs and add “RouteTable.Routes.MapHubs();” line to the “Application_Start” method of the page as shown below. Without this route mapping MVC framework would not be able to map the requests sent by SignalR infrastructure. Also make sure you register this routs before you map any other routes in this method.

[sourcecode language="csharp"]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SRJQM
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Register the default hubs route: ~/signalr
RouteTable.Routes.MapHubs();

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

}
}
}

[/sourcecode]

Step 6) Create a new Class named “SRChatServer” that inherits from “Hub” class. Add a simple new method named “SendMessage” that will broadcast message to all the mobile clients that are connected to this hub.

[sourcecode language="csharp"]

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;

namespace SRJQM
{
[HubName("sRChatServer")]
public class SRChatServer : Hub
{
public void SendMessage(string user, string message)
{
Clients.All.addMessage(user, message);
}
}
}

[/sourcecode]

Step 7) Now let’s create the Chat Model\View\Controller using which user will be able to send and receive broadcasted messages from the hub created in above step.

Step 8) Create a Class named “ChatController” in Controllers section. Add [Authorize] attribute to this class as we want to restrict its access only to the users who are logged into the application. Add “Index” method that will simply redirect the user to the Index.cshtml view inside the chat area which we will create in next step.

[sourcecode language="csharp"]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace SRJQM.Controllers
{
[Authorize]
public class ChatController : Controller
{
public ActionResult Index()
{
try
{
ViewBag.Message = "Welcome to chat sample : " + User.Identity.Name;
return View();
}
catch (Exception ex)
{
throw ex;
}
}

}
}

[/sourcecode]

9) Create a folder (area) named “Chat” inside “Views” folder. Add “Index.cshtml” inside this folder. This is the main page that will connect to SignalR Server Hub created above. It also contains UI that is used for sending and receiving messages that are broadcasted by the SignalR server hub.

[sourcecode language="html"]

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.signalR-1.1.2.min.js" type="text/javascript"></script>
<script src="~/signalr/hubs"></script>
@model SRJQM.Models.LoginModel
@{
ViewBag.Title = "Chat Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
<div data-role="content">
<div data-role="fieldcontain">
<ul id="messages">
</ul>
</div>
<div data-role="fieldcontain">
<label for="txtMessage">
Message:
</label>
<input name="txtMessage" id="txtMessage" placeholder="Type Message" value="" type="text">
</div>
<div class="ui-grid-a">
<div class="ui-block-a">
<a id="btnSendChat" data-role="button" data-theme="b" href="#">Send </a>
</div>
<div class="ui-block-b">
<a id="btnClear" data-role="button" data-theme="b" href="#">Clear </a>
</div>
</div>
</div>
<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
<script type="text/javascript">
$(function () {
var chatHub = $.connection.sRChatServer;

// Start the connection
$.connection.hub.start();

// Declare a function on the blog hub so the server can invoke it
chatHub.client.addMessage = function (user, message) {
$('#messages').append('<li><strong>' + user + '</strong>: ' + message + '</li>');
};

$("#btnSendChat").click(function (event) {
chatHub.server.sendMessage("@User.Identity.Name", $("#txtMessage").val());
$("#txtMessage").val("")
});

$("#btnClear").click(function (event) {
$("#txtMessage").val("")
});
});
</script>

[/sourcecode]

10) Goto Views > Home folder and code conditional link inside Index.cshtml, About.cshtml, and Contact.cshtml views as shown below. This link will help user to navigate to chat module.

[sourcecode language="csharp"]

<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
@if (Request.IsAuthenticated)
{
<li>@Html.ActionLink("Chat", "Index", "Chat", routeValues: null, htmlAttributes: null)</li>
}
</ul>

[/sourcecode]

That’s it.
Compile the project and open multiple instances of browser or mobile, login into the application using different registered users and start using the application.

Step 5          Step 6

Step 7          Step 8

Tuesday, October 9, 2012

SignalR To Rescue

SignalR To Rescue

Asynchronous library for .NET to help build real-time, multi-user interactive web applications.

Many asp.net based real time applications uses some traditional techniques to trigger some business on client. Some old techniques include an recursive timely call like Ajax call to server to fetch data at intervals, a trigger from server using duplex channel when using WCF etc… These all traditional techniques has some or more disadvantages like a constant callbacks increasing server load, firewalls restricting duplex protocols hiding clients and resulting in broken links in duplex channels etc.


But now SignalR has emerged to rescue us from these types of architectural bottlenecks. One can easily build notification systems, chat applications, triggers across multiple applications and other myriads of real-time application using this simple yet powerful technology.


In this article I will jot down a very basic sample of broadcasting message to a group or to a specific client using SignalR and asp.net. For further technical documentation please refer https://github.com/SignalR/SignalR/wiki


Prerequisites


In order to take advantage of SignalR a small integration of its infrastructure is required. To keep it simple I will use use Package Manager Console and Nuget package of SignalR later in the project.


Application


Two important parts needs to be coded for creating basic SignalR based applications.


- Server Hub: A simple class containing methods that can be called from client hub. Also it is the main container of logic on server side. It can trigger methods on client hub with specific connection or with a group of connections.


- Client Hub: A piece of code that is used for registering to server hub. It can contain methods that call server hub methods. It can also contain methods that are called from server hub. Client hubs can be coded in native ASP.Net or JavaScript.


Step 1) Create a new Asp.Net Web Application (“SignalRNotification”) in Visual Studio. Remove all the default folders and web forms created by template if any.



Step 2) Install SignalR infrastructure
Go to Tools > Library Package Manager > Package Manager Console



Run below command
Install-Package SignalR



The above steps will install SignalR infrastructure required to make use of this technology

For detail description and latest news for SignalR release please refer http://nuget.org/packages/signalr

Step 3) Create a new class named NotificationHub that inherits from Hub.

[sourcecode language="csharp"]
using System;
using SignalR.Hubs;

namespace SignalRNotification
{
[HubName("notificationHub")]
public class NotificationHub:Hub
{
public void NotifyUsers(string message)
{
//Invokes onReceiveNotification function for all the Clients
Clients.onReceiveNotification(string.Format("{0} {1}", message, DateTime.Now.ToString()));
}
}
}
[/sourcecode]

In the above code one can chose to send message to all clients, a group of clients or to a specific client. To keep things simple the above code simply broadcast the message to all clients.

Step 4) Create a web form Admin.aspx. Add a textbox and a button to it as shown below. It includes reference to magical scripts that is actually responsible for connecting to SignalR hub and creating the proxy class. Internally this script registers the client using a unique GUID by making an ajax call. We will use this form for sending messages.

[sourcecode language="html"]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="SignalRNotification.Admin" %>

Admin
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script><script type="text/javascript" src="Scripts/jquery.signalR-0.5.3.min.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
$(function () {
// the generated client-side hub proxy
var server = $.connection.notificationHub;
// Start the connection
$.connection.hub.start();
$('#xbtnNotify').click(function () {
var message = document.getElementById('txtMessage').value;
//call the method on server using the proxy
server.notifyUsers(message);
});
});

// ]]></script>

<form id="form1">
<h1>Administrator</h1>
<div>Message :
<textarea id="txtMessage" style="width: 400px;" rows="3" cols="1"></textarea>
<input id="xbtnNotify" type="button" value="Send this to All Users" /></div>
</form>

[/sourcecode]

Step 5) Create a web form User.aspx as shown below. We will use this form for receiving messages.

[sourcecode language="html"]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="User.aspx.cs" Inherits="SignalRNotification.User" %>

User

<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script><script type="text/javascript" src="Scripts/jquery.signalR-0.5.3.min.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script><script type="text/javascript">// <![CDATA[
// the generated client-side hub proxy
$(function () {
var server = $.connection.notificationHub;
//This is the method that will be invoked from the server!!
server.onReceiveNotification = function (message) {
$("#messages").append('
<li>' + message + '</li>

');
};
// Start the connection
$.connection.hub.start();
});
// ]]></script><pre>
<form id="form1">
<div>
<h1>User</h1>
</div>
<ul id="messages"></ul>
</form>
</pre>

[/sourcecode]

That’s it.

A simple way to do complex things.
In my next article I will explain how to create CHAT server using SignalR.