Visual Studio 2008 Tips and Tricks

Tip # 1: Track Active Item 
When using Visual Studio Often it is difficult to figure out which file is being edited specially when working with Solution having many projects and many files. I found a simple way to easily keep track of this.

All you need to do is to enable Tools->Options->Projects & Solutions->Track Active Item In Solution Explorer.

 When you enable this feature current open file is automatically selected in your solution explorer.

Tip # 2: Speed up ASPX page loading by opening it in Source View
Often when I double click on aspx or asxc file, it takes some time to create its design view and often I just have to adjust its markup little bit. We can set Tools->Options->HTML Designer->Source View.

This will always open ASPX files in source view.

Tip # 3: Speed up IDE by Turning off Animations
Visual Studio 2008 comes with many animations such as when you Take mouse over Tool Box or Solution Explorer it comes in an animated way. But if your PC is slow then you can turn it off to get some speed. You can do it by unchecking Tools->Options->Environment->Animate environment tools.

These are the few useful tips for Visual Studio 2008. Please share with me if you know some other tips as well.

Microsoft WebsiteSpark Program!!! An opportunity to boom your business

WebsiteSpark is a recently announced program by Microsoft. Basically this program is for freelance developers and companies who are providing web development and design services to their customers. Through this program they will get free software and support from Microsoft for three years.

Eligibility Criteria and Enrollment in WebsiteSpark
Eligibility Criteria is very simple:-
  • Companies whose primary business is to provide Web development and design services to their customer.
  • Company must have 10 or less employees
So, if you want to get benefits from this program, go to WebsiteSpark Homepage and signup now.
In enrollment process you have to get an ‘Approval Code’ from a Microsoft Champ, Network Partner or Hosting Partner. For further details about enrollment visit WebsiteSpark Faqs.

What software are available for free in WebsiteSpark Program?
WebsiteSpark program provides following softwares to their members for free of cost for three years:-

Development Tools
  • Visual Studio® 2008 Professional Edition 3 user licenses
  • Expression® Studio 2 (or 3) 1 user license, available only to the Primary Contact for the Web Pro
  • Expression® Web 2 (or 3) 2 user licenses
  • Windows Web Server® 2008 (or Windows Web Server 2008 R2 when available) 3 user licenses
  • SQL Server® 2008 Web 3 user licenses  
Production and Deployment
  • Windows Web Server® 2008 (or Windows Web Server 2008 R2, when available) (4 Processor License)
  • SQL Server® 2008 Web (4 Processor License)
What are other benefits of WebsiteSpark Program?
There are other benefits from WebsiteSpark Program as well which are listed below:-
  • Professional Support from Microsoft
  • Free online training
  • Managed newsgroups on MSDN (a community of over six million developers) and/or other Microsoft online properties
  • Access to broad community support through connections with Network Partners, Hosting Partners, and peers with complementary services and technologies
  • You will also qualify for Special Offers from Microsoft
What will happen once 3 year period is completed?
After the completion of three years there is no obligation to continue use of any of software and there is no cost for those three years except $100 program fee at end of three years.
Also WebsiteSpark members can purchase all software (mentioned above) in only $999/year. Another offer is to purchase only production server software i.e. Windows Web Server® 2008 R2 and SQL Server® 2008 Web in only $199/year.

In the current period of recession, WebsiteSpark program is a great opportunity for freelance developers and companies to establish and grow their business through support and trainings from Microsoft. Anyone who feels interested should go to WebsiteSpark home page. Also it is my humble request to share this with all freelancers and small companies to help them.

How to Test System Generated Emails without Internet in Vista

Recenetly I have to develop a system which generates highly formatted emails. And I decided that I will do that in my home instead of office. After spending some time I figure out a way to do this. I configured IIS server in Windows Vista to save emails in my local drive. and I can see those emails from my outlook express. Here are the details that how to configure IIS:-
1- Run IIS from Start->run->inetmgr
2- Select your PC name from connections pane. and Right Click on SMTP E-Mail in middle pane.

3- In Features screen select Store e-mail in a pickup directory.

4- I have entered D:\Mails in the path.
5- Now goto D:\Mails (or what ever folder you mentioend).
6- When your application sends mail , mails will be saved in that folder with .eml extension. You can view those files with outlook.

7- If still not getting emails in your folder then try to add this line in your code before sending email:-

smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

How to Auto Refresh / Re Load Page

Sometimes we need a page which shows real time date e.g. Stock exchange, cricket match, etc. To add auto refresh / re load you need to add the following meta tag in your markup's head section.
<meta http-equiv="refresh" content="600">

If you want to add this from code behing, then you can add it like this:-
protected void Page_Load(object sender, EventArgs e)
HtmlMeta hmRefresh = new HtmlMeta();
hmRefresh.HttpEquiv = "Refresh";
hmRefresh.Content = "10";//Time in seconds

System.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\...' is denied

This exception is a very common exception. It usually occurs when we move our application to IIS server (usually on production environment).

This exception occurs because IIS uses ASP .Net (IIS_IUser in Vista) user account and ASP .Net is not authorized to access that location.

To give a quick fix to this, follow these steps:-

  1. Give read/write rights to ASP.NET user to C:\Inetpub\yourfolder\ folder:-
    1. Right Click on FOlder and Select Properties
    2. Go to Security Tab
    3. Click Add, then click Location.
    4. Select your pc name, usually first item.
    5. Press Ok, then press advance and then Find Now.
    6. Select ASP.NET user if not exist then select Authenticated Users.
    7. Press Ok. And Select Read/Write/Modify/List Folder Contents.
  2. Go to IIS->WebSites->DefaultWebSite->YourSiteName->Properties, and at Virtual Directory Tab check 'Read' and 'Write' button.

How to Enable Internet Explorer Advance Tab in Vista

Recently my system got crashed and IT guys installed windows Vista on it, by default they have disabled Advance Tab in Tools-> Internet Options. And I was unable to debug Javascript through my Visual Studio.

After searching the net for a while i found a registry key which opens that option:-

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Internet Explorer\Control Panel]

Save this code as IE.reg and double click on it. After that I was able to view Advance Tab in IE and enabled javascript debugging in IE.

Just for refrence I am adding the path to enable javascript debugging in IE.

Tools-> Internet Options -> Advance -> Check Disable Script debugging (Internet Explorer)

Tools-> Internet Options -> Advance -> Check Disable Script debugging (Others)

Microsoft, Yahoo! Change Search Landscape

Global Deal Creates Better Choice for Consumers and Advertisers

SUNNYVALE, CA and REDMOND, WA - 29 July, 2009 - Yahoo! and Microsoft announced an agreement that will improve the Web search experience for users and advertisers, and deliver sustained innovation to the industry. In simple terms, Microsoft will now power Yahoo! search while Yahoo! will become the exclusive worldwide relationship sales force for both companies' premium search advertisers. More...

Why .Net sessions are terminated/loss unexpectedly

There are many cases when ASP.Net website works great in development environment but as we migrate our website to production server, it starts giving unexpected session timeouts. This article discuss those problems and provide solutions to resolve them.

Here are some of the reasons why this happens:- 

Cause 1: IIS Settings:
1- Application Pool is recycled. - We will know this looking at the system logs
2- IIS/worker process is restarted. - System logs will tell this as well
3- Application Domain is restarted. - We need to monitor for application restarts for the ASP.NET counter in perform to check this.
4- IIS worker process can get recycled depending on the configuration, low on virtual memory, crash due to unhanded exception etc.

1- Goto Start->run->inetmgr->Application pools.
2- Select your application pool and right click -> properties.
3- And see the settings for Recycle worker process (in minutes), set an appropriate value there.
4- Alternatively you can recycle your process when your site generally stays idle i.e. you can select 'You can set values in Recycle worker process at time' and give appropriate time to recycle process.

Cause 2: Modifications in Application Contents:
1- Bin folder of the application is modified.
2- Web.config or the machine.config is modified.
3- Global.asax file is modified.
4- Something in the code is causing session loss, it can be anything like you are adding/removing files in your application folder through code e.g. uploading images. You will need to look into the code to have a fix on this. Like Session.Abandon() or Session.Clear();

Try stopping anti virus software on server and see that session as loosing frequently or not. If problem solves after that then Exclude the anti virus scanning from the IIS/ASP.NET default folders and your application folders.
a- <drive>:\WINDOWS\system32\inetsrv
b- <drive>:\WINDOWS\assembly\GAC_32
c- <drive>:\WINDOWS\Microsoft.NET\Framework\
d- Any application directory containing web.config files, global.asa or global.asax, .net assemblies, and/or other web content which your web apps use.

Check your code, that if your application looses session after a particular operation i.e. you might be changing the contents of your Bin folder or modifying web.config file through your code.

Cause 3: Application is hosted in Shared Server or in Web Farm/Garden:
If your application is hosted on a shared server where other applications are also running on the same server then it might be chances that due to other applications IIS is restarted and causing frequent session loss in your application.

Also if your application is hosted in a Web Garden or Web Farm, then you will also notice frequent session loss. E.g. if first request from user is process by server/process 1 and second request is processed by server/process 2, then session will also appear blank.

In both the cases you can go for a seperate state managment.

You can configure a seperate state server, in which session will not lost due to IIS restarts or server/process switching. First configure state server in your machine. For details and configuration of state server see How to Configure Asp.Net State Server.

Also change your web.config file like this:-
    <sessionState mode="StateServer" cookieless="true" timeout="30"/>

How To Get The IP Address of Users using ASP .Net

If you want to track or analyze who is accessing your website, you can easily do this by capture the IP address of an incoming connection to your aspx page.
Here is the Code to access user's IP Address

Label1.Text = Request.ServerVariables["REMOTE_ADDR"];

How to Optimize Web Site Performance

  1. White Space Filtering through HTTP Module.
  2. Merge all inline styles and multiple CSS into one big global css file.
  3. Merge all inline javascripts and multiple javascript files into one big .js file and add reference to this file whenever you require.
  4. Minify JavaScript and CSS files using CSS Optimizer and Free JavaScript Optimizer or any other tool which you like.
  5. Try using less images in your web page.
  6. Optimize your images with image optimizer I use Trout's GIF Optimizer to optimize gif files. PngOptimzer to optimize my PNG files, both the optimizer does not effect the quality of your image.
  7. If your pagesize is increasing because of ViewState then try to save viewstate on server side. Here is a simpe example to Save ViewState on the File System
These six steps really helps your site in loosing the weight and they do not take much effort at all. After implementing these six steps see the performance of your application. If after that you are not satisfied enough then try following links:-
10 ASP.NET Performance and Scalability Secrets
Performance Optimization of ASP.NET Applications on Client-side

Also take a look at 15 Tools to Help You Develop Faster Web Pages.

Save Files in Database or in File System

When we talk about design some times it is bit tricky to decide wether to store file in database or store file at file system. Here are some advantages of both the aproaches:-

Storing Files on File System
  1. Your database size will increase rapidly, and backup size will also increased in same proportion.
  2. You can access files from different ways (i.e. FTP or Web Browser)
  3. Database such as Access or MSDE and Sql Server 2005 Express edition(I think it is 4GB) is limited to 2GB size.
  4. In case your database is corrupted, even then you can access the documents.
Storing Files on Database
  1. Better Security since database have a very good security mechanism.
  2. If Files are stored outside database, then it is a chance that you delete the record from database and do not update the file on file system. Which might end up in some inconsistent state.
I strongly recommend to store images on file system. Comments are welcome.

How to add a confirmation on Button Click

Here is the code how you can add a client side confirmation box on button click :-
<asp:Button ID="btnDelete" runat="server" Text="Delete" 
OnClientClick="return confirm('Do You Want to Delete Record');"/> 

Send Mails Via .Net

Here is the code to send mails via .Net:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Threading;

/// <summary>
/// Summary description for Emailing
/// </summary>
public class Emailing
private const int SmtpPort = 25;
private const string SmtpServer = "__SMTP SERVER NAME___";
private const string UserName = "__ USER NAME ___";
private const string Password = "__ PASSWORD __";
private const bool EnableSsl = false; //For Gmail Server set it to true

/// <summary>    
/// Sends the mail    
/// </summary>    
/// <param name="toEmailAddresses">';' seperated To email addresses.</param>    
/// <param name="fromEmailAddress">From email address.</param>    
/// <param name="subject">The subject.</param>    
/// <param name="body">The body.</param>    
/// <param name="mailAttachments">';' seperated mail attachments.</param>    
/// <param name="isBodyHTML">is body HTML.</param>   
public static void SendMail(string toEmailAddresses, string fromEmailAddress, string subject,
string body, string mailAttachments, bool isBodyHTML)
char[] splitter = { ';' };
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHTML;

//Adding Multiple To Addresses
string[] mailAddresses = toEmailAddresses.Split(splitter);
foreach (string mailAddress in mailAddresses)
if (mailAddress.Length != 0)
mailMessage.To.Add(new MailAddress(mailAddress));

//Adding Multiple Attachments
string[] attachments = mailAttachments.Split(splitter);
foreach (string attachment in attachments)
if (attachment.Length != 0)
Attachment attachFile = new Attachment(attachment);

SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = SmtpServer;
smtpClient.EnableSsl = EnableSsl;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = UserName;
NetworkCred.Password = Password;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = NetworkCred;
smtpClient.Port = SmtpPort;
mailMessage = null;
smtpClient = null;
/// <summary>    
/// Sends the mail on thread.    
/// </summary>    
/// <param name="toEmailAddresses">';' seperated To email addresses.</param>    
/// <param name="fromEmailAddress">From email address.</param>    
/// <param name="subject">The subject.</param>    
/// <param name="body">The body.</param>    
/// <param name="mailAttachments">';' seperated mail attachments.</param>    
/// <param name="isBodyHTML">is body HTML.</param>    
public static void SendMailOnThread(string toEmailAddresses, string fromEmailAddress, string subject,
string body, string mailAttachments, bool isBodyHTML)
Thread mailThread; mailThread = new System.Threading.Thread(delegate()
SendMail(toEmailAddresses, fromEmailAddress, subject, body, mailAttachments, isBodyHTML);
mailThread.IsBackground = true; mailThread.Start();



You can use this class like :-

//Send Simple Mail
Emailing.SendMail("", "", "Subject is test", "body is Test", "", true);

//Send mail on thread with two attachments
Emailing.SendMailOnThread("", "", "Subject is test", "body is Test", 
"c:\\setup.log;c:\\setup1.log;", true);

In case you want to send emails through Gmail server, then use these settings:-
private const int SmtpPort = 465;//if 465 do not work then try 587
private const string SmtpServer = "";
private const string UserName = "__ USER NAME ___";
private const string Password = "__ PASSWORD __";
private const bool EnableSsl = true;

How to set Session Timeout in ASP.Net

Here are different places from where you can set timeouts. Check all these settings in your application:-

1- Web Config
You can define session time out in sessionstate tag of web.config file. Also if you are using forms authentication then also define session timeout in forms as mentioned below:-
<forms loginurl="sampleloginpage.aspx" name="samplecookie" timeout="45" path="/" requiressl="true" protection="All">
<sessionstate mode="InProc" stateconnectionstring="tcpip=" cookieless="false" timeout="45">

2-Global.asax Session_Start Event
You can also set this in global.asax file as mentioned here:-
Session.Timeout = 60 ; // in Session.Start() event

To set session timeout to 45 minutes write this in the web.config file :
<sessionstate mode="InProc" stateconnectionstring="tcpip="
 sqlconnectionstring="data source=;Trusted_Connection=yes" cookieless="false" timeout="20">

The maximum limit for session timeout is 525,600 minutes(1 year) - (365 days x 24 hours x 60 min)

If all mentioned above did not help you then it might be due to anti virus software. Software scans the files in application folder and updates their date/time. Which causes IIS to restart. There fore i uninstalled the anti virus from server. However, if you exclude the application folder from virus scan that will also do the job. Also you need to remove .config,.aspx,.ascs and other extensions specific to your application for further security.



I am creating this blog to support .Net community. Input from all the guys is welcomed