ProgressBar using JQueryUI and SignalR


Introduction 


Today we can see more and more web applications developed are equipped with AJAX. Although the success of AJAX compelled more developers to adapt and shift towards ajax-based applications. Still we have some areas left behind specially when it comes to real-time progress indication or notification. In this case, we have the only option to display the progress by showing progress bar or spinning wheel to make the Client believe that something is happening behind the scene without showing any Server-Side information to the Client. 
In earnest, with this one-way or disconnected approach there aren't many ways in which one can accomplish the real-time progress indication in AJAX. To cop with this scenario one can build a real-time progress bar using a new and still-in-progress library: SignalR; a Microsoft .NET Framework signaling library being developed by the ASP.NET team, shifted as a part of Visual Studio 2013.

This article will describe as illustrated in the following screen shot; 

Using the code  

For creating the sample application as follows I used Visual Studio 2012,  jQuery 1.7,  SignalR 2.0 and JQuery UI 
First of all, we need to add SignalR to the web application. There are several ways to do this, the simplest being right-clicking in your project, Manage NuGet packages, search Online for signalr and selecting to install Microsoft ASP.NET SignalR. 
Next, we add to the project a OWIN Startup class and add Configuration method inside it to map SignalR library. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
 
 
 
[assembly: OwinStartup(typeof(RealTimeProgressBar.Startup))]
namespace RealTimeProgressBar
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
} 

Following is the hub class that does the server side processing; 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;
 
 
namespace RealTimeProgressBar
{
    public class ProgressHub : Hub
    {
        public string msg = "Initializing and Preparing...";
        public int count = 100;
 
        public void CallLongOperation()
        {
            for (int x = 0; x <= count; x++)
            {
                
                    // delay the process to see things clearly
                    Thread.Sleep(100);
 
                    if (x == 20)
                        msg = "Loading Application Settings...";
 
                    else if (x == 40)
                        msg = "Applying Application Settings...";
 
                    else if (x == 60)
                        msg = "Loading User Settings...";
 
                    else if (x == 80)
                        msg = "Applying User Settings...";
 
                    else if (x == 100)
                        msg = "Process Completed!...";
                    
                    // call client-side SendMethod method
                    Clients.Caller.sendMessage(string.Format
                            (msg + " {0}% of {1}%", x, count));
 
                
            }
 
 
        }
 
    }
 
}  

By the time, our server is ready. We have a method called CallLongOperation that is called from the client side. This method simulates a long running operation with 100 iterations and, at every iteration, notifies the client of the current status. The Thread.Sleep() method was introduced to slow down the server, otherwise we could hardly see the progress in action.

Next, we have to prepare the client. Create a new HTML page (or use the page where you want to show the notifications).

<span style="white-space: pre-wrap;"><html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Real-time Progress Bar using SignalR and JQuery UI</title>
    <link type="text/css" href="Content/ui.all.css" rel="stylesheet" />
    <link href="Content/redmond/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" />
 
    <script src="Scripts/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="Scripts/ui.core.js"></script>
    <script type="text/javascript" src="Scripts/ui.progressbar.js"></script>
    <%--  --%>
    <!-- signalr library -->
    <script src="Scripts/jquery.signalR-2.0.2.min.js"></script>
    
    <!-- autogenerated signalr hub script -->
    <script src="http://www.codeproject.com/signalr/hubs"></script>
 
    <script type="text/javascript" language="javascript">
 
        $(document).ready(function () {
 
            // initialize progress bar
            $("#progressbar").progressbar({ value: 0 });
 
            // initialize the connection to the server
            var progressNotifier = $.connection.progressHub;
 
            // client-side sendMessage function that will be called from the server-side
            progressNotifier.client.sendMessage = function (message) {
                // update progress
                UpdateProgress(message);
            };
 
            // establish the connection to the server and start server-side operation
            $.connection.hub.start().done(function () {
                // call the method CallLongOperation defined in the Hub
                progressNotifier.server.callLongOperation();
            });
 
        });
 
        function UpdateProgress(message) {
            // get result div
            var result = $("#result");
            // set message
            result.html(message);
            // get progress bar
            var value = $("#progressbar").progressbar("option", "value");
            // update progress bar
            $("#progressbar").progressbar("value", value + 1);
  
        }
 
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
 
        <div style="width: 30%; margin: 0 auto;">
            <div id="result" style="font-family: Tahoma; font-size: 0.9em; color: darkgray; margin-top: 230px; padding-bottom: 5px">
                Initializing and Preparing...
            </div>
            
            <div id="progressbar" style="width: 300px; height: 15px"></div>
            <br />
        </div>
 
    </form>
 
    
 
</body>
</html></span> 

The above code does starts automatically when DOM loaded and can do the following;   
  • Establishes the persistent connection between the client and the server 
  • Declares a client side function that will be called by the server 
  • Calls the server's method that performs the time consuming operation
  • Updates the JQuery UI ProgressBar  




|

Using PhoneGap in Eclipse for Android



PhoneGap is an open source application platform that enables you to create natively-installed mobile applications using HTML and JavaScript.

This post assumes that you have installed and configured Eclipse for Android application development and have some know how about Android Native Application development. If not then please follow Getting Started Tutorials first and come later to follow this tutorial.

Now you have configured Eclipse and is ready to develop applications using Android platform. Follow the below steps;

1. Create an "Android Application Project" in Eclipse by clicking File > New


2. Follow the steps for creating Android Application and click Finish. So your application look like this




At this point, Eclipse has created an empty Android project. However, it has not yet been configured to use PhoneGap. You'll do that next.

3. Download and extract PhoneGap from here

4. Create an assets/www directory and a libs directory inside of the new Android project. All of the HTML and JavaScript for your PhoneGap application interface will reside within the assets/www folder.

5. To copy the required files for PhoneGap into the project, first locate the directory where you downloaded PhoneGap, and navigate to the lib/android subdirectory and copy the files as follows;
  • Copy cordova-1.5.0.js to the assets/www directory within your Android project.
  • Copy cordova-1.5.0.jar to the libs directory within your Android project.
  • Copy the xml directory into the res directory within your Android project
Your project should look like this



 6. Next, create a file named index.html in the assets/www folder. This file will be used as the main entry point for your PhoneGap application's interface. Let's have a look to index.html file below

<html>
  <head>
  <title>PhoneGap</title>
     <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>
  </head>
  <body>
     <h1>Hello PhoneGap</h1>
  </body>
</html>

7. You will need to add the cordova-1.5.0.jar library to the build path for the Android project. Right-click cordova-1.5.0.jar and select Build Path > Add To Build Path
  
8. Open your main application Activity file. This file will have the same name "MainActivity" by default. It will be located under the src folder in the project package that you specified earlier in this process.

9. In the main Activity class, add an import statement for org.apache.cordova.DroidGap:

import org.apache.cordova.DroidGap;

10. Change the base class from Activity to DroidGap; this is in the class definition following the word extends :

public class MainActivity extends DroidGap {

11. Replace the call to setContentView() with a reference to load the PhoneGap interface from local assets/www/index.html file, which you created earlier

super.loadUrl("file:///android_asset/www/index.html");

your activity should look like this



You have now configured the files within your Android project to use PhoneGap. The last step is to configure the project metadata to enable PhoneGap to run.

12. Begin by opening the AndroidManifest.xml file in your project root. In AndroidManifest.xml, add the following supports-screen XML node as a child of the root manifest node:

<supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:resizable="true" android:anyDensity="true" />

Next, you need to configure permissions for the PhoneGap application.

13. Copy the following <uses-permission> XML nodes and paste them as children of the root <manifest> node in the AndroidManifest.xml file:

<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" />

The <uses-permission> XML values identify the features that you want to be enabled for your application. The lines above enable all permissions required for all features of PhoneGap to function

After you have configured application permissions, you need to modify the existing <activity> node.

14. Locate the <activity> node, which is a child of the <application> XML node. Add the following attribute to the <activity> node:  

android:configChanges="orientation|keyboardHidden" 

15. Next, you need to create a second <activity> node for the org.apache.cordova.DroidGap class. Add the following <activity> node as a sibling of the existing <activity> XML node:

<activity android:name="org.apache.cordova.DroidGap" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> <intent-filter></intent-filter> </activity>

At this point, your project is configured to run as a PhoneGap project for Android. If you run into any issues, verify your configuration against the example provided at the PhoneGap getting started site for Android.

To launch your PhoneGap application in the Android emulator, right-click the project root, and select Run As > Android Application.

   
Congratulations! you have developed your first phonegap application for Android platform.