Search This Blog


.NET Tips & Tracks

Use "App_Offline.htm" feature while updating a web site
"App_Offline.htm" feature provides a super convenient way to bring down an ASP.NET application while you updating a lot of content or making big changes to the site where you want to ensure that no users are accessing the application until all changes are done. The way app_offline.htm works is that you place this file in the root of the application. When ASP.NET sees it, it will shut-down the app-domain for the application and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application. When you are done updating the site, just delete the file and it will come back online.

To refresh a aspx page at regular interval
<meta http-equiv="refresh" content="10">

Fade Effect on Page Exit
<meta http-equiv="Page-Exit" content="progid:DXImageTransform.Microsoft.Fade(duration=.9)">

You have developed and deployed a web application on a web server. When users are making a request to the default.aspx file on the web server from their browser, they are being prompted to download the default.aspx file on their computer. What could be the problem.
Problem with aspnet_isapi.dll This behavior means that although the request is going to the IIS, it is not being executed by the worker process because IIS is not sure what to do with this file. This is because the aspnet_isapi.dll is either not present or IIS is not pointing to aspnet_isapi.dll.

Adding a Print Button with Javascript
Add this line to the Page_Load event btnPrint.Attributes("onClick") ="javascript:window.print();"
Add a button to the page called 'btnPrint' Technically, that's it, but, let's say you want to do something a little fancier, using DotNet.
Then, add a subroutine (let's call it 'DoPrint'): Sub doPrint(Source as Object, E as EventArgs)
lblResults.text="Page has successfully been sent to the printer!"
End Sub
Then, add a direction to this sub, in the button's tag: onServerclick="doPrint"

To print certain areas of a page
Create a style sheet for printing purpose, normally by removing/hiding background colors, images.... After that include it with media="print", so that this style sheet will be applied while printing. <LINK media="print" href="styles/printStyle.css" type="text/css" rel="stylesheet">

Password matching regular expression
Password must be at least 4 characters, no more than 8 characters, and must include at least one upper case letter, one lower case letter, and one numeric digit. ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$

Make Window Fit any Resolution
1) Create function definition
<script language="Javascript">
function resolution()
UserWidth = window.screen.availWidth
UserHeight = window.screen.availheight
window.resizeTo(UserWidth, UserHeight)
2) Call the function on load event of body.
<body OnLoad=”resolution();”>

Quickly move to matching brace in Visual Studio
Just press Ctrl+] and VS.NET will take you to the matching brace. It also will take you to the matching comment, region or quote depending on what is at the cursor now.

Incremental search in Visual Studio.
1. Press Ctrl+I.
2. Start typing the text you are searching for. Note: you'll see the cursor jump to the first match, highlighting the current search string.
3. Press Ctrl+I again to jump to the next occurrence of the search string.
4. To stop search, press Esc. Advanced tip: Press Ctrl+Shift+I to search backwards.

Clear all text boxes in ASP.Net
private void Button1_Click(object sender, System.EventArgs e)
Control myForm = Page.FindControl("Form1");

foreach (Control ctl in myForm.Controls)
((TextBox)ctl).Text = "";
This will clear EVERYTHING from the textboxes - even if you had them pre-populated with data. A simple way to just reset it to the condition at Page_Load time, just do this in the Reset SubRoutine: Server.Transfer("YourPageName.aspx")

How to form Color Picker in ASP.NET
<SELECT id="DropDownList1" name="DropDownList1" runat="server">

Using this control we'll change the background Color of each Item in DropDown.

private void Page_Load(object sender, System.EventArgs e)
// Put user code to initialize the page here
if (!IsPostBack)
foreach(FieldInfo col in typeof( KnownColor).GetFields() )
if (col.FieldType == typeof(KnownColor) )
DropDownList1.Items.Add(new ListItem(col.Name ,col.Name));
for (int i= 0 ;i < DropDownList1.Items.Count;i++)
DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);
Make sure to Import the System.Reflections namespace, as well as the System.Drawing namespace, for this example

Optimize the launch of the Visual Studio 2005
Disable "Start Page".
1. Go to Tools Options.
2. In Environment Startup section, change At startup setting to Show empty environment.

Disable splash screen.
1. Open the properties of Visual Studio 2005 shortcut.
2. Add the parameter /nosplash to the target.

Close all unnecessary panels/tabs to prevent them from appearing when the IDE loads.

Visual Studio Full Screen Mode
You can quickly toggle into Full Screen mode by pressing Shift+Alt+Enter.

Auto-complete the word in Visual Studio 2005
Type the first few characters of a control/variable/type name and hit Ctrl+Space or Alt+RightArrow to auto-complete the word. If there is more than one possibility Intellisense suggestions will pop up a window with available options.

How to change the default browser used in VS 2005
To change what browser is launched and used when running web apps in Visual Studio 2005 and Visual Web Developer (for example: to use FireFox instead of IE) do this:
1. Right click on a .aspx page in your solution explorer
2. Select the "browse with" context menu option
3. In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename
4. Click the "Set as Default" button to make this the default browser when you run any page on the site.
Note that there is also an optional drop-down at the bottom of the dialog that lets you select the default browser window size when loading.

Prevent caching of webform in
private void Page_Load(object sender, System.EventArgs e)

ASP.Net Server Controls Not Showing on pages
Try running aspnet_regiis from the command prompt. Here's the default location: C:\WINNT\Microsoft.NET\Framework\<>\aspnet_regiis.exe -i

Currently logged in user
To get the user ID of the user who is currently logged in, you would get it using this: System.Web.HttpContext.Current.User.Identity.Name

Get windows Identity(win auth)

Page: 1 2 3
Disabling a Button Until Processing is Complete
Here's the scenario - let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times.

For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this:

<INPUT id="Button1" onclick="document.form1.Button1.disabled=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert">

Then, in the very last line of the 'doInsert' subroutine, add this line: Button1.enabled="True"

Adding a MailTo Link inside a DataGrid
Suppose you have a database table which contains an email field, and you'd like to display that field, as well as others in a DataGrid. Let's go one step further - - let's say you'd like to display that email field as a clickable MailTo link. One way that this can be easily be done using TemplateColumns. First, you create your DataGrid start and end tags. Then, inside these tags, you include 'Columns' start and end tags. That's where you put your TemplateColumn. Here's how to do it:
Put any other boundcolumns you want inside here also

<asp:TemplateColumn HeaderText="Email Address" HeaderStyle-Font-Bold="True">
<A HREF="Mailto:<%# Container.DataItem("email") %>">
<%# Container.DataItem("email") %>

Create a Printer Friendly page (no Headers or Footers)
Let say you've got great dynamic page, with user controls for your header and your footer, but you need to have the ability for the end-user to have a print-out without the header and the footer. One way to accomplish this would be to have your content section, completely in a User Control also. That way, you could just create a blank page, and put the user control there. From the original page, just link to this new blank page. All you'll see is the content. Then, you can use the Javascript Print Function for printing. Inlude an ASP button Server Control in your new Print-Friendly page, called 'btnPrint'. Then, in the Page_Load event, type in:

btnPrint.Attributes("onClick") ="javascript:window.print();"

That's all there is to it. You can get fancier, if you'd like, actually adding an 'OnServerClick' sub, so that you could use ASP.Net to return a 'Successful Print' message...from this point on, it's up to you on how you'd like to customize this!

Use Path.GetRandomFileName() or Path.GetTempFileName() when working with temp files
Do not reinvent function for generating unique name for temporary files. Use one of the existing methods:
System.IO.Path.GetTempFileName() - use this method if you want to create temporary file in user's temp folder.
System.IO.Path.GetRandomFileName() - use this method if you just want to generate unique file name.

Speed up string comparison
Click here

Popup Window Code
You can use Javascript to do so. e.g. <input type="Button" Value="Open New" onclick="'webform1.aspx');">

Uploading Large Size File
ASP.NET limits the size of requests (and therefore file uploads) as a precaution against denial-of-service attacks. By default, ASP.NET won't accept requests whose size exceeds 4 MB. You can change that by modifying the maxRequestLength attribute of Machine.config's

<httpRuntime> element. The following maxRequestLength attribute expands the permissible request size to 8 MB (8192K):

<httpRuntime ... maxRequestLength="8192" ... />

1 comment:

Asha said...

Hi Manab,

Thanku so much for sharing ur knowledge in a wide range.....