Sunday, 20 October 2013

Difference between Response.Redirect and Response.RedirectPermanent in ASP.NET

Leave a Comment
In my previous article, I’ve explained difference between Response.Redirect and Server.Transfer in ASP.NET. You can also see list of ASP.NET FAQ. In this article, I am going to explain difference between Response.Redirect and Response.RedirectPermanent. First of all I am going to explain difference between HTTP response Status Code 301 and HTTP response Status Code 302.

What is HTTP response status code?

Whenever a user accesses web page in a web browser (client) or Google (or any other search engine like Bing) crawls the web page for rebuilding its search index, a request is made to web server for processing the web page. The web server returns an HTTP status code in response to the request. This status code provides relevant information about the status of the request. This status code also gives Googlebot information about web site and the requested page. Below are the most common status codes:

 CodeDescription
200Page or resource has been found successfully.
404Requested Page or resource does not found.
503Server is temporary unavailable.
301Permanent Redirect. The requested page has been permanently moved to a new location.
302Temporary Redirect. the requested page is temporarily located somewhere else.
A complete list of HTTP status codes can be found at Wikipedia.

In .NET 4.0, Microsoft has introduced some improvements related to Search Engine Optimization (SEO). SEO is most important for a digital marketing websites. A huge percentage of traffic to sites now comes from different search engines like google or bing. It is very common behavior within web applications to move pages or resources and other content around over time, which can lead to an accumulation of outdated links in search engines. To overcome this issue and to enhance SEO of websites, Microsoft has introduced Response.RedirectPermanent method in.NET 4.0. The main objective of this method is to indicate correct HTTP response status code to search engine. The Response.Redirect returns HTTP response status code as 302 whereas Response.RedirectPermanent returns HTTP response status code as 301.

Difference between Response.Redirect and Response.RedirectPermanent and Server.Transfer

 Suppose, you are having two pages: Page1.aspx and Page2.aspx.
  1. Response.Redirect: Response.Redirect will redirect request from Page1.aspx to Page2.aspx.  Response.Redirect() method returns HTTP response status code 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URL. So whenever search engine will try to crawl your website, it will not update its search index database and will keep old page URL into search index database because of HTTP response status code 302 which indicates that resource has temporarily moved to another location. This means that using a temporary redirect can negatively impact page ranking.
  2. Response.RedirectPermanent: Response.RedirectPermanent will redirect request from Page1.aspx to Page2.aspx and return HTTP response status code 301 (permanent redirect). So whenever search engine will try to crawl your website, it will update its search index database and use the new URL to rebuild search index. Thus your search engine page ranking will improve.
  3. Server.Transfer: Server.Transfer will transfer request from Page1.aspx to Page2.aspx and return HTTP response status code 200 (Page found). Search Engine will be unaware of any redirection which took place between Page1.aspx and Page2.aspx and will keep Page1.aspx to its search index database. In Server.Transfer, web browser URL doesn’t get changed. Please check more for Server.Transfer.

How to monitor HTTP response status code? 

You can monitor HTTP response status code by using various website traffic monitoring tool. One of the best tools to monitor website traffic is FIDDLER. Fiddler is a free web debugging proxy which logs all HTTP(s) traffic between your computer and the Internet. Use it to debug traffic from virtually any application that supports a proxy like IE, Chrome, Safari, Firefox, Opera, and more.
  1. Response.Redirect: Create Page1.aspx and Page2.aspx in your web application. In Page_Load of Page1.aspx, write below code to redirect from Page1.aspx to Page2.aspx. Browse Page1.aspx and monitor traffic using FIDDLER.
    protected void Page_Load(object sender, EventArgs e)
        {
           Response.Redirect("Page2.aspx");        
        }
    
    
  2. Response.RedirectPermanent: Create Page1.aspx and Page2.aspx in your web application. In Page_Load of Page1.aspx, write below code to redirect from Page1.aspx to Page2.aspx. Browse Page1.aspx and monitor traffic using FIDDLER.
    protected void Page_Load(object sender, EventArgs e)
        {
           Response.RedirectPermanent("Page2.aspx");     
        }
    
    
  3. Server.Transfer: Create Page1.aspx and Page2.aspx in your web application. In Page_Load of Page1.aspx, write below code to transfer from Page1.aspx to Page2.aspx. Browse Page1.aspx and monitor traffic using FIDDLER.
    protected void Page_Load(object sender, EventArgs e)
        {
           Server.Transfer("Page2.aspx");    
        }
    
    
Comments and suggestions are most welcome. Happy coding!
Read More...

Difference between Response.Redirect and Server.Transfer in ASP.NET

1 comment
In this article, I am going to explain difference between Response.Redirect and Server.Transfer in detail. This is one of the frequently asked questions related to ASP.NET

Response.Redirect

  1. Syntax
    Response.Redirect("webpageURL.aspx");
    
  2. Response.Redirect is used to redirect current user’s page request (For example Page1.aspx) to another target page (Page2.aspx) of same server or some other server.
  3. When the web server receives a request for redirection using Response.Redirect, it sends a response header to the web browser (client) which instructs the web browser (client) to send a new target page request back to the server.
  4. In other words, Response.Redirect causes two request/response cycles (two round trips):
    1. First Cycle
      • Request: Web browser (client) has requested page (Page1.aspx).
      • Response: Response.Redirect sends HTTP status code 302 to Web browser along with the new URL location (Page2.aspx) of the target page.
    2. Second Cycle
      • Request: Once web browser receives this code, it requests to open the new location (Page2.aspx) of the resource that was suggested by the server.
      • Response: Web server returned Page2.aspx to Web browser.
  5. Diagram
  6. Response.Redirect is slower in performance as it involves extra round trip.
  7. Response.Redirect can be used to redirect to .aspx and html pages of same server or some another server.
    Response.Redirect("Page2.aspx");
    Response.Redirect("Page2.html");
    
  8. Response.Redirect can be used to redirect a user to an external website or other server URL as well as URL on same server.
    So we can use the Response.Redirect method to redirect users request to another page on same server like below:
    Response.Redirect("Page2.aspx");
    
  9. Response.Redirect method to redirect users request to another page of different server like below:
    Response.Redirect("http://www.microsoft.com/myPage.aspx");
    
  10. Response.Redirect changes the URL in the web browser thus URL can be bookmarked if necessary.
  11. Response.Redirect generates HTTP Status Code 302 (temporary redirect).
  12. By Response.Redirect, we can’t preserve all posted form variables or query string values of source page (Page1.aspx). All the Query Strings and Form variables are lost during the redirect and they are not available to the redirected (target : Page2.aspx) URL.

Server.Transfer

  1. Syntax
    Server.Transfer (“webpageURL.aspx”);
    
  2. Server.Transfer is used to redirect current user’s page request (For example Page1.aspx) to another target page (Page2.aspx) of same server.
  3. When the web server receives a request for redirection using Server.Transfer, the original request is simply rewritten and transferred to some other page (Page2.aspx) on the same server.
  4. In other words, Server.Transfer causes only one request/response cycle (one round trip):
    • Request: Web browser (client) has requested Page1.aspx. Server.Transfer transferred original request (Page1.aspx) to some other page (Page2.aspx) on the same server.
    • Response: Web server returned Page2.aspx to Web browser.
  5. Diagram

  6. Server.Transfer is good in performance. Server.Transfer changes the "focus" on the Web server and transfers the request on some other page of same server. It doesn’t involve extra round trip which therefore reduces the load on Web server and makes applications run faster. 
  7. Server.Transfer can be only used to transfer requestes to .aspx pages of same server.
  8. Using Server.Transfer, we cannot transfer request to external website url or some other server url.
  9. Server.Transfer doesn’t change the URL in the web browser thus Browser URL history doesn’t get updated. This makes confusion while debugging.
  10. All posted form variables and query strings can optionally remain available to the target Page (Page2.aspx). Server.Transfer is having overloaded method:
    Server.Transfer(string urlPath, bool preserveForm;)
    
    If you set "preserveForm" to true, using a statement such as Server.Transfer("Page2.aspx", true); the existing query string and any form variables of Page1.aspx will still be available to the Page2.aspx. By default, preserveForm is always true.

    For example, If Page1.aspx has a TextBox control called "txtBox1" and Server.Transfer transferred Page1.aspx to Page2.aspx with the preserveForm parameter set to True then we would be able to retrieve value of the "txtBox1" of Page1.aspx by using  "PreviousPage.FindControl" method on Page2.aspx.
    TextBox txtBox2 = (TextBox)this.Page.PreviousPage.FindControl("txtBox1");
    
    If we set preserveForm=true to preserve query string and form variables then we may receive error: "The View State is invalid for this page and might be corrupted". This problem occurs because the EnableViewStateMac attribute of the <pages> element is set to true by default. For more detail on this error, visit PRB: "View State Is Invalid" Error Message When You Use Server.Transfer

    The workaround of this error is to set the enableViewStateMac property to false on the target page.
Comments and suggestions are most welcome. Happy coding!
Read More...

Tuesday, 15 October 2013

Tutorial 6: Create Back To Top hyperlink with animation effect in ASP.NET using jQuery

Leave a Comment
In my previous article, I've explained how to get selected text and value of ASP.NET DropDownList using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to create Back To Top hyperlink with animation effect in ASP.NET using jQuery. In real world web applications, a web page can be longer than the browser window size therefore user have to scroll down in order to see all contents of web page. Back To Top link will be very useful if user want to get back to the top of the page after seeing all the contents.
  • Create a new web form Example1.aspx in ASP.NET web application. Add one div area
    with some dummy text content in the web form. Also add hyperlink below div area.
    <div id="Area1">
                <h1>Scroll down and click on Back To Top</h1>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.
                <br />
                <br />
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.
                <br />
                <br />
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.
                <br />
                <br />
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat mauris eu nisl convallis ultricies. Aenean aliquet pellentesque nisi. Maecenas suscipit, orci quis faucibus blandit, nunc urna tempus justo, sit amet gravida tortor lorem eu justo. Vivamus sagittis diam purus, ac dapibus odio suscipit ut. Nullam viverra quis lacus at congue. Duis consectetur dapibus luctus. In risus purus, tristique nec ornare nec, venenatis in mi. Etiam in lobortis velit, et scelerisque risus. Nullam a nisi velit. Aenean lacinia dui massa, id ornare dui dignissim ut. Fusce ultrices gravida lectus, faucibus tincidunt massa placerat pharetra. Suspendisse cursus risus quis faucibus luctus. Sed fringilla euismod dolor in imperdiet. Proin ornare lacus et risus aliquet feugiat id pulvinar mauris. Donec sed mattis dui, et ornare lorem.
                <br />
                <br />
                Nullam dolor ligula, gravida in aliquam eget, consequat pulvinar neque. Pellentesque sit amet diam euismod, dictum mi vitae, euismod odio. Mauris posuere, felis sed semper scelerisque, erat risus eleifend arcu, nec vestibulum velit sem sit amet orci. Etiam tempor pulvinar porta. Mauris ac felis ut urna accumsan accumsan vitae at metus. Integer tempus mauris euismod nulla lacinia sollicitudin. In hac habitasse platea dictumst. Nam ut risus porttitor justo suscipit iaculis id id tortor. Phasellus vel lorem vitae nisi elementum euismod eu sed nulla. Aliquam sit amet tempus quam. Nam ut ante ac lacus rutrum facilisis. Etiam in vehicula diam. Vestibulum lacinia turpis et quam faucibus, non pretium velit laoreet. Nullam eleifend, odio a tincidunt aliquet, tortor lectus eleifend neque, at pulvinar enim ligula id libero.
                <br />
                <br />
                Aliquam tempor elementum quam non pretium. Sed consectetur pulvinar iaculis. Morbi purus quam, viverra vel ante rhoncus, venenatis egestas dui. Maecenas nec nibh justo. Nam in nisl tincidunt, interdum est quis, laoreet tellus. Nunc at lacus at massa consequat tempus. Vestibulum pulvinar nulla vel felis sagittis scelerisque. Vivamus pellentesque elit eu orci vestibulum, nec auctor quam cursus. Nam ut ipsum fringilla, lacinia est ac, dictum elit. Vivamus quis ipsum ac neque tincidunt hendrerit. Curabitur pretium mauris vitae laoreet consequat.
                <br />
                <br />
                Maecenas malesuada fermentum cursus. Aenean fermentum tristique sagittis. Aliquam rhoncus metus a ante vestibulum, ac tempus arcu elementum. Morbi adipiscing ullamcorper ligula. Praesent sed dui pulvinar, ultrices ligula in, fringilla diam. Donec cursus pulvinar lobortis. Suspendisse potenti. Cras at dolor fermentum, fermentum nunc ut, convallis nibh. In viverra ut eros quis scelerisque. Sed blandit felis eu mauris consectetur semper. Vivamus ac eleifend metus. Etiam in enim pellentesque, fermentum augue quis, varius metus.
                <br />
                <br />
                Maecenas sollicitudin sem et pharetra hendrerit. Suspendisse eu ipsum hendrerit, facilisis mi non, posuere quam. Sed porttitor sem ut orci facilisis, non euismod turpis volutpat. Duis pharetra lectus a mi luctus, ut malesuada odio ultricies. Duis ut luctus lorem. Proin feugiat lorem sit amet augue facilisis, et accumsan libero semper. Phasellus nibh sapien, tempus eu malesuada in, condimentum vel est. Proin fringilla justo id orci dapibus, in dignissim nisi consequat. Curabitur euismod justo velit, vitae malesuada ante tempor egestas. Quisque ultricies nunc est, vitae sagittis augue auctor pharetra. Maecenas eu felis fermentum, sagittis quam fermentum, pulvinar magna.                      
            </div>
    <a id="BackToTop" href="#top"><strong><span class="auto-style1">Back To Top</span></strong></a>
  • Define the css style for the hyperlink as below:
    <style type="text/css">
            .auto-style1 {
                color: #0000CC;
                font-size: x-large;
                cursor:hand;
            }
      </style>
  • Write below jQuery code for animation effect.
    <script type="text/javascript">
            $(function () {
                $("#BackToTop").click(function () {
                    $('html,body').animate({ scrollTop: $("#Area1").offset().top },
                    { duration: 'normal', easing: 'swing' });
                    return false;
                });
            });
    </script>
  • In the jQuery code, we are selecting hyperlink BackToTop and animating it using jQuery. Inside animate() function we've used scrollTop and then $("Area1").offset().top as the position that our function scrolls to. We can replace $("Area1") with any element of your choice. We have set the speed duration to "normal". You can also use the keywords fast and slow or set the time in milliseconds for duration. We've add easing effect by easing: 'swing'. Instead of swing, we can also use linear for easing effect. We can also add different easing effects by including the jQuery UI. You can read more about easing effects here. In the end of the code we are returning false, which prevents our link from going to its target: #top.
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding!
Read More...

Sunday, 13 October 2013

Tutorial 5: Getting selected text and value of ASP.NET DropDownList using jQuery

Leave a Comment
In my previous article, I've explained how to Select Deselect all CheckBoxes of ASP.NET CheckBoxList using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to get selected text and value of ASP.NET DropDownList using jQuery.
  • Create a new web form Example1.aspx in ASP.NET project and add one ASP.NET DropDownList. Also add a div tag to display selected text and value of the ASP.NET DropDownList in runtime.
     <asp:DropDownList ID="ddlCountry" runat="server">
                    <asp:ListItem Value="">Select Country</asp:ListItem>
                    <asp:ListItem Value="1">India</asp:ListItem>
                    <asp:ListItem Value="2">England</asp:ListItem>
                    <asp:ListItem Value="3">USA</asp:ListItem>
                    <asp:ListItem Value="4">France</asp:ListItem>
    </asp:DropDownList>
    <div id="ddl"></div>
    
  •  Create a empty string variable.
     var ddltext = "";
    
  • In the document.ready() function in the jQuery script block, use bind() to attach
    a handler to the keyup and change events.
     $("#<%=ddlCountry.ClientID%>").bind("keyup change", function () {
  •  Check whether the selected value of the DropDownList is empty or not. If selected value is not empty then retrieve the Text/Value pair and display in the div tag (ddl) area else clear the div area. 
    $("#<%=ddlCountry.ClientID%>").bind("keyup change", function () {
                    if ($(this).val() != "") {
                        ddltext = "Country Text : " + $(this).find(":selected").text() + " Country Value : " + $(this).val();
                        $("#ddl").text(ddltext);
                    }
                    else {
                        $("#ddl").text("");
                    }
                });
    

Complete Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            var ddltext = "";
            $("#<%=ddlCountry.ClientID%>").bind("keyup change", function () {
                if ($(this).val() != "") {
                    ddltext = "Country Text : " + $(this).find(":selected").text() + " Country Value : " + $(this).val();
                    $("#ddl").text(ddltext);
                }
                else {
                    $("#ddl").text("");
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Please select country:</h3>
            <asp:DropDownList ID="ddlCountry" runat="server">
                <asp:ListItem Value="">Select Country</asp:ListItem>
                <asp:ListItem Value="1">India</asp:ListItem>
                <asp:ListItem Value="2">England</asp:ListItem>
                <asp:ListItem Value="3">USA</asp:ListItem>
                <asp:ListItem Value="4">France</asp:ListItem>
            </asp:DropDownList>
        </div>
        <br />
        <div id="ddl"></div>
    </form>
</body>
</html>
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding! 
Read More...

Saturday, 12 October 2013

Tutorial 4: Select Deselect all CheckBoxes of ASP.NET CheckBoxList using jQuery

Leave a Comment
In my previous article, I've explained how to display selected items of ASP.NET CheckBoxList using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to Select Deselect or Check Uncheck all CheckBoxes of ASP.NET CheckBoxList using jQuery. I'll be using one additional CheckBox control to perform this functionality. This additional CheckBox will be used to Select Deselect all CheckBoxes of ASP.NET CheckBoxList.
  • Create a new web form Example1.aspx in ASP.NET project and add one ASP.NET CheckBoxList (chkboxList) and one CheckBox (chkboxSelectAll) control.
  • <asp:CheckBox ID="chkboxSelectAll" runat="server" Text="Select All" />
                <asp:CheckBoxList ID="chkboxList" runat="server">
                    <asp:ListItem>News</asp:ListItem>
                    <asp:ListItem>Offers</asp:ListItem>
                    <asp:ListItem>Products</asp:ListItem>
                    <asp:ListItem>Advertisement</asp:ListItem>
    </asp:CheckBoxList>
    
  • Write below jQuery code to Check Uncheck all CheckBoxes of ASP.NET CheckBoxList chkboxList on CheckBox (chkboxSelectAll) click event.
    $("#<%=chkboxSelectAll.ClientID%>").click(function () {
                    if ($(this).is(":checked")) {
                        $("#<%=chkboxList.ClientID%> input[type=checkbox]").attr("checked", "checked");
                    }
                    else {
                        $("#<%=chkboxList.ClientID%> input[type=checkbox]").removeAttr("checked");
                    }
                });
    
  • In above code, if  CheckBox chkboxSelectAll is check then I am adding check attribute to all CheckBox of CheckBoxList chkboxList else remove check attribute for CheckBox of CheckBoxList chkboxList. 
  • Whenever any CheckBox of CheckBoxList chkboxList is getting clicked then we have to also verify all CheckBox of CheckBoxList chkboxList. If all CheckBox of CheckBoxList chkboxList are checked then we have to add check attribute to CheckBox chkboxSelectAll else we have to remove check attribute for CheckBox chkboxSelectAll.
    $("#<%=chkboxList.ClientID%>").click(function () {
                    if ($("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").length == $("#<%=chkboxList.ClientID%> input").length) {
                        $("#<%=chkboxSelectAll.ClientID%>").attr("checked", "checked");
                    } else {
                        $("#<%=chkboxSelectAll.ClientID%>").removeAttr("checked");
                    }
    });

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%=chkboxSelectAll.ClientID%>").click(function () {
                if ($(this).is(":checked")) {
                    $("#<%=chkboxList.ClientID%> input[type=checkbox]").attr("checked", "checked");
                }
                else {
                    $("#<%=chkboxList.ClientID%> input[type=checkbox]").removeAttr("checked");
                }
            });

            $("#<%=chkboxList.ClientID%>").click(function () {
                if ($("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").length == $("#<%=chkboxList.ClientID%> input").length) {
                    $("#<%=chkboxSelectAll.ClientID%>").attr("checked", "checked");
                } else {
                    $("#<%=chkboxSelectAll.ClientID%>").removeAttr("checked");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Please choose type of subscription letters:</h3>
            <asp:CheckBox ID="chkboxSelectAll" runat="server" Text="Select All" />
            <asp:CheckBoxList ID="chkboxList" runat="server">
                <asp:ListItem>News</asp:ListItem>
                <asp:ListItem>Offers</asp:ListItem>
                <asp:ListItem>Products</asp:ListItem>
                <asp:ListItem>Advertisement</asp:ListItem>
            </asp:CheckBoxList>
        </div>
    </form>
</body>
</html>
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding! 
Read More...

Friday, 11 October 2013

Tutorial 3: Display selected items of ASP.NET CheckBoxList using jQuery

1 comment
In my previous article, I've explained how to disable CUT, COPY and PASTE options for TextBox using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to display selected items of ASP.NET CheckBoxList using jQuery.
  • Create a new web form Example1.aspx in ASP.NET project and add one ASP.NET CheckBoxList. Also add a div tag to display selected items of the ASP.NET CheckBoxList in runtime.
    <asp:checkboxlist id="chkboxList" runat="server">
                <asp:listitem>News</asp:listitem>
                <asp:listitem>Offers</asp:listitem>
                <asp:listitem>Products</asp:listitem>
                <asp:listitem>Advertisement</asp:listitem>
    </asp:checkboxlist>
    <div id="SelectedItems"></div>
    
  • In the document.ready() event, define the click() function of CheckBoxList.
     $("#<%=chkboxList.ClientID%>").click(function () {
    
  • Create a empty string variable.
     var strSelectedItems = "";
    
  • Use jQuery selector to retrieve all the checked boxes and apply the each() function to
    loop through each element returned.
    $("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").each(function () {
    
    Please note that at run time ASP.NET CheckBoxList will render as table <table id="chkboxList"> and all CheckBox items will render as a <input type="checkbox"> and <label> pair format.
    <table id="chkboxList">
     <tr>
      <td><input id="chkboxList_0" type="checkbox" name="chkboxList$0" value="News" /><label for="chkboxList_0">News</label></td>
     </tr><tr>
      <td><input id="chkboxList_1" type="checkbox" name="chkboxList$1" value="Offers" /><label for="chkboxList_1">Offers</label></td>
     </tr><tr>
      <td><input id="chkboxList_2" type="checkbox" name="chkboxList$2" value="Products" /><label for="chkboxList_2">Products</label></td>
     </tr><tr>
      <td><input id="chkboxList_3" type="checkbox" name="chkboxList$3" value="Advertisement" /><label for="chkboxList_3">Advertisement</label></td>
     </tr>
    </table>
    
  • Get the text of selected CheckBox and append to the string variable strSelectedItems
     strSelectedItems = strSelectedItems + " " + $(this).next().text();         
    
  • As mentioned above, each CheckBox item will render as a <input type="checkbox"> and <label> pair format. The label holds the text of the CheckBox element. Therefore in above code, while retrieving the text of the CheckBox element , we have used $(this).next().text(), where $(this) refers to the current CheckBox element and next() refers to the consecutive <label> element.
  • Display value of string variable strSelectedItems in div after the execution of each() function. 
  •  $("#SelectedItems").text(strSelectedItems);
    

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Display selected items of ASP.NET CheckBoxList using jQuery</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%=chkboxList.ClientID%>").click(function () {
                var strSelectedItems = "";
                $("#<%=chkboxList.ClientID%> input[type=checkbox]:checked").each(function () {
                    strSelectedItems = strSelectedItems + " " + $(this).next().text();                    
                });
                $("#SelectedItems").text(strSelectedItems);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Please choose type of subscription letters:</h3>
            <asp:CheckBoxList ID="chkboxList" runat="server">
                <asp:ListItem>News</asp:ListItem>
                <asp:ListItem>Offers</asp:ListItem>
                <asp:ListItem>Products</asp:ListItem>
                <asp:ListItem>Advertisement</asp:ListItem>
            </asp:CheckBoxList>
            <div id="SelectedItems">          
            </div>
        </div>
    </form>
</body>
</html>

Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding! 
Read More...

Tuesday, 8 October 2013

Tutorial 2: Disable CUT, COPY and PASTE options for TextBox using jQuery

Leave a Comment
In my previous article, I've explained how to create default text or Watermark text for empty TextBox in ASP.NET using jQuery. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to disable CUT, COPY and PASTE functionality for TextBox using jQuery in ASP.NET applications. Sometimes we want to restrict users to perform CUT, COPY and PASTE operations in few scenarios like confirming email address or confirming password or requesting sensitive information.

Create a new web form Example1.aspx in ASP.NET web application. Create two TextBox : txtEmail and txtEmailConfirm.
 <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
 <asp:TextBox ID="txtEmailConfirm" runat="server"></asp:TextBox> 
  • In the document.ready() event, use bind to attach the required event handler for cut, copy, and paste events for txtEmail TextBox.
     $("#<%=txtEmail.ClientID%>").bind('cut copy paste', function (e) {
    
  • Override the default cut, copy, paste behavior of event and display alert box.
     e.preventDefault();
     alert("Cut Copy Paste is disabled for this textbox");
    
  • Repeat above steps for txtEmailConfirm TextBox.
     $("#<%=txtEmailConfirm.ClientID%>").bind('cut copy paste', function (e) {
                    e.preventDefault();
                    alert("Cut Copy Paste is disabled for this textbox");
                });

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Tutorial 2: Disable Cut Copy Paste for Textbox using jQuery</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#<%=txtEmail.ClientID%>").bind('cut copy paste', function (e) {
                e.preventDefault();
                alert("Cut Copy Paste is disabled for this textbox");
            });
            $("#<%=txtEmailConfirm.ClientID%>").bind('cut copy paste', function (e) {
                e.preventDefault();
                alert("Cut Copy Paste is disabled for this textbox");
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Confirm Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmailConfirm" runat="server"></asp:TextBox></td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
In above jQuery code, I've repeated same logic for second TextBox txtEmailConfirm. What if we have to do same task for multiple TextBoxes? We'll be ending up by repeating same logic for every TextBox. This task can be minimized by adding a common CSS Class (like class="txtdisable") to the TextBox controls on which we want to disable CUT, COPY and PASTE options and then using jQuery to disable controls having common specific CSS Class. See below source code for reference:
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Tutorial 2: Disable Cut Copy Paste for Textbox using jQuery</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".txtdisable").bind('cut copy paste', function (e) {
                e.preventDefault();
                alert("Cut Copy Paste is disabled for this textbox");
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Name</td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Enter Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server" CssClass="txtdisable"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Confirm Email Id</td>
                    <td>
                        <asp:TextBox ID="txtEmailConfirm" runat="server" CssClass="txtdisable"></asp:TextBox>
                    </td>
                </tr>

            </table>
        </div>
    </form>
</body>
</html>


Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding!
Read More...

Tutorial 1: Creating default text or Watermark text for empty TextBox in ASP.NET using jQuery

Leave a Comment
In my previous article, I’ve given beginner’s introduction on how to use jQuery with ASP.NET applications. You can also see list of ASP.NET+jQuery tutorials. In this tutorial, I am going to explain how to create a TextBox in ASP.NET with some default text or watermark text. This text will be displayed only when the TextBox is empty and out of focus. A typical example can be a Search Box or User Name TextBox. Create a new web form example1.aspx in your asp.net web application project. Add a ASP.NET TextBox control in web form. See below .aspx code for reference:
<asp:TextBox ID="txtName" runat="server" ToolTip="Enter Your Name"></asp:TextBox>
  • In the document.ready() event, retrieve the TextBox control using its client id and save in a local variable for further operations.
  • On the focus event, check if TextBox contains the default text value. If TextBox contains default text value then clear the TextBox . See  below code:
    var txtNameBox = $("#<%=txtName.ClientID%>");
                txtNameBox.focus(function () {
                    if (txtNameBox.val() == this.title)
                        txtNameBox.val("");
               });
    
  • You will notice that I have set ToolTip property of the TextBox. Text (“Enter Your Name”) of the ToolTip property will be displayed as the Watermark text in TextBox. The ToolTip property of the ASP.NET TextBox control is rendered as title at runtime. Therefore, the ToolTip text “Enter Your Name” is retrieved using this.title in above code.
  • On the blur event check whether TextBox control is empty or not. If it is empty then add Watermark text to TextBox control. See below code:
    txtNameBox.blur(function () {
                    if (txtNameBox.val() == "")
                        txtNameBox.val(this.title);
                });
    
  • Call the blur event on page load so that the TextBox control will be out of focus initially.
    txtNameBox.blur();
    

Complete Code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>This is method 2</title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">
        $(function () {
            var txtNameBox = $("#<%=txtName.ClientID%>");
            txtNameBox.focus(function () {
                if (txtNameBox.val() == this.title)
                    txtNameBox.val("");
            });
            txtNameBox.blur(function () {
                if (txtNameBox.val() == "")
                    txtNameBox.val(this.title);
            });
            txtNameBox.blur();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1>This is method 2</h1>
            <asp:TextBox ID="txtName" runat="server" ToolTip="Enter Your Name"></asp:TextBox>
        </div>
    </form>
</body>
</html>
Source code can be downloaded from GitHub. Comments and suggestions are most welcome. Happy coding!
Read More...

Sunday, 6 October 2013

Beginner’s introduction on how to use jQuery with ASP.NET applications

Leave a Comment
jQuery is a client side open source javascript library which is best to do DOM manipulation, performing AJAX requests, creating various effects or animation and so forth. In this article, I am going to explain how to integrate jQuery with ASP.NET application. I’ll explain how to use jQuery with ASP.NET applications and common tasks which can be accomplished using jQuery library in my upcoming articles. You can also see list of ASP.NET+jQuery tutorials.

Create a new website in visual studio and add a new web form Example1.aspx. Include jQuery source file in web form. You can download latest jQuery from jQuery official website.
<script src="js/jquery-1.8.js"></script>

Executing jQuery code when the DOM is ready

The web form is now ready to use jQuery. We will now embed jQuery code or markup in the following script block:
<script type="text/javascript">
$(document).ready(function () {
            alert(' Alert 2 : DOM is ready to manipulate!');
        });    
</script>
jQuery executes an event named ready() when the DOM is loaded and accessible for manipulation. All the jQuery code which manipulates DOM should be included in the $(document).ready() function. This function gets fired before the page contents and elements are rendered.

Different ways of attaching ready() event :
  1. $(document).ready(function () {
                alert(' Alert 2 : DOM is ready to manipulate!');
            });
    
  2. $(function () {
                alert(' Alert 3 : DOM is ready to manipulate!');
            });
    
  3. $(function ($) {
                alert(' Alert 4 : DOM is ready to manipulate!');
            });
    
Please note that we can attach more than one ready() events to the document. These events are executed in the order they were added into code.

Executing jQuery code when the browser window is completely loaded

As stated earlier, ready() event  will execute code before the browser window loads, but after the DOM is loaded and accessible for manipulation. But, sometimes we can use jQuery to execute code once the entire web page document (including all assets like CSS) is completely loaded.
This functionality can be achieved by attaching a load() event handler to the window object. jQuery provides load() event which invokes a function once the browser window is completely loaded.
$(window).load(function () {
            alert(' Alert 1 : Browser Window and all assets are loaded!');
        });

Executing jQuery code when DOM is parsed without using ready()

  • The ready()  event is not always needed. If jQuery code is not manipulating DOM then you can include it anywhere in the document. This means we can avoid usage of ready() event.
  • We can avoid usage of ready() event even if jQuery code is manipulating DOM.  Simply write your jQuery code in HTML document before the closing </body> element. Since the browser will parse the document from top to bottom, your jQuery code will execute successfully if you have included jQuery code before the closing </body> element. Thus there is no need to use the ready() event.
<script type="text/javascript">
        alert(' Alert 5 : ' + $('p').text());
</script>
Example 1:  Copy and paste below cone in Example1.aspx file.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="js/jquery-1.8.js"></script>
    <script type="text/javascript">

        $(window).load(function () {
            alert(' Alert 1 : Browser Window and all assets are loaded!');
        });

        $(document).ready(function () {
            alert(' Alert 2 : DOM is ready to manipulate!');
        });

        $(function () {
            alert(' Alert 3 : DOM is ready to manipulate!');
        });
        $(function ($) {
            alert(' Alert 4 : DOM is ready to manipulate!');
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p>This is sample paragraph text. </p>
        </div>
    </form>
    <script type="text/javascript">
        alert(' Alert 5 : ' + $('p').text());
    </script>
</body>
</html>
Please notice the order in which alert() function is getting executed in above code. Source code can be downloaded from GitHub.


It is recommended to include all CSS files before including jQuery in web page.
Comments and suggestions are most welcome. Happy coding!
Read More...

Saturday, 5 October 2013

Create Dynamic Image Gallery Slideshow using ASP.NET and jQuery Lightbox

Leave a Comment
In my previous post, I've explained how to upload multiple files using ASP.NET 4.5 . In this post, I am going to explain how to create dynamic image gallery using ASP.NET 4.5 and jQuery. The user uploads multiple images at once and those images will be added to a photo gallery or album. As part of uploading image process, we need to store original images on website’s uploads folder. At the same time, we also need to create thumbnail of images. We can divide complete functionality in below three processes:
  1. User uploads multiples images to create a new photo gallery. Store gallery details into database.
  2. Create thumbnail for uploaded images.
  3. Display gallery using jQuery colorbox plugin to get lightbox effect.

Upload multiple images and create gallery

First of all create table tblGallery into database to implement slideshow functionality. SQL Scripts can be downloaded from GitHub.

Column NameData Type
GalleryIdint (set identity property=true)
GalleryNamevarchar(50)
GalleryDescriptionvarchar(500)
GalleryCreatedDatedatetime
Create a new webform CreateAlbum.aspx and write following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateAlbum.aspx.cs" Inherits="CreateAlbum" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create Album</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Gallery Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtGalleryName" runat="server" Width="90%" MaxLength="100">
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvtxtGalleryName" runat="server" ErrorMessage="Enter Gallery Name"
                            ForeColor="Red" ControlToValidate="txtGalleryName">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>Enter Gallery Description
                    </td>
                    <td>
                        <asp:TextBox ID="txtGalleryDescrption" runat="server" TextMode="MultiLine" Width="90%"
                            Height="50px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvtxtGalleryDescrption" runat="server" ErrorMessage="Enter Gallery Description"
                            ForeColor="Red" ControlToValidate="txtGalleryDescrption">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>Upload Photos to Album</td>
                    <td>
                        <asp:FileUpload AllowMultiple="true" ID="MultipleFileUpload" runat="server"></asp:FileUpload></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvFileUploadGallery" runat="server" ErrorMessage="Upload Gallery Photos"
                            ForeColor="Red" ControlToValidate="MultipleFileUpload">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
This webform has two textbox to enter Gallery Name and Gallery description respectively, one file upload control to upload multiple files and one button to submit the data. After completion on .aspx page, write below code on button click event handler in code behind page CreateAlbum.aspx.cs:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            if (MultipleFileUpload.HasFiles)
            {
                int MaxGalleryId, ReturnValue;
                ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
                if (ReturnValue != 0)
                {
                    string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
                    Directory.CreateDirectory(Server.MapPath(GalleryPath));

                    string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
                    Directory.CreateDirectory(Server.MapPath(ThumbnailPath));

                    StringBuilder UploadedFileNames = new StringBuilder();

                    foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
                    {
                        //Upload file
                        string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                        string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
                        uploadedFile.SaveAs(SaveAsImage);

                        //Create thumbnail for uploaded file and save thumbnail on disk
                        Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
                        string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
                        Thumbnail.Save(SaveAsThumbnail);
                    }
                    HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
                }
            }
        }

        catch
        {
            HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
        }
    }
On button click, I am saving gallery details into database table tblGallery and saving images into website’s uploads folder. In the mean time I am also creating thumbnail for image. Refer next section for thumbnail creation.

Creating thumbnail

I've created a function CreateThumbnail which converts given image into thumbnail form. This function accepts below three parameters and returns a bitmap image of the changed thumbnail image which we can save on the disk.
  1. ImagePath : Path of original image
  2. ThumbnailWidth : Required width for thumbnail
  3. ThumbnailHeight : Required height for thumbnail
/// <summary>
    /// CreateThumbnail function returns a Bitmap image of the changed thumbnail image which we can save on the disk.
    /// </summary>
    public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
    {
        System.Drawing.Bitmap Thumbnail = null;
        try
        {
            Bitmap ImageBMP = new Bitmap(ImagePath);
            ImageFormat loFormat = ImageBMP.RawFormat;

            decimal lengthRatio;
            int ThumbnailNewWidth = 0;
            int ThumbnailNewHeight = 0;
            decimal ThumbnailRatioWidth;
            decimal ThumbnailRatioHeight;

            // If the uploaded image is smaller than a thumbnail size the just return it
            if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
                return ImageBMP;

            // Compute best ratio to scale entire image based on larger dimension.
            if (ImageBMP.Width > ImageBMP.Height)
            {
                ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
                ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
                lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
                ThumbnailNewWidth = ThumbnailWidth;
                decimal lengthTemp = ImageBMP.Height * lengthRatio;
                ThumbnailNewHeight = (int)lengthTemp;
            }
            else
            {
                ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
                ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
                lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
                ThumbnailNewHeight = ThumbnailHeight;
                decimal lengthTemp = ImageBMP.Width * lengthRatio;
                ThumbnailNewWidth = (int)lengthTemp;
            }
            Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
            Graphics g = Graphics.FromImage(Thumbnail);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
            g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);

            ImageBMP.Dispose();
        }
        catch
        {
            return null;
        }

        return Thumbnail;
    }

Display gallery using jQuery colorbox plugin

Create new webform Album.aspx to display gallery slideshow using jQuery colorbox plugin. Write following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Album.aspx.cs" Inherits="Album" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>View Gallery</title>
    <script src="js/jquery-1.8.js" type="text/javascript"> </script>
    <script src="js/jquery.colorbox.js" type="text/javascript"></script>
    <script>
        $(document).ready(function () {
            //Examples of how to assign the ColorBox event to elements
            $(".group1").colorbox({ rel: 'group1', transition: "fade", slideshow: "true" });
        });
    </script>
    <link rel="stylesheet" href="css/colorbox.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1><%= GalleryName %></h1>
            <h2><%= GalleryDescription %></h2>
            <asp:DataList ID="dlGallery" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
                Width="100%">
                <ItemTemplate>
                    <table border="1">
                        <tr>
                            <td>
                                <a href='<%#Eval("GalleryImagePath") %>' class='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
                                    <img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
                                </a>
                            </td>
                        </tr>
                        <br />
                    </table>
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>
In above code, I am binding gallery data into datalist and display it using jQuery colorbox plugin.  I’ve added few scripts and css file references in header section of above code. Using these files we can get lightbox slideshow effect.  These files are included in sample code. You can download sample code from GitHub. Another important thing to be noticed is href link tag.
<a href='<%#Eval("GalleryImagePath") %>' class='group1' rel='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
<img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
</a>
  • href='<%#Eval("GalleryImagePath") %>' : This will have image path.  
  • rel='group1' : This allows to group any combination of elements together for a gallery.
  • title='<%= GalleryName %> : <%= GalleryDescription %>' : This attribute is used to display image caption.
On page load following jQuery script is getting executed to assign Colorbox events to elements. For detail documentation about Colorbox plugin check their official page.
<script>
        $(document).ready(function () {
            //Examples of how to assign the ColorBox event to elements
            $(".group1").colorbox({ rel: 'group1', transition: "fade", slideshow: "true" });
        });
</script>
Complete source code and SQL scripts of this tutorial can be downloaded from GitHub. Source code mainly contains three webforms:
  1. CreateAlbum.aspx : To upload images and create gallery.
  2. AlbumList.aspx : To view complete list of created galleries.
  3. Album.aspx : To display images of a specific gallery using lightbox effect.
Please note that this is basic tutorial to create dynamic image gallery slideshow using ASP.NET and jQuery Lightbox. New functionalities like Cover Image for every gallery or different title for every image can be added.
Comments and suggestions are most welcome. Happy coding!
Read More...

Thursday, 3 October 2013

Upload Multiple Files using ASP.NET 4.5

Leave a Comment
In earlier versions of ASP.NET (version less than 4.5), we didn't have any inbuilt functionality to upload multiple files at once. ASP.NET FileUpload control allows uploading only one file at a time. Alternate solutions to upload multiple files are third party controls like Telerik or Devexpress. We can also use various jQuery Plugin like Uploadify to achieve similar functionality. 
In ASP.NET 4.5, we can upload multiple files at once using ASP.NET FileUpload control. In ASP.NET 4.5, FileUpload Control support HTML5 multiple attribute.

Below are the steps to upload multiple files using ASP.NET 4.5 :
  1. In Visual Studio 2012, create a new website using .Net 4.5 framework.
  2. Add a new web form (for example FileUpload.aspx) in newly created website.
  3. In code-beside file of FileUpload.aspx, write following code for FileUpload Control:
    <asp:fileupload AllowMultiple="true" id="MultipleFileUpload" runat="server">
    </asp:fileupload>
    In above code, I have set AllowMultiple property of FileUpload Control to true.
  4.  Add one button to upload multiple files using FileUpload Control on button click.
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    
  5. Write below code on button click event handler.
    protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (MultipleFileUpload.HasFiles)
            {
                StringBuilder UploadedFileNames = new StringBuilder();
    
                foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
                {
                    string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                    uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Files/"), FileName));
                    UploadedFileNames.AppendFormat("{0}<br />", FileName);
                }
                Response.Write("Uploaded Files are : <br/>" + UploadedFileNames);
            }
        }
    
    
  6. On button click, I am checking for multiple files and saving those files into Files folder of web application.
  7. Compile source code and run the website application.
I had selected five images to upload. Once I had clicked on Upload button, all five images were uploaded successfully in Files folder. Source code can be downloaded from Github.
All HTML5 enabled web browsers support above functionality. I have tested this feature in IE 10, Mozilla and Google Chrome. For all other browsers, it will work like normal ASP.NET FileUpload Control.
Comments and suggestions are most welcome. Happy coding! 
Read More...

Wednesday, 2 October 2013

Sitecore: Kick idle or inactive users automatically

Leave a Comment
Sitecore licensing can be based on total number of concurrent user sessions.  When Sitecore client concurrent user sessions limit reaches to its threshold value, next user who wants to login on Sitecore content tree/ desktop will be denied to login. User will get below message because Sitecore license has a concurrent number of users limitation:
There are too many users using the system at this time.
Too many inactive and idle users can cause slowness to Sitecore client and you may also observe performance issues while doing content authoring.  Most of the time users have a habit to exit Sitecore application by simple closing the browser window. Thus Sitecore client never gets a log off command from user manually and user session does not get killed immediately. Since Sitecore server never received a log off command, it waits until the user session time out occurs.  Standard session timeout is 20 minutes.
When managing Client sessions, Sitecore keeps track of every user logged in to the system and assigns a Sitecore user session id to every user accessing a Sitecore Client application. Sitecore Client user session is not limited in time and is kept alive until the browser is opened.
To allow new users to login on Sitecore client, we have to kick inactive and idle user sessions.  Follow below steps to kick inactive and idle user sessions manually:
  1. Login on Sitecore client. Please make sure that either you have login using admin credentials or you have admin privileges.
  2. Navigate to below url:
    http://Sitecore-domain-path/Sitecore/shell/Applications/Login/Users/Kick.aspx
    If you are using Sitecore 8 :
    http://Sitecore-domain-path/sitecore/client/Applications/LicenseOptions/KickUser
  3. You will get list of current user sessions (active and inactive) with login time and last request time.
  4. Select user who is inactive or idle and click on KICK button.
Monitoring active and inactive user session queue can be a tedious task. We can kick Sitecore users if they are inactive or idle for a specified period of time. Using DomainAccessGuard class, we can kick users from Sitecore Programmatically. DomainAccessGuard class allows getting details of all current user sessions. DomainAccessGuard class exists in Sitecore.Web.Authentication namespace.

Following code will kick Sitecore users if they are inactive or idle for a specified period of time:
using System;
using Sitecore.Web.Authentication;
using System.Collections.Generic;

namespace Sitecore
{
    public class KickUserSession
    {
        private TimeSpan maximumIdleTime;

        public KickUserSession(string maximumIdleTime)
        {
            this.maximumIdleTime = TimeSpan.Parse(maximumIdleTime);
        }

        public void Run()
        {
            List<DomainAccessGuard.Session> userSessionList = DomainAccessGuard.Sessions;

            if (userSessionList != null && userSessionList.Count > 0)
            {
                foreach (DomainAccessGuard.Session userSession in userSessionList.ToArray())
                {
                    TimeSpan span = (TimeSpan)(DateTime.Now - userSession.LastRequest);
                    if (span > this.maximumIdleTime)
                    {
                        DomainAccessGuard.Kick(userSession.SessionID);
                        Sitecore.Diagnostics.Log.Audit("Kicked out user is : " + userSession.UserName, this);
                    }
                }
            }
        }
    }
}
Source code and dll can be downloaded from GitHub.
  • Copy Sitecore.KickUserSessionAgent.dll in /bin folder of Sitecore website.
  • Add the following agent into the <scheduling> section in web.config:
<!-- Agent to kick users who are idle for 30 minutes -->
<agent type=" Sitecore.KickUserSessionAgent.KickUserSession" method="Run" interval="00:05:00">
        <param desc="maximumIdleTime">00:30:00</param>
</agent> 
You can configure the maximum inactivity time before a user will be kicked. Please set the appropriate value for the maximumIdleTime parameter.
Comments and suggestions are most welcome. Happy coding!
Read More...