Wednesday, October 13, 2010

Check if request is coming from web browser or Mobile Browser

To Check the source of request call this method in page load function and if it return true then redirect it to mobile site.


public bool isMobileBrowser()
{
//GETS THE CURRENT USER CONTEXT
HttpContext context = HttpContext.Current;

//FIRST TRY BUILT IN ASP.NT CHECK
if (context.Request.Browser.IsMobileDevice)
{
return true;
}
//THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
{
return true;
}
//THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
{
return true;
}
//AND FINALLY CHECK THE HTTP_USER_AGENT
//HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
{
//Create a list of all mobile types
string[] mobiles = new[]
{"iphone","midp", "j2me", "avant", "docomo","novarra", "palmos", "palmsource",
"blackberry", "mib/", "symbian","wireless", "nokia", "hand", "mobi",
"phone", "cdm", "up.b", "audio","SIE-", "SEC-", "samsung", "HTC",
"mot-", "mitsu", "sagem", "sony", "alcatel", "lg", "eric", "vx",
"NEC", "philips", "mmm", "xx","panasonic", "sharp", "wap", "sch",
"rover", "pocket", "benq", "java","pt", "pg", "vox", "amoi",
"bird", "compal", "kg", "voda","sany", "kdd", "dbt", "sendo",
"sgh", "gradi", "jb", "dddi","moto" };

//Loop through each item in the list created above
//and check if the header contains that text
foreach (string s in mobiles)
{
if (context.Request.ServerVariables["HTTP_USER_AGENT"].
ToLower().Contains(s.ToLower()))
{
return true;
}
}
}

return false;
}

Class For Timer Control in Web Application

Below is the code for timer control add this class into your BLL folder and put this line in page behind

"<%@ Register Namespace="CodeControls" TagPrefix="cc" %>"


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Text;

///
/// Timer can be used to control the sequence of an event or process.
/// Timer Control's stopwatch counts downwards from 'X' to ZERO time for measuring elapsed time.
///
namespace CodeControls
{
[ToolboxData("<{0}:Timer runat='server' Enabled='true'>")]
public class Timer : Label, ICallbackEventHandler
{
protected override void OnLoad(EventArgs e)
{
AutoStart();
base.OnLoad(e);
}

//protected override void OnInit(EventArgs e)
//{
// AutoStart();
// // base.OnLoad(e);
//}

#region Load Timer
private void AutoStart()
{
//Is Not Page Request A Call Back?
if (!this.Page.IsCallback && Enabled && (IsAutoStart || IsManualStart))
{
//First Request or Page Refresh?
if (!Page.IsPostBack)
{
TimeLeft = TimeOut;
CreateTimerCookie(false);
//Load the Timer Script for the Post Back/Page Load
LoadTimer();
}
else
{
//Update lastIntervalTime cookie for this PostBack
UpdateTimerCookie();

if (IsPostBackOnTimeOut)
{
TimeLeft = 0;
TimerEventArgs eArgs = new TimerEventArgs(0);
if (TimeOutOccurred != null)
{
TimeOutOccurred(this, eArgs);
}
this.Text = "0:0:0.0";
IsManualStart = false;

//...Halt Timer
}
else
{
//Load the Timer Script for the Post Back/Page Load
LoadTimer();
}
}

}
else
{
//If the request is a Call Back then update the Timer Settings
// UpdateTimerCookie();
}

}

public void ManualStart()
{
if (!IsAutoStart)
{
IsManualStart = true;
TimeLeft = TimeOut;
CreateTimerCookie(true);
AutoStart();
}
}

#endregion

#region ICallbackEventHandler Members

public int iTimeLeft = 0;
// Define method that processes the callbacks on server.
public void RaiseCallbackEvent(String eventArgument)
{
Int32.TryParse(eventArgument, out iTimeLeft);

//Raise an Page Event From a Custom Control
TimerEventArgs e = new TimerEventArgs(TimeLeft);
if (iTimeLeft != TimeOut && iTimeLeft >= 0)
if (IntervalReached != null)
IntervalReached(this, e);

if (iTimeLeft < ismanualstart =" false;" itimeleft =" GetTimeLeft();" timeleft =" iTimeLeft;" timercookie =" new" expires =" DateTime.Now.AddDays(1d);" timercookie =" HttpContext.Current.Request.Cookies[" expires =" DateTime.Now.AddDays(1d);" dt =" DateTime.Now.AddDays(-3);" t =" DateTime.Now.Subtract(dt);" timeleft =" TimeLeft" cs =" Page.ClientScript;" cbreference =" cs.GetCallbackEventReference(this," callbackscript = "function CallTheServer(arg, context) {" sb =" new" scriptcallbacktimerdeclaration =" #region" timer =" new" interval="{0};" timeout="{1};" timeleft="{1};" synchronizestopwatch="{2};" countdown=" {{" millisecond="0;" second="0;" minute="0;" timervhour="0;" ispostbackontimeout="'{3}';" scriptcallbacktimerdeclaration =" String.Format(scriptCallBackTimerDeclaration," scriptcountdowntimer =" #region" initialize="function()" refcountdowntimer="setTimeout('Timer.ShowCountDownTimer()',100);" stopcountdowntimer="function()" updatecountdowntimer="function" hour="Math.floor(Timer.TimeLeft/3600);" minute =" Math.floor((Timer.TimeLeft" second =" Timer.TimeLeft" millisecond="0;" showcountdowntimer =" function()">0 || Timer.Minute>0 || Timer.Second>0)
{
if (Timer.MilliSecond<=0) { Timer.MilliSecond=9; Timer.Second-=1; Timer.TimeLeft-=1; } else Timer.MilliSecond-=1; if (Timer.Second<=0) { Timer.MilliSecond=9; Timer.Second=59; Timer.Minute-=1; Timer.TimeLeft-=1; } if (Timer.Minute<=-1) { Timer.Minute=59; Timer.Hour-=1; } if(Timer.Hour<=-1) { Timer.MilliSecond=0; Timer.Second=0; Timer.Minute=0; Timer.Hour=0; } } else { Timer.TimeLeft=-9; if(Timer.IsPostBackOnTimeOut=='true') Timer.CallTimeOutHandler(); else Timer.CallServer(); Timer.StopCallBackTimer(); } Timer.Display=document.getElementById('__DControls__Timer__Display'); Timer.Display.innerHTML =Timer.Hour+'hr '+ Timer.Minute+'min '+Timer.Second+'sec'; if(Timer.TimeLeft>0)
Timer.RefCountDownTimer=setTimeout('Timer.ShowCountDownTimer()',100);
else
{
if(Timer.IsPostBackOnTimeOut=='true')
Timer.CallTimeOutHandler();
}
}
";
#endregion

String scriptCallBackTimerMembers =
#region Call Back Timer Members
@"
Timer.CallTimeOutHandler=function()
{
__doPostBack('TimeOutPostBack','-9');
}

Timer.StopCallBackTimer=function()
{
clearTimeout(Timer.RefCallBackTimer);
}

Timer.StartCallBackTimer=function()
{
if(Timer.TimeLeft>0)
{
if(Timer.TimeLeft*1000<=0) Timer.RefCallBackTimer=window.setTimeout('Timer.CallServer()', Timer.TimeLeft*1000); else if(Timer.Interval>0)
Timer.RefCallBackTimer=window.setTimeout('Timer.CallServer()', Timer.Interval);
}
else
{
Timer.StopCallBackTimer();
}
}

Timer.CallServer=function()
{
CallTheServer(Timer.TimeLeft, '');
}

function ReceiveServerData(Result, context)
{
if(Timer.SynchronizeStopWatch==Timer.CountDown.Sync)
{
Timer.TimeLeft=Result;
Timer.Initialize();
}
else
{
Timer.StartCallBackTimer();
}
}

function ProcessCallBackError(arg, context)
{
Timer.StopCallBackTimer();

}

Timer.Initialize();
";
#endregion
//alert('Error : Call Back Method Failed'+' Arg : '+arg+' Context : '+context); put back it in function ProcessCallBackError if needed
// sb.Append("");

return sb.ToString();
}


#endregion

#region Timer Events
[Description("Notifies your application when a specified Time Out occurred.")]
[Category("Timer")]
public event TimerTimeOutEvent.TimerTimeOutEventHandler TimeOutOccurred;
protected virtual void OnTimeOutOccurred(TimerEventArgs e)
{
if (TimeOutOccurred != null) TimeOutOccurred(this, e);
}

[Description("Notifies your application when a specified period of time has elapsed. It is trigged through a client callback method.")]
[Category("Timer")]
public event TimerIntervalEvent.TimerIntervalEventHandler IntervalReached;
protected virtual void OnIntervalReached(TimerEventArgs e)
{
if (IntervalReached != null) IntervalReached(this, e);
}

#endregion

///
/// After Page_Init(), the LoadViewState event is fired to load values from the hidden __VIEWSTATE
/// So all property values stored in the ViewState won't be avalable in the Page Init() Stage.
///
#region Properties
private bool _enabled = true;
[Description("Enabled state of the Timer.")]
[Category("Timer Settings")]
public new bool Enabled
{
get
{
return _enabled;
}

set
{
_enabled = value;
}
}
private bool _IsAutoStart;
[Description("Auto Start Timer.")]
[Category("Timer Settings")]
public bool IsAutoStart
{
get
{
return _IsAutoStart;
}

set
{
_IsAutoStart = value;
}
}

[Browsable(false)]
[DefaultValue(false)]
public bool IsManualStart
{
get
{
HttpCookie timerCookie = HttpContext.Current.Request.Cookies["TimerSettings"];
if (timerCookie != null)
if (timerCookie["isManual"] != null)
return bool.Parse(timerCookie["isManual"].ToString());
return false;
}

set
{
HttpCookie timerCookie = HttpContext.Current.Request.Cookies["TimerSettings"];
if (timerCookie != null)
{
timerCookie["isManual"] = value.ToString();
HttpContext.Current.Response.Cookies.Add(timerCookie);
}
}
}

private int _timeOut;
[Description("TimeOut defined in seconds.")]
[Category("Timer Settings")]
public int TimeOut
{
get
{
return _timeOut;
}

set
{
_timeOut = value;
}
}

private int _interval;
[Description("Interval defined in seconds.")]
[Category("Timer Settings")]
public int Interval
{
get
{
return _interval;
}

set
{
_interval = value;
}
}

private int _timeLeft;
[Browsable(false)]
public int TimeLeft
{
get
{
HttpCookie timerCookie = HttpContext.Current.Request.Cookies["TimerSettings"];
if (timerCookie != null)
Int32.TryParse(timerCookie["timeLeft"].ToString(), out _timeLeft);
return _timeLeft;
}

set
{
HttpCookie timerCookie = HttpContext.Current.Request.Cookies["TimerSettings"];
if (timerCookie != null)
{
timerCookie["timeLeft"] = value.ToString();
HttpContext.Current.Response.Cookies.Add(timerCookie);
}

_timeLeft = value;
}
}

private bool _serverSideTimeSync;
[Description("Update Timer's StopWatch with Server Time for each interval.")]
[Category("Timer Settings")]
public bool ServerSideTimeSynchronize
{
get
{
return _serverSideTimeSync;
}

set
{
_serverSideTimeSync = value;
}
}


private bool _disableRightClick;
[Description("Disables mouse right click.")]
[Category("Timer Settings")]
public bool DisableRightClick
{
get
{
return _disableRightClick;
}

set
{
_disableRightClick = value;
}
}

private bool _doPostbackOnTimeOut;
[Description("Allow full postback on Timeout.")]
[Category("Timer Settings")]
public bool DoPostBackOnTimeOut
{
get
{
return _doPostbackOnTimeOut;
}

set
{
_doPostbackOnTimeOut = value;
}
}

[Browsable(false)]
public bool IsPostBackOnTimeOut
{
get
{
String eventTarget = this.Page.Request["__EVENTTARGET"];
return eventTarget == "TimeOutPostBack" ? true : false;
}
}
#endregion
}


#region Timer Event Arg Class Definition

public class TimerEventArgs
{
private int _timeLeft;
public int TimeLeft { get { return _timeLeft; } }

public TimerEventArgs(int timeLeft)
{
_timeLeft = timeLeft;
}
}

public class TimerIntervalEvent
{
public delegate void TimerIntervalEventHandler(object sender, TimerEventArgs e);
}

public class TimerTimeOutEvent
{
public delegate void TimerTimeOutEventHandler(object sender, TimerEventArgs e);
}
#endregion

Class File For Hashing Value Using SHA256 Algorithum

using System;
using System.Security.Cryptography;
using System.Text;

namespace Hash
{
public class Hash
{
public Hash() { }

public enum HashType : int
{
MD5,
SHA1,
SHA256,
SHA512
}

public static string GetHash(string text, HashType hashType, string key)
{
string hashString;
switch (hashType)
{
case HashType.MD5:
hashString = GetMD5(text);
break;
case HashType.SHA1:
hashString = GetSHA1(text);
break;
case HashType.SHA256:
hashString = GetSHA256(text, key);
break;
case HashType.SHA512:
hashString = GetSHA512(text);
break;
default:
hashString = "Invalid Hash Type";
break;
}
return hashString;
}

public static bool CheckHash(string original, string hashString, HashType hashType, string key)
{
string originalHash = GetHash(original, hashType, key);
return (originalHash == hashString);
}

private static string GetMD5(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);

MD5 hashString = new MD5CryptoServiceProvider();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}

private static string GetSHA1(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);

SHA1Managed hashString = new SHA1Managed();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}

private static string GetSHA256(string text, string key)
{


UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;

byte[] message = UE.GetBytes(text);
byte[] hashkey = UE.GetBytes(key);

HMACSHA256 hashString = new HMACSHA256(hashkey);

//SHA256Managed hashString = new SHA256Managed();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}

private static string GetSHA512(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);

SHA512Managed hashString = new SHA512Managed();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
}
}