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 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.";
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.";


Friday, November 21, 2008

Centering: Auto-width Margins

By setting its right and left margin widths to "auto", it will make the content box horizontally centered. This is the preferred way to accomplish horizontal centering with CSS, and works very well in most browsers with CSS2 support.

Unfortunately, IE5/Win does not respond to this method. The workaround is to set the text-align to center.

Margin example:

h1 {margin: 10px}
all four margins will be 10px

h1 {margin: 10px 2%}
top and bottom margin will be 10px, left and right margin will be 2% of the total width of the document.

h1 {margin: 10px 2% -10px}
top margin will be 10px, left and right margin will be 2% of the total width of the document, bottom margin will be -10px

h1 {margin: 10px 2% -10px auto}
top margin will be 10px, right margin will be 2% of the total width of the document, bottom margin will be -10px, left margin will be set by the browser

Thursday, November 13, 2008

Host File

The short answer is that the Hosts file is like an address book. When you type an address like into your browser, the Hosts file is consulted to see if you have the IP address, or "telephone number," for that site. If you do, then your computer will "call it" and the site will open. If not, your computer will ask your ISP's (internet service provider) computer for the phone number before it can "call" that site. Most of the time, you do not have addresses in your "address book," because you have not put any there. Therefore, most of the time your computer asks for the IP address from your ISP to find sites.

Windows NT/2000/XP Pro c:\winnt\system32\drivers\etc\hosts

For more info, go to HERE

Wednesday, November 12, 2008

Open Command Window Here

One of Microsoft's Power Toys. This PowerToy adds an "Open Command Window Here" context menu option on file system folders, giving you a quick way to open a command window (cmd.exe) pointing at the selected folder.


Launch the application without using mouse.

Alt+Space to bring the Launchy to front. Type the name of the executable, it will show the matching list while you are typing. Press Enter when you done and application will launch. It is open source and FREE.

Tuesday, November 11, 2008

Address Completion in Browsers

IE: type the site address between the "www." and ".com" and then use Ctrl+Enter to auto-complete the "www." and ".com"

Sunday, November 02, 2008

SQL 2005 installation

I always run into problem with installation of SQL 2005. Here is step by step guide:

Tuesday, October 28, 2008

Essential Visual Studio Tips & Tricks that Every Developer Should Know

Found this great post on Stephen Walther's blog.

tip 1: don't need to select a line to copy or delete it

If you want to copy a line of code then you can simply press CTRL-c to copy the line and press CTRL-v to paste the line. If you want to delete a line, don’t select it first, just press CTRL-x. You’ll be surprised how much time this one tip will save you.

tip 3: Never create properties by hand

just type prop + TAB + TAB. When you type prop + TAB + TAB, you get a code snippet (template) for entering a property. Use TAB to move between the template parameters. Press the ENTER key when you are finished creating the propert.

I found these two are most useful and time saving for me. Others are at:

Monday, October 27, 2008

Jing Project: Visual conversation starts here.

Jing is a great screen capture tool and it's free!! This is so far the best screen capture tool I used. Another feature is it also can record your activity, so it also a great tool to create the video demo.


Photo viewing tool. like ACDSee, but it is FREE.

Tuesday, October 21, 2008

Take dnn site offline

It's better to take the DNN site offline for maintenance. The best way to do this is to upload an App_Offline.htm file to the root.

Monday, October 06, 2008

Navigate the parent page from the IFrame page (child page)

When user clicks the link/button on a page inside the IFrame, it will bring up another page inside the IFrame and the parent page will not change.

Sometimes we do need the link/button on the Iframe page update the parent page. Here is how to do it.

If the link is used, make the target property "_top".

If the button is used, in the code-behind, do this:
Response.Write("<" + "script>" + "'http://webpage_address','_top');<" + (char)47 + "script>");

Thursday, September 04, 2008

Use overloaded web methods in web services (asmx)

In order to use the overloaded methods in the web services (asmx), two things need to be done.

1. When creating a new webservice in Visual Studio .NET 2005, the IDE automatically adds the following line on top of your serviceName.cs file:

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

Change it to WsiProfiles.None

2. Add the MessageName in the [WebMethod(MessageName="UniqueName1"]

Wednesday, September 03, 2008

Make default button on the page

There are different ways control the page behavior when user enter the text in the text box then press the Enter key.

One way is to user the Javascript function to monitor the key pressed. If it's the enter key, then activate the submit button (the default button).

Another way is to put the page around a panel and use the "defaultbutton" property.

The best way to do this is to use the "UseSubmitBehavior" property for the button. Just make it false for buttons that not default.

Tuesday, August 26, 2008

Export data to csv file

Use the following code to export data to the csv file:

string attachment = "attachment; filename=MyFilename.csv";
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "text/csv";
Response.AddHeader("Pragma", "public");
Response.Write("hello world"); //data goes here;

Clear the current page (window)

In order to clear out the current page (make the page as a blank page), use following code:

Response.Flush();//will send the current response stream to the browser

Response.End() ;// will end the response,

Friday, August 22, 2008

Change the table schema

To change the schema of the tables, use this script command:

Alter schema "new_schema_name" transfer "old_schema_name.table_name"

Thursday, August 14, 2008

Retrieve images from Database using ASHX

Most of articles (which I found) about retrieve images from database are using Response.writebanary(...) to aspx file, then point the image's url to this aspx file. It worked fine for the most website. The luck ran out for me when I tried to implement a module for a dnn site. Because DNN only allows the user control (ascx) files, I had trouble to imped the image on my user control inside the DNN. The DNN will log me out every time after I displayed an image from the database.

The solution is quite simple, but took me a while to found it. Instead of using the aspx page as the image url to display the image on the page, use ASHX (HTTPHandle) file instead. The code used inside the ASHX file is almost the same as in the ASPX page.

For more detail on how to retrieve the image from database using ASHX: Go here

Tuesday, August 12, 2008

Restart IIS

To restart IIS

  • Click Start, click Run type IISReset, and then click OK.

    A Command Prompt window opens displaying the status of the IISReset command. You should read the status at the command prompt to make sure that IIS stops and restarts.

Thursday, August 07, 2008

ASP.NET UploadFile control

I am currently working on a project requires uploading the image to the database. It also requires to have a confirmation screen before saving the image to the database. What I found out is the UploadFile control's PostedFile object will get lost every time after the postback. So, there is no file on the confirmation screen to be saved to the database.

Only workaround I found for this issue is to save the PostedFile object to the Session state.

Monday, August 04, 2008

Create Javascript inside the code behind page

I often ran into the situation that need to create the Javascript function dynamically instead of having it on the Aspx page. For example, if there is a text box inside one of the view in the MultiView, the Javascript function to detect the Enter Key press will not work when the view with text box is not showing (the rendered html code does not contain this specific text box).

In case like this, we need to create the Javascript code dynamically. The Javascript function will only show up if the perticular view is showing. We use the "Page.ClientScript.RegisterClientScriptBlock" to accomplish this problem.

First, use ServerSideControl.FindControl("controlName").ClientId to find unique client side id for this control.

Then use the Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ScriptId", "my Javascript code") to register the Javascript code.

To find this control inside the Javascript function: var btn = document.getElementById('" + strMyControlId + "');"

We can put above code inside a function and call it before making the view containing the text box visible to true.

MSDN: Page.ClientScript.RegisterClientScriptBlock
JavaScript with ASP.NET 2.0 Pages - part I

Monday, July 21, 2008

Progress Bar

Essential Object offers a complete free to use progress bar for It is very nice tool with great flexibility for user to change the layout and it's very easy to use. Here is the link. However, the disadvantage is you'll have to install the full control set to your VS. The dll has to be included in the bin folder to deploy the site. (Telerik has a progress bar only for using with the upload control. I find it is odd that they didn't including a progress bar for general use.)

An alternative solution is to use an simple user control. The disadvantage is the look & feel of the progress bar. It's not as good looking as the progress bar from EO, but you can get the full source code. Here is the code in c#:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ProgressBar.ascx.cs" Inherits="ProgressBar" %>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class ProgressBar : System.Web.UI.UserControl
private System.Drawing.Color _colFillColor = System.Drawing.Color.Green;
private System.Drawing.Color _colBackcolor = System.Drawing.Color.White;
private System.Drawing.Color _colBorderColor = System.Drawing.Color.Black;
private int _intBorder = 1;
private int _intCellspacing = 1;
private int _intCellpadding = 1;
private int _intHeight = 15;
private int _intWidth = 130;
private int _intBlockNumber = 20;
private int _intValue;
TableRow _tblBlock;

public System.Drawing.Color BGColor
return _colBackcolor;
_colBackcolor = value;

public System.Drawing.Color FillColor
return _colFillColor;
_colFillColor = value;

public System.Drawing.Color BorderColor
return _colBorderColor;
_colBorderColor = value;

public int BorderSize
return _intBorder;
_intBorder = value;

public int Cellpadding
return _intCellpadding;
_intCellpadding = value;

public int CellSpacing
return _intCellspacing;
_intCellspacing = value;

public int Blocks
return _intBlockNumber;
_intBlockNumber = value;

public int Value
return _intValue;
_intValue = value;

public int Height
return _intHeight;
_intHeight = value;

public int Width
return _intWidth;
_intWidth = value;

protected void Page_PreRender(object sender, System.EventArgs e)
int intBlocks;
// add a new row to the table
_tblBlock = new TableRow();
// create cells and add to the row
for (intBlocks = 1; (intBlocks <= this.Blocks); intBlocks++)
TableCell tblCell = new TableCell();
tblCell.Text = " ";
decimal temp = (Convert.ToDecimal(this.Blocks) / 100) * Convert.ToDecimal(this.Value);
if ((intBlocks <= temp))
tblCell.BackColor = this.FillColor;
// set the progress bar properties
tblProgressBar.CellPadding = this.Cellpadding;
tblProgressBar.CellSpacing = this.CellSpacing;
tblProgressBar.Width = this.Width;
tblProgressBar.Height = this.Height;
tblProgressBar.BackColor = this.BGColor;
tblProgressBar.BorderColor = this.BorderColor;
LabelProgress.Text = this.Value + "% complete";

Wednesday, July 16, 2008

Debug javascript inside VS2005

writing JavaScript functions in the is not an easy task specially lacking the debugging feature in VS2005 (VS2008 has this build in). However, there is an easy way to enable debugging feature in the VS2005.

1. uncheck the "disabling scripting debug" in the IE internet option.
2. add "debugger;" in the script block to enable javascript debugging.

for more detail, click here

Tuesday, July 15, 2008

Restore the SQL 2005 Database using script

The SQL 2005 management studio has wizard for restore the database. It works pretty good for most cases, but I found the scripting is much for flexible. Recently, I tried to restore a database to with a different name, but the wizard won't let me to do it. Here is the example of the alternative script way. It worked great for me.

Restore Database YourDBName
From Disk = 'TheBAKFileName.bak'
With Move 'MDFFileName' To 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\YourDBName.MDF',
Move 'LDFFileName_Log' To 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\YourDBName.ldf',

Tuesday, July 08, 2008

DNN installation problem

I tried to install the latest DNN 4.8.x last night, but the process is not very smooth. In the middle of the installation, the DNN hung up on the install the database script page. Not sure what was going on. Some people had the same experience (google search). The "Custom" and "Typical" installation choices are not working for some reason. The "Auto" did the job. I think the "Auto" is the traditional way of installing the DNN.

Monday, July 07, 2008

Multiple IEs

When developing the web applications, we have to make sure that the application is not only running fine on multiple browsers (IE and firefox), but also running on different version of IEs (firefox always keep the user in the latest version).

The MultipleIEs by tredosoft is a great tool for web developers to test the application on multiple version of the IE. I have latest version of IE installed on my pc and added only IE 6 for MultipleIEs.

MultipleIEs links at:

Wednesday, July 02, 2008

Prevent XSS in (Regular expression)

I've been working on the security of a web application to prevent the XSS (cross site scripting). I read many articles about how to handle this issue. There are two ways that I found is easy to implement and will prevent most of the XSS attack.

The first is to use HttpUtility.HtmlEncode in the code behind page. It will encode specially characters in the script code, so the script will not run when the page is rendered.

The second is to use the Regular Expression validator on the client side (I think custom validaor calling the System.Text.RegularExpressions.Regex.IsMatch(string input, string pattern) is most secure).

Here are some frequently use regular expressions I found on the web:

1. Name

2. Address (allow number, text only, ., -, and space. no special characters are allowed)

3. Email

4. Social Security #:

5. Date:

Regular Express Library

Friday, June 27, 2008


Today I downloaded the FireBug Add-on for FireFox. It is very cool tool. I thought the IE toolbar is very useful tool for debugging the UI related issue on the web app. So far, I only play a few functioanlities and I am very impressed. Specially, the "inspect" function. Once you click the button and move the mouse over the page you are looking at, the FireBug will take you directly to the section over the rendered HTML code and show all the style information on the right panel.

You can get FireBug from

Monday, June 23, 2008

social bookmarking: is a very convienent online bookmark tool. I found it very helpful to put all your bookmark in a central place. It saves me the trouble from email links to my home in order to keep the bookmark in sync.

You also can share your links with your friends. (i didn't try this feature yet.)

Tuesday, June 17, 2008

ASP.NET Security: 8 Ways to Avoid Attack

Found a nice article on the Divx on how to avoid attack for by Wei Meng Lee. All the tips are short and easy to understand.
Tip 1—Cross-site Scripting
Tip 2 —SQL Injection
Tip 3—Validate your User Inputs
Tip 4—Use Hashing to Store your Passwords
Tip 5—Encrypt Sensitive Data
Tip 6—Store Secure Information in the Registry
Tip 7—Do Some Housekeeping before You Deploy Your Web Application
Tip 8—Use Sessions, but Not Cookie-less Sessions

For details, click

Prevent Cross-Site Scripting in

Found a great article on MSDN on how to prevent the cross-site scripting in Here is the link:

Monday, June 16, 2008 Set MaxLength in muliti-line textbox

When set the MaxLength property in the textbox, it will prevent user to enter text longer than the MaxLength value. However, when you change the TextMode from SingleLine to MultiLine, the MaxLength property has no effect.

Here is a work-around for this issue:
const int LENGTH_TEXT = 100;

protected void Page_Load(object sender, EventArgs e)

= "function isMaxLength(txtBox) {";
+= " if(txtBox) { ";
+= " return ( txtBox.value.length <=" + LENGTH_TEXT + ");";
+= " }";
+= "}";

this.txtMyTextBox.Attributes.Add("onkeypress", "return isMaxLength(this);");
lengthFunction ,

Click here for more detail.

Debug with FireFox in Visual Studio 2005

There are times when we need to make sure that our code not only works with IE, but also with other popular web browsers, such as FireFox.

Here are the steps to do this:
1. Right click the aspx page;
2. Select "browser with" option;
3. In the pop up dialog box, select "add" to add a broswer. Find and point to firefox.exe
4. Click the "Set as Default" button.

Thursday, June 12, 2008

Cropper in C#

Today I find a very nice screen capture tool. It's small, light, easy to use, FREE, and written in C#. So, no more Ctrl+PrintScreen, then paste to paint to edit.

New step: select the size of the screen need to be captured and double click!! (make sure to select the output types. I like the "clipboard" option to save it to memeory, so I can paste directly in the word doc or outlook email)

It will save the picture to the memory or file (jpeg, bmp, and png)

Brian Scott : Cropper in C#

Thursday, May 29, 2008

Custom formatting HTML in Visual Studio 2005

Sometimes the aspx source file(html) can be very hard to read. Luckly, the VS2005 included build in format html tool. Just select the portion of the aspx source page, right click the mouse, and choose the "format selection". The aspx source file will look much better with consistent indenting.

For more details, please visit Scott Guthrie's blog

Wednesday, May 28, 2008

UpdatePanel & UpdateProgress in Ajax

When adding an UpdatePanel-control to your page, you can achieve a partial-update of your page on a postback. Only the content in the UpdatePanel is refreshed, the other parts of the page remain unchanged.

To let the user know that the network conversation is taking place, the ASP.NET AJAX UpdateProgress control provides immediate feedback by displaying an animated image, ‘loading’ text, or other HTML that disappears once the network response is received.

For more details on how to apply them to the application, please reference at:

Tuesday, May 27, 2008

Dynamic Control (textbox) Creation

One problem I had with the dynamic control creation is the controls are not saved in the viewstate after postback unless you put the code of creating the controls in the Page_Load or Page_Init event.

One of the recent project I worked with required the application to create multiple labels & textboxes on the page according to user's interaction(button-click). I didn't want to create all the controls in the Page_Load and put them to different panels and hide them. One interesting thing I found (tip from co-worker) is that all the information in the textbox are saved in the viewstate no matter is pre-defined or dynamic created. In order to retreive the dynamic created textbox value, Request.Form need to be used.

According to MSDN, "The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method."

The solution I used is to save the textbox.uniqueid to a hashtable and call the Request.Form[textbox's uniqueid].tostring() to retrevie the value of the textbox.

here is the link to Bilal Haidar's blog of "Loading control dynamically in"

Tuesday, May 20, 2008

Dynamic SQL in stored procedure

By using sp_executesql (system stored procedure), you can write the dynamic SQL inside the stored procedure.

sp_ExecuteSql accepts a list of parameters, the first two of which MUST be either ntext, nchar or nvarchar. The first is your sql statement and the second is the parameter names. The third part is the list of parameter values.

DECLARE @SqlString nvarchar(4000)
SET @SqlString = N'SELECT * FROM ' + @TableName + ' WHERE ID = @ID';
EXECUTE sp_executesql
,N'@ID int'

The @TableName and @ID are parameters passed into the stored procedure.

for more info, check:

Friday, May 02, 2008

Basic C# Generic Predicate Delegate

Find a very useful (practical) example of combining generic, predicate, and delegate together on the List (removing items in the list).

//create a list of candidates
List candidates = new List();
for (int i=2; i <= 100; i++) { candidates.Add(i); } //use predicate and delegate to remove the items on the list candidates.RemoveAll (delegate(int x) { return x>2&& x%2==0; }

//or use the predicate only

static bool RemoveUnWantedItems(int x)
return (x>2&& x%2==0;);

Thursday, May 01, 2008

Passing Value-Type parameters vs Passing Reference-Type parameters

In the real world coding, I rarely think about this issue much. The debugger always shows the values for you when you debug the application. However, when taking an exam (or interview), you will get a question about it and you are asked what is the output look like on the blank paper.

Again, the MSDN reference helped a lot. It listed all the examples with output. Here is the link:

Thursday, April 10, 2008

Web Application Projects vs Web Site Projects

Maor David had a great post on Web Application Projects vs Web Site Projects. Details is here:

There is also a great MSDN article on this: Scroll down to the section "Comparing Web Site Projects and Web Application Projects".

In addition to the articles above, one thing I dislike the web site project is VS always put the solution file (.sln) is inside the My documents folder. I like to put the solution file in the same folder as the web site in. Here is the simple work around to do this:
  1. Create a blank solution file first (file -> new project -> other project types -> virtual studio solutions -> blank solution).
  2. Add the website in the solution (right click the blank solution -> Add new website).

Tuesday, April 01, 2008

How to expand a fixed VHD

There are times that I wish the virtual hard drive that I created could be bigger. Here is how to do it:

  1. download the VhdResizer from here:
  2. select the old VHD as source and name your new VHD (make sure that your new VHD name is different from the source VHD name.), then hit resize buttom.
  3. after the VhdResizer finished running, you'll notice that the size of the new VHD is increased.

Wish it was this simple. Here is the steps you have to follow in order to expand the extra spaces you just allocated to the new VHD. (if you run the new VHD right now, you will notice that it's still have the same space. But if you go to Computer Management, you will see the extra space is unallocated).

Here are the steps to make the extra space available to your new VHD:
  1. attach the new VHD as data disk to your old VHD. (old VHD will be your C: and new VHD will be D:) (again, make sure the new VHD name is different from the old VHD name before you attach the new VHD to the old. Otherwise, you won't be able to extend the partition.).
  2. run the old VHD.
  3. open Command Prompt and type "diskpart".
  4. type "list disk". it will list all the disk avaiable on your VHD.
  5. type "select disk [disk index #].
  6. type "list partition".
  7. type "select partition [partition #].
  8. type "extend".

This should do it. Good luck.

Monday, March 31, 2008

Remove Source Control Binding on Visual Studio 2005

Source control in VS2005 is great. However, there are times when you want to unbind the projects from the Source control (wanted to write some test code, but don't want to check the code out). I used to do it manually by searching the .vss in the project directory and then, manually edit the solution file or the project files. It works, but it's painful.

The correct way to do it is listed below and I hope it will save you time in the future.

1. Open the project/solution in the VS2005.
2. Click File -> Source Control -> Change Source Control.
3. The Change Source Control window will pop up. You can see all the binding information from here.
4. Select all the projects you don't want to bind to the source safe and click the unbind button.
5. A confirmation dialog box will pop up. Click OK to unbind your project/solution from the source safe.

This will safely removing the binding between your project and the source safe.