JQuery Mobile and Asp.net WebForms 4.5

Hi,

I was searching for some examples on the responsive web design and frameworks and i was impressed by JQuery mobile and it’s roadmap towards the future and it’s broad capabilities. You can view JQuery Mobile at http://view.jquerymobile.com/1.3.0/

So, in further searches – it was obvious that lesser people have tried it with web forms. I didn’t find any examples (may be there are.. but nothing good appeared on google search).

So here is a another to the point simple example:

Steps

  1. Create Empty Web Forms Project (VS 2012)
  2. From NuGet – Add Jquery
  3. Add Jquery UI (For normal site)
  4. Add JQuery Mobile (For Mobile Site)
  5. Add “Site.Master” Master page
  6. Add “Site.Mobile.Master” Page (To used as master page for mobile site)
  7. Add Default.aspx
  8. Add Default.mobi.aspx
  9. Add Global.asax

Main Idea

“Every .aspx page in normal page has its respective .mobi.aspx” It’s hybrid project and we will simple use asp.net url routing to map if the request comes from mobile site (only in case of .aspx) – All other things remain same.

So,

Here are questions:

  1. How to do URL Rewrite?
  2. How to setup jQuery Mobile?

1- How to do URL Rewrite?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
namespace Test.WebWithMobile
{
public class Global : System.Web.HttpApplication
{
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.Browser.IsMobileDevice)
            {
                //Request.Url.MakeRelativeUri(new Uri(Request.Url.AbsoluteUri)).ToString() + Request.Url.AbsoluteUri.Replace(“.aspx”, “.mobi.aspx”)
                if ((!Request.Url.OriginalString.ToLower().Contains(“mobile”)
                    && Request.Url.OriginalString.ToLower().EndsWith(“.aspx”))
                    || Request.Url.OriginalString.IndexOf(“.aspx”) == -1)
                {
                    var url = Request.Url.OriginalString;
                    if (url.ToLower().IndexOf(“.aspx”) == -1)
                        url += “Default.aspx”;
                    url = url.Replace(“.aspx”, “.mobi.aspx”);                    
                    var path = Request.Url.MakeRelativeUri(new Uri(url));
                    HttpContext.Current.RewritePath(“~/” + path);
                }//Request.ApplicationPath);
            }
}
}

2- How to setup jQuery Mobile?

<head runat=”server”>
<meta name=”viewport” content=”width=device-width, initial-scale=1, maximum-scale=1″ />
<title></title>
<link href=”Content/jquery.mobile-1.3.0.min.css” rel=”stylesheet” />
    <script src=”Scripts/jquery-1.9.1.min.js”></script>
    <script src=”Scripts/jquery.mobile-1.3.0.min.js”></script>
<asp:ContentPlaceHolder ID=”head” runat=”server”>
</asp:ContentPlaceHolder>

</head>
<body>
<form id=”form1″ runat=”server”>
<div data-role=”page”>
            <div data-role=”header”>Mobile Header</div>
            <div data-role=”content”>
<asp:ContentPlaceHolder ID=”ContentPlaceHolder1″ runat=”server”>
</asp:ContentPlaceHolder>
</div>
        </div>
</form>
</body>

That’s It !!!

Surprised … but that’s it… This will get your going with query mobile and setting up web solution.

  1. Intro to JQuery Mobile
  2. Responsive Web Design
  3. PluralSight Training
  4. Download Source Code

JQM

SignalR – Simple Implementation

Hi Guys,

Back with an interesting post here. I was recently trying to find a simple and to the point example of SignalR with no big code snippets to work with. It was somewhat complex to understand the whole picture. Anyways, here is the “to the point” with no extra details small application.

It consists of

  1. Web Application (Our Host for SignalR)
  2. Windows Client Application (Demonstrating how you can invoke SignalR and Interact with)
  3. Source Code attached at end of this article
Web Application – The Host
Follow these steps
* Create Empty VS 2012 – Web Application Project
* Install SignalR Package from NuGet (Microsoft ASP.Net SignalR)
Signlar_Select
* Add Global.asax
* Put in following Code

       protected void Application_Start(object sender, EventArgs e)        {

            RouteTable.Routes.MapHubs();

        }

*  Add Default.aspx

* Paste following HTML

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”WebCommunicator.Default” %>

<!DOCTYPE html>

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

    <title></title>

    <script src=”Scripts/jquery-1.6.4.min.js”></script>

    <script src=”Scripts/jquery.signalR-1.0.1.js”></script>

    <script src=”signalr/hubs”></script>

    <script src=”Scripts/app.js”></script>

</head>

<body>

    <form id=”form1″ runat=”server”>

    <div>

        <input id=”txt” style=”width: 200px;” /><input type=”button” id=”btnSend” value=”Send”/>

        <div id=”messages”>

        </div>

    </div>

    </form>

</body>

</html>

 *  Add Hub code in App_Code folder for the project

    

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.AspNet.SignalR;

using Microsoft.AspNet.SignalR.Hubs;

 

namespace WebCommunicator.App_Code

{

    [HubName(“commHub”)]

    public class CommunicationHub : Hub

    {

        public void send(string message)

        {

            Clients.All.addMessage(message);//this should be in js

            Clients.Caller.sendAcknlowedge(message + ” received …”);

        }

    }

}

*  Add app.js in Scripts folder in web project

$(document).ready(function () {

    $(function () {

        var commHub = $.connection.commHub;

        commHub.client.addMessage = function (message) {

            $(“#messages”).append(“<li>” + message + “</li>”);

        };

        commHub.client.sendAcknlowedge = function (message) {

            $(“#messages”).append(“<li><b><i>Server Responded: ” + message + “</i></b></li>”);

        };

        $(“#btnSend”).click(function () {

            commHub.server.send($(“#txt”).val());

        });

        $.connection.hub.start();

    });

});

AND THAT’s IT FOR Server Side Code …

Easy Right? 🙂

Now, Let’s make Windows Client for it…

Windows Client

* Create a New Windows Form Project (You can make WPF/ Windows Phone Etc …)

* Install Client Package for SignalR from NuGet

Full Code Snippet for the Window Form (Paste this code and add a text box and two buttons in designer)

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using Microsoft.AspNet.SignalR;

using Microsoft.AspNet.SignalR.Client;

using Microsoft.AspNet.SignalR.Client.Hubs;

 

namespace WebCommunicator.WinClient

{

    public partial class Form1 : Form

    {

        IHubProxy proxy;

        HubConnection connection;

        public Form1()

        {

            InitializeComponent();

            this.FormClosing += Form1_FormClosing;

        }

 

        void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (connection != null)

                connection.Disconnect();

            connection = null;

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

//Put your url here.. i published to iis before using it from client.

             connection = new HubConnection(@”http://172.16.27.128/WC/“);

            proxy = connection.CreateHubProxy(“commHub”); //name from the hubName attribute

           //to receive the callback from server. You can do anything on this!

             proxy.On(“sendAcknlowedge”, 

                msg => 

                this.Invoke(() => listBox1.Items.Add(msg)));

            connection.Error += connection_Error;

            connection.Start().Wait();

        }

        void connection_Error(Exception obj)

        {

            MessageBox.Show(obj.Message);

        }

//send message to server

        private void button2_Click(object sender, EventArgs e)

        {

            proxy.Invoke<string>(“send”, textBox1.Text); //this “send” is defined on hub

        }

    }

    public static class ControlExtensions

    {

        public static void Invoke(this Control Control, Action Action)

        {

            Control.Invoke(Action);

        }

    }

}

That’s IT for client…

Now, as you have already deployed the web application… You can open multiple browsers from a machine or from multiple machine and see the magic.

I had two machines (Mac and Windows) – Used safari from mac and  windows for forms app and IE test… It worked all great.

Signlar in Action

NOTE:

This is really to the point working solution. I will describe each item in next article soon. Also you can find details for each of them everywhere on the internet. I had to share this as i had problem gathering information. So, hopefully that will some of people.

Gotchas:

  1. Leave aside what you know about applications. Just start with it. If you will think too much, you will never get it working.
  2. Remember HubName
  3. Make sure order of js files inclusion is correct, just like mentioned above
  4. if you get $.connection as undefined means that you don’t have javascript files loaded correctly.

You can download source code from here… WebCommunicator.zip (Source Code)