Wednesday, May 21, 2008

Call javascript function on coditiona bassis of c#

// May 21, 2008
if (IsPostBack)// when it will post back
{
string str = "hello()";


Page.ClientScript.RegisterStartupScript(this.GetType(), "adf", str,true );

}
else // when first time page laod
{
string str = "hello()";


Page.ClientScript.RegisterStartupScript(this.GetType(), "adf", str,true );

}

On JavaScript Section

[script language="javascript" type="Text/javascript"]
function hello()
{
alert('hi');
return false;
}
[/script]



Or Simply we can use it

if(true)
{

string strhelpondesk = " [ script language='javascript'] document.getElementById('ctl00_ContentPlaceHolder1').style.display = 'block'; [/script]";
Page.RegisterStartupScript("strhelpondesk", strhelpondesk);


}

Thanks
HElpondesk team

How we can use captcha image in our registration page

1) Class for capthca image.

using System;
using System.Data;
using System.Data.SqlClient;
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.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

/// [summary]
/// Summary description for randomImage
/// [/summary]
/// //This class is used to generate CaptchaImage on SignUp1 page.Image will generate randomly When different user
/// //user comes to SignUp1 page
public class randomImage
{
#region Private Properties

// Internal properties.
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;
#endregion

#region Public Properties
// Public properties (all read-only).
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}

#endregion

#region Public Methods
// For generating random numbers.
private Random random = new Random();
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
public randomImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}

// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width, height and font family.
// ====================================================================
public randomImage(string s, int width, int height, string familyName)
{
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(familyName);
this.GenerateImage();
}
// ====================================================================
// This member overrides Object.Finalize.
// ====================================================================
~randomImage()
{
Dispose(false);
}

// ====================================================================
// Releases all resources used by this object.
// ====================================================================
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}

// ====================================================================
// Custom Dispose method to clean up unmanaged resources.
// ====================================================================
protected virtual void Dispose(bool disposing)
{
if (disposing)
// Dispose of the bitmap.
this.image.Dispose();
}
// ====================================================================
// Sets the image width and height.
// ====================================================================
private void SetDimensions(int width, int height)
{
// Check the width and height.
if (width [= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height [= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}

// ====================================================================
// Sets the font used for the image text.
// ====================================================================
private void SetFamilyName(string familyName)
{
// If the named font is not installed, default to a system font.
try
{
Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
font.Dispose();

}
catch (Exception ex)
{
string msg = ex.Message;
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}
// ====================================================================
// Creates the bitmap image.
// ====================================================================
private void GenerateImage()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);

// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.White , Color.White);
g.FillRectangle(hatchBrush, rect);

// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width ] rect.Width);

// Set up the text format.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
float v = 30F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.SkyBlue , Color.SkyBlue );
g.FillPath(hatchBrush, path);

// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i [ (int)(rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}

// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();

// Set the image.
this.image = bitmap;
}
/// [summary]
/// This function helps to create a new random code which will be displayed in the
/// ImageRegistrationStr1 and will be used as digital signature.
/// [/summary]
/// [param name="codeCount"] The codeCount to be followed inside the function[/param]
/// [returns] String kind of variable which will be loaded with random code we needed.[/returns]
public string CreateRandomCode(int codeCount)
{
//try
//{
// String variable which contains all the possible characters.
string allChar = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
// String type array which will be filled by dividing the above string variable.
string[] allCharArray = allChar.Split(',');
// variable for temporary use.
string randomCode = "";
int temp = -1;
//Create an Object of Random Class
Random rand = new Random();

for (int Counter = 0; Counter [ codeCount; Counter++)
{
if (temp != -1)
{
//Create an Object of Random Class using specified seed value
rand = new Random(Counter * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(17);
if (temp != -1 && temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
//checkCode = randomCode;
////Session["CheckCode"] = checkCode;
}
return randomCode;
//}

//catch (Exception ex)
//{
// Session["Error"] = ex.Message;
// Response.Redirect("PageForErrors.aspx");
//}

}

#endregion

#region Constructor of the class
public randomImage()
{
//
// TODO: Add constructor logic here
//
}
#endregion
}



2) Code of JPEGImage.aspx.cs page which convert in image and call in image source as


#region [------------------------------ Directories----------------------------------------]
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawingy;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
#endregion
//This page is used to generate CaptchaImage which is randomly changed when user at SignUp1 page
public partial class Users_JPEGImage : System.Web.UI.Page
{
#region [--------------------------Page Load ----------------------------------]
protected void Page_Load(object sender, EventArgs e)
{
// Create a CAPTCHA image using the text stored in the Session object.
randomImage ci = new randomImage(this.Session["CaptchaImageText"].ToString(), 200, 50, "Century Schoolbook");


// Change the response headers to output a JPEG image.
this.Response.Clear();
this.Response.ContentType = "image/jpeg";

// Write the image to the response stream in JPEG format.
ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

// Dispose of the CAPTCHA image object.
ci.Dispose();

}
#endregion
}

2a) nothing much in its aspx page

[script src="http://www.google-analytics.com/urchin . js" type="text/javascript"]
[/script]
[script type="text/javascript"]
_uacct = "UA-4349440-1";
urchinTracker();
[/script]
[/head]
[body]
[form id="JpegImage" method="post" runat="server"]

[/form]
[/body]
[/html]

3) on signup page

a)

on page load initial the session value with image text

this.Session["CaptchaImageText"] = objrandom.CreateRandomCode(7);

b)

display captcha image in signup page.

[asp:Image ID="Image2" ImageUrl="JPEGImage.aspx" runat="server" Width="167" Height="64"
EnableViewState="false" /]


c) on submit button campare text and captcha image value before save user information.


this.Session["CaptchaImageText"] = objrandom.CreateRandomCode(7);

Tuesday, May 20, 2008

Set Auto Image Size Thumbnail and image resize functions are described below

how we have to call these functions:-

We must give the read write premmison to folder and we select right click and remove readonly property of folder.

1) Set Auto Image Size :-
MyobjectofClassWhereIputMyFunction.AutoImageSize(Request.PhysicalApplicationPath + "UsersImage\\Thumbnail\\" +

objPicName.ToString(), Request.PhysicalApplicationPath + "UsersImage\\Thumbnail\\" + "PlaceGoing2_" + e.Item.ItemIndex +

objPicName.ToString(), 51);






using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Collections;

///
/// This function used for setting the size of image at run time
///

/// orgpath where the image is exist or stroe, modpath where we want to store the image, size it is

size of image
///
public void AutoImageSize(string orgpath, string modpath, int size)
{
//int maxDimension = 153;//this value can be any thing......
int maxDimension = size;
Bitmap bm = new Bitmap(orgpath);
double num = ((float)bm.Width) / ((float)bm.Height);
if (System.IO.File.Exists(modpath))
{
System.IO.File.Delete(modpath);
}
if ((num > 1.0) && (bm.Width > maxDimension))
{

System.Drawing.Image image = new Bitmap(maxDimension, (int)(((double)maxDimension) / num));
Graphics graphics = Graphics.FromImage(image);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(bm, 0, 0, maxDimension, (int)(((double)maxDimension) / num));
image.Save(modpath);
image.Dispose();
}
else if (bm.Height > maxDimension)
{
System.Drawing.Image image = new Bitmap((int)(maxDimension * num), maxDimension);
Graphics graphics = Graphics.FromImage(image);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(bm, 0, 0, (int)(maxDimension * num), maxDimension);
image.Save(modpath);
image.Dispose();
}
else
{
System.Drawing.Image image = new Bitmap(bm);
image.Save(modpath);
image.Dispose();
}

bm.Dispose();
}


public void Resize(string sPhysicalPath, string sOrgFileName, string sThumbNailFileName, ImageFormat oFormat, int

intMaxSize)
{

try
{
FileInfo objFileInfo = new FileInfo(sPhysicalPath + sThumbNailFileName);
if (objFileInfo.Exists)
{
objFileInfo.Delete();
}

if (sOrgFileName.IndexOf(".bmp") > 0)
{
Size ThumbNailSize = new Size();
Bitmap oImg = new Bitmap(sPhysicalPath + sOrgFileName);

if (oImg.Width > intMaxSize || oImg.Height > intMaxSize)
{
if (oImg.Width > oImg.Height)
{
ThumbNailSize.Height = (int)((intMaxSize * 1.0F / oImg.Width * 1.0F) * oImg.Height * 1.0F);
ThumbNailSize.Width = intMaxSize;
}
else
{
ThumbNailSize.Width = (int)((intMaxSize * 1.0F / oImg.Height * 1.0F) * oImg.Width * 1.0F);
ThumbNailSize.Height = intMaxSize;
}
}
else
{
ThumbNailSize.Height = oImg.Height;
ThumbNailSize.Width = oImg.Width;
}

// System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.

System.Drawing.Image.GetThumbnailImageAbort myCallback = new

System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

System.Drawing.Image myThumbnail = oImg.GetThumbnailImage(ThumbNailSize.Width, ThumbNailSize.Height,

myCallback, IntPtr.Zero);
myThumbnail.Save(sPhysicalPath + @"\" + sThumbNailFileName);
oImg.Dispose();
}
else
{
Size ThumbNailSize = new Size();
System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + sOrgFileName);

if (oImg.Width > intMaxSize || oImg.Height > intMaxSize)
{
if (oImg.Width > oImg.Height)
{
ThumbNailSize.Height = (int)((intMaxSize * 1.0F / oImg.Width * 1.0F) * oImg.Height * 1.0F);
ThumbNailSize.Width = intMaxSize;
}
else
{
ThumbNailSize.Width = (int)((intMaxSize * 1.0F / oImg.Height * 1.0F) * oImg.Width * 1.0F);
ThumbNailSize.Height = intMaxSize;
}
}
else
{
ThumbNailSize.Height = oImg.Height;
ThumbNailSize.Width = oImg.Width;
}

System.Drawing.Image oThumbNail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
Graphics oGraphic = Graphics.FromImage(oThumbNail);

oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle oRectangle = new Rectangle(0, 0, ThumbNailSize.Width, ThumbNailSize.Height);
oGraphic.DrawImage(oImg, oRectangle);
oThumbNail.Save(sPhysicalPath + sThumbNailFileName, oFormat);

oImg.Dispose();
}

objFileInfo = null;
}
catch (Exception ex) { throw ex; }
}

Friday, May 16, 2008

Normal javascript validations for signup pages replace spaceDotSpace with

// JScript File




function setFocus()
{

if(document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13") . style . display =='block')
{
document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13") . style . display='none';
document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13") . style . visibility='hidden';
}

document . getElementById("ctl00_ContentPlaceHolder1_txtDateOfBirth") . focus();
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = true;

return false;

}






function chkDobAge()
{



// function for DOB


ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtDateOfBirth');



if(ctrl . value=="" || ctrl . value=="mm/dd/yyyy" )
{

alert('Please enter date of birth');
ctrl . focus();
return false;
}


var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Date of birth must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}

var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\ . )31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\ . )(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\ . )29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\ . )(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
var errorMessage = 'Please enter valid date as month, day, and four digit year . \nYou may use a slash, hyphen or period to separate the values . \nThe date must be a real date . 2-30-2000 would not be accepted . \nFormay mm/dd/yyyy . ';
if ((ctrl . value . match(RegExPattern)) && (ctrl . value!=''))
{

}
else
{
alert('Enter valid date in US format(MM/DD/YYYY)');
ctrl . focus();
ctrl . value="";
return false;
}

var objDate = ctrl . value;
var currentTime = new Date();
var month = currentTime . getMonth() + 1
var day = currentTime . getDate()
var year = currentTime . getFullYear()
var objCurrentDate=month + "/" + day + "/" + year;


if (Date . parse(objDate) >= Date . parse(objCurrentDate))
{

alert('Date of birth should not be greater than current date');
ctrl . value="";
ctrl . focus();
return false;
}





// end of fucntion DOB


//chk age


//// Getin the DOB
var DOBmdy = (document . getElementById("ctl00_ContentPlaceHolder1_txtDateOfBirth") . value) . split('/');
// Created date object for geting previous 13 year date
var DOBmdyMonth = DOBmdy[0] -1;
var myDate=new Date();

// Geting the previous dates
var Previousdate = myDate . getDate();


var PreviousMonth = myDate . getMonth();


var CurrentYear = myDate . getFullYear();

var PreviousYear = CurrentYear-13;

// End of // Geting the previous dates

// to find that DOB is in Leap year It it return 0 that mean it is leap year
var leapyear = DOBmdy[2]%4;
if (leapyear == 0)
{
// now check that month of leap year is Fab
if(DOBmdyMonth == 1)
{
// if month is Fab then check that date of month is 29
if(DOBmdy[1]== 29)
{
// now compare with 1 March Becz 29 is not in Fab month now
if(DOBmdy[2] < PreviousYear)
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;

}// condition DOBmdy[2] < PreviousYear end of if scope of if year is less
else if((DOBmdy[2] == PreviousYear) && (DOBmdyMonth < PreviousMonth))
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;

}
else if( (DOBmdy[2] == PreviousYear) && (DOBmdyMonth == PreviousMonth) && (DOBmdy[1] > 1))// here 1 is 1t march
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;

}
else
{

var divEmailPreviewMain = document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13");
divEmailPreviewMain . style . display='block';
divEmailPreviewMain . style . visibility='visible';
divEmailPreviewMain . style . position="absolute";
divEmailPreviewMain . style . top = '400px';
divEmailPreviewMain . style . left= '350px';
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = true;


return false;

}


// check that user is able to join site or not




if(DOBmdy[2] {


} // condition DOBmdy[2] else
{


var divEmailPreviewMain = document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13");
divEmailPreviewMain . style . display='block';
divEmailPreviewMain . style . visibility='visible';
divEmailPreviewMain . style . position="absolute";
divEmailPreviewMain . style . top = '400px';
divEmailPreviewMain . style . left= '350px';
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = true;


return false;



}// condition DOBmdy[2]


}// condition Previousdate == 29 end of If Scope
else
{

if((DOBmdy[2] < PreviousYear) && (DOBmdy[1] < Previousdate) && (DOBmdyMonth < PreviousMonth))
{
}// if conditon for okay user ((DOBmdy[2] < PreviousYear) && (DOBmdy[1] < Previousdate) && (DOBmdyMonth < PreviousMonth))
else
{

var divEmailPreviewMain = document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13");
divEmailPreviewMain . style . display='block';
divEmailPreviewMain . style . visibility='visible';
divEmailPreviewMain . style . position="absolute";
divEmailPreviewMain . style . top = '400px';
divEmailPreviewMain . style . left= '350px';
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = true;


return false;




} // end of Else scope of condition ((DOBmdy[2] < PreviousYear) && (DOBmdy[1] < Previousdate) && (DOBmdyMonth < PreviousMonth))


}//condition Previousdate == 29 end of Else Scope


}// condition CurrentMonth end of If Scope

} // condition leapyear == 0 end of If Scope



// end of check that month of leap year is Fab



// if DOB is in normal year


// second attempt for DOB normal text

// if year is less
if(DOBmdy[2] < PreviousYear)
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;

}// condition DOBmdy[2] < PreviousYear end of if scope of if year is less
else if((DOBmdy[2] == PreviousYear) && (DOBmdyMonth < PreviousMonth))
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;

}
else if( (DOBmdy[2] == PreviousYear) && (DOBmdyMonth == PreviousMonth) && (DOBmdy[1] < Previousdate))
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;

}
else if( (DOBmdy[2] == PreviousYear) && (DOBmdyMonth == PreviousMonth) && (DOBmdy[1] == Previousdate))
{
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = false;


}
else
{

var divEmailPreviewMain = document . getElementById("ctl00_ContentPlaceHolder1_divUnderAge13");
divEmailPreviewMain . style . display='block';
divEmailPreviewMain . style . visibility='visible';
divEmailPreviewMain . style . position="absolute";
divEmailPreviewMain . style . top = '400px';
divEmailPreviewMain . style . left= '350px';
document . getElementById("ctl00_ContentPlaceHolder1_imgBtnNext") . disabled = true;


return false;
}






//end of chk age


}











function registration()
{


var ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtEmailAddress');


if(ctrl . value=="" )
{
ctrl . focus();
alert('Please enter email address');

return false;
}



var emailReg = /^(([^<>()[\]\\ . ,;:\s@\"]+(\ . [^<>()[\]\\ . ,;:\s@\"]+)*)|(\" . +\"))@((\[[0-9]{1,3}\ . [0-9]{1,3}\ . [0-9]{1,3}\ . [0-9]{1,3}\])|(([a-zA-Z\-0-9]+\ . )+[a-zA-Z]{2,}))$/
if (! ctrl . value . match(emailReg))
{
alert('Enter valid email address');
ctrl . value="";
ctrl . focus();

return false;
}

// end of email id

// first name

ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtFirstName');


if(ctrl . value=="" )
{

alert('Enter first name');
ctrl . focus();
return false;
}



var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('First name must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}



var name=ctrl . value;
for(i=0;i {
if(!((name . charCodeAt(i)>=65 && name . charCodeAt(i)<=90)||(name . charCodeAt(i)>=97 && name . charCodeAt(i)<=122)||(name . charCodeAt(i)==32)))
{
alert('Enter valid first name');
ctrl . value="";
ctrl . focus();
return false
}
}


// end of first name


// function for last name
ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtLastName');


if(ctrl . value=="" )
{
ctrl . focus();
alert('Enter last name');

return false;
}



var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Last name must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}



var name=ctrl . value;
for(i=0;i {
if(!((name . charCodeAt(i)>=65 && name . charCodeAt(i)<=90)||(name . charCodeAt(i)>=97 && name . charCodeAt(i)<=122)||(name . charCodeAt(i)==32)))
{
alert('Enter valid last name');
ctrl . value="";
ctrl . focus();
return false
}
}



// end of function for last name

// function for screen name


ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtScreenName');


if(ctrl . value=="" || ctrl . value=="eg . nycgirl100 . . . ")
{
ctrl . focus();
alert('Enter screen name');

return false;
}



var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Screen name must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}

// end of function for screen name

// fucntion for password

ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtPassword');


if(ctrl . value=="" )
{
ctrl . focus();
alert('Please enter password');

return false;
}



var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Password must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}




var str=ctrl . value;
if((str . length)< 6 )
{
alert('Password must be atleast six character');
ctrl . focus();
ctrl . value="";
return false
}




// end funtion for password


// function for confirmation password


ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtConfirmPassword');


if(ctrl . value=="" )
{
ctrl . focus();
alert('Please enter confirm Password ');

return false;
}

var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Confirm password must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}

var str=ctrl . value;
if((str . length)< 6 )
{
alert('Confirm password must be atleast six character');
ctrl . focus();
ctrl . value="";
return false
}

var txtPassword = document . getElementById('ctl00_ContentPlaceHolder1_txtPassword');



if(ctrl . value != txtPassword . value)
{
alert('Confirm password should be same as the Password ');
ctrl . value="";
txtPassword . value="";
txtPassword . focus();
return false;
}


// end function for confirmation passoword



// function for zipcode
ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtZipCode');


if(ctrl . value=="" )
{
ctrl . focus();
alert('Please enter zipcode');

return false;
}


var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Zipcode must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}


var zip;

zip=ctrl . value;
for(i=0;i {
if(!((zip . charCodeAt(i)>=48) && (zip . charCodeAt(i)<=57)))
{
alert('Enter digits between 0-9');
ctrl . focus();
ctrl . value="";
return false
}
}




var str=ctrl . value;
if((str . length) != 5)
{
alert('Enter US zipcode only');
ctrl . focus();
ctrl . value="";
return false
}




// end for function zipcode

// function for DOB


ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtDateOfBirth');



if(ctrl . value=="" || ctrl . value=="mm/dd/yyyy" )
{

alert('Please enter date of birth');
ctrl . focus();
return false;
}


var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Date of birth must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}

var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\ . )31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\ . )(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\ . )29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\ . )(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
var errorMessage = 'Please enter valid date as month, day, and four digit year . \nYou may use a slash, hyphen or period to separate the values . \nThe date must be a real date . 2-30-2000 would not be accepted . \nFormay mm/dd/yyyy . ';
if ((ctrl . value . match(RegExPattern)) && (ctrl . value!=''))
{

}
else
{
alert('Enter valid date in US format(MM/DD/YYYY)');
ctrl . focus();
ctrl . value="";
return false;
}

var objDate = ctrl . value;
var currentTime = new Date();
var month = currentTime . getMonth() + 1
var day = currentTime . getDate()
var year = currentTime . getFullYear()
var objCurrentDate=month + "/" + day + "/" + year;


if (Date . parse(objDate) >= Date . parse(objCurrentDate))
{
//alert("The dates are valid . ");
alert('Date of birth should not be greater than current date');
ctrl . value="";
ctrl . focus();
return false;
}





// end of fucntion DOB








// function for sex

ctrl1 = document . getElementById('ctl00_ContentPlaceHolder1_rbtGenderMale');
ctrl2 = document . getElementById('ctl00_ContentPlaceHolder1_rbtGenderFemale');



if (ctrl1 . checked ==false )
{
if(ctrl2 . checked==false)
{
alert('Select gender');
return false;
}


}




// end of function for sex

//function for Pic extension
ctrl = document . getElementById("ctl00_ContentPlaceHolder1_picName");
if(document . getElementById("ctl00_ContentPlaceHolder1_picName") . value!="")
{


var photo=ctrl . value;
var index=photo . lastIndexOf(" . ");
var temp=photo . substring(index+1,(photo . length));
temp=temp . toUpperCase();
if(!(temp=="BMP" || temp=="JPG" || temp=="JPEG" || temp=="GIF"))
{
alert('Select an Bmp, Jpg or Gif file');
ctrl . value="";
ctrl . focus();
return false;
}

}







// end function for pic extension

// function for cpathcha image



ctrl = document . getElementById('ctl00_ContentPlaceHolder1_txtForVerficationOfCode');

if(ctrl . value=="" )
{
ctrl . focus();
alert('Enter same character as in image');

return false;
}



var str=ctrl . value;
if((str . charCodeAt(0)==32))
{
alert('Verification code must not be start with a blank character');
ctrl . value="";
ctrl . focus();
return false;
}




if((str . length) != 7)
{
alert('Enter all image text');
ctrl . focus();

return false
}

// end of function for captcha image







return true;
}


Thursday, May 8, 2008

Function for Transfering Focus to Submit Button When the Enter is press after entereing data in textBox

On C#
txtDescription.Attributes.Add("onkeypress", "return clickButton_focus(event,'" + btnSave.ClientID + "');");

On html

function clickButton_focus(e, buttonid)
{
var bt = document . getElementById(buttonid);
if (typeof bt == 'object'){
if(navigator .appName . indexOf("Netscape")>(-1)){
if (e . keyCode == 13){
bt.click();
return false;
}
}
if (navigator .appName.indexOf("Microsoft Internet Explorer")>(-1)){
if (event .keyCode == 13){
bt .click();
return false;
}
}
}
}

Date Time Formats Operations

DateTime Value Manipulation

Addition and Subtraction Operators

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

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");

// Add one hour, one minute and one second
theDate = theDate + new TimeSpan(1, 1, 1); // theDate = 2 Jan 2007 21:16:01

// Subtract twenty-five days
theDate = theDate - new TimeSpan(25, 0, 0, 0); // theDate = 8 Dec 2006 21:16:01
----------------------------------------------------------------------------
----------------------------------------------------------------------------

compound assignment operators.
----------------------------------------------------------------------------
DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");

// Add one hour, one minute and one second
theDate += TimeSpan.Parse("01:01:01"); // theDate = 2 Jan 2007 21:16:01

// Subtract twenty-five days
theDate -= TimeSpan.Parse("25.00:00:00"); // theDate = 8 Dec 2006 21:16:01
------------------------------------------------------------------------------
----------------------------------------------------------------------------
Add Methods

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");
TimeSpan duration = TimeSpan.Parse("1.01:01:01");

theDate = theDate.Add(duration); // theDate = 3 Jan 2007 21:16:01

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

DateTime theDate = DateTime.Parse("2 Jan 2007");

theDate = theDate.AddYears(1); // theDate = 2 Jan 2008
theDate = theDate.AddMonths(2); // theDate = 2 Mar 2008
theDate = theDate.AddDays(1.5); // theDate = 3 Mar 2008 12:00:00
theDate = theDate.AddHours(-6); // theDate = 2 Mar 2008 06:00:00
theDate = theDate.AddMinutes(150); // theDate = 2 Mar 2008 08:30:00
theDate = theDate.AddSeconds(10.5); // theDate = 2 Mar 2008 08:30:10.5
theDate = theDate.AddMilliseconds(499); // theDate = 2 Mar 2008 08:30:10.999
theDate = theDate.AddTicks(10000); // theDate = 2 Mar 2008 08:30:11

Also takes -ve value

E.g .AddYears(-1); etc

----------------------------------------------------------------------------
----------------------------------------------------------------------------
Subtract Method
----------------------------------------------------------------------------
----------------------------------------------------------------------------


DateTime theDate = DateTime.Parse("2 Jan 2007");
TimeSpan subtract = TimeSpan.Parse("1.01:00:00");
DateTime startDate = DateTime.Parse("1 Jan 2007");
DateTime endDate = DateTime.Parse("2 Jan 2007 12:00:00");
TimeSpan diff;

// Subtract a TimeSpan from a DateTime
theDate = theDate.Subtract(subtract); // theDate = 31 Dec 2006 23:00:00

// Find the difference between two dates
diff = endDate.Subtract(startDate); // diff = 1.12:00:00

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

UTC and Local DateTime Conversion

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


DateTime localDate = DateTime.Parse("1 Jul 2007 12:00");

DateTime utcDate = localDate.ToUniversalTime(); // 1 Jul 2007 05:30
DateTime rangoon = utcDate.ToLocalTime(); // 1 Jul 2007 12:00


----------------------------------------------------------------------------
----------------------------------------------------------------------------
Conversion from DateTime to String
----------------------------------------------------------------------------
----------------------------------------------------------------------------

Basic Conversions
----------------------------------------------------------------------------
----------------------------------------------------------------------------

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToLongDateString(); // result = "03 January 2007"
result = theDate.ToShortDateString(); // result = "03/01/2007"
result = theDate.ToLongTimeString(); // result = "21:25:30"
result = theDate.ToShortTimeString(); // result = "21:25"

Using ToString with Format Specifiers
----------------------------------------------------------------------------
----------------------------------------------------------------------------

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d"); // result = "03/01/2007"
result = theDate.ToString("f"); // result = "03 January 2007 21:25"
result = theDate.ToString("y"); // result = "January 2007"


Available Format Specifiers
----------------------------------------------------------------------------
----------------------------------------------------------------------------
The full list of format specifiers for DateTime conversion is as follows:

Specifier Description Example
d Short date format. This is equivalent to using ToShortDateString. "03/01/2007"
D Long date format. This is equivalent to using ToLongDateString. "03 January 2007"
f Date and time using long date and short time format. "03 January 2007 21:25"
F Date and time using long date and time format. "03 January 2007 21:25:30"
g Date and time using short date and time format. "03/01/2007 21:25"
G Date and time using short date and long time format. "03/01/2007 21:25:30"
m Day and month only. "03 January"
r Date and time in standard Greenwich Mean Time (GMT) format. "Wed, 03 Jan 2007 21:25:30 GMT"
s Sortable date and time format. The date elements start at the highest magnitude (year) and reduce along the string to the smallest magnitude (seconds). "2007-01-03T21:25:30"
t Short time format. This is equivalent to using ToShortTimeString. "21:25"
T Long time format. This is equivalent to using ToLongTimeString. "21:25:30"
u Short format, sortable co-ordinated universal time. "2007-01-03 21:25:30Z"
U Long format date and time. "03 January 2007 17:25:30"
y Month and year only. "January 2007"

Using Picture Formats for Custom Formatting (hh:mm:dd etc.)

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d-MM-yy"); // result = "3-01-07"
result = theDate.ToString("HH:mm"); // result = "21:25"
result = theDate.ToString("h:mm tt"); // result = "9:25 PM"



Available Picture Formatting Codes
----------------------------------------------------------------------------
----------------------------------------------------------------------------
The above example shows several formats and the results. The full list of available formatting codes is as follows:

Specifier Description Examples
y One-digit year. If the year cannot be specified in one digit then two digits are used automatically. "7"
"95"
yy Two-digit year with leading zeroes if required. "07"
yyyy Full four-digit year. "2007"
g or gg Indicator of Anno Domini (AD). "A.D."
M One-digit month number. If the month cannot be specified in one digit then two digits are used automatically. "1"
"12"
MM Two-digit month number with leading zeroes if required. "01"
MMM Three letter month abbreviation. "Jan"
MMMM Month name. "January"
d One-digit day number. If the day cannot be specified in one digit then two digits are used automatically. "3"
"31"
dd Two-digit day number with leading zeroes if required. "03"
ddd Three letter day name abbreviation. "Wed"
dddd Day name. "Wednesday"
h One-digit hour using the twelve hour clock. If the hour cannot be specified in one digit then two digits are used automatically. "9"
"12"
hh Two-digit hour using the twelve hour clock with leading zeroes if required. "09"
H One-digit hour using the twenty four hour clock. If the hour cannot be specified in one digit then two digits are used automatically. "1"
"21"
HH Two-digit hour using the twenty four hour clock with leading zeroes if required. "09"
t Single letter indicator of AM or PM, generally for use with twelve hour clock values. "A"
"P"
tt Two letter indicator of AM or PM, generally for use with twelve hour clock values. "AM"
"PM"
m One-digit minute. If the minute cannot be specified in one digit then two digits are used automatically. "1"
"15"
mm Two-digit minute with leading zeroes if required. "01"
s One-digit second. If the second cannot be specified in one digit then two digits are used automatically. "1"
"59"
ss Two-digit second with leading zeroes if required. "01"
f Fraction of a second. Up to seven f's can be included to determine the number of decimal places to display. "0"
"0000000"
z One-digit time zone offset indicating the difference in hours between local time and UTC time. If the offset cannot be specified in one digit then two digits are used automatically. "+6"
"-1"
zz Two-digit time zone offset indicating the difference in hours between local time and UTC time with leading zeroes if required.


We can implement like Response.Write(localDate.ToString("dddd , MMM , dd, yyyy"));

IMPORTANT NOTE

Some of the formatting codes use the same letter as a format specifier. When used within a format string that is greater than one character in length this does not present a problem. If you need to use a single character picture format string, the letter must be preceded by a percentage sign (%) to indicate that the standard format specifier is not to be used.


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

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d"); // result = "03/01/2007"
result = theDate.ToString("%d"); // result = "3"

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

Disable F5 Button for Avoidig Unwanted refresh

[ script language="javascript" type="text/javascript"]
function document . onkeydown()
{
if ( event . keyCode == 116 )
{
event . keyCode = 0;
event . cancelBubble = true;
return false;
}
}

[/script]

Wednesday, May 7, 2008

Delete Reocrds by check all check box from gridView datagrid datalist

Delete Reocrds by check all check box from gridView datagrid datalist

This will give you a list of all the fields in the record. At the top a check box for select/unselect button and eache row

contain check box for specified selection and bottom of the list is a DELETE button.






[script language="javascript" type="text/javascript"]
function check_uncheck(Val)
{
var ValChecked = Val.checked;
var ValId = Val.id;
var frm = document.forms[0];
// Loop through all elements
for (i = 0; i [ frm.length; i++)
{
// Look for Header Template's Checkbox
//As we have not other control other than checkbox we just check following statement
if (this != null)
{
if (ValId.indexOf('CheckAll') != - 1)
{
// Check if main checkbox is checked,
// then select or deselect datagrid checkboxes
if (ValChecked)
frm.elements[i].checked = true;
else
frm.elements[i].checked = false;
}
else if (ValId.indexOf('deleteRec') != - 1)
{
// Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
if (frm.elements[i].checked == false)
frm.elements[1].checked = false;
}
} // if
} // for
} // function
//Delete confirmation Function
function confirmMsg(frm)
{
// loop through all elements
for (i = 0; i [ frm.length; i++)
{
// Look for our checkboxes only
if (frm.elements[i].name.indexOf("deleteRec") != - 1)
{
// If any are checked then confirm alert, otherwise nothing happens
if (frm.elements[i].checked)
return confirm('Are you sure you want to delete your selection(s)?')
}
}
}

[/script]

HTML part

[asp:GridView ID="GridViewNewsDelete" DataKeyNames="NewsId" runat="server" ]
[Columns]
[asp:TemplateField]
[HeaderTemplate]
[asp:CheckBox ID="CheckAll" onclick="return check_uncheck (this );" runat="server" /][/HeaderTemplate]
[ItemTemplate]
[asp:Label ID="NewsId" Visible="false"
Text='[%# DataBinder.Eval (Container.DataItem, "NewsId") %]'
runat="server" /]
[asp:CheckBox ID="deleteRec" onclick="return check_uncheck (this );"
runat="server" /][/ItemTemplate]
[/asp:TemplateField]
[/Columns]
[/asp:GridView]


[asp:Button ID="Button1" runat="server" OnClientClick="return confirmMsg(this.form)"
Text="Button" OnClick="Button1_Click" /]



C# coding

if (!IsPostBack)
{
BindGridView();
}



protected void Button1_Click(object sender, EventArgs e)
{
string gvIDs = "";
bool chkBox = false;
//'Navigate through each row in the GridView for checkbox items
foreach (GridViewRow gv in GridViewNewsDelete.Rows)
{
CheckBox deleteChkBxItem = (CheckBox)gv.FindControl("deleteRec");
if (deleteChkBxItem.Checked)
{
chkBox = true;
// Concatenate GridView items with comma for SQL Delete
gvIDs += ((Label)gv.FindControl("NewsId")).Text.Trim();
NewsId = Convert.ToInt32(gvIDs);

// call delete function

MiddleLayerFunctions.deleteNewsWithoutImage("deleteNewsWithoutImage", NewsId);
}
}
if (chkBox)
{
// OR Execute SQL Query only if checkboxes are checked to avoid any error with initial null string




MiddleLayerFunctions.deleteNewsWithoutImage("deleteNewsWithoutImage", NewsId);




BindGridView();




}




}

Friday, May 2, 2008

JavaScript function for currency check with two decimal

function IntDec()
{
var name = document.getElementById('TextBox1').value;

if (name.indexOf(".") != -1 )// First check text box contain period or not
{
var digitonly = /^[-]?\d*\.?\d*$/;
var arrString = name.split('.');
if(arrString.length == 2)// check if user enter one or more than one
decimal
{
if(arrString[1].length ==2)// chk if user enter more than 2 decimal
{
var intPart = arrString[0];
if(intPart.length == 0)
{
alert('Amount is very low');
document.getElementById('TextBox1').value= '00.'+ arrString
}

if(!intPart.match(digitonly)) // check that all inputs are
digit or not
{
alert('Must Enter Digit')
document.getElementById('TextBox1').value="";
document.getElementById('TextBox1').focus();
return false;
}// end of chekc alll inputs are digit or not


var decimalPart = arrString[1];
if(!decimalPart.match(digitonly)) // check that all inputs are
digit or not
{
alert(decimalPart);
alert('Must Enter Digit')
document.getElementById('TextBox1').value="";
document.getElementById('TextBox1').focus();
return false;
}// end of chekc alll inputs are digit or not



}
else
{
if(!name.match(digitonly)) // check that all inputs are digit or not
{
alert('Must Enter Digit')
document.getElementById('TextBox1').value="";
document.getElementById('TextBox1').focus();
return false;
}// end of chekc alll inputs are digit or not


alert('Please Enter 2 digit decimal');


document.getElementById('TextBox1').value = arrString[0]+'.00';
document.getElementById('TextBox1').focus();
return false;
}// end chk if user enter more than 2 decimal
}
else // if user enter one or more than one decimal
{
alert('Please Enter Signle Periond');
document.getElementById('TextBox1').value="";
document.getElementById('TextBox1').focus();
return false;

} // end of user enter one or more than one decimal
}// end of chekc user enter period or not
else
{

var digitonly2 = /^[-]?\d*\.?\d*$/;
//document.getElementById('TextBox1').value="";
if(!name.match(digitonly2)) // check that all inputs are digit or not
{
alert('Must Enter Digit')
document.getElementById('TextBox1').value="";
document.getElementById('TextBox1').focus();
return false;
}// end of chekc alll inputs are digit or not

alert('Enter corrrect format e.g. 0000000000.00 ');

document.getElementById('TextBox1').value +='.00';
return false;
}

return true;

}