Asp.net

Encoding HTML special characters

The HTML Encode method in asp.net applies HTML encoding to a specified string. This is useful method of encoding form data.It converts potentially unsafe characters to their HTML-encoded equivalent.

e.g.
() is converted to >.
(&) is converted to &.
(“) is converted to ".

How to Use:

1.
2. div.InnerHtml = Server.HtmlEncode(“Enter a word <here>”);

Asp.net

URL Encryption

Why:

It always good to send query string values in encrypted format. Encrypted URLs prevents sending illegal requests or invalid data to the application server. Users or attackers cannot see the request details of the URL as they are encrypted.

Example

Before encryption,

http://localhost:60608/EncryptURLDemo/Default2.aspx?text=amol

After encryption,

http://localhost:60608/EncryptURLDemo/Default2.aspx?q=dSoxSTYQLHY3arcO+hfCO7uMyRNnIpRCoUqk0oyR80c=

How:

Method 1: Manually encrypt / decrypt query string parameter

  1. Copy EncryptionHelper.dll into Bin directory of your web application.
  2. To encrypt query string values,
    string url=string.Format("~/Default2.aspx?text= {0}",EncryptionHelper.Encrypt("valuehere"));
  3. To decrypt query string values,
    if (Request.QueryString["text"] != null)
    Text = EncryptionHelper.Decrypt(Request.QueryString["text"]);

Method 2: Automatic encrypt / decrypt query string using HttpModule

  1. Copy EncryptionHelper.dll into Bin directory of your web application.
  2. Add the following lines to the web.config’s section:
    <httpModules>
     <add type = "QueryStringModule" name = "QueryStringModule" />
    </httpModules>
Asp.net

Creating aspnetdb tables in to your Existing MSSQL database

Many of my asp.net web developer friends always ask me questions about aspnet db like , How to create aspnet database in MSSQL? , Is it possible to add aspnet tables and stored procedures into existing MSSQL database? etc.. So I decide to write on that, It might be useful to all.

Here is simple steps to create ASPNET Database

  1. Open visual studio command prompt and run Aspnet_regsql.exe command OR run Aspnet_regsql.exe file from C:WindowsMicrosoft.NETFrameworkv2.0.50727 directory.
  2. It opens Asp.net SQL server setup wizard,  Click on Next button
  3. Select Configure SQL server for application services , and click on Next Button
  4. Enter your database server details and select database name where you want to create aspnet table. It creates new database called aspnetdb if default database name is selected. Click on Next button. aspnetDb
  5. Confirm you details and click Next
  6. Done.
Asp.net

Asp.net: Send Compressed CSS and JS files to client browser

Why:

Compress your css and js files to load pages faster on client side. It reduces size of CSS and JS files so page size will get reduced.
Now majority of browsers support compressed files.

How

Add Global.asax file in your web application and delete all content and place following line in it,

<%@ Application Language="C#" Inherits="Global" %>

Then add Global.cs class file in your APP_CODE folder and put the following functions in it.

public class Global : System.Web.HttpApplication
{
public Global()
{
InitializeComponent();
}

private void InitializeComponent()
{
this.PostReleaseRequestState +=
new EventHandler(Global_PostReleaseRequestState);
}

private void Global_PostReleaseRequestState(
object sender, EventArgs e)
{
string contentType = Response.ContentType;

if (contentType == "text/css" ||
contentType == "application/x-javascript" || contentType == "text/javascript")
{
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;

string acceptEncoding =
Request.Headers["Accept-Encoding"];

if (acceptEncoding != null)
{
if (acceptEncoding.Contains("gzip"))
{
Response.Filter = new GZipStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader(
"Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
Response.Filter = new DeflateStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader(
"Content-Encoding", "deflate");
}
}
}
}
}

The browser will tell the server whether it supports GZIP or DEFLATE compression (via the Accept-Encoding header). If its an older browser that doesn’t support compression, it will just be sent as uncompressed HTML and your site will still work.

Ajax, Asp.net, Javascripts

Cancel previous Ajax requests on new request

If you are using ajax in web application , then there might be possibility that user does repetitively action such as click on button more than once which sends same asynchronous requests for every single click,
Before completing first request, another request for the same functionality is get sent and so on…

Here is the simple solution that helps to cancels previous ajax request,

Copy following two java scripts functions on page. it will cancel previous asynchronous requests. It works in asp.net ajax.

  
function pageLoad()
        {
Sys.WebForms.PageRequestManager.getInstance( ).add_initializeRequest(cancelPostBack);
         }
function cancelPostBack(sender, args)
        {
if (Sys.WebForms.PageRequestManager.getInstance( ).get_isInAsyncPostBack())
            {
              args.set_cancel(true);
            }
        }
Asp.net

Set themes from Global.asax

We can able to set themes dynamically depending on users prefrence from global.asax. for following e.g i stored theme name in session after user logged in.

//Global.asax
void Application_PreRequestHandlerExecute(object src, EventArgs e)
{
Page p = this.Context.Handler as Page;
if (p!= null)
{
p.PreInit += new EventHandler(page_PreInit);
}
}

void page_PreInit(object sender, EventArgs e)
{
Page p = this.Context.Handler as Page;
if (p != null)
{
if(Session["Theme"]!= null)
p.Theme = Session["Theme"].ToString();
else
p.Theme = "DefaultTheme";
}
}
Asp.net

Error Handling in asp.net

ASP.NET provides several levels at which you can handle and respond to errors that may occur when you run an ASP.NET
application. ASP.NET provides three main methods that allow you to trap and respond to errors when they
occur: Page_Error, Application_Error, and the application configuration file (Web.config).

1. In Page

public void Page_Error(object sender,EventArgs e)
{
        Exception objErr = Server.GetLastError().GetBaseException();
        string err =   "Error Caught in Page_Error event

" + "
Error in: " + Request.Url.ToString() + "
Error Message: " + objErr.Message.ToString()+ "
Stack Trace:
" + objErr.StackTrace.ToString(); Response.Write(err.ToString()); Server.ClearError(); }

2.In Global.asax

using System.Diagnostics;
protected void Application_Error(object sender, EventArgs e)
{
  Exception objErr = Server.GetLastError().GetBaseException();
  string err =   "Error Caught in Application_Error eventn" +
                 "Error in: " + Request.Url.ToString() +
                 "nError Message:" + objErr.Message.ToString()+
                 "nStack Trace:" + objErr.StackTrace.ToString();
  EventLog.WriteEntry("Sample_WebApp",err,EventLogEntryType.Error);
  Server.ClearError();
  //additional actions...
}

3. Web.config


   

Modes in web.config:-
On: Unhandled exceptions redirect the user to the specified defaultRedirect page.  This mode is used mainly in production.

Off: Users receive the exception information and are not redirected to the defaultRedirect page.  This mode is used mainly in development.

RemoteOnly: Only users who access the site on the local computer (by using localhost) receive the exception information.  All other users are redirected to the defaultRedirect page. This mode is used mainly for debugging.

Asp.net

Reset asp.net form

If we use third party controls on form then HTML reset button might not be work.

For this we need to do – add Onclick event to button as below ,

btnClear.Attributes.Add("onClick","document.forms[0].reset();return false;");