Powered By Blogger

Thursday, March 18, 2010

CLASS FILE FOR DATABASE OPERATION



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.Data.SqlClient;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Web.Configuration;


///
/// Summary description for MyFunction
///

public class EBizFunction
{
public string ConnectionStr = ConfigurationManager.ConnectionStrings["EBizConnectionString"].ToString();
SqlConnection con;
SqlCommand com;
SqlDataReader dr;
SqlDataReader Drr;
SqlDataAdapter da;
DataSet ds;
ArrayList ArrList = new ArrayList();
int Result;
static Random random = new Random();
string FromMail = ConfigurationManager.AppSettings["SenderUsername"].ToString();
string password = ConfigurationManager.AppSettings["SenderPassword"].ToString();
string host = ConfigurationManager.AppSettings["HostIP"].ToString();
//string portNo = ConfigurationManager.AppSettings[""].ToString();
string portNo = "587";
string[] StrArr = null;


public EBizFunction()
{
//
// TODO: Add constructor logic here
//
}

public SqlConnection DBConnect()
{
try
{
con = new SqlConnection(ConnectionStr);
if (con.State != ConnectionState.Open)
{
con.Open();
}
return con;
}
catch (Exception)
{

throw;
}

}

public string ExecScalar(string Qry)
{
try
{
com = new SqlCommand(Qry, DBConnect());
return Convert.ToString(com.ExecuteScalar());
}
catch (Exception)
{
throw;
}
finally
{

con.Close();
}
}

public int ExecQry(string Qry)
{
try
{
com = new SqlCommand(Qry, DBConnect());
return com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{

con.Close();
}
}

public string[] ExecDataReader(string Qry)
{
try
{

com = new SqlCommand(Qry, DBConnect());
dr = com.ExecuteReader();
return StrArr;
}
catch
{
return StrArr = null;
}
finally
{

con.Close();
}
}

public DataSet FillDataset(string Qry)
{
ds = new DataSet();
ds.Clear();
da = new SqlDataAdapter(Qry, DBConnect());
da.Fill(ds);
return ds;
}

public ArrayList FillArrayList(string Qry)
{
try
{
ArrList.Clear();
FillDataset(Qry);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if(ds.Tables[0].Rows[i][0].ToString()!="") ArrList.Add(ds.Tables[0].Rows[i][0].ToString()); } return ArrList; } catch (Exception) { throw; } finally { ds.Clear(); con.Close(); } }

public ArrayList FillArrayListTwoValues(string Qry)
{ try
{ ArrList.Clear(); FillDataset(Qry); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (ds.Tables[0].Rows[i][0].ToString() != "") { ArrList.Add(ds.Tables[0].Rows[i][0].ToString() + " (" + ds.Tables[0].Rows[i][1].ToString()+ ")"); } } return ArrList; } catch (Exception) { throw; } finally { ds.Clear(); con.Close(); } }

public void GenerateRandomValue()
{ Result= RandomNumber(0, 1000); }

public int RandomNumber(int min, int max)
{ Random random = new Random(); return random.Next(min, max); }

public string RandomString(int size, bool lowerCase)

{ StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } if (lowerCase) return builder.ToString().ToLower(); return builder.ToString(); }

public void SendMail(string ToMail, string MailBody ,string SubjecT)

{ System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings"); System.Net.NetworkCredential credential = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password); int i = 0; //Create the SMTP Client SmtpClient client = new SmtpClient(); client.Host = settings.Smtp.Network.Host; client.Credentials = credential; HttpResponse response = HttpContext.Current.Response; MailMessage email = new MailMessage(); email.IsBodyHtml = true; email.From = new MailAddress(FromMail); email.To.Add(
ToMail);


//email.To.Add(strToEmail)
email.Subject = SubjecT;
email.IsBodyHtml = true;
email.Body = MailBody;
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

try
{
client.Send(email);
}
catch (Exception exc)
{
response.Write("Send failure: " + exc.ToString());
}
}

public void SendMail(string FrmMail, string ToMail, string MailBody, string SubjecT)
{
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);

int i = 0;
//Create the SMTP Client
SmtpClient client = new SmtpClient();
client.Host = settings.Smtp.Network.Host;
client.Credentials = credential;
HttpResponse response = HttpContext.Current.Response;
MailMessage email = new MailMessage();



email.IsBodyHtml = true;
email.From = new MailAddress(FrmMail);

email.To.Add(ToMail);

//email.To.Add(strToEmail)
email.Subject = SubjecT;
email.IsBodyHtml = true;
email.Body = MailBody;
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

try
{
client.Send(email);

}
catch (Exception exc)
{
response.Write("Send failure: " + exc.ToString());

}
}

public string SplitUp(string StrToSpilt, char cut,int Indx,char EndCut)
{
string[] Splt = null;
Splt = StrToSpilt.Split(cut);
return Splt[Indx].TrimEnd(EndCut);
}

public string[] SplitUp(string StrToSpilt, char cut)
{
string[] Splt = null;
Splt = StrToSpilt.Split(cut);
return Splt;
}

public int NoOfDays(DateTime FromDate, DateTime ToDate)
{
TimeSpan ts = ToDate.Subtract(FromDate);
int day = ts.Days;
return day+1;
}

public string IndianDateConverter(string Dat)
{
string[] StrArr;
string str;
StrArr = Dat.Split('/');
str = Convert.ToString(StrArr[0]);
StrArr[0] = Convert.ToString(StrArr[1]);
StrArr[1] = str;
Dat = "";
Dat = StrArr[0] + "/";
Dat += StrArr[1] + "/";
Dat += StrArr[2];
return Dat;
}

}


JavaScript Validations in ASP.Net

Validations



validate ONLY NUMBERS on TEXTBOX
-------------------------------------------
--------

function OnlyNumber(e)

{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (event)
keycode = event.keyCode;

else if (e)
keycode = e.which;
else
return true;
if((keycode >= 48 && keycode <= 57) || keycode == 13)
{
return true;
}
else
{
alert('Enter Only Number');
return false;
}
return true;
}


validate ONLY NUMBERS on TEXTBOX
-------------------------------------------
--------

function OnlyCharacters(e)

{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (event)
keycode = event.keyCode;

else if (e)
keycode = e.which;
else
return true;
if( (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122) || keycode == 13 )
{
return true;
}
else
{
alert('Enter Only Characters');
return false;
}
return true;
}


validate SPECIAL Character on TEXTBOX
-------------------------------------------
--------


.CS
---------


Txt_Pwd.Attributes.Add("onkeypress", "return alphanumeric_SomeSpl(this);");


HEAD
---------


function alphanumeric_SomeSpl(e)

{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (event)
keycode = event.keyCode;

else if (e)
keycode = e.which;
else
return true;
//Number, Character,Enter key(13),Underscore,Hyphen,@,fullstop,comma,dollar,
if( (keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122) || keycode == 13 || keycode == 45 || keycode == 64 || keycode == 46 || keycode == 44 || keycode == 36 || keycode == 95 )
{
return true;
}
else
{
alert('Character Not Allowed Only');
return false;
}
return true;
}


validate Character on date Field
-------------------------------------------


.CS
---------


txt_FromDateFilter.Attributes.Add("onkeypress", "return TypeDate1();");



HEAD
---------


function TypeDate1()
{
var txt1=document.getElementById('<%=txt_FromDateFilter.ClientID %>');
var fromDate = txt1.value;
var iChars = "!@#$%^&*()+=[]\\\';,.{}|\":<>?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < fromDate.length; i++)
{
if (iChars.indexOf(fromDate.charAt(i)) != -1)
{
alert ("Invalid From Date Format.\n Characters not allowed \n Ex: 12/31/2000 or 12-31-2000");
txt1.value='';
return false;
}

}
return true;
}

-----------------------------------------------------------------------------------------------

Validate for FUTURE date
------------------------------------


HEAD
---------


//Check For Past Date, if it is past date it l clear the value....
function DateChek(txtDate)
{
var Lstid=txtDate.id;
var txtBox=document.getElementById(Lstid);
var spanDays = $get("spanDays");

var toDate=txtBox.value;
var mySplitResult;
var dt;



var myDay1;
var MyMon1;
var myYear1;

mySplitResult= toDate.split("/");
myDay1=mySplitResult[0];
MyMon1=mySplitResult[1];
myYear1=mySplitResult[2];
dt=MyMon1 + '/' + myDay1 + '/' + myYear1;



var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
spanDays.innerHTML='';
if(Date.parse(month + "/" + day + "/" + year)>Date.parse(dt))
{

alert('Enter Future Date');
//spanDays.innerHTML='Enter Future Date';
txtBox.value="";
return false;
}

}

BODY


<asp:TextBox ID="txt_FromDateFilter" runat="server" CssClass="TxtBxCalender" onchange="DateChek(this)"></asp:TextBox>

-------------------------------------------------------------------------------------------------


To Date must be greater than or equal to From Date.

HEAD
---------

function ValidateDate()

{


// var fromDate = document.forms['recentUpdates'].elements['fromDate'].value;

// var toDate = document.forms['recentUpdates'].elements['toDate'].value;
var txt1=document.getElementById('<%=txt_FromDate.ClientID %>');
var txt2=document.getElementById('<%=txt_ToDate.ClientID %>');
var spanDays = $get("spanDays");



var fromDate = txt1.value;

var toDate = txt2.value;

var mySplitResult = fromDate.split("/");
var dt;

var myDay;
var MyMon;
var myYear;

var myDay1;
var MyMon1;
var myYear1;

myDay=mySplitResult[0];
MyMon=mySplitResult[1];
myYear=mySplitResult[2];
dt=MyMon + '/' + myDay + '/' + myYear;
fromDate=dt;

mySplitResult= toDate.split("/");
myDay1=mySplitResult[0];
MyMon1=mySplitResult[1];
myYear1=mySplitResult[2];
dt=MyMon1 + '/' + myDay1 + '/' + myYear1;
toDate=dt;

var alertReason1 = 'To Date must be greater than or equal to From Date.'

var endDate = new Date(toDate);

var startDate= new Date(fromDate);


// var startDateValuecmp = startDate.getTime();
// var endDateValuecmp = endDate.getTime();
spanDays.innerHTML='';
if(fromDate == '' && toDate == '')

{

alert("Please enter From Date and To Date.");

return false;

}

else if(fromDate == '')

{
txt2.value='';
alert("Please enter From Date. ");

return false;

}
else if(txt1.value == '')

{
txt2.value='';
alert("Please enter From Date. ");

return false;

}

else if(toDate == '')

{

alert("Please enter To Date. ");

return false;

}
else if(toDate != '' && fromDate == '')

{
txt2.value='';
alert("Please enter From Date. ");

return false;

}


else if (fromDate !='' && toDate != '' && startDate > endDate)

{
txt2.value='';
alert(alertReason1);

return false;

}
else if (fromDate !='' && toDate != '' && startDate <= endDate)
{

var startingdate=new Date(myYear,MyMon,myDay);
var endingdate=new Date(myYear1,MyMon1,myDay1);
var one_day=1000*60*60*24;
//alert("Difference is " + Math.ceil((endingdate.getTime()-startingdate.getTime())/(one_day)) + " days ");
spanDays.innerHTML="You are applying leave for " + ( Math.ceil((endingdate.getTime()-startingdate.getTime())/(one_day)) + 1 )+ " day(s) "
return true;
}


}

BODY
---------


<asp:TextBox ID="txt_TODATE" runat="server" CssClass="TxtBxCalender" onchange="ValidateDate()"></asp:TextBox>


====================================================================


GET MULTIPLE SELECTED VALUES IN LISTBOX USING JAVASCRIPT


Add 3 hidden fields and a list box, enable multiple select in listbox property

HEAD
---------



function MultipleSelect(listfield,HidID,HidID1,HidID2)
{
var selected="";
var Lstid=listfield.id;
var LstBox=document.getElementById(Lstid);
var HiddenFld=document.getElementById(HidID);
var HiddenFld1=document.getElementById(HidID1);
var HiddenFld2=document.getElementById(HidID2);
HiddenFld.value='';
HiddenFld1.value='';
HiddenFld2.value='0';
for (i=0; i < LstBox.length; i++)
{
if (LstBox.options[i].selected)
{

selected=LstBox.options[i].text; // Name and Designation
selected1=LstBox.options[i].value; //Mail ID and Emp Code

if(i==0)
{
HiddenFld.value = selected;
HiddenFld1.value = selected1;
}
else
{
HiddenFld.value = HiddenFld.value + "," + selected ;
HiddenFld1.value = HiddenFld1.value + "," + selected1 ;

}

}
}
HiddenFld2.value=i;

}

.CS
---------


ListBox_AbsenceWork.Attributes.Add("onchange", "MultipleSelect(this,'" + HiddenField1.ClientID + "','" + HiddenField2.ClientID + "','" + HiddenField3.ClientID + "')");

===================================================================

Monday, March 15, 2010

Gridview Row Editing Event , Row Deleting Event, Selected Index Changed Event


Get Values in Row Editing Event

string Val= GridView1.Rows[e.NewEditIndex].Cells[1].Text;

Get Values in Row Deleting Event

string Val=GridView1.Rows[e.RowIndex].Cells[1].Text;

Get Values in SelectedIndexChanged Event

string Val=GridView1.SelectedDataKey["Fs_EmpCode"].Tostring();


Hide Columns in a GridView

GridView1RowCreated Event

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].CssClass = "hiddencol";
e.Row.Cells[2].CssClass = "hiddencol";
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].CssClass = "hiddencol";
e.Row.Cells[2].CssClass = "hiddencol";
}


StyleSheet:

.hiddencol
{
display:none;
}


Client Click in Gridview command field

Gridview_RowDataBound Event

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}

Important Note:

The important bit here is to use exactly the OnClientClick
content provided (except the wording in the message, of course). If you,
for example, instead, had "return confirm('Are you sure you want to delete the
record')"
like many others have suggested, this would
mean the Delete command would never be posted back to the server. The
actual onclick function call generated/rendered by ASP.NET






Tuesday, March 9, 2010

Username availability



<div>



<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

</asp:ScriptManager>



<asp:TextBox ID="UserName" runat="server" CssClass="txt" onkeyup="usernameChecker(this.value);" />
<span id="spanAvailability"></span>


<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");

function usernameChecker(username)
{
clearTimeout(usernameCheckerTimer);
if (username.length == 0)
spanAvailability.innerHTML = "";
else
{
spanAvailability.innerHTML = "<span style='color: #ccc;'>checking...</span>";
usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
}
}

function checkUsernameUsage(username)
{
// initiate the ajax pagemethod call
// upon completion, the OnSucceded callback will be executed
PageMethods.IsUserAvailable(username, OnSucceeded);
}

// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName)
{

if (methodName == "IsUserAvailable")
{
if (result == true)
spanAvailability.innerHTML = "<span style='color: DarkGreen;'>Available</span>";
else
spanAvailability.innerHTML = "<span style='color: Red;'>Unavailable</span>";
}
}
</script>

</div>

--------------------------------------------------



Sql
-----

CREATE PROCEDURE CheckUserName( @User_Name VARCHAR(50) )
AS
BEGIN

IF EXISTS (SELECT * FROM TLOGIN WHERE USERNAME = @User_Name )

SELECT '1'; --user name already exist in database

ELSE

SELECT '0'; --user name does not exist in database

END





.aspx.cs
----------

using System.Web.Services;
using System.Data.SqlClient;



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

}


[WebMethod]
public static bool IsUserAvailable(string username)
{

string returnValue = string.Empty;

string conString = "Password=iclip;Persist Security Info=True;User ID=iclip;Initial Catalog=ebiz;Data Source=purush";

SqlConnection sqlConn = new SqlConnection(conString);

try
{

SqlCommand sqlCmd = new SqlCommand("CheckUserName", sqlConn);

sqlCmd.CommandType = CommandType.StoredProcedure;

sqlCmd.Parameters.AddWithValue("@User_Name", username.Trim());

sqlConn.Open();

int success = int.Parse((sqlCmd.ExecuteScalar().ToString()));

if (success == 1) // User Name Not Available
{
//returnValue = "<img src='Images/no.jpeg'><font color='#cc0000'><b>'" + username + "'</b> is already in use.</font></img>";
return false;
}
else//User_Name is available
{
return true;
//returnValue = "Available";
}

}
catch
{
return false;
}
finally
{
sqlConn.Close();
}


}
}


Wednesday, February 24, 2010

AutoCompleteExtender with Animation

AutoCompleteExtender with Animation

<cc1:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" BehaviorID="AutoCompleteEx"
DelimiterCharacters="" Enabled="True" ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionInterval="10"
EnableCaching="true" CompletionSetCount="12" TargetControlID="txtName" >
<Animations>
<OnShow>
<Sequence>
<OpacityAction Opacity="0" />
<HideAction Visible="true" />
<ScriptAction Script="
// Cache the size and setup the initial size
var behavior = $find('AutoCompleteEx');
if (!behavior._height) {
var target = behavior.get_completionList();
behavior._height = target.offsetHeight - 2;
target.style.height = '0px';
}" />
<Parallel Duration=".4">
<FadeIn />
<Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
</Parallel>
</Sequence>
</OnShow>
<OnHide>
<Parallel Duration=".4">
<FadeOut />
<Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
</Parallel>
</OnHide>
</Animations>

</cc1:AutoCompleteExtender>

Friday, January 29, 2010

File word count, whitespace count,Word Matches in C#



load event()
{
string FPath = @"D:\x.docx";
string text = File.ReadAllText(FPath);
MatchWord(FPath,"TestWordTOCount");
}

public void MatchWord(string Fname, string WordToMatch)
{
int count;
StreamReader reader = File.OpenText(Fname);
string contents = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(contents, WordToMatch);
count = matches.Count;
}

static int CountNonSpaceChars(string value)
{
///
/// Counts the number of non-whitespace characters.
/// It closely matches Microsoft Word 2007.
///

/// String you want to count non-whitespaces in.
/// Number of non-whitespace chars.

int result = 0;
foreach (char c in value)
{
if (!char.IsWhiteSpace(c))
{
result++;
}
}
return result;
}

static int CountChars(string value)
{

///
/// Return the number of characters in a string using the same method
/// as Microsoft Word 2007. Sequential spaces are not counted.
///

/// String you want to count chars in.
/// Number of chars in string.


int result = 0;
bool lastWasSpace = false;

foreach (char c in value)
{
if (char.IsWhiteSpace(c))
{
// A.
// Only count sequential spaces one time.
if (lastWasSpace == false)
{
result++;
}
lastWasSpace = true;
}
else
{
// B.
// Count other characters every time.
result++;
lastWasSpace = false;
}
}
return result;
}

Saturday, January 9, 2010

Encoding and Decoding string c#

Encode

public string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}

Decode

public string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}



Friday, January 8, 2010

Load Image using Ajax C# and VB.net



Create a Empty Page as

ImagePrev.aspx

And Create a new page with the below code:


<div>
<asp:ScriptManager id="ScriptManager1" runat="server">
</asp:ScriptManager><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Image id="Image1" runat="server"></asp:Image>
<br />
<div id="ImagePreviewer" runat="server" style="background-position: center center;
background-image: url(Images/no-image.gif); width: 150px; background-repeat: no-repeat;
height: 150px">
</div>
<asp:FileUpload id="FileUpload1" runat="server"></asp:FileUpload>
<br />
<asp:LinkButton id="lnk_viewImg" runat="server" OnClick="lnk_viewImg_Click">View Image</asp:LinkButton>
<br />
</ContentTemplate>

</asp:UpdatePanel>

</div>


ImagePrev.aspx.cs

protected void lnk_viewImg_Click(object sender, EventArgs e)
{
//Image1.ImageUrl = FileUpload1.

Stream stream = default(Stream);

//HttpPostedFile oFile = Request.Files(0);
HttpPostedFile oFile = Request.Files[0];

stream = oFile.InputStream;

byte[] uploadedFile = new byte[stream.Length + 1];
byte[] a = null;

stream.Read(uploadedFile, 0, Convert.ToInt32(stream.Length));

if (Session["UploadImage"] != null)
Session["UploadImage"] = uploadedFile;
else
Session.Add("UploadImage", uploadedFile);

//ImagePreviewer.Style.Item("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)";
//ImagePreviewer.Style.Add("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)";
ImagePreviewer.Style.Add("BACKGROUND-IMAGE", "url(ImagePrev.aspx)");

}

ImagePrev.aspx.vb

button click

' Create a stream object.
Dim stream As IO.Stream
' Get the file that was selected.
Dim oFile As HttpPostedFile = Request.Files(0)
' Place the file into the stream.
stream = oFile.InputStream
' Create a byte array for the image.
Dim uploadedFile(stream.Length) As Byte
Dim a() As Byte
' Store the image into the byte array.
stream.Read(uploadedFile, 0, stream.Length)
' Store the byte array into a session variable.
If Session.Item("UploadImage") IsNot Nothing Then
Session.Item("UploadImage") = uploadedFile
Else
Session.Add("UploadImage", uploadedFile)
End If

' Set the ImagePreviewer's url to the ImagePrev page.
'ImagePreviewer.Style.Value("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)"
Me.ImagePreviewer.Style.Item("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)"