Monday, December 08, 2008
Format data in gridview
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
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
Friday, November 21, 2008
Centering: Auto-width Margins
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
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
Launchy
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.
http://www.launchy.net
Tuesday, November 11, 2008
Address Completion in Browsers
Sunday, November 02, 2008
SQL 2005 installation
http://sequelserver.blogspot.com/2007/06/20070703sql-server-2005-installation.html
Tuesday, October 28, 2008
Essential Visual Studio Tips & Tricks that Every Developer Should Know
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: http://weblogs.asp.net/stephenwalther/archive/2008/10/21/essential-visual-studio-tips-amp-tricks-that-every-developer-should-know.aspx
Monday, October 27, 2008
Jing Project: Visual conversation starts here.
www.jingproject.com
Tuesday, October 21, 2008
Take dnn site offline
Monday, October 06, 2008
Navigate the parent page from the IFrame page (child page)
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>" + "window.open('http://webpage_address','_top');<" + (char)47 + "script>");
Thursday, September 04, 2008
Use overloaded web methods in web services (asmx)
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
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
string attachment = "attachment; filename=MyFilename.csv";
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "text/csv";
Response.AddHeader("Pragma", "public");
Response.Write("hello world"); //data goes here;
Response.End();
Clear the current page (window)
Response.Flush();//will send the current response stream to the browser
Friday, August 22, 2008
Change the table schema
Alter schema "new_schema_name"
Thursday, August 14, 2008
Retrieve images from Database using ASHX
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
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 ASP.net code behind page
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
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#:
ProgressBar.aspx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ProgressBar.ascx.cs" Inherits="ProgressBar" %>
CellPadding="1"
CellSpacing="1"
Height="10px"
Width="200px">
ProgressBar.ascx.cs
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
{
get
{
return _colBackcolor;
}
set
{
_colBackcolor = value;
}
}
public System.Drawing.Color FillColor
{
get
{
return _colFillColor;
}
set
{
_colFillColor = value;
}
}
public System.Drawing.Color BorderColor
{
get
{
return _colBorderColor;
}
set
{
_colBorderColor = value;
}
}
public int BorderSize
{
get
{
return _intBorder;
}
set
{
_intBorder = value;
}
}
public int Cellpadding
{
get
{
return _intCellpadding;
}
set
{
_intCellpadding = value;
}
}
public int CellSpacing
{
get
{
return _intCellspacing;
}
set
{
_intCellspacing = value;
}
}
public int Blocks
{
get
{
return _intBlockNumber;
}
set
{
_intBlockNumber = value;
}
}
public int Value
{
get
{
return _intValue;
}
set
{
_intValue = value;
}
}
public int Height
{
get
{
return _intHeight;
}
set
{
_intHeight = value;
}
}
public int Width
{
get
{
return _intWidth;
}
set
{
_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;
}
_tblBlock.Cells.Add(tblCell);
}
tblProgressBar.Rows.Add(_tblBlock);
// 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
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
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',
REPLACE
Tuesday, July 08, 2008
DNN installation problem
Monday, July 07, 2008
Multiple IEs
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: http://tredosoft.com/Multiple_IE
Wednesday, July 02, 2008
Prevent XSS in ASP.net (Regular expression)
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
"^([A-Za-z']|-|\s)+$"
2. Address (allow number, text only, ., -, and space. no special characters are allowed)
"^([a-zA-Z0-9.]|-|\s)+$"
3. Email
"^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$"
4. Social Security #:
"\d{9}"
5. Date:
"^(([1-9])|(0[1-9])|(1[0-2]))\/(([0-9])|([0-2][0-9])|(3[0-1]))\/(([0-9][0-9])|([1-2][0,9][0-9][0-9]))$"
Regular Express Library
Friday, June 27, 2008
FireBug
You can get FireBug from http://getfirebug.com/
Monday, June 23, 2008
social bookmarking: del.icio.us
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
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 http://www.devx.com/security/Article/20898/1954?pf=true
Prevent Cross-Site Scripting in ASP.net
Monday, June 16, 2008
ASP.net: Set MaxLength in muliti-line textbox
Here is a work-around for this issue:
const int LENGTH_TEXT = 100;Click here for more detail.
protected void Page_Load(object sender, EventArgs e)
{
string
lengthFunction = "function isMaxLength(txtBox) {";
lengthFunction += " if(txtBox) { ";
lengthFunction += " return ( txtBox.value.length <=" + LENGTH_TEXT + ");";
lengthFunction += " }";
lengthFunction += "}";
this.txtMyTextBox.Attributes.Add("onkeypress", "return isMaxLength(this);");
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"txtLength",
lengthFunction , true);
}
Debug with FireFox in Visual Studio 2005
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#
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
For more details, please visit Scott Guthrie's blog
Wednesday, May 28, 2008
UpdatePanel & UpdateProgress in ASP.net Ajax
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 asp.net application, please reference at: http://www.codegod.de/webappcodegod/updatepanel-tutorial-aspnet-ajax-AID281.aspx
Tuesday, May 27, 2008
Dynamic Control (textbox) Creation
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 ASP.net"
Tuesday, May 20, 2008
Dynamic SQL in 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.
Example:
DECLARE @SqlString nvarchar(4000)
SET @SqlString = N'SELECT * FROM ' + @TableName + ' WHERE ID = @ID';
EXECUTE sp_executesql
@SQLString
,N'@ID int'
,@ID
The @TableName and @ID are parameters passed into the stored procedure.
for more info, check:
http://doc.ddart.net/mssql/sql2000/html/acdata/ac_8_con_04_9uek.htm
http://msdn.microsoft.com/en-us/library/ms175170.aspx
Friday, May 02, 2008
Basic C# Generic Predicate Delegate
//create a list of candidates
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
Thursday, May 01, 2008
Passing Value-Type parameters vs Passing Reference-Type parameters
Again, the MSDN reference helped a lot. It listed all the examples with output. Here is the link:
http://msdn.microsoft.com/en-us/library/0f66670z(VS.71).aspx
Thursday, April 10, 2008
Web Application Projects vs Web Site Projects
There is also a great MSDN article on this: http://msdn2.microsoft.com/en-us/library/aa730880(VS.80).aspx. 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:
- Create a blank solution file first (file -> new project -> other project types -> virtual studio solutions -> blank solution).
- Add the website in the solution (right click the blank solution -> Add new website).
Tuesday, April 01, 2008
How to expand a fixed VHD
- download the VhdResizer from here: http://vmtoolkit.com/files/folders/converters/entry87.aspx
- 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.
- 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:
- 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.).
- run the old VHD.
- open Command Prompt and type "diskpart".
- type "list disk". it will list all the disk avaiable on your VHD.
- type "select disk [disk index #].
- type "list partition".
- type "select partition [partition #].
- type "extend".
This should do it. Good luck.
Monday, March 31, 2008
Remove Source Control Binding on Visual Studio 2005
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.