Monday, August 30, 2010

Url Rewriting Made Easy - Article 2

Before I explain what is URL Rewriting and how simple it is to go for, kindly ready my previous article on same topic i.e. Url Rewriting Made Easy - Article 1, in this article I have explained some basics about URL Rewriting.
The very obvious question rises is, why should you go for URL Rewriting?
Why Should I go For rewriting URL?
  • Short URLs
  • easy to type & easy to remember URLs
  • Site Structure is Visible through URLs
  • URLs are precise and which won't change
  • URLs WHICH MAKE SENSE for End USER as well as for SEO purpose
Now if we look at above points as a web developer then we are very sure that these all things prone to change, we need to pass parameters and change directory structure of the web application. If the web application is very huge then managing above things is a headache.
Lets discuss the case of online shopping; "As a developer for e-commerce application or for online super market projects"; as per above bullet points we need separate URL for followings
  • Every Product should be identified separately
  • Category as well as subcategory should have separate identity
  • Price Range wise
  • Miscellaneous
  • Etc...
Basically one should be able to maintain and manage URLs as per requirement and need.
Now there is a trick, we have to show one URL on browser and internally use different url. Yes we are showing something which is readable and easy; which satisfies all bullet points listed above, but internally we can manage our logic our way rather in traditional way... 
e.g. we are displaying url say "http://www.mysite.com/product1" and we can internally use url "http://www.mysite.com/default.aspx?category=product1" its quite logical.Now the ultimate question arises is how to achieve this? So lets start building the logic. Check out following diagram, it is a logical flow of URL Rewrite operation.


So the very important thing we need to rewrite url is HTTP handlers, but before developing this handler we need to decide what URLs we should build for web application. For this Demo Code we will develop URLs which will be either Datewise as well as Product Namewise or show all products. Lets Consider we have following URLs which internally redirects to Default.aspx page with query string.
  • http://www.yoursite.com/PRODUCTS.aspx
  • http://www.yoursite.com/2010.aspx
  • http://www.yoursite.com/2010/08.aspx
  • http://www.yoursite.com/2010/08/24.aspx
Above links will be internally redirect to Default page in respective order as
  • http://www.yoursite.com/default.aspx?products=allproducts
  • http://www.yoursite.com/dafault.aspx?year=2010
  • http://www.yoursite.com/dafault.aspx?year=2010&month=08
  • http://www.yoursite.com/default.aspx?date=2010-08-24
So Rewriting of URL gives us flexibility of having different URLs for different kind of query string, in above example we have four different URLs pointing toward same page. I think this is the beautiful part, search engines see four different, readable URLs but we can handle data in traditional way. (For easy Reference check out DemoCode)
This URL module is same as Article 1 but RewriteModule.cs file is added. Function of PostBack.Browsers is similar i.e. to maintain URL during postbacks.
Now we will develope Code for RewriteModule.cs, this class file implement IHttpModule interface, whose code is as below.
namespace Rewrite
{
    public class RewriteModule : IHttpModule
    {
        public RewriteModule()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region IHttpModule Members

        public void Dispose()
        {
            //  throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            //   throw new NotImplementedException();
            context.BeginRequest += new EventHandler(RewriteModule_BeginRequest);

        }

        void RewriteModule_BeginRequest(object sender, EventArgs e)
        {
            // throw new NotImplementedException();
            HttpContext context = ((HttpApplication)sender).Context;
            string path = context.Request.Path.ToUpperInvariant();
            string url = context.Request.RawUrl.ToUpperInvariant();

            path = path.Replace(".ASPX.CS", "");
            url = url.Replace(".ASPX.CS", "");

            if (url.Contains("/PRODUCTS/"))
            {
                RewriteProduct(context);
            }
            else RewriteDefault(context);
        }

        #endregion

        private static readonly Regex YEAR = new Regex("/([0-9][0-9][0-9][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        private static readonly Regex YEAR_MONTH = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        private static readonly Regex YEAR_MONTH_DAY = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])/([0-3][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compled);

        private void RewriteDefault(HttpContext context)
        {
            string url = context.Request.RawUrl;

            if (YEAR_MONTH_DAY.IsMatch(url))
            {
                Match match = YEAR_MONTH_DAY.Match(url);
                string year = match.Groups[1].Value;
                string month = match.Groups[2].Value;
                string day = match.Groups[3].Value;
                string date = year + "-" + month + "-" + day;
                context.RewritePath(@"~/default.aspx?date=" + date, false);
            }
            else if (YEAR_MONTH.IsMatch(url))
            {
                Match match = YEAR_MONTH.Match(url);
                string year = match.Groups[1].Value;
                string month = match.Groups[2].Value;
                string path = string.Format("default.aspx?year={0}&month={1}", year, month);
                context.RewritePath(@"~/" + path, false);
            }
            else if (YEAR.IsMatch(url))
            {
                Match match = YEAR.Match(url);
                string year = match.Groups[1].Value;
                string path = string.Format("default.aspx?year={0}", year);
                context.RewritePath(@"~/" + path, false);
            }
            else
            {
                context.RewritePath(url.Replace("Default.aspx", "default.aspx")); 
            }

        }

        private void RewriteProduct(HttpContext context)
        {
            string path = "default.aspx?products=allproducts";
            context.RewritePath(@"~/" + path, false);
        }
    }
}
Lets understand this code first. We have divided logic in two functions, one handles Dates using Regular Expression and other simple handles Product category. i.e. RewriteDefault and RewriteProduct functions. Both functions can be static. To rewrite URL we are using context.RewritePath function, and we have added one eventHandler for context.BeginRequest; i.e.RewriteModule_BeginRequest. Here I assume that the reader is aware about implementation of HTTPMODULE.
After this we will develop index.aspx page, which looks like following
HTML side of Index.aspx is as below
Please Refer HTML of index.aspx, due to limitation of HTML rendering and Blogger compatibility I am not able to display code here. (Please refer html of index.aspx, check demo code.)
index.aspx page uses four URLs discussed above and redirects it self Default.aspx. Now HTML of Default.aspx and Code Behind are as below
This is Default.aspx Page
Here you can see Messages

Code Behind is as below
protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["date"])) 
        {
            //Write your logic Instead of following code.
            message.InnerText = "Logic For fetching data as per Date: " + Request.QueryString["date"];
        }
        else if (!string.IsNullOrEmpty(Request.QueryString["year"]) && !string.IsNullOrEmpty(Request.QueryString["month"])) 
        {
            //Write your logic Instead of following code.
            message.InnerText = "Logic For fetching data as per Year and Month: " + Request.QueryString["year"] + "/" + Request.QueryString["month"];
        }
        else if (!string.IsNullOrEmpty(Request.QueryString["year"])) 
        {
            //Write your logic Instead of following code.
            message.InnerText = "Logic For fetching data as per Year: " + Request.QueryString["year"];
        }
        else if (!string.IsNullOrEmpty(Request.QueryString["products"])) 
        {
            //Write your logic Instead of following code.
            message.InnerText = "Logic For fetching data for all Products: " + Request.QueryString["products"];
        }
    }
In web.config file (as per HTTPMODULE implementation) we add following code


We are done with our rewrite url logic, for handling Postbacks check out the logic written in "HandlePostBacks.cs" and "PostBack.browser" files. This logic is already explained in Url Rewriting Made Easy - Article 1
Download Demo codes
Submit this story to DotNetKicks

Read more...

Sunday, August 22, 2010

Url Rewriting Made Easy - Article 1

Rewriting of URL is one of the Major point in terms of Search Engine Optimization as well as in terms of Readability and usability. 
We should go for rewriting of URL because of following reasons
  1. Search Engines Recognizes different URLs.
  2. Same Page can be executed with different unique URLs.
  3. We can also introduce our keywords in the URLs.
In this article we will discuss very preliminary way to generate unique URL which internally can target to same page. We will also discuss how to maintain the URL during postbacks. We have to consider postback case because though we manage to redirect to some URL which is rewritten, during postbacks it again changes to the actual URL.
 
In general Our URLs looks like below
http://www.yourSite.com/products.aspx?category=Kids
http://www.yourSite.com/products.aspx?category=Science
http://www.yourSite.com/products.aspx?category=Biology
We are going to use a less used feature of Asp.Net i.e. "Request.PathInfo" using which we will able handle
URLs which are as below
http://www.yourSite.com/products.aspx/Kids
http://www.yourSite.com/products.aspx/Science
http://www.yourSite.com/products.aspx/Biology
This is one of the simplest approach to Handle URL Rewriting.  Now Lets start implementing it, before we go ahead check out the folder structure of the DemoCode for this article which is as below.
Lets Discuss one File at a time
  • Default.aspx: This file contains simple Div Tag with 3 links point to Product.aspx with desired URLs. Check out following code for the same. Check out URLs.



  • Product.aspx: HTML of Product.aspx contains following simple code.


    code behind of Product.aspx is as follows








    protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request.PathInfo.Substring(1))
            { 
                case "Kids":
                    Response.Write("This is Kids Section");
                    break;
                case "Science":
                    Response.Write("This is Science Section");
                    break;
                case "Biology":
                    Response.Write("This is Biology Section");
                    break;
            }
    
            Response.Write("
    
    
    Check out the URL");
        }
        protected void Button_Click(object sender, EventArgs e)
        {
            Response.Write("URL is Not Changing After PostBack");
        }

    This is very simple way to implement and understand which category is being called. upto this point code can work very well. But to make sure that on post back also i.e. on button click on Product.aspx page same URL should be maintained, we have to write Control Adapter which we have written in "HandlePostBacks.cs" file
  • HandlePostBacks.cs:  In this file we have overriden Render function of Control Adapter class to rewrite the Raw URL during postbacks. check out following code.











    public class HandlePostBacks : System.Web.UI.Adapters.ControlAdapter
    {
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(new RewriteForPostBack(writer));
        }
    }
    
    public class RewriteForPostBack : System.Web.UI.HtmlTextWriter
    {
        public RewriteForPostBack(HtmlTextWriter writer) : base(writer)
        {
            this.InnerWriter = writer.InnerWriter;
        }
    
        public RewriteForPostBack(System.IO.TextWriter writer) : base(writer)
        {
            base.InnerWriter = writer;
        }
    
        public override void WriteAttribute(string name, string value, bool fEncode)
        {
            if (name == "action")
            {
                HttpContext context;
                context = HttpContext.Current;
                value = context.Request.RawUrl;
                       }
            base.WriteAttribute(name, value, fEncode);
        }
    }

    Now we have almost done with our logic, now what remains is to register above adapter so that it get called automatically. For this we will write logic in "postback.browser" file

  • Postback.browser: We write simple logic which tells .net which adapter control should be used, check following code.



    
        
          
        
      

And we are done with the implementation DOWNLOAD demo code and check it out, very simple and can implement easily on other pages.
Download Demo Code here --> UrlRewitting-Simple Approach 1.zip Submit this story to DotNetKicks

Read more...

Saturday, August 14, 2010

Solved: Could not load type 'System.Web.UI.ScriptReferenceBase'

I came across following error while using AjaxToolKit 3.5, well it is a very common error I think, and I got the solution too.
Could not load type 'System.Web.UI.ScriptReferenceBase' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
Above error occurs because of the presence of  asp:ToolkitScriptManager, just replace this toolkitscriptManager with normal asp:ScriptManager
This simply works, no need to get panic about this error :)

Submit this story to DotNetKicks

Read more...

Friday, August 13, 2010

Page Methods

This article is all about the page methods and their usage. PageMethods is the part of Ajax.net and Script Manager.
MS Ajax gives us ability to directly create a web method on aspx page. And also enable to directly call this web method from the page. This method is termed as Page Method.
This is very easy way to implement Ajax functionality on the page. Like ICallback event handler here also we need to manipulate the string.
Page Method works simply as Web Methods
Script Manager Play critical role for the use of Page Methods, we need to set EnablePageMethods attribute to true.

To use web method attribute in Aspx page, use namespace
using System.Web.Services
Page Method should be static, as per the design by MS. So our web method (Page Method) will be as follows.

Now to call above method from client script we need to add PageMethods before the method name
PageMethods.HelloUser("Test User");
This will simply call the Method defied in Page, i.e. .cs file
Many times we need to handle different methods in different way, so in that case we need some special mechanism to handle the response from the server. We may also need to handle method failure errors in some customized way; we can also achieve this by adding extra parameters in PageMethods call.
In short we can add callback methods for successful invocation of pagemethods as well as for the failure of the pagemethod.

Basic Method prototype is
PageMethods.MethodName([para1,para2,…],[OnSucceeded, defaultFailedCallback,userContext]);

Above code work perfectly for normal scenario.
There might be possibility that we create our own JavaScript wrapper class, which internally uses PageMethods in that’s case, we might have following requirements.
  • Set defaultFailedCallback
  • Set defaultSucceededCallback
  • get defaultFailedCallback
  • get defaultSucceededCallback
  • set timeout
  • get timeout
Let’s say we have defined default Failed and Succeeded callbacks. Thus whenever we call some method like PageMethod.HelloUser(username), now if this method call completes its execution successfully our default Succeeded callback function will be called automatically. If method throws some error or failed, default Failed callback function will be called.
Also we need to call some already existing PageMethods but from some other pages; then in that case we should be able to set the path of the page in which methods are defined.
Considering above requirement we can modify the code as below.

With this understanding we can use pageMethods very effectively to handle static Page methods.

Download Demo Code here --> PageMethod3.5.zip

Submit this story to DotNetKicks

Read more...

ICallback Event Handler

This article will explain the use of “ICALLBACKEventHandler” in asp.net 2.0.
About ICallbackEventHandler:
ASP.NET 2.0 introduces an interface ICallbackEventHandler (System.Web.UI.ICallbackEventHandler) to allow asynchronous communication with the server. Unlike Postback, in Callback only user defined information is sent back to the server.
ICallbackEventHandler uses DoCallback event to send user defined data to server (instead of postback event), and return the String to client; on client side JavaScript manipulates the string. This interface implements two functions on server side (i.e. c# or vb) and we need to implement two functions on client side i.e. in JavaScript.(You can DOWNLOAD demo Code for Reference)
Use of ICallbackEventHandler:
To use ICallbackEventHandler, we need to impliment it on the page or on the User control. The code will be look like

Once we impliment this interface; we will have to play with 4 functions, two client side functions i.e. java script function, and two server side function i.e. c# (in this case).
As from ICallbackEventHandler, we have to use two functions namely (These functions or methods belongs to ICallbackEventHandler interface. C#)
1.public void RaiseCallbackEvent(String eventArgument)
2.public String GetCallbackResult()
RaiseCallbackEvent function gets call automatically whenever there is a CallbackEvent. And after this function 2nd function i.e. GetCallbackResult get called automatically.
2nd function returns a string to client.
How to raise a CallbackEvent?
To raise a callback event from client side we will use javascript function.
There will be two javascript functions whos functionality is as follows
1.Function which will call RaiseCallbackEvent, i.e. raise a callback event.
2.Function which will handle the response from the server. This function will be called automatically after GetCallbackResult(). I.e. the string returned by GetCallbackResult will appear in JavaScript as input to this function.
We will go on developing the code for better understanding of ICallbackEventHandler.
1.Create ASPX page design as follows

In above design “CheckForTimeZone()” in the button tag, is a javascript function, we will add it latter, under javascript tag.
Here button is a HTML control.
2.After this; we will write following JavaScript to the Aspx page.

You can just copy paste the code.
In above code “CallServer(selectedItem, "")” will be responsible for calling “RaiseCallbackEvent” on server side.
And “ReceiveServerData(retValue)” function gets called by
public String GetCallbackResult().
To make above code work the way we want; we will write code in aspx.cs file.
3.We will add C# code i.e. ASPX.Cs file

Please go through the above code line by line and then continue with following explanations.
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
If we debug the code “cbReference” will contain “WebForm_DoCallback('__Page',arg,ReceiveServerData,context,null,false)”;
Observe the string, WebForm_DoCallback contains ReceiveServerData, it’s a java script function we have written in step 2.

Again “callbackScript” will contain some string. Actually it is a JavaScript function which we will register to the client page. Using

Using above line of code we have registered our CallServer function to the page.
In above point we are registering the CallServer function. Now again see the 2nd point we are passing selected item of the Dropdown list to this function.
i.e. CallServer(selectedItem, "");
if you see the source code of the page then CallServer function will appear as follows

This CallServer function is responsible to raise the callbackEvent i.e. RaiseCallbackEvent(String eventArgument), and the “arg” will be appeared as eventArgument.
4.We will add RaisecallbackEvent and GetCallbackResult.
Add following code to aspx.cs file


Download Demo Code here --> ICallbackEventHandler.zip Submit this story to DotNetKicks

Read more...

Thursday, August 12, 2010

Asp.Net - Handling Long Running Process in Web Development

Sometimes in web development we need to run long processes. During such time we come across browser request time out issues. Whether we use Ajax or not, if process is very long running, browser will through time out error. Also there are some processes which needs to be initiated in background, then user can redirect to other page. Once the Process is over user can retrieve the data from long running process.
In case of Ajax.Net if we use script manager then also we have to define time out for the request. Imagine the scenario in which we can’t predict what time the process will take to execute e.g. it may take 5-7 minutes in such cases browser may give timeout error.
In this article we will discuss about this issue and how to use Ajax to handle long running process; using IAsyncResult, ICallbackEventHandler.
Concept behind Logic
Web application is a client-server architecture, so when client hits server; server will reply. If long process is running on the server, then we need some mechanism by which we will come to know that long process is over. And using Ajax we can very well do polling. But when on server side, long running process is going on , rest of the code will not get execute unless that process overs. To handle this issue we will use IAsyncResult . Using this interface and delegates we will able to run asyncronous process on server side.
For this logic is we invoke one method on server side and continue with other tasks; once first method is over it will automatically call another server method so that we can update some parameters say VAR1 and VAR2. And using ICallback we will check for VAR1 and VAR2, as soon as we get updated values, we will change status of long running method on client. (In Demo code we have used Session Variable Named result )
About IAsyncResult, delegate and AsyncCallback in our code (Refer DEMO CODE for better understanding)
Classes which support asynchronous operation or method implements IAsyncResult interface. IAsyncResult objects are passed to methods invoked by AsyncCallback, when an asynchronous operation overs. Classes which supports AsyncCallback in their methods return object of IAsyncResult; check out FileStream.BeginRead and FileStream.EndRead, these methods support AsyncCallback hence return type is IAsyncResult. Same is true for BeginGetRequestStream method of WebRequest.
If we see the parameters in these method then there is one parameter “AsyncCallback callback”; now callback is the method which gets called once Async method is over. In our code this method is represented by CallBackMethod function.
PROCESS FLOW(LOGICAL FLOW)
In our this code, we have used async method of delegate, i.e. BeginInvoke and EndInvoke.
On server side, we have used delegate and on button click event function named DoSomething() get called. This function take cares of LongRunningMethod registration for delegate and invoking of LongRunningMethod; this will be asynchronouse invokation on server side. While invoking LongRunningMethod we register AsyncCallback method i.e. CallBackMethod. In CallBackMethod we get object of IAsyncResult class as paramter. In this method we have just called EndInvoke method of delegate.
CallBackMethod method can be used to do other operations which may be dependent on the LongRunningMethod.
We will write our LongRunningMethod,that will be as follows

Above methos is simple implemtation for longrunning method.
We will declare delegate for above function , parameters for delegate and method should be same.
private delegate void LongRun(string name);
Implementation of Async process on server side

On button click event we will call DoSomething function.

Long.BeginInvoke in DoSomething will invoke LongRunningMethod method.
While implenting this just check parameters for BeginInvoke in .net.
CallBackMethod get called automatically after LongRunningMethod. CallBackMethod is used to end the invokation of delegate.
Upto this point we were discussing about Asynchronouse method invocation on server side. Now we will talk about Ajax check using ICallbackEventHandler for LongRunningMethod. (Note: if your are new to ICallbackEvent Handler, check out my article on ICallback, you can also download ICallback Demo. )
On Button Click in Above code (i.e. in LongRunningProcess.aspx page in demo) we initiate Long Running Process and Redirect to RedirectedPage.aspx. On Redirected Page we use ICallback to check status of LongRunning Process. We have used Session["result"] to check the status. Please make sure that you are understanding the code.
Using ICallbackEventHandler client browser polls to server for chekcing whether LongRunningMethod is over or not; in predefined time interval. If the process is over we send SUCCESS to client side. So if response from server singnifise that the LongRunningMethod is over we update the client. (RedirectedPage.aspx takes care of the status check, on this page we can have our other elements and other business logic, while in backend we can check for status of longrunning process.)
Here I assume that you are aware about the ICallbackEvent Handler, if not then please go through my article related to ICallback.
Download Demo Code For Free --> LongRunningProcess.zip , ICallbackEvent Handler
Submit this story to DotNetKicks

Read more...

Tuesday, August 10, 2010

Different ways of web page Redirect in Asp.Net

As a website developer many times we come across situation where we need to redirect pages, as there are many ways to redirect pages in asp.net and in HTML as well; one should know the difference between various web page redirect methods.
In this article we will discuss various web page redirecting methods we can use in asp.net

  1. Hyperlink: This is a traditional way of web page redirect which can use with HTML TAG i.e "A" tag. This is a static link on a page, which can be used as a tag with various style attributes. Also we can put data in opening and closing tag of "A". Asp.Net provides Hyper Link control, which is a class inherited from Webcontrol class. This control needs user to click explicitly on link for web page redirect.
    
     

    There are many attributes and events which are associated with hyperlink control, which can be used for many purposes.

    Hyperlink has following characteristics
    • New request is performed on Target Page.
    • Current page information doesn't get passed. Need to use query string to pass parameters
    • User Need to Initiate the web page transfer request.
    • Redirects to any page, not only restricted to current domain.
    When to Use
    • For navigation without any processing, e.g. Menu's list Items
    • When user should control the navigation.
  2. CrossPagePostBacks :By default, buttons in an ASP.NET Web page post the page to itself. i.e. it simply acts as a submit button of HTML. Where as Cross-page posting enables us to change the style of submitting the page, we can configure a button on an ASP.NET Web page to post the current page to a different page. Typically in multi-page forms, we can use such buttons on the page to move to the next and previous pages of the form.

    Though cross page posting is similar to hyperlinks, in cross page posting, the target page is invoked using an HTTP post command, which sends the values of controls on the source page to the target page. In addition if source and target page are in the same web application then the target page can access public properties of the source page. You can check out the article on cross page post by, click on CROSS PAGE POSTBACK
    Hyperlink has following characteristics
    • Post current Page Information into Target Page.
    • Makes Post information available into target page.
    • User Need to Initiate the cross page postback request.
    • Redirects to any page, not only restricted to current domain.
    • Enables the target page to read public properties of the source page if the pages are in the same Web application.
    When to Use
    • To pass current page information to the target page (as in multi-page forms).
    • When user should control the navigation.
  3. Response.Redirect: This is simple HTTP redirection we can directly use in code behind. very simple to use  When we use Response.Redirect the browser issues a new request to the target server in the form of an HTTP GET request. Response.Redirect is same as form submit in HTML, it does exactly same, actually in HTML response.redirect come as submit only. This method passes the server elements using query string. We can always use this method in code behind with our logic to redirect to other page(s).
    Hyperlink has following characteristics



    • Performs a new HTTP GET request on the target page.
    • Passes the query string (if any) to the target page. In Internet Explorer, the size of the query string is limited to 2,048 characters.
    • Provides programmatic and dynamic control over the target URL and query string.
    • Enables you to redirect to any page, not just pages in the same Web application.
    • Enables you to share information between source and target pages using session state.

    When to Use
    • For conditional navigation, when you want to control the target URL and control when navigation takes place. For example, use this option if the application must determine which page to navigate to based on data provided by the user.
  4. Server.Transfer: In case of Server.Transfer, server simple transfers the current source page context to the target page. The target page then renders in place of the source page. To use Server.Transfer, source page and target page should be in the same web application. When we use transfer method target page can read control values and public property values from the source page. Transfer between source and target pages happens on the server, because of this the browser has no information about the changes page, and it retains all information about the original i.e. source URL. Browser history doesn't get update to reflect the transfer. This is the best strategy to keep URL hidden, if user refresh the page he/she will be redirected to source page rather than new transferred page.
    Server.Transfer has following characteristics
    • Instead of source page control is transfered to new page which get renders in place of source
    • Redirects only to target pages that are in the same Web application as the source page.
    • Enables us to read values and public properties from source page.
    • Browser information Does not update with information about the target page. Pressing the refresh or back buttons in the browser can result in unexpected behavior.
    When to Use
    • For conditional navigation, when you want to control when navigation takes place and you want access to the context of the source page.
    • Best used in situations where the URL is hidden from the user.
Submit this story to DotNetKicks

Read more...

Thursday, August 5, 2010

Cross Page PostBack In Asp.Net

In web development, many times we come across following situation

We need to redirect to new page, but we also need some data which belongs to previous page, we might need to display the data on new page. So what things we normally do are,
eighter keep the data in session, or in hidden variable, or put data in application variable, or again run the code to get same data and bind it to similar kind of control.

I think this is something which we can avoid by simply applying logic of Cross Page Postback, where we can directly identify the controls whose value we need to display on new page.
E.g.
step1--> We have Grid View on say PAGE1.aspx and we redirect to PAGE2.aspx.
step2--> On PAGE2.aspx we need same Grid View to Display. For this we will probably use traditional ways to maintain the grid.

Now what if I say we can directly access grid which is already filled with data, and simply put the same grid on PAGE2.aspx. This sounds very simple. And it is very simple. For better understanding just check out following code which I have written on PAGE2.aspx



It looks very easy to use the code. You can DOWNLOAD the demo code, explained below
In above code check out the If condition where we have check whether it is a CrossPagePostBack or not.
We have following things in our web application.
  • Page1.aspx (with cs code)
  • Page2.aspx (with cs code)


Lets build Page1.aspx first, we have following HTML in Page1.aspx file. 



check out the PostBackUrl of button. which is set to Page2.aspx, we just need to do this in our code so that Page1 will be accessible in Page2.aspx
which looks like following page

Now we will write code in Page1.aspx.cs file which is as below, you can generally copy paste the code in your files.



This is what we have to do for Page1.aspx, we are done with our code. In Page1.aspx we simple have two textboxes and one Grid View control which we bind to some sample table. In Page2.aspx we Just make Grid View Object and set the reference of Page1's Grid View to new gird view thats it. If you observe the code written for Page2.aspx, we don't retrieve the data from any where and bind it to Grid View, we simple set the reference. This makes code execution also easy, and in similar way we can always pick some random controls which we need to display on some other page. We can also have many links referring to different pages depending on the requirement.

Download Demo Code here --> CrossPagePostback.zip

Submit this story to DotNetKicks

Read more...