Sunday, April 19, 2009

Convert dd/mm/yyyy to mm/dd/yyyy

Copy and paste the below code in the method where we need to change dd/mm/yyyy to mm/dd/yyyy

IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
string datetime = "24/04/2009";
DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);

Happy Coding :)

Saturday, April 18, 2009

Switching between http to https

Sometimes we need to make few pages to run in https and few run in http, I thought to find someway where we can change the browsing of page from http to https or https to http. There is very simple way to do it.
Let's start.

1. Create a module with name Secure.cs file under App_code folder and paste the below code

using System;
using System.Linq;
using System.Web;
using System.Xml.Linq;

///
/// Summary description for Secure

///
public class Secure :IHttpModule
{
public Secure()
{
}

public void Dispose()
{
}

public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}

private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication httpApp;
HttpContext httpContext;
try
{
httpApp = (HttpApplication)source;
httpContext = httpApp.Context;
string str = httpContext.Request.RawUrl;
XDocument xmlDoc = XDocument.Load(httpContext.Server.MapPath("Secure.xml"));
var q = from c in xmlDoc.Descendants("Page")
where c.Attribute("URL").Value.Trim().ToLower().Equals(str.Trim().ToLower())
select (string)c.Element("Secure");
foreach (string name in q)
{
if (Convert.ToBoolean(name))
{
httpContext.Response.Redirect(httpContext.Request.Url.ToString().Replace("http", "https"));
}
else
{
httpContext.Response.Redirect(httpContext.Request.Url.ToString().Replace("https", "http"));
}
}
}

catch (Exception ex)
{
}
}
}

2. In web.config, add below lines
<httpModules/>
<add name="MyHttpModule" type="Secure"/>
</httpModules/>



3. Create a XML with name secure.xml like below image, In the below xml replace your URL attribute of page element with your url(directory + page name) and in secure element specify true means, you want it to be accessed as https and if it is false , it means you want to access it as http
. You can change the xml file in production system also and you don't need to compile the application and deploy and so many other things.






Happy Coding :)

Monday, April 6, 2009

ASP.NET Static variable

Let's examine behavior of static keyword in ASP.NET

Create a class TestStatic with static member.

public class TestStatic
{
private static string strTest = string.Empty;

public static string Test
{
get
{
return strTest;
}
set
{
strTest = value;
}
}
}


Create a aspx page and place two buttons on it. On click of Button1 event assign value to Test along with with DateTime.

protected void Button1_Click(object sender, EventArgs e)
{
TestStatic.Test = "Logged in successfully" + DateTime.Now.ToLongTimeString();
}

and on click of button2 event write the value of Test on the page

protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(TestStatic.Test);
}

Run the application and click Button1, now value has been assigned into TestStatic. Test will contain "Logged in successfully" along with date time stamp.

Now click on Button2, the value assigned into TestStatic.Test will be displayed on the page with time stamp.






Now open another browser instance(using start menu or shortcut in taskbar or shortcut in desktop). Copy URL of above test application and paste on the address bar of the browser and hit enter. Obviously you will get both the buttons (Button1 & Button2).
I have used FireFox.

Don't click on Button1, Click on Button2. You will get the value of TestStatic.Test.
The value of TestStatic.Test displayed on the page will be the value which has been assigned using last browser.



This behavior is obvious because ASP.NET is multi threaded application, so the value of static member shared between threads.

Bottomline is, be carefull while using static variable in ASP.NET as it might put your application in weired situation. Use static variable only when you are sure static variable will be accessed in thread safe manner.

Happy Coding :)

Thursday, April 2, 2009

Restrict Duplicate Record Insertion On Page Refresh

The two ways which I believe is pretty simple to prevent duplicate record insertion on page refresh.

1. Using ViewState and Session


public partial class _Default : System.Web.UI.Page
{
private bool _refreshState;
private bool _isRefresh;
public bool IsRefresh
{
get
{
return _isRefresh;
}
}
protected override void LoadViewState(object savedState)
{
object[] allStates = (object[])savedState;
base.LoadViewState(allStates[0]);
_refreshState = (bool)allStates[1];
_isRefresh = _refreshState == (bool)Session["__ISREFRESH"];
}

protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] allStates = new object[2];
allStates[0] = base.SaveViewState();
allStates[1] = !_refreshState;
return allStates;
}

protected void Button2_Click(object sender, EventArgs e)
{
if(!IsRefresh)
Response.Write("Thanx for visiting");
}
}




2. Use Response.Redirect


public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
Boolean blnRefreshed = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
//code to save your data here
Response.Redirect("default.aspx");
}

}


The second one has a performance overhead. Let’s check how.
Put break point on Page_Load and click on button. The break points on Page_Load will be hit twice intead of one due to Response.Redirect, the second hit is overhead.

The second hit can be avoided by using the first method.

Happy Coding :)

ArrayList to DataTable

From last couple of days, i found few programmer in asp.net forum wanted to convert ArrayList to DataTable. So i thought to put it here for reference.

Below is the simple example of converting double dimensional array list into data table.

Dim arrList As ArrayList = New ArrayList()
Dim dt As New DataTable()
Dim intCnt As Integer = 0
dt.Columns.Add(New DataColumn("Name", System.Type.GetType("System.String")))
dt.Columns.Add(New DataColumn("Age", System.Type.GetType("System.String")))
arrList.Add(New String() {"Richards", "25"})
arrList.Add(New String() {"Marie", "30"})
arrList.Add(New String() {"Sandy", "35"})
arrList.Add(New String() {"Michael", "40"})
For Each item As Object In arrList
Dim dr As DataRow
Dim arrItem As String() = DirectCast(item, String())
dr = dt.NewRow()
dr("Name") = arrItem(0)
dr("Age") = arrItem(1)
dt.Rows.Add(dr)
Next

Happy Coding :)

Site Meter