Monday, December 08, 2008

Format data in gridview

To format the date and time, use DataFormatString="{0:MM/dd/yyyy hh:mm tt}"

d = day of month without leading zero
M = month without leading zero
yyyy = year as four digits
h = hours in 12 hour format without leading zero
mm = minutes with leading zero
tt = two character am/pm designaror

To format the "%", use DataFormatString="{0:0%}"

To format the currency "$xx.xx", use DataFormatString="{0:C}"

Tuesday, December 02, 2008

Validate image size, type, and dimension

When upload images to file server or database, most likely we'll put some restrictions on the size, dimensions, and type of image.

In my asp.net project, I used the custom validator to accomplish this goal. In the validator function, we can check the size, dimension, and type. Make sure to use Page.IsValid in order to show the error messages.

    protected void valImage_ServerValidate(object source, ServerValidateEventArgs args)
{
int maxSize = 1024 * 1024;
int maxWidth = 350;
int maxHeight = 225;

if (args.IsValid)
{
if (FileUploadImage.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image file size must be less than 1 MB.";
}
else if (FileUploadImage.PostedFile.ContentType != "image/jpeg" &&
FileUploadImage.PostedFile.ContentType != "image/pjpeg")
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image file type must be jpeg.";
}
else
{
GetNewImage(); //put image stream in the session state;
using (Bitmap bitmap = new Bitmap(FileUploadImage.PostedFile.InputStream, false))
{
if (bitmap.Width > maxWidth || bitmap.Height > maxHeight)
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image dimension must be less than 225px in height and 300px in width.";
}
}
}
}
}


reference: http://aspalliance.com/781_CodeSnip_Validate_Image_Size_Dimension_and_Type_Uploads;
http://www.mikeborozdin.com/post/ASPNET-Image-Uploading-(part-I).aspx