Will be speaking in three events in April – Join and Learn

Hello All,

In this month (April’13), I’ll be speaking in three events on ASP.NET, WCF, SQL Server 2012. Join these sessions with me and learn the technology you are interested in. Event details are

Simple steps to improve performance of ASP.NET Applications Significantly

This is webcast and you can join from anywhere. Just require a PC and internet connection. Register at the following site and you’ll get the attendee details

http://kolkatageeks.com/WebCast.aspx

Timing details – 07th April 2013, 2-3PM

N-tier architecture using WCF and ASP.NET and ASP.NET MVC

This will offline event and organised by C3 Corner at Noida on 13th April 2013. Please get the details from below link.

Learn WCF With C# Corner

Exciting feature for SQL devs in SQL 2012

This will be a offline event and organized by Delhi User Group and will be taking Place in Microsoft Office Gurgaon on 20th April 2013.

To connect with Delhi User Group (Group), join it on facebook at below link and get updated on all the events organised by DUG and join that interest you.

Connect with Delhi User group

Join with me on these events and you’ll also get to hear other Speakers in these event. Hope you all learn and enjoy.

Thanks,
Brij

Learning ASP.NET Signal R – Part 2

This is second post in the series on ASP.NET SignalR. You can access first post from the following link

Learning ASP.NET SignalR – Part 1

In this post, we’ll examine, How SignalR works on various environments. We’ll try dig it out with the help of an example.

First let me know, when you require real time update your UI?
A chat application?

Right. But it’s not the chat application only, you can use it at many other scenarios like any real time data requirement, collaborative applications, Real time loggers, Real Time dashboards, Games, Stock market, Real time news, Live match feeds etc… and many more.

But for this analysis, we’ll use chat application. And will discuss other scenarios in my next post.

So let’s create an chat sample application.

Let me tell you my environment. I am using VS2012 Pro for this development and my OS is Windows 8.

So to create a simple chat application. Start  File -> New Project-> ASP.NET Empty Web Applications and say name it SignalRChat

Now Tools -> Library Package Manager ->Package Manager Console.

A console will be opened and put the following command

install-package Microsoft.AspNet.SignalR

and Press enter. Wait for few seconds, it will install the SignalR and will download all the required libraries in your project. Add Global.asax in your project and add the following line in your Application_Start() method

RouteTable.Routes.MapHubs();

This is required to add the default hub route and it will be added at Client side. Now lets add a class say named ChatHub which implements Hub Class and it is available under the namespace Microsoft.AspNet.SignalR . Now add a method as

 public void Distribute(string name, string message)
        {
            // Call the broadcastMessage method to update all clients.
            Clients.All.broadcastMessage(name, message);
        }

Now it’s time add an HTML page. Let’s add Chat.htm. On this page add the following scripts and hub class

  <script src="/Scripts/jquery-1.8.2.min.js" ></script>
  <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
  <script src="/signalr/hubs"></script>

Update the the version of the scripts file that is available in your solution. Now add the following javascript code in your HTML file,

  <script type="text/javascript">
         $(function () {
             // Declare a proxy to reference the hub.
             var chat = $.connection.chatHub;
             // Create a function that the hub can call to broadcast messages.
             chat.client.broadcastMessage = function (name, message) {
                 // Html encode display name and message.
                 var encodedName = $('<div />').text(name).html();
                 var encodedMsg = $('<div />').text(message).html();
                 // Add the message to the page.
                 $('#discussion').append('<li><strong>' + encodedName
                     + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
             };
             // Get the user name and store it to prepend to messages.
             $('#displayname').val(prompt('Enter your name:', ''));
             // Set initial focus to message input box.
             $('#message').focus();
             // Start the connection.
             $.connection.hub.start().done(function () {
                 $('#sendmessage').click(function () {
                     // Call the Send method on the hub.
                     chat.server.distribute($('#displayname').val(), $('#message').val());
                     // Clear text box and reset focus for next comment.
                     $('#message').val('').focus();
                 });
             });
         });
    </script>

If you see the above script, first it creates the reference of HUB Class. This is actually, required to perform all the steps. It adds a method which receives the chat message.  It receives the message at run time and update the UI accordingly. And It also adds a event on the send button and call the distribute method on the server to broadcast the message. One thing, you keep in mind that it has a check whether the HUB is started or not. And Click event of Send button will be fired only if HUB is ready or it is ready to accept the request. Also we require to add some HTML Controls. It could be as

  <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion">
        </ul>
    </div>

So now the code is ready to start. Let’s run the code. Now You’ll be prompt to put name and you can open the same URL on some other browser and starts chatting amongst browsers. So your code is running.

So this is a very simple application of Application. So now I’ll try to run the same application in different environment. Current browser is Firefox19 on windows 8. Let’s visit firebug net tab

FF19Chat

Now if you see the the above first red marked encircled area, there is a negotiation request sent to the server to negotiate the protocol that will be used. Again if you see the next encircled area where it is written transport=websockets  and also a connectionToken is there. It means websockets is supported and it is used here.

Now I am going to run the same application on different environment that has OS WinXP SP3 and IE8. So let’s run, now when see this

SignalRChatIE8

Now if you see here red encircled area, here the transport is foreverFrame. And when I ran this it was working as similar as I ran on Win8 and FF19 it was transport=websockets. Here also you can see the page is getting refreshed.

Now I will show it you on another browser on the winXp3 machine

SignalRChatfirefox15

So here if see here the encircled area and here is the transport is serverSentEvents.

You can see here, as I discussed in my first post in this series, that according to the supported technologies appropriate one is selected  based on the order that was pictorially shown and discussed.

So the whole Idea, in this post to explain you that SignalR provides complete abstraction over technology and you need to use the similar simple API to work on it. You don’t need to care about the underneath technologies and environment.

Now in my next post, I’ll discuss various scenarios, where you can use this technology and make best use of it.

So hope, you must have enjoyed this post a lot.

Thanks,
Brij

Learning ASP.NET SignalR – Part 1

Hello All,

Today I am going to discuss one of the new technologies that changed the way we used to think about How the web works. I’ll be writing a series on this technology and this post is first part of it.

You must have been working on the ASP.NET for long or might be since inception. And till date (or till this technology got introduced) , You got to know from every where that Web is stateless. A webpage is recreated every time from scratch it is posted back to server. In traditional web programming, all the information within the page and control gets wiped off on every postback.

I have taken the above lines from one of my post which I had written long back.

The web page used to work on PULL approach means you have to pull the data from the server. It means whenever you want to get some data from server, you require to send some request to server so that it can send the updated data along with the response. Remember, many times we required to update the UI as soon as the data gets updated to the server and then we used some polling method which keeps sending some request to server and checks if the data is updated and if yes, it refreshes the page or you have done something similar. So it works like

StatelessWeb

But things are changing rapidly. Web Sockets introduced in HTML5 provides us a capability to create a full duplex channel over web.

But SignalR provides an abstraction over persistent connection. It makes you tension free about the type of browser and web server versions.It works in a consistent way in all the environment.

SignalR

Although all the latest web browsers supports the new technology WebSockets but this is not the case every time. Some of your user might be still using IE6/IE7 etc and you cannot simply say that I cannot support this. Ultimately this is buyer’s world. So you have to support as per your Client’s requirement and here SignalR wont let you down. So How does SignalR work on all the browsers? It actually checks the browser’s capability and accordingly takes the decision as

Technology Selection

So I think you all must have got an Idea the way SignalR works. but let’s try to dig into it. As you can see in the pic, it starts from top to bottom as if the environment supports Web Sockets else server sent event else forever frame else polling, means it has fall back one step further until your browser supports it.

So in simple words, What is ASP.NET SignalR?

We can say it is Real time – Means updates the web page Real time
Push Approach – Server pushes the data to all the connected Clients.

So let’s see How it works pictorially?

SignalR-Flow

As you can see in the above pic the An event generator generates event and notifies to SignalR hub. Signal R Hub process it and forwards the the message to the appropriate Client(s).

You also can see that Client could be any like any .NET windows, web, console client, WP, Windows store apps, Android etc.  Similarly, event generator could be any Client initiates notification on some logic, database, any other server based on some logic. You can imagine the reach and simplicity of it. And I can assure you that it is very fast as well.

So what are the main components of ASP.NET SignalR?

  •     SignalR – A meta package that brings in SignalR.Server and SignalR.Js
  •     SignalR.Server – Server side components needed to build SignalR endpoints
  •     SignalR.Js – Javascript client for SignalR
  •     SignalR.Client – .NET client for SignalR
  •     SignalR.Ninject – Ninject dependeny resolver for SignalR

You can install SignalR via Nuget. I’ll let you know, How to install it.

First, let me tell you, that to work on it, you need to have either VS 2010 SP1 or VS 2012.

Then you can install SignalR via Nuget Packages using the following command. To install it ,

Open Visual Studio, Go to  Tools-> Library Package Manager -> Package Manager Console.  A console (Named as Package Manager Console) will be opened and run the following command

Install-Package Microsoft.AspNet.SignalR

You can also install the SignalR sample using the following NuGet package..

Install-Package Microsoft.AspNet.SignalR.Sample

Hope you all got have basic Idea about SignalR and the way it works. In my next post, I’ll be discussing one example and show, How does SignalR works on various browsers and environment?

Keep Learning,
Brij

Accessing other domain web services via jQuery Ajax (CORS)

Now a days, most of the web developers are working on mainly Client side programming to make the web more responsive, intuitive and user friendly. So avoiding the code behind, accessing the server via Ajax, passing and getting the data in JSON format, generating the DOM elements at Client side etc becoming very common these days and these all prepared the ground for many Client side libraries to come up and that’s what we are seeing now a days.

One of the most popular Client side library, jQuery, provides a lot of wrapper methods for writing quick and easy Client side code. You guys must have used jQuery ajax to initiate a ajax call and passing data to and fro in JSON format. As you must be knowing that XMLHTTPRequest  is the base for all Client side ajax call. All the Client side libraries provides a wrapper over it for making any AJAX call. So I’ll start with an example

I have created an empty web application and added a web page . I also added a jQuery script file. I created one small web method GetRatingValues at code behind that returns a list of numbers (Gave a name called rating). So let’s see the code and get it running

So my aspx code is like

<form id="form1">
<div><input onclick="GetRatingData()" type="button" value="GetRatings" />
<div id="ratingDetails" style="display: none;">
<h1>Available Rating Values</h1>
<div id="ratingValues"></div>
</div>
</div>
</form>

And my javascript code is like

<script type="text/javascript" language="javascript">// <![CDATA[
        function GetRatingData() {
            GetRatingValues();
        }
        function AjaxSucceeded(result) {
            $("#ratingDetails").show();
            $("#ratingValues").html(result.d);
        }
        function AjaxFailed(result) {
            alert('Failed to load');
        }

        function GetRatingValues() {
            $.ajax({
                type: "Post",
                url: "First.aspx/GetRatingValues",
                contentType: "application/json; charset=utf-8",
                data: '',
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }

// ]]></script>

And my web method at code behind is as

 [WebMethod()]
    public static string GetRatingValues()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        IList ratingList = new List() { "5", "4", "3", "2", "1" };
        string str = ser.Serialize(ratingList);
        return str;
    }

Now if you run the code and Click on the button. It’ll run perfectly fine and page will be displayed as

SamedomainAjaxCall

Now let’s have another scenario. I have added a simple HTML page (Test.html) in my solution and I have added the following script on my aspx page

 function GetHTML() {
            $.ajax({
                type: "GET",
                url: "Test.html",
                success: ShowHTML,
                error: AjaxFailed
            });
        }
        function ShowHTML(data) { alert(data); }
        function AjaxFailed(result) {
            alert('Failed to load');
        }

Now if you run this code. It’ll display the html content of the page. I ran it and it displayed as expected

GetAjaxHTML

Let’s also see the HTTP Headers that I have taken via firebug

HTTP Headers

GetRequest1

Also let’s see the response of the URL

Response

If you see the encircled area in both the above picture they are pointing to localhost.

If you see the URL in both AJAX call they are pointing to same domain. But have you ever tried to initiate an jQuery AJAX call to some other domain .

What I have done here, I am running my application from IIS and I added a domain for Testing (localtest.me) in IIS. So I changed the URL in my AJAX call as

OtherDomainNewBut now if you try to run this code, it would not run. Because now the URL targeting to other domain. Let’s see again the HTTP Headers and response.

GetRequestOther

Let’s see the Response

GetResponseOtherDomainNow if you see here in the above picture the encircled area, both are different and pointing to different domain and didn’t get any result.

But why?

As I already described that every AJAX request is built on XMLHTTPRequest object and XMLHTTPRequest has some security limitation. It follows same-origin policy, it means that any HTTP request using XMLHTTPRequest initiated by a web application, can be processed only if it loaded from same domain/origin. If it requests to any other domain it will not be successful.

But as now we make lots AJAX call and some times to third party web services, it becomes hurdle to our development. To overcome this issue W3C has come up with feature called Cross-Origin Resource Sharing (CORS) which enables cross site data transfer without compromising security. To use this , we require to add few new HTTP headers that allows to add set of other origins/domains and the content type that is required to transfer.

Also let’s understand what is meant by other domain/origin?

If I have a domains like mydomain.com and mydoman1.com so as it is clear from seeing that these are different domain. Similarly subdomains like abc.mydomain.com and xyz.mydomain.com are also considered as from different origin/domain. Also at certain times the url also contains port number so if the port number is different, it also be treated as from different origin.

So as a thumb rule, you can say if the portion of URL before first single slash is different, it would be considered as from different origin and same origin policy would not be applied.

So now, let’s again back to our example. To run our example, we need to add these custom headers.  ASP.NET provides a way to add these new headers by adding some config entry. so I added the following in my web.config

GetConfig

Now if we run the code it runs successfully. Let’s analyse again the HTTP Headers and Response.

GetrequestOtherSuccess

And the Response

GetresponseOtherSuccess

Now if you see the dark encircled area, they are pointing to different domain and yet got the response. But the successful result caused by the thin encircled area in header pic, which is a new header got added. And we made this entry in web.config

But what would happen if I change the URL that I used in my first sample as

 function GetRatingValues() {
            $.ajax({
                type: "Post",
                url: "http://localtest.me/TestCORS/First.aspx/GetRatingValues",
                contentType: "application/json; charset=utf-8",
                data: '',
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }

And if you run it again, It would not run. because in my last example, I was using Get Request. For Post (type: “Post”)request I can  transfer some data back and forth to server. So here I need to define one more entry in web.config that will add another header in the request as

Postheader ConfigNow after adding it, if you run the code then it’ll run like a charm.

One more point, I’ll make a here that providing * for Access-Control-Allow-Origin is not a good Idea, because it allows to access any other domain URL so it’s if you specify the particular domains here.

Hope you all have enjoyed this post. Do share your feedback.

Thanks,
Brij

Authentication and Session timeout – Session expired message on clicking the login button

In my starting phase of Career, My client reported me a peculiar issue. They said that they get redirected to session expired page even before they actually Login.

In that application, We developed a generic methodology, then whenever a user clicks on any action that requires a post back, it first checks whether session is expired or not and if expired then redirects to a custom session expired page. Later, user can click on login link and redirected to Login page.

[As asked by one of my blog readers, There could be many ways for the generic methodology. I have seen people place common code at several place like Master Page,  some put in base class that further worked as base class for all the web pages. I used it in a base class. In my view there are other places like Global.asax and methods could be Application_PreRequestHandlerExecute, Application_AcquireRequestState .]

I analyzed that Issue and found that users used to open the website first page which is obviously the Login page and some of them left the page for a while around 15 or more minutes and after that they when they again back to system, used to enter the credentials and click on login button, it redirects them to session expired page.

It left them annoying and even me too. I have myself seen to many application where I open the Login page and after sometime when I enter my Login details but it redirects me to session expired page.

Some of my colleagues was saying, how a session can expire even before successfully login. I have also found many other developers have same question. So I thought of writing a blog post on it.

So first let me explain, how session works

Session_Life_Cycle

So as you can see above, as soon as user accesses the site and the first page gets opened, the countdown of the session timeout starts. So it does not matter whether you Login or not, session will be expired after the specified amount of time. So if your website does not have a check on session expiration before Login then it wont be visible to your user and even if user Logins after the specified amount of time, A new session will be created.

But so many people get confused about authentication and session. Session start and expire does not have any connection with authentication start and authentication timeout. Authentication works separately.

As you know, A user request any Page, It goes through many HTTPModules and lastly served by a HTTPHandler. We can show it pictorially as

ASP.NET Request Proessing

As you can see, An asp.net request goes through many HTTPModules and finally served by a HTTPHandler. Many features of ASP.NET are developed as HTTP Module. Session and Authentication are also developed as HTTPModules . For session handling we have SessionStateModule which is available under the namespace System.Web.SessionState and various Authentication mechanism in ASP.NET like Form Authentication is also available via a HTTPModule FormsAuthenticationModule which is under the namespace System.Web.Security.  So these two are separate modules and works independently.

Normally in our application, as soon as user clicks on sign out, we used to kill session. Normally, we set authentication time out and session timeout same but what may happen if we have

<forms timeout="15" loginUrl="Login.aspx" name=".ASPXFORMSAUTH">

and

<sessionState timeout="10">

What could happen

user's browsing history

As you can see in the above scenario, I have set session time out is less than authentication timeout. After browsing for 5 mins, I left it for around 12 mins and my session got timeout.  As my session time out is 10 mins while my authentication time out is 15 mins. But I’ll be still authenticated and able to browse application even my session expired and got recreated and my existing session data will be lost.

So normally we put the authentication time out and same time out as same. This is just first step to avoid the discrepancy between the timeout of Authentication and Session.

But at certain browsers, it behaves differently. Like Session gets time out if the last request made was 10 (in my example session timeout is 10 minutes) or more minutes and on every request the counter get resets for 10 minutes but Authentication timeout does not work in same ways in different browsers. Like if have authentication timeout for 10 minutes, the authentication timeout counter does not get reset on every request to 10 minutes. Sometimes there are some performance improvement has been done which resets on the counter only at certain points say if after 5 or 7 minutes as to reset the authentication timeout on very request is costly. And this may lead to discrepancy.

Other scenario, If some how IIS gets reset the sessions of the users connected to that web server will become invalid while the user authentication will still be valid.

To avoid any unprecedented event like above, I put a check for an authentication and session on every page, So that user cannot continue further if session or authentication is not valid. Also if we found user is not authenticated any more then used to clear and abandon the session and redirects the user to login page. Similarly, if session is not available then the remove the user the authentication as well.

Also, at the time of user clicking on Logoff, one should clear and abandon the session. So that same session is not available after Logoff.

So as you can see, that session and authentication works separately and they work parallely and independently.

So for the problem stated earlier in this post, I suggested a solution to avoid the issue but you can yourself can put your own logic to prevent the issue.

Hope you all have enjoyed this post. Please share your valuable feedback.

Cheers,
Brij

How to access the input control’s data at Server side during Client Callback : A useful trick

Client callback is one way to update the webpage without performing the full page postback. It maintains the Client state while updating the Webpage. During Client callback the webpage runs through modifies version of Page Life Cycle.

The LifeCycle of a page in Client Call Back is  as

Page Lifecycle iin Callback

If you want to learn  more about Client Callback, click here.

But the main drawback of  Client Callback, The input data is not posted from Client to Server. Also,  It does not maintain the view state during partial postback as you can see the Page life cycle of Client callbak it is not saved or SaveViewState event is not fired.

Lets see it with an example.

I have created a simple form to collect some information of an person data. And it has a submit button, which initiates a Callback. As

 <table>
 <tr><td><asp:Label id="lblFName" runat="server" Text="First Name" /> </td>
 <td><asp:TextBox ID="tbFName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMName" runat="server" Text="Middile Name" /> </td>
 <td><asp:TextBox ID="tbMName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblLName" runat="server" Text="Last Name" /></td><td><asp:TextBox ID="tbLName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblAge" runat="server" Text="Age" /></td><td><asp:TextBox ID="tbAge" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMailId" runat="server" Text="Email" /></td><td><asp:TextBox ID="tbEMail" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblSex" runat="server" Text="Sex" /></td><td><asp:TextBox ID="tbSex" runat="server"></asp:TextBox></td></tr><tr>
 <td colspan="2"><input id="btnCallBack" type="button" value="Submit" onclick="InitiateCallBack();"/></td></tr>
</table>

Server side code is as

public partial class Callback : System.Web.UI.Page,ICallbackEventHandler
{
    string result;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsCallback)
            return;
        //Creating a reference of Client side Method, that is called after callback on server
        String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
            "ReceiveServerData", "");

        //Putting the reference in the method that will initiate Callback
        String callbackScript = "function CallServer(arg, context) {" +
            cbReference + "; }";

        //Registering the method
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);
    }
    public void RaiseCallbackEvent(String eventArgument)
    {
        string firstName = tbFName.Text;
        //Read other data as well

    }
    public string GetCallbackResult()
    {
        return result;
    }
}

And the client side method is

function InitiateCallBack() {
     //Intiate the callback
     CallServer("",'');
}

// Called after the server side processing is done
function ReceiveServerData(arg, context) {
    //arg: hold the result
    //Updating the UI
    document.getElementById('divCallbacl').innerHTML = arg;
}

After filling this form, I submitted it. Now if you try to access the entered using control’s property, you would not get it.

Let’s dig it more and check the form collection, whether the data is passed from Client to server or not

So as you can see that the data is not passed in form collection

But let’s put the following lines of code in java-script, just before initiating the call for Callback as

 function InitiateCallBack() {
	__theFormPostCollection.length = 0;
        __theFormPostData = "";
        WebForm_InitCallback();

        //Intiate the callback
        CallServer("",'');
}

Now let’s run the code and submit the form as earlier.

Now let’s check the form collection.

What a surprise, we got all the input data in form collection. That’s nice.

Now access the data using control’s property.

and you got it.

Now let’s try to see, what does the extra lines of code does

//This Clear the earlier the old data in form collection.
__theFormPostCollection.length = 0;
//It sets the forms data to empty
__theFormPostData = "";
//This method builds the body of the POST request when the page loads. The body of the page is a string 
//(that is __theFormPostData) filled with the contents 
of the view state and all of the input fields in the form.
WebForm_InitCallback();

But I would suggest to use these line at caution. Use only when you need to collect the update from Page during Callback. If you don’t need to get some data or it is in readonly page, don’t use it it introduce extra overhead to your page and costs at performance point of view.

Hope you  all have enjoyed the post.

Page.ClientScript.RegisterStartupScript is not working : A Solution

This is going to be a very short post but will be useful many developers.

You have registered some JavaScript block from server side. But it’s not working. Actually it’s not getting rendered on Client side when you see the PageSource. But the same code works in different projects/applications/pages. Say you have code like this

           Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowStatus", "javascript:alert('Record is not updated');", true);
 

It is registering one one startup script that will be fired when the page will be loaded.
Say you have used at several time and it was working but now it is failing.  Similarly Page.ClientScript provide many other methods that will also not work.

One of the main reasons is, We start using Ajax on our pages. Ajax requires a ScriptManager to handle all the ajax related (Partial postback) tasks. Ajax requires lots of JavaScript code that is managed by the ScriptManager. And it must be noted on a single page only one instance of ScriptManager is allowed.

So whenever we have an instance of  ScriptManager on our page, we need to register the Script using ScriptManager. So you need to change the code like this

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowStatus", "javascript:alert('Record is not updated');", true);

       

Now this code make the script start working. Similarly , we also need to change other Page.ClientScript methods to appropriate ScriptManager method.

Cheers,

Brij

IsCrossPagePostBack : Cross page PostBack

Download sample from here

Last few days, I was working on one of my module in my web application. During writing code, I came accorss one property IsCrassPagePostBack of Page Class. I have seen this earlier but never tried to dig. So I thought of exploring it and here I am sharing my findings with you all.

First, Let’s start from beginning. We know when we submit a page, entire form data with hidden fields, including view state is posted to the server. One must be using IsPostBack property a lot. It is false when page loaded first time but returns true if any postback takes place. Whenever we click any server side control like button, linkbuttons etc or any other control with autopostback true. All the data including hidden field, View State etc.. is posted to the server and available for processing at codebehind. Continue reading…

ASP.NET: Asynchronous Programming

Click here to download the sample code

Introduction:

Have you ever tried using Async pages in asp.net? Did you ever explore it in
respect of ASP.NET?

If No. This is the article for you. In this, I will be discussing, what is Async
programming? what are the benefits? Async in respect of ASP.NET and its uses
and lots more.

Async programming:

In a literal meaning, Asynchronous operation means that a process operates independently of other processes. If there are multiple operations, All that can be handled different processes/thread without waiting to complete the other ones. So here in coming sections, we will be discussing, how Asynchronous programming comes into the picture in ASP.NET.

Async Programming in ASP.NET:

Normally the kind of websites that we make are not scalable enough that could have been. These websites are very limited and confined. ASP.NET provides us a way to develop our websites more scalable. Continue reading…

Invalid View State error While expanding your Web Farm

Last few days back, I faced one peculiar issue, while adding a new system in my Web Farm. My users started facing an issue “InValid View State” intermittently.

First, I could not guess what is the issue and thought of some programming issue. But later after analysis I found the issue is caused by the changes in the Web Farm.

Just before discuss the solution, Let’s analyse this.

First,  What is Web Farm?

A Web Farm is used in highly available applications and which have a lot of users that cannot be served by a single server. They provides better performance and are easily scalable. It means we’ll have multiple web servers behind a Network Load Balancer (NLB). Whenever a request comes, it first goes to the load balancer, which checks all the available web servers and finds the web server which has comparatively less requests to serve, and passes the request to that web server. Continue reading…

Follow

Get every new post delivered to your Inbox.

Join 85 other followers