Pages

Search Code Shode

Wednesday, June 13, 2012

Upload and Show Profile Picture Based on Session ID in ASP.NET

This was a question asked to in asp.net forums. It asked How to Upload and Show Profile Picture Based on Session ID in ASP.NET. I found it interesting and thought to write a post for it. So here we are with the solution:

FileUpload.aspx


<form id="form1" runat="server">
<div>
    <asp:FileUpload ID="FileUploadControl" runat="server" />
    <asp:Button runat="server" ID="UploadButton" Text="Upload" OnClick="UploadButton_Click" />
    <asp:Image ID="ProfilePic" runat="server" Height="150px" Width="150px" />
    <br />
    <br />
    <asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />
</div>
</form>



FileUpload.aspx.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class FileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["UserSessionID"] == null)
            Session["UserSessionID"] = System.Guid.NewGuid().ToString();//probably  create this in global.asax in OnSessionStart event

        ProfilePic.ImageUrl = "HttpHandler.ashx?ID=" + Session["UserSessionID"].ToString();
    }
    protected void UploadButton_Click(object sender, EventArgs e)
    {
        if (FileUploadControl.HasFile)
        {
            try
            {
                string ext = System.IO.Path.GetExtension(FileUploadControl.PostedFile.FileName);
                Session["UserSessionID"] = Session["UserSessionID"] + ext;
                FileUploadControl.SaveAs(Server.MapPath("~/") + Session["UserSessionID"]);
                StatusLabel.Text = "Upload status: File uploaded!";
                ProfilePic.ImageUrl = "HttpHandler.ashx?ID=" + Session["UserSessionID"].ToString();
            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }
    }
}


HttpHandler.ashx


<%@ WebHandler Language="C#" Class="HttpHandler" %>

using System;
using System.Web;

public class HttpHandler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        string imagePath = context.Request.QueryString["ID"];

        // split the string on periods and read the last element, this is to ensure we have
        // the right ContentType if the file is named something like "image1.jpg.png"
        System.IO.FileInfo imageFile = new System.IO.FileInfo(context.Request.PhysicalApplicationPath + imagePath); 
        bool fileExists = imageFile.Exists;
        if (fileExists)
        {
            context.Response.ContentType = "image/" + imageFile.Extension;
            context.Response.WriteFile(context.Server.MapPath(imagePath));
        }
        else
        {
            context.Response.ContentType = "image/jpeg";
            context.Response.WriteFile(context.Server.MapPath("NoImage.jpg"));
        }
       
            context.Response.Write(imagePath);
       
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

Monday, June 11, 2012

Best Practices for Speeding Up Your Web Site

Today I found a greate article for  best practices for making web pages fast.The list includes 34 best practices divided into 7 categories.

 1) Content

    * Minimize HTTP Requests
    * Reduce DNS Lookups
    * Avoid Redirects
    * Make Ajax Cacheable
    * Post-load Components
    * Preload Components
    * Reduce the Number of DOM Elements
    * Split Components Across Domains
    * Minimize the Number of iframes

2) Server

    * Use a Content Delivery Network
    * Add an Expires or a Cache-Control Header
    * Gzip Components
    * Configure ETags
    * Flush the Buffer Early
    * Use GET for AJAX Requests

3) CSS

    * Put Stylesheets at the Top
    * Avoid CSS Expressions
    * Choose over @import
    * Avoid Filters

4) Javascript

    * Put Scripts at the Bottom
    * Make JavaScript and CSS External
    * Minify JavaScript and CSS
    * Remove Duplicate Scripts
    * Minimize DOM Access
    * Develop Smart Event Handlers

5) Cookie

    * Reduce Cookie Size
    * Use Cookie-free Domains for Components

6) Images

    * Optimize Images
    * Optimize CSS Sprites
    * Don’t Scale Images in HTML
    * Make favicon.ico Small and Cacheable

7) Mobile

    * Keep Components under 25K
    * Pack Components into a Multipart Document

For details check out this 

Create TextBox Dynamically using jQuery and Read Control Value In Code Behind - ASP.NET


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

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

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnOfficial").click(function() {
                var hdValue = $("#theValue");
                var num = ($("#theValue").val() - 1) + 2;
                hdValue.val(num);
                var newDiv = $(document.createElement('div')).attr("id", 'my' + num + 'Div');
                newDiv.after().html('<input type="text"  name="TextBox' + num + '" value="TextBox' + num + '" >');
                newDiv.appendTo("#Div1");

            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="Div1">
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <input type="button" id="btnOfficial" value="Add Another TextBox" />
    <input type="hidden" value="1" id="theValue" runat="server" />
    <asp:Button ID="btnSave" runat="server" Text="Read" OnClick="btnSave_Click" />
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<string> alForm = new List<string>();
        //Textbox id is started
        // with 2 like(TextBox2,TextBox3.....
        for (int i = 2; i < Request.Form.Count - 2; i++)
        {
            string strId = "TextBox" + i.ToString();
            string strValue = Request.Form[strId].ToString();
            alForm.Add(strValue);
            strValue = "";


        }
        //Uncomment this line and test.
        //foreach (string x in Request.Form)
        //{

        //   string strValue = Request.Form[x].ToString();
        //  alForm.Add(strValue);

        //}
        GridView1.DataSource = alForm;
        GridView1.DataBind();
    }
}

Sunday, June 10, 2012

Back Button Problem Solved using ASP.NET Cache


A web browser's back button is essential for users to navigate across different web sites and web pages. However, for certain data sensitive web applications, using a web browser's back button can have unexpected and undesirable results. With poor planning, it could even crash a web site.
Take the following scenario as an example:
You developed a web survey for users to complete. Once the survey is submitted, the response is recorded in a database with a pre-coded caseID. Now, suppose a user just submitted his survey, then for some reason, he hit the browser's back button. Then, with or without making any changes, he submitted the survey again. Here, you ended up with two records (duplicate or not) with the same caseID. If the caseID is set to be unique, the user would get an error message.
In fact, the back button problem has pestered programmers for so long and caused so many headaches that across the net there is a flurry of questions, such as "How do I disable a browser's back button?".
Unfortunately, it is not possible to disable a browser's back button. Nor is it a good idea to do so. However, viable and simple solutions to get rid of this annoyance do exist.
The following is how you code it in a Class ASP way:
<%
   Response.Buffer = True
   Response.ExpiresAbsolute = Now() - 1
   Response.Expires = 0
   Response.CacheControl = "no-cache"
%>

This code snippet basically directs the page in concern to expire immediately once it is posted and set the page to cache none of its content. In ASP .NET, you can do something similar to disable browser page caching, like the following:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");

You can place the code in the page_load event. Ideally, the code should be executed whenever the page is loaded. And, whenever a user tries to go back to the page, he/she should get a "Page has Expired" warning.
However, some browsers may ignore the page cache settings and some users may still get away with submitting a form multiple times. This leads us to a second, more reliable solution: the timestamp solution. You should always use this solution while also adding the response caching instructions to the Page_Load procedure.
Here is the code showing you how:
protected void Page_Load(object sender, EventArgs e)
   {
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetExpires(Now.AddSeconds(-1));
      Response.Cache.SetNoStore();
      Response.AppendHeader("Pragma", "no-cache");

      if (Page.IsPostBack){
            if (isPageExpired()){
               Response.Redirect("expired.htm");
            }
            else {
               Session("TimeStamp") = Now.ToString;
               ViewState("TimeStamp") = Now.ToString;
            }
      }
      //...........
      //your own function here
   }

      private boolean isPageExpired()
      {
         if (Session("TimeStamp") == null ||
            ViewState("TimeStamp") == null)
            return false;
         else if (Session("TimeStamp") == ViewState("TimeStamp"))
            return true;
         else
            return false;
      }

The code is pretty self-explanatory. Whenever a page is loaded, it checks whether it is a resubmitted one by calling the isPageExpired function. If the function returns true, it redirects the page to the page-expired response; if not, it sets two timestamps: one saved in session state, the other view state.
The isPageExpired function compares the timestamp saved in session state and the timestamp in viewstate. If they are different, the user has submitted a form from cache; then, the page directs them to the Page-expired response.
So here it is, two simple solutions to the back-button problem.



اشتہارات