Thursday, October 31, 2013

Send Email From ASP.Net using Gmail as SMTP Client

Day before yesterday, I faced a very unusual problem in sending email through ASP.Net / C# application using gmail as the smtp host. Following is the code I used to send email.

MailMessage mail = new MailMessage();

mail.From = new MailAddress("", "Enquiry");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;

SmtpClient smtp = new SmtpClient("", 587);

//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("", "<my gmail pwd>");
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;


There is no problem with this code and the email will be sent successfully without any error.


When the email is received in the recipient inbox, the "from address" displayed will be of gmail account which is used as the network credential for smtp client. This is because, gmail will over-write the "from address".


You need to follow the below mentioned steps to display the "from address" correctly:

1. Login to your Gmail account.

2. Go to Settings Menu

3. In the Accounts Tab, Click on the link "Add another email address you own"

4. Enter the email address which you want in the "From address" field and click on "Next Step" button.

5. Select Option "Send through Gmail" and click on "Next Step" button.

6. Click on the "Send Verification" button. You will receive an email from Gmail team. This email will have a verification code and a verification link. You need to either enter the verification code or click on the verification link.

7. Enter the Verification code sent by gmail.

8. The account which you require in the "From Address" field will be linked as an alias with your gmail account.

After following the above steps, execute the above given code again. You will see that the "from address" field is not of gmail but the one which is set for the MailMessage.

The above steps also need to be followed when configuring email account for mail clients like Outlook using gmail as the smtp client.

I hope you find this post useful. You can give your inputs in the comments section.

Thanks & Regards,

Sunday, October 13, 2013

URL Routing in ASP.Net Web Forms - Same number of Parameters

Yesterday, our team faced an interesting issue in URL Routing. My subordinate was finding difficulty in resolving a problem with routes having same number of parameters. So, I thought of sharing it with you the same. Issue goes like this.


Two routes were created in Global.asax file as shown below:

routeCollection.MapPageRoute("ProjectType", "{dealtype}/{searchstring}", "~/result.aspx");
routeCollection.MapPageRoute("CompanyDetail", "company-details/{personID}", "~/companyregistration.aspx");

Now, in the above case, in "ProjectType" route both the parameters are dynamic whereas for the "CompanyDetail" route, one part of the route is hard-coded i.e. 'company-details' and other parameter is dynamically set. But, when I redirect to route of company details, it was still requesting result.aspx instead of companyregistration.aspx. We tried both the ways of redirecting to the route.

Response.RedirectToRoute("CompanyDetail", new { personID = lngPersonID.ToString() });


Response.Redirect("company-details/" + lngPersonID.ToString());

But it was requesting result.aspx.


After trying quite a few options, we made the following change in the Global.asax file and it worked. We just changed the order of the route declaration.

routeCollection.MapPageRoute("CompanyDetail", "company-details/{personID}", "~/companyregistration.aspx");
routeCollection.MapPageRoute("ProjectType", "{dealtype}/{searchstring}", "~/result.aspx");

After changing the order of declaration, both the routes were working.


After looking at this issue, following points can be concluded:

Routes without any hard-coded identifier must be declared at the last.
If there are more than one routes without any hard-coded identifier and having the same number of identifier, then the route declared first will override all others and will be considered by ASP.Net.

I hope this article was useful to you. You can post your inputs and extra information in the comments section.

You can also subscribe to this blog by registering your email to get notifications of new posts.

Thanks & Regards,

Thursday, October 10, 2013

Add Prefix www automatically in URL in ASP.Net

When opening a website from the browser, some people don't like to write the www prefix and open the website without it. Thus, to maintain the uniformity, ASP.Net provides a facility to add automatically, the www prefix in case it's not found.

You just need to add the following rewriter rule in your web.config file:

    <rule name="Add WWW prefix" stopProcessing="true">
      <match url="(.*)" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^yourdomain\.com$" />
      <action type="Redirect" url="{R:0}" redirectType="Permanent" />

This will automatically add the www prefix in the URL if not found.

Same thing can also be done to remove the prefix www as given in the below code below:

    <rule name="Remove WWW prefix" stopProcessing="true">
      <match url="(.*)" ignoreCase="true" />
        <add input="{HTTP_HOST}" pattern="^www\.yourdomain\.com$" />
      <action type="Redirect" url="{R:1}" redirectType="Permanent" />

The above <rewrite> code is to be written within the <system.webServer> tag of web.config file.

You can now subscribe to this blog to get email notifications of the articles posted.

Thanks & Regards,

Wednesday, October 9, 2013

URL Routing in ASP.Net Web Forms - Pass Parameters in Hyperlink and Anchor tag

When you add hyperlinks to a Web page, if you want to specify a route URL instead of a physical file you have two options:

  1. You can hard-code the route URL.
  2. You can specify the route parameter names and values and let ASP.NET generate the URL that corresponds to them. You can also specify the route name if required in order to uniquely identify the route. If you change route URL patterns later, you would have to update any hard-coded URLs, but if you let ASP.NET generate the URLs, the correct URLs are always automatically generated (unless the parameters in the patterns are changed).

Let's say you have registered following Routes in the global.asax file.

public static void RegisterRoutes(RouteCollection routeCollection)
            routeCollection.MapPageRoute("Home", "home/{city}/{area}", "~/About.aspx", true, new RouteValueDictionary { { "city", "Ahmedabad" }, { "area", "Satellite" } });
            routeCollection.MapPageRoute("Result", "result/{city}/{searchstring}", "~/result.aspx");

Hard Coded URL

In the following procedure you add hyperlinks and anchor tag that use hard-coded URLs to a Web page.

<asp:HyperLink ID="lnkHome" runat="server" NavigateUrl="~/home/Ahmedabad/Paldi">Home</asp:HyperLink>
<a href="~/home/Ahmedabad/Paldi" runat="server" id="lnkAHome">Anchor - Home</a>

The above markup creates HyperLink and anchor tag controls with hard-coded URLs.

Automatically Generate URL from Markup

In the HTML Source Editor, add the following code in NavigateURL for Hyperlink and Href for Anchor Tag:

<asp:HyperLink ID="lnkResult" runat="server" NavigateUrl="<%$RouteUrl:city=Ahmedabad,searchstring=property-brokers-in-ahmedabad,routename=Result%>">Result</asp:HyperLink>
<a href="<%$RouteUrl:city=Ahmedabad,searchstring=property-brokers-in-ahmedabad,routename=Result%>" runat="server" id="lnkAResult">Anchor - Result</a>

The above markup uses RouteUrl expressions to create URL for the route that is named Result.

Create Automatically Generated URLs by using C# code

When you want to generate the URL from the code-behind, you don't need to give value to NavigateURL or href in the HTML source. You need to generate it in the Page_Load event in code-behind as given 


// Step - 1
RouteValueDictionary routeParams = new RouteValueDictionary  
                    { "city", "Surat" }, 
                    { "searchstring", "parle-point" },
                    { "qs", "result" }

// Step - 2

    VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "Result", routeParams);

// Step - 3
    lnkResultUsingCode.NavigateUrl = vpd.VirtualPath;
    lnkAResultUsingCode.HRef = vpd.VirtualPath;

Step - 1: The above code creates an instance of the RouteValueDictionary class that contains three parameters. The third parameter is qs, which is not in the URL pattern. Because it is not in the URL pattern, the category parameter and its value will be rendered as a query-string parameter.

Step - 2: Then, it instantiates a VirtualPathData object by calling the GetVirtualPath method of the RouteCollection class. GetVirtualPath() method takes RouteName and and RouteValueDictionary object as its parameters.

Step - 3: Finally, VirtualPathData object vpd is to be assigned to the NavigateURL and href properties of Hyperlink and Anchor Tag respectively.

Accessing URL Parameter Values in ASP.NET Pages

In an ASP.NET page that has been invoked by ASP.NET routing, you can retrieve the values of URL parameters in markup or in code. We have already seen how to retrieve parameter values in Code in my previous articles. Let's see how we can retrieve the parameter values in the HTML markup itself.

City: <asp:Label ID="Label1" runat="server" Text="<%$RouteValue:city%>"></asp:Label><br />
Searched For: <asp:Label ID="Label2" runat="server" Text="<%$RouteValue:searchstring%>"></asp:Label>

The above markup uses RouteValue expressions to extract and display the values of the URL parameters that are passed to the page.

I hope this article is useful for you. Please provide your inputs or extra information in the comments section.

Thanks & Regards,

Monday, October 7, 2013

URL Routing in ASP.Net Web Forms - Access Script and Image Paths

When we implement URL Routing in Web Forms, one thing that need to be taken into consideration is the path of the images and scripts that need to be assigned to the "src" attribute of the <img> or <script> 

tags. The file source need to be resolved using the ResolveClientUrl() function as explained below:


Actual ASPX File is in root directory :

The Route Created for Home.aspx:
routeCollection.MapPageRoute("Home", "home/{city}/{area}", "~/Home.aspx", true, new RouteValueDictionary { { "city", "Ahmedabad" }, { "area", "Satellite" } });

Javascript File Location:

Image file Location:

Thus the actual URL displayed will be ~/home/Ahmedabad/Satellite.

But the "src" attribute will always look for the relative path and it will never be able to access the actual file if written in normal way as mentioned above for javascript and image.

Thus, we need to write it as given below:

<script  src='<%= ResolveClientUrl("~/js/xyz.js") %>' />
<img  src='<%= ResolveClientUrl("~/images/abc.jpg") %>' />

The above method will be able to access the actual file from its location.

I hope this blog post is useful for you. Do write your inputs in the comments section.

Thanks & Regards,

Friday, October 4, 2013

URL Routing in ASP.Net Web Forms Part - 3 - URL Routing versus URL Rewriting

ASP.NET routing differs from URL rewriting. URL rewriting processes incoming requests by actually changing the URL before it sends the request to the Web page. For example, an application that uses URL rewriting might change a URL from /Products/Widgets/ to /Products.aspx?id=4. Also, URL rewriting typically does not have an API for creating URLs that are based on your patterns. In URL rewriting, if you change a URL pattern, you must manually update all hyperlinks that contain the original URL.

With ASP.NET routing, the URL is not changed when an incoming request is handled, because routing can extract values from the URL. When you have to create a URL, you pass parameter values into a method that generates the URL for you. To change the URL pattern, you change it in one location, and all the links that you create in the application that are based on that pattern will automatically use the new pattern.

Thanks and Regards,

URL Routing in ASP.Net Web Forms Part - 2

In my previous post, I introduced the concept of URL Routing in ASP.Net. Now, let's look at the practical implementation for the same.

In a Web Forms application, you need to define routes in the Global.asax file. Following example shows how the routes are defined in the Global.asax file:

// Create a Method to register routes and call that methos in Application_Start event of Global.asax file.

public static void RegisterRoutes(RouteCollection routeCollection)
            routeCollection.MapPageRoute("ProductDetail", "product/{productname}", "~/productdetail.aspx");
            routeCollection.MapPageRoute("ProductList", "products/{categoryname}/{subcategoryname}", "~/products.aspx", true, new RouteValueDictionary { { "categoryname", "Books" }, { "subcategoryname", 

"Biography" } });

void Application_Start(object sender, EventArgs e)

In the above code 2 routes are defined in the routeCollection object using MapPageRoute Method. Generally MapPageRoute takes 3 parameters (routeName,routeUrl,physicalFile). Alternatively, if we want to provide default values to the parameters of RouteURL, you can pass a RouteValueDictionary which is used to assign default values to the URL parameters. In the above example, the second route has URL set as products/{categoryname}/{subcategoryname} and the default values for {categoryname} and {subcategoryname} are set using RouteValueDictionary.

RegisterRoutes() method need to be called in the Application_Start event, so that routes get registered when on the application start.

Generally, using querystring the above thing is implemented as mentioned below:

productdetail.aspx?productname=5 point someone

To Send request to the Routed page you can use Response.Redirect or Response.RedirectToRoute.

In the above example, you need send request as given below:

Response.RedirectToRoute("ProductDetail", new { productname = "5 point someone" });
Response.RedirectToRoute("ProductList", new { categoryname = "Books", subcategoryname = "Biography" });

You can also use the Response.Redirect:

Response.Redirect("product/5 point someone");

But, the preferrable method is Response.RedirectToRoute().

For getting the parameter values passed on the destination page you need to use Page.RouteData.Values[""]. In the above example, values will be retrieved as given below:

string strProductName = Page.RouteData.Values["productname"].ToString();

string strCategoryname = Page.RouteData.Values["categoryname"].ToString();
string strSubCategoryname = Page.RouteData.Values["subcategoryname"].ToString();

For more details you can check following links of MSDN:

I hope you found this article useful. Please feel free to give your inputs in the comments section.

Thanks & Regards,

Wednesday, October 2, 2013

URL Routing in ASP.Net Web Forms Part - 1

Dear Friends,

With the start of development of a new project using ASP.Net Web Forms, the most important requirement of it was that the Web Portal to be developed must be SEO Friendly and thus it lead me to look for various options for the same.

Our Site can be made SEO Friendly by many ways like using friendly URLs, Div based html design and few other options. But, the most important of it was the use of friendly URLs. In the MVC architecture, this feature is inbuilt but if you need to develop the portal using ASP.Net Web Forms, you need to implement the ASP.Net Routing concept.

Few of the benefits of using URL Routing are mentioned below:

  • Help in SEO (Search Engine Optimization) and hence improve page hits by putting relevant keywords in the URL.
  • Users are becoming more tech savvy and find directly manipulating the URL easier than inputting text boxes and clicking buttons.
  • Short and easy to type URLs are good.
  • URLs are persistent i.e. users do not want to rely on your page names and folder structure when application is accessed. For e.g. if a user bookmarks a page and for some reasons developer need to restructure the code files. User might not get to the same page through the same bookmark.

For Example, generally, if we need to pass parameters from one page to another using ASP.Net we will be using querystring in the URL as given below,


But, using the URL Routing, we need to use


Search engine does not consider any value after ".aspx" in its listing, but using URL Routing, it is now possible to keep any keywords which can be crawled by the web crawler. Moreover, every search engine gives first preference to URL while searching any keywords.

I hope you liked the article. I will be posting the exact implementation of URL routing in the Part-2 of this blog series of URL Routing.

You can give your inputs in the comments section.