Category Archives: ASP.NET

Useful Features of ASP.NET

In this post, lets discuss about some of the useful features of ASP.NET

1. Faster compilation.

This configuration setting was introduced post .NET 3.5 SP1. Add it to web.config file.

<compilation optimizeCompilations="true">

Refer MSDN for details.

2. Retail mode at the machine.config

    <deployment retail="true"/>

It overrides the web.config settings to enforce debug to false, turns custom errors on and disables tracing. No more forgetting to change attributes before publishing – just leave them all configured for development or test environments and update the production retail setting.

3. Intellisense for MasterPages in the content pages

Most of the time you have to use the “findcontrol” method and cast the controls in master page from the content pages when you want to use them, the MasterType directive will enable intellisense in Visual Studio once you do this

Just add one more directive to the page

<%@ MasterType VirtualPath="~/Masters/MainMasterPage.master" %>

If you don’t want to use the Virtual Path and use the class name instead

<%@ MasterType TypeName="MainMasterPage" %>

4. Is Client Connected?

Check to see if the client is still connected, before starting a long-running task

if (this.Response.IsClientConnected)
   // long-running task

5. Server control properties based on target browser

<asp:Label runat="server" ID="labelText" ie:Text="This is IE text" mozilla:Text="This is Firefox text" Text="This is general text" />

6. Page.ViewStateUserKey to Counter One-Click Attacks

Consider using Page.ViewStateUserKey to counter one-click attacks. If you authenticate your callers and use ViewState, set the Page.ViewStateUserKey property in the Page_Init event handler to prevent one-click attacks.

void Page_Init (object sender, EventArgs e) {
ViewStateUserKey = Session.SessionID;

Set the property to a value you know is unique to each user, such as a session ID, user name, or user identifier.

A one-click attack occurs when an attacker creates a Web page (.htm or .aspx) that contains a hidden form field named __VIEWSTATE that is already filled with ViewState data. The ViewState can be generated from a page that the attacker had previously created, such as a shopping cart page with 100 items. The attacker lures an unsuspecting user into browsing to the page, and then the attacker causes the page to be sent to the server where the ViewState is valid. The server has no way of knowing that the ViewState originated from the attacker. ViewState validation and HMACs do not counter this attack because the ViewState is valid and the page is executed under the security context of the user.

By setting the ViewStateUserKey property, when the attacker browses to a page to create the ViewState, the property is initialized to his or her name. When the legitimate user submits the page to the server, it is initialized with the attacker’s name. As a result, the ViewState HMAC check fails and an exception is generated.

Check out this link for details.

7. Emails to local folder

While testing, you can have emails sent to a local folder on your computer instead of an SMTP server

        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="c:\EmailFolder\" />

This is not a complete list, but will keep adding and updating this.

Internet Information Services (IIS) useful commands

In this article, lets take a look some of the IIS commands which are used quite often by the developers.

Apppool recycle
C:\Windows\System32\inetsrv\appcmd.exe recycle apppool WebsiteAppPoolName

where WebsiteAppPoolName is the name of application pool name

Website Start
C:\Windows\System32\inetsrv\appcmd.exe start site WebsiteName

where WebsiteName is the name of the site

Website Stop
C:\Windows\System32\inetsrv\appcmd.exe stop site WebsiteName

where WebsiteName is the name of the site

If you need to frequently recycle apppool or start/stop the website(s) then I would suggest to create a powershell script and run it.

C# Extension Methods

In this article, let’s know about CSharp Extension methods. Basically this feature was introduced in C# 3.0


Extension methods enable you to “add” methods to existing types. They are special kind of static method. They make it possible to extend existing types with additional methods.

Extension methods are declared by specifying this keyword on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.


1. Extend “int” datatype.

public static class MyExtensions

  public static bool IsEvenNumber(this int number)

    if (number % 2 == 0)
     return true;
     return false;

To call “IsEvenNumber” extension method from main, consider following code snippet.

class Program
 static void Main(string[] args)
 int i = 45;




So in the example above, “IsEvenNumber” has became part of  int datatype and is accessible via intellisense.

2. Extend “string” datatype.

public static class MyExtensions
public static bool IsNullOrEmpty(this string input)
if (input == null || input == string.Empty)
return true;
return false;


To call “IsNullOrEmpty” extension method from main, consider following code snippet.

class Program
static void Main(string[] args)
string str = "";




So in the example above, “IsNullOrEmpty” has became part of string datatype and is accessible via intellisense.

You can even include the namespance of the Extension methods and reuse them anywhere in your project.

Source Code Download:

Github [Repository Link] [Direct Download Link]

Related articles

Book Review: “Nuget 2 Essentials” from Packt Publisher

In this post, I am going to review a book Nuget 2 Essentials from Packt Publisher.


Recently I have gone through a book “Nuget to Essentials” and as a developer, I have found it to be a concise, interesting and very useful introduction to Nuget. Authors Damir Arh and Dejan Dakic have covered Nuget Package Manager and related topics very brilliantly.

It is so easy to read and the information is very interesting that each time you turn a page,
you want to learn and know more about Nuget! Every topic in this book is covered with examples. You can download the example code files for all Packt books you have purchased from your account. Since All the examples are written in C# language, only basic knowledge of the language is required to start reading this book.

Here is a list of the positive things, I found about the book:

  • Doesn’t require any prior knowledge about NuGet
  • Example source codes are written in C#
  • All the concepts on real-world examples step by step with a section that explain you the whole process each time in every topic
  • Very comprehensive writing. Authors explained almost everything which makes things clear!
  • Very informative, even if you are a beginner, an intermediate or an advanced user
  • Covers all aspects of using NuGet, from the basics to the advanced scenarios of creating packages and hosting an internal server

After you’ve read the book, you know how to easily find and refer third-party libraries from your projects, create packages from your class libraries for others to use and publish them to the official NuGet gallery and host your own internal NuGet server and publish packages to it.

One thing I have noticed about Packt Publisher is that they offer eBook versions of every book published with PDF and ePub files available, which is very great and added advantage.

Since everything is covered related to Nuget Package Manager along with simple and easily understandable examples, I strongly recommended this book to every .NET developer who wants to learn more about NuGet. A must have ‘Essential‘ book.

Book Details

Language : English
Paperback : 116 pages
Release Date : November 2013
ISBN / ISBN 13 : 178216586X / 9781782165866
Author(s) : Damir Arh, Dejan Dakic
Topics and Technologies : All Books, Open Source

Win Free Copies of the new book NuGet 2 Essentials from Packt Publishing

I recently came across a new book NuGet 2 Essentials from Packt Publishing. You would be pleased to know that I have teamed up with Packt Publishing to organize a Giveaway of the book.

And three lucky winners stand a chance to win 3 digital copies of this book. Keep reading to find out how you can be one of the Lucky Winners.


  • Install NuGet in all supported versions of Visual Studio
  • Use NuGet with source control and build servers
  • Create a NuGet package for your own class library
  • Publish your package to the official NuGet gallery
  • Create packages with multi-platform and multi-language support
  • Automatically configure target projects from the packages you create
  • Include custom install and uninstall scripts in your packages
  • Support debugging of your packaged libraries
  • Install your own internal NuGet server
  • Configure NuGet to use different NuGet servers

How to Enter?
All you need to do is head on over to the book page and look through the product description of the book and drop a line via the comments below this post to let us know what interests you the most about this book. It’s that simple.

Winners will get an e-copy of the Book.

The contest will close on 31st Dec 2013. Winners will be contacted by email, so be sure to use your real email address when you comment!

Realtime Currency Converter in C# ASP.NET using Yahoo API

In this article, Let’s see how to convert worldwide currencies in realtime using Yahoo API.


1. Create a ASP.NET empty project, call it as “RealtimeCurrencyConverterUsingYahooAPI”.

2. Add a webpage called “Default.aspx” to the project.

3. Since we are using jQuery, include the jQuery latest library in the project. Add a reference to it on “Default.aspx” page.

<script src="jquery-1.10.2.js"></script>

4. Add the following webmethod in code behind.

using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Services;

public static Decimal ConvertCurrency(decimal amount, string fromCurrency, string toCurrency)
WebClient client = new WebClient();
Stream response = client.OpenRead(string.Format("{0}{1}=X", fromCurrency.ToUpper(), toCurrency.ToUpper()));
StreamReader reader = new StreamReader(response);
string yahooResponse = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(yahooResponse))
string[] values = Regex.Split(yahooResponse, ",");
if (values.Length > 0)
decimal rate = System.Convert.ToDecimal(values[1]);
return rate * amount;
return 0;

The webmethod simple get response from yahoo URL. Parses it and returns the calculated result back on the screen.

5. To call this webmethod from “Default.aspx”, just add the following jQuery Code.

<script type="text/javascript">

$(document).ready(function () {
$('#submit').click(function () {
var errormsg = "";
var amount = $('#txtAmount').val();
var fromCurrency = $('#drpFromCurrency').val();
var toCurrency = $('#drpToCurrency').val();
type: "POST",
url: "Default.aspx/ConvertCurrency",
data: "{amount:" + amount + ",fromCurrency:'" + fromCurrency + "',toCurrency:'" + toCurrency + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#results').html(amount + ' ' + fromCurrency + ' equals ' + data.d.toFixed(2) + ' ' + toCurrency);
error: function (jqXHR, exception) {


If you don’t know how to call a webmethod in jQuery, Please refer this.

6. To style the table, I have just added a stylesheet and referred it in the “Default.aspx” page. You can generate such styles very easily from here.

7. Now run the project and you will find the output like e.g

Source Code Download:

Github [Repository Link] [Direct Download Link]

jQuery IP Location Plugin – jqIpLocation Example

In this post, we will see how to get location of an IP address. To achieve this, we will use jquery’s popular plugin “jqIpLocation”.

About jqIpLocation plugin:

jqIpLocation is a jQuery Plugin that returns the location of an IP address in JSON format. You can get country, country code, city name, region name, latitude and longitude information about IP address location.

Now Let’s see how it works with an Example.

1. Create a new project in Visual Studio, name it as “jqIpLocationPluginExample”.

2. Select the Empty template for web forms.

3. Once the project is created, add a webpage, call it as “Default.aspx”.

4. Download the plugin from here. Extract the rar file and copy the folder to our project.

5. Include the Javascript resources into our Default.aspx page’s <head> section.

<script src="jqIpLocation/jquery-1.6.3.min.js"></script>
 <script src="jqIpLocation/jqIpLocation.js"></script>

6. Create a table on page, consider following code snippet.

<table class="CSSTableGenerator">
 <asp:Label ID="lblIP" runat="server" ClientIDMode="Static"></asp:Label>
 <asp:Label ID="lblCountry" runat="server" ClientIDMode="Static"></asp:Label>
 <td>Country Code</td>
 <asp:Label ID="lblCountryCode" runat="server" ClientIDMode="Static"></asp:Label>
 <asp:Label ID="lblCity" runat="server" ClientIDMode="Static"></asp:Label>
 <asp:Label ID="lblRegion" runat="server" ClientIDMode="Static"></asp:Label>
 <asp:Label ID="lblLatitude" runat="server" ClientIDMode="Static"></asp:Label>
 <asp:Label ID="lblLongitude" runat="server" ClientIDMode="Static"></asp:Label>

If you observe, I have applied “CSSTableGenerator” class to table, which I have generated from here. I have added it in “StyleSheet1.css” file in the project and included the reference for the same.

7. Add the following Javascript code that will returns you IP Location information in JSON format.

<script type="text/javascript">
 $(function () {

var ipAddress = "";

 ip: ipAddress,
 success: function (location) {


8. Now save everything and run the project, you will see following output.

Please note: I have hard coded IP address, you can change and try with some another IP.

Live Demo 1 | Live Demo 2

Source Code Download:

Github [Repository Link] [Direct Download Link]