A day with .Net

My day to day experince in .net

Archive for December, 2012

Real-time progress bar using JQuery UI and SignalR

Posted by vivekcek on December 26, 2012

So your web application do some long running process, like calling some 10 web services and consolidate information and display to user.In such scenarios it is a best practice to show a progress bar to the user, that display how much processing is finished or how much percentage completed.

Why SignalR?

SignalR can be used to avoid continuous polling to the server by client to know about the status of work.
SignalR can initiate call from the server to client after some operation is finished.

Other things you can learn from this post

1. Call SignalR hub method on page load
2. Redirect to another page from SignalR hub method.
3. Access the query string through java-script.

Example Idea

An application that post a status update to social medias like Facebook,twitter etc through single window.


Quick to code

1. I recommend Visual Studio 2012, because the web site template project include jquery and jquery ui pre installed.

2. Create a new website (not web application project)


3. Use Nuget Package Manager and install SignalR as shown below


4. Install Json2.js using Nuget as shown below.


5. Check the script folder and ensure all script files shown in below picture are present.


6. Ensure CSS for Jquery Ui is present in Content folder.


7. Create 3 WebForm’s Default.aspx, Progress.aspx and Result.aspx

8. In Default.aspx add a button. In the click event add below code.

 protected void Button1_Click(object sender, EventArgs e)

9. In App_Code folder add a class named Social. This class perform a virtual log running process. This class contain a hub method named ‘postStatus(string message)’.We will call this method in the Progress.aspx page load.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using SignalR;
using SignalR.Hubs;
/// <summary>
/// Summary description for Server
/// </summary>
namespace SignalR
    public class Social : Hub

        public void postStatus(string message)

            Caller.displayMessage(String.Format("Posted to: {0} ...", "Facebook.com"));

            Caller.displayMessage(String.Format("Posted to:: {0} ...", "googleplus.com"));

            Caller.displayMessage(String.Format("Posted to:: {0} ...", "Twitter.com"));

            Caller.displayMessage(String.Format("Posted to:: {0} ...", "Diggit.com"));

            Caller.displayMessage(String.Format("Posted to:: {0} ...", "blogger.com"));

            Caller.displayMessage(String.Format("Processing Result"));


10. Add the below code in HTML of Progress.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Progress.aspx.cs" Inherits="Progress" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link href="Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <script src="Scripts/json2.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.3.js" type="text/javascript"></script>
    <script type="text/javascript" src='<%= ResolveClientUrl("~/signalr/hubs") %>'></script>

    <script type="text/javascript">

        var proxy = $.connection.social;
        proxy.displayMessage = function (message) {

        proxy.redirectMe = function (target) {
            var url = target;
            location.href = '<%= Page.ResolveUrl("'+url+'") %>';

        proxy.updateGaugeBar = function (perc) {

        $.connection.hub.start().done(function () {
            var msg = querySt("message");

        function querySt(Key) {
            var url = window.location.href;
            KeysValues = url.split(/[\?&]+/);
            for (i = 0; i < KeysValues.length; i++) {
                KeyValue = KeysValues[i].split("=");
                if (KeyValue[0] == Key) {
                    return KeyValue[1];

    <form id="form1" runat="server">
            <b>Status:</b>&nbsp;&nbsp;&nbsp;<span id="msg"></span>
        <div id="bar"></div>

Posted in SignalR | Tagged: , , , | Leave a Comment »

Jquery Reference Part2

Posted by vivekcek on December 25, 2012

1. Each function in jquery.

The below function take all the div’s with specified classes and iterate through them.

$('div.BlueDiv,div.RedDiv').each(function (index) {
alert(index + '=' + $(this).text());

2. Modify attribute of a div by raw DOM object and Jquery wrapped object.

$('div').each(function (i) {
this.title = "hai"; //raw dom object not jquery object so no intellisense
$(this).attr('title', 'title2'); //jquery objcet wrpped with $ with intellisense

3. Set font size of all div.

 $('div').css('font-size', '20px'); //automatic iteration

4. JSON Map and Chaining with jquery

                        title: 'titile 4',
                        style: 'font-size:40px;background-color:yellow'  //JSON MAP
            .css('color', 'Red'); //Chaining

5.Append table to a div.

$('#OutPutDiv').append('<table><tr><td style="font-size:50px">AppendChild</td></tr></table>');

6. wrap a div.

$('#OutOutDiv').wrap('<div style="font-size:40px"></div>'); //wraps outputdiv inside wrap

7. Remove div.


8. addClass,hasClass,removeClass,JSON map Css

                'background-color': 'Navy',

            $('div').removeClass('class1 class2');
            if ($('#TestDiv').hasClass('HighLight'))

Posted in Jquery | Leave a Comment »

Jquery Reference Part1

Posted by vivekcek on December 25, 2012

1. How to start with jquery?

Download the latest jquery file and save it in folder. Refer this file by

<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>

Now add a script tag with document.ready() function.

<script type="text/javascript">
        $(document).ready(function () {
            //code here

document.ready() function executed when the DOM is ready. Fire before the images are loaded

2. Select all div using jquery.

var divs = $('div');//by tag name

3. Iterate through all div

 $('div').each(function () {

4. Get all div and span elements

 var divspans = $('div,span');

5.Get Div by id


6. Get div by css class

var divclss = $('.BlueDiv');
var divclss = $('div.BlueDiv'); //fast

7. Change css

$('.BlueDiv').css('border', '2px solid red');

8. Get all div with a title attribute

var divTtile = $('div[title]');

9. Get all dive with title attribute value ‘test’

var divWithTitle = $('div[title="test"'); //case sensitive

10. Get all input tag

var inputs = $(':input');

11. Table row coloring with jquery

 $('tr:odd').css('background-color', 'Green');
 $('tr:even').css('background-color', 'Red');
 //speacial effect to first child
 $('tr:first-child').css('background-color', 'Navy');
 //table id given
 $('#mytable tr:odd').css('background-color', 'Yellow');

12. Start with, end with, contains

alert($('div[title$="india"').html()); //ends with
alert($('div[title^="india"').html()); //start with
alert($('div[title*="india"').html()); //some where contains with

Posted in Jquery | Leave a Comment »

Access Query string in javascript functions-SignalR tips

Posted by vivekcek on December 19, 2012

Try this Tip.

 <script type="text/javascript">

function querySt(Key) {
    var url = window.location.href;
    KeysValues = url.split(/[\?&]+/);
    for (i = 0; i < KeysValues.length; i++) {
            KeyValue= KeysValues[i].split("=");
            if (KeyValue[0] == Key) {
                return KeyValue[1];


Now access by

var value = querySt("name");

Posted in javascript | Leave a Comment »

Configure AppFabric Server for Session State using power shell

Posted by vivekcek on December 17, 2012

In this post i am going to tell you about some problems you may experience when using AppFabric server as your caching state provider. Please note that i am using AppFabric 1.0 (WindowsServerAppFabricSetup_x86_6.1/x64). The commands for 1.1 version may be different.

So first of all you must download and install AppFabric 1.0. Refer my old blog.Install Windows Server AppFabric Caching

After successful installation go to Cache Administration Power Shell. Issue the following commands. You must run the power shell in Administrator mode.Also i hope you have only one cache host in your cluster.



The above command shows the status of the cache host.The cache host may be DOWN or UP.If host is DOWN issue the below



Now issue



Now give permission for all client accounts by


Grant-CacheAllowedClientAccount everyone

Do a restart



Disable Security for session State Provider

This step is very important. In this step you will disable security mode in cache server through power shell.Use the below

command for that.


Set-CacheClusterSecurity -ProtectionLevel None -SecurityMode None

Now you need to specify this in your web config file of asp.net application as below.



    <securityProperties mode="None" protectionLevel="None" />

some time you may experience the below error

ErrorCode :SubStatus:The connection was terminated, possibly due to server or network problems or serialized Object size is greater than MaxBufferSize on server. Result of the request is unknown.

To handle this we have to change the configuration in server side and clients web.config.

1. In power shell export the server configuration to a directory by using the below command

Export-CacheClusterConfig -File [yourfilepath] 

2. Open the file using notepad and add the blow tag and save the file.

    <transportProperties maxBufferSize="8388608" />

3. Now stop the cluster.Import the saved config file and restart cluster.

Import-CacheClusterConfig -File [yourfilepath]

4. In the web.config of client add the below.


    <securityProperties mode="None" protectionLevel="None" />
<transportProperties connectionBufferSize="131072" maxBufferPoolSize="268435456" 
                       maxBufferSize="8388608" maxOutputDelay="2" channelInitializationTimeout="60000" 

The full Cache Server config.

<?xml version="1.0" encoding="utf-8"?>
        <section name="dataCache" type="Microsoft.ApplicationServer.Caching.DataCacheSection, 

Microsoft.ApplicationServer.Caching.Core, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <dataCache size="Small">
            <cache consistency="StrongConsistency" name="default">
                    <eviction type="Lru" />
                    <expiration defaultTTL="10" isExpirable="true" />
            <host replicationPort="22236" arbitrationPort="22235" clusterPort="22234"
                hostId="1326169401" size="895" leadHost="true" account="MACHINE1\Administrator"
                cacheHostName="AppFabricCachingService" name="Machine1" cachePort="22233" />
            <securityProperties mode="None" protectionLevel="None">
                    <allow users="everyone" />
                    <allow users="IIS_IUSRS" />
                    <allow users="Administrator" />
                    <allow users="NETWORKSERVICE" />
                    <allow users="MACHINE2\Administrator" />

The full web config

<?xml version="1.0"?>

  For more information on how to configure your ASP.NET application, please visit

    <section name="dataCacheClient" 


Version=,Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowLocation="true" allowDefinition="Everywhere"/>
    <localCache isEnabled="true" sync="TimeoutBased" objectCount="1000" ttlValue="600"/>
     <host name="Machine1" cachePort="22233"/>
<securityProperties mode="None" protectionLevel="None" />
<transportProperties connectionBufferSize="131072" maxBufferPoolSize="268435456" 
                       maxBufferSize="8388608" maxOutputDelay="2" channelInitializationTimeout="60000" 


6E37C9740DD97EDE3D3'   decryptionKey='B32BDECF54ADED4DE7106A42A78B6E1358A9AE9212D512C6'   validation='SHA1'/>
    <sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
        <add name="AppFabricCacheSessionStoreProvider" 

type="Microsoft.ApplicationServer.Caching.DataCacheSessionStoreProvider" cacheName="default" sharedId="MvcApplication"/>
        <add assembly="Microsoft.ApplicationServer.Caching.Client, Version=, Culture=neutral, 

        <add assembly="Microsoft.ApplicationServer.Caching.Core, Version=, Culture=neutral, 

    <httpRuntime />
 <customErrors mode="Off"/>
    <modules runAllManagedModulesForAllRequests="true"/>

Posted in Windows Server AppFabric Caching | Tagged: , , , | Leave a Comment »

Load balance virtual machines in azure

Posted by vivekcek on December 16, 2012

The new IasS (Infrastructure as a service) facility in windows azure helps us to create virtual machines in azure cloud platform. We can install additional software’s to these virtual machines. We can create a server farm by networking these virtual machines. So we have a lot of control than the PaaS (Platform as a service) feature of azure cloud.

So in this post I am going to explain how to create 2 virtual machine, network them and configure load balancing. My final aim is to host an asp.net application in these 2 machines.


If you don’t know how to create virtual machines in azure read my old blog post. Create a virtual machine in azure and host an asp.net web site.

Setup Machine1

1. Select Windows Server 2012 from gallery.


2. Provide machine name and password. This password is used to login to your virtual machine through remote desktop.


3. Provide a DNS name. This DNS name is used to access the web site hosted in that virtual machine. We create a Standalone virtual machine.


4. We don’t want to create an availability set. So select none.


5. It will take some time to create a virtual machine. After that you have to add a TCP endpoint to this machine.


6. Give name and settings as shown below.


7. So all settings for the first machine over now.

Setup Machine2

1. Select Windows Server 2012 from gallery. Use the same VHD used for Machine1.

2. Provide machine name and password.


3. This time we are not going to create a standalone machine. We want to connect our Machine2 to Machine1.So select connect to existing virtual machine.


4. Select none for availability set.


5. After the Machine2 is created we need to configure endpoint for that machine. This time we create a load balance endpoint that connected to endpoint of first machine.


6. Give the endpoint settings as given below.


Now verify endpoints in Machine1 and Machine2





Posted in Azure | Tagged: , , | Leave a Comment »