Tuesday, November 12, 2013

Allow Account access while sending Email From ASP.Net using Gmail as SMTP Client

In my previous blog post Send Email From ASP.Net using Gmail as SMTP Client, I had shown how we can send email from ASP.Net application using gmail as smtp client and how to avoid the overriding of the "From Email Address" with the gmail account at the receipient inbox.

But, before doing all this, the gmail account which is to be used as smtp client need to be authenticated so that it can be used in the web-applications and devices (laptops, tablets, smart-phones) as smtp client. This can be achieved with the following 3 steps:

  • After entering correct email and password,you will be asked to confirm that this account will be used for devices and applications. Click on "continue".

  • Your account access for devices and applications is enabled.

I hope this post is helpful to you.

Thanks & Regards,

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("abc@mydomain.com", "Enquiry");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);

//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "<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="http://www.yourdomain.com/{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="http://yourdomain.com/{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,