Set “debug=false” in web.config, when deploying ASP.NET application

For debugging purpose, developers usually enables the debug mode in web.config file.This causes ASP.NET to produce extra information in the compiled assemblies such as debug symbols, metadata. However, performance will be suffered as it takes longer to compile and run, consumes more memory and resource caching is not performed. Therefore, we should set the debugging option back to false to avoid the effect on performance.

There are two ways to achieve this.

1) In web.config file, set <compilation debug=”false”/>

2) You can also disable the <compilation debug=”true”/> switch for all ASP.NET applications on the system by setting the following in Machine.config:

<system.web>
<deployment retail=”true”/>
</system.web>

Compress Viewstate

In ASP.NET we can compress viewstate of the page, with the help of System.IO.Compression namespace.

With the help of GZipStream class we can reduce the size of viewstate of the page.

The following class contains two methods for compressing and decompressing a stream.

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.IO.Compression;

public static class CompressViewState
{
public static byte[] Compress(byte[] data)
{
MemoryStream output = new MemoryStream();
GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true);
gzip.Write(data, 0, data.Length);
gzip.Close();
return output.ToArray();
}

public static byte[] Decompress(byte[] data)
{
MemoryStream input = new MemoryStream();
input.Write(data, 0, data.Length);
input.Position = 0;
GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);
MemoryStream output = new MemoryStream();
byte[] buff = new byte[64];
int read = -1;
read = gzip.Read(buff, 0, buff.Length);
while (read > 0)
{
output.Write(buff, 0, read);
read = gzip.Read(buff, 0, buff.Length);
}
gzip.Close();
return output.ToArray();
}
}

In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.

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

public partial class _Default : System.Web.UI.Page
{
private ObjectStateFormatter _formatter = new ObjectStateFormatter();

protected override void SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
_formatter.Serialize(ms, viewState);
byte[] viewStateArray = ms.ToArray();
ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(CompressViewState.Compress( viewStateArray)));
}

protected override object LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__VSTATE"];
byte[] bytes = Convert.FromBase64String(vsString);
bytes = CompressViewState.Decompress(bytes);
return _formatter.Deserialize(Convert.ToBase64String(bytes));
}

}

Sql Bulk Copy in .Net

Sometimes, we need to insert a large amount of data in sql table. .Net Framework 2.0 and later version contain a “SqlBulkCopy” class in “System.Data.SqlClient” namespace.

SqlBulkCopy provides simplest and fastest way to copy large amounts of data to SqlServer, Instead of inserting all data row by row.

Here, is the example of SqlBulkCopy class

private void BulkCopy(DataTable dtSource, string strDestinationTableName)
{
   SqlConnection sqlCon = new SqlConnection("Your Connection String");
   SqlBulkCopy sqlBC = new SqlBulkCopy(sqlCon);
   sqlBC.DestinationTableName = strDestinationTableName;

   /*
   Here is the column mapping to the source and destination table.
   You can also use column name instead of column index for mapping.   
   */

   //sqlBC.ColumnMappings.Add(SourceTableColumnIndex, DestinationTableColumn Index

   sqlBC.ColumnMappings.Add(0, 0);     
   sqlBC.ColumnMappings.Add(1, 1);
   sqlBC.ColumnMappings.Add(2, 2);
   sqlBC.ColumnMappings.Add(3, 3);
   sqlBC.ColumnMappings.Add(4, 4);

   try
   {
    sqlCon.Open();
    sqlBC.BatchSize = 500; //BatchSize Indicates the total number of rows sent to the server at a time.
    sqlBC.WriteToServer(dtSource);
    sqlCon.Close();
   }
   catch (Exception ex)
   {
    if (sqlCon.State == ConnectionState.Open)
        sqlCon.Close();
    throw ex;
   }
}

Variable declaration

Hello all,

Today, I am writing some common naming convention for declaring variables.

Camel Notation : The first letter is lowercase and each appended word begins with an uppercase letter. For e.g.: var myTestVar = 0

Pascal Notation : The first letter is uppercase and each appended word begins with an uppercase letter. For e.g.: var MyTestVar = 0

Hungarian Type Notation : Pretends a lowercase letter to the beginning of a Pascal Notation variable name to indicate the type of the variable. For e..g.: var iMyTestVar = 0 where i for integer.

Convert string into title case in c#

The System.String class contains methods ‘ToUpper’ and ‘ToLower’ which convert the string to Uppercase and Lowercase. But String class does not have the Title Case conversion.

‘TextInfo’ class provide this method. It is in System.Globalization.

using System.Globalization;
TextInfo myText = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;
string sample = "this IS a blog for net";
string titleCase = myTextInfo.ToTitleCase(sample);
Response.Write(titleCase);

Output : This Is A Blog For Net

Password Strength Meter

To show password strength following function is useful.

function passwordChanged() 
{
var strength = document.getElementById('strength');

var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");

var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");

var enoughRegex = new RegExp("(?=.{6,}).*", "g");

var pwd = document.getElementById("password");

var strColor;
var strText;
var strWidth;

if (pwd.value.length == 0) 
{
strText = 'Type Password'; strColor = 'White'; strColor = "#cccccc";strWidth = 150;
} 
else if (false == enoughRegex.test(pwd.value)) 
{
strText = 'Very Weak!'; strColor = 'White'; strColor = "red"; strWidth = 50;
} 
else if (strongRegex.test(pwd.value)) 
{
strText = '<span style="color: green;">Strong!</span>';
strColor = "green"; strWidth = 150;
} 
else if (mediumRegex.test(pwd.value)) 
{
strText = '<span style="color: orange;">Medium!</span>';
strColor = "orange"; strWidth = 100;
} 
else 
{
strText = '<span style="color: red;">Weak!</span>';
strColor = "#E41B17"; strWidth = 75;
}

strengthBar.style.backgroundColor = strColor;
strengthBar.style.width = strWidth;
strength.innerHTML = strText;

}

Add two div tag in page.

<input id="password" onkeyup="return passwordChanged();" type="password" maxlength="20" name="password" size="15" />
<div id="strength">Type Password</div>
<div id="strengthBar" style="height: 2px; width: 150px; border: 1px solid black; background-color: #cccccc;"></div>

Why Response.Redirect throws exception in try catch block ?

If you use the Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. When you use try-catch statement then you will find it.

This problem occurs in above methods because both methods call Response.End internally. The Response.End method ends the execution and redirect it to the Application_EndRequest event. So the line of code that follows Response.End is not executed.

If you want to solve this problem then use Response.Redirect with endresponse parameter like Response.Redirect (“pagename”, false). so it suppress the internal call to Response.End method and for Server.Transfer, use Server.Execute method instead of Server.Transfer method.