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.

6

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)

1

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

2

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

3

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

4

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

5

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)
    {
        Response.Redirect("Progress.aspx?message=hai");
    }

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
{
    [HubName("social")]
    public class Social : Hub
    {

        public void postStatus(string message)
        {

           
            Caller.updateGaugeBar(10);
            Caller.displayMessage(String.Format("Posted to: {0} ...", "Facebook.com"));
            Thread.Sleep(2000);

            
            Caller.updateGaugeBar(40);
            Caller.displayMessage(String.Format("Posted to:: {0} ...", "googleplus.com"));
            Thread.Sleep(3000);

            
            Caller.updateGaugeBar(64);
            Caller.displayMessage(String.Format("Posted to:: {0} ...", "Twitter.com"));
            Thread.Sleep(2000);

            Caller.updateGaugeBar(77);
            Caller.displayMessage(String.Format("Posted to:: {0} ...", "Diggit.com"));
            Thread.Sleep(2000);

            Caller.updateGaugeBar(92);
            Caller.displayMessage(String.Format("Posted to:: {0} ...", "blogger.com"));
            Thread.Sleep(2000);

            Caller.displayMessage(String.Format("Processing Result"));
            Caller.updateGaugeBar(100);
            Thread.Sleep(2000);
            
            Caller.redirectMe("Result.aspx");
        }


    }
}

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">
    <title></title>
    <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) {
            $("#msg").html(message);
        };

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

        proxy.updateGaugeBar = function (perc) {
            $("#bar").progressbar({value:perc})
        };

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

        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];
                }
            }
        }


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

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

 $('div').attr(
                    {
                        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.

$('#OutOutDiv').remove();

8. addClass,hasClass,removeClass,JSON map Css

 $('#OutPutDiv').css({
                'background-color': 'Navy',
                'color':'White'
            });

            $('#TestDiv').addClass('HighLight');
            $('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
        });
    </script>

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
alert(divs.length);

3. Iterate through all div

 $('div').each(function () {
                alert($(this).html());
            });

4. Get all div and span elements

 var divspans = $('div,span');
 alert(divspans.length);

5.Get Div by id

alert($('#TestDiv').html());

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]');
alert(divTtile.length());

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

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

10. Get all input tag

var inputs = $(':input');
alert($(inputs[2]).val());


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];
        }
    }
}

</script>

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.

1.

Get-CacheHost

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
command.

2.

Start-CacheHost

Now issue

3.

Start-CacheCluster

Now give permission for all client accounts by

4.

Grant-CacheAllowedClientAccount everyone

Do a restart

5.

Restart-CacheCluster

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.

6.

Set-CacheClusterSecurity -ProtectionLevel None -SecurityMode None

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

7.

<dataCacheClient>
    <hosts>
        ...
    </hosts>

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

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.

<advancedProperties>      
    <transportProperties maxBufferSize="8388608" />
</advancedProperties> 

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

Stop-CacheCluster 
Import-CacheClusterConfig -File [yourfilepath]
Start-CacheCluster

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

<dataCacheClient>
    <hosts>
        ...
    </hosts>

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

The full Cache Server config.

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

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

The full web config

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <configSections>
    <section name="dataCacheClient" 

type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,Microsoft.ApplicationServer.Caching.Core, 

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

validationKey='AFD1EF00AB1FDE92459609D9322D97D5B47627B331FC4600248ADD5CBF2454641010B0A12EB87A2E00B39E07575132374B1486A4471E0

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

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

PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, Culture=neutral, 

PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>
    <httpRuntime />
 <customErrors mode="Off"/>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

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.

load

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.

1

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

2

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.

3

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

4

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

8

6. Give name and settings as shown below.

9

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.

5

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.

6

4. Select none for availability set.

7

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.

10

6. Give the endpoint settings as given below.

11

Now verify endpoints in Machine1 and Machine2

Machine1

14

Machine2

12

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