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