Tag Archives: C#

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

<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>

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

 <system.net>
    <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="c:\EmailFolder\" />
        </smtp>
    </mailSettings>
</system.net>

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

C# Extension Methods


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

Introduction

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.

Examples

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;

 Console.WriteLine(i.IsEvenNumber());
 Console.ReadLine();
 }
 }

 

int-Extension

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 = "";

Console.WriteLine(str.IsNullOrEmpty());
Console.ReadLine();
}
 }

 

string-Extension

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]

Box.com [Direct Download Link]

Related articles

Tuple in C# 4.0


A Tuple in C# is an ordered sequence, means each object being of a specific type. It is introduced in C# 4.0 with dynamic programming. It can be useful when returning more than one value from a method.

A Tuple has many items. Each item can have any data type. The Tuple class provides a unified syntax for creating objects with typed fields.

Visual studio provides the intellisense for tuple object depends upon the data type of the item.

Methods


//Creates a new 1-tuple, or singleton.
public class Tuple <T1>

//Creates a new 2-tuple, or pair.
public class Tuple <T1, T2>

//Creates a new 3-tuple, or triple.
public class Tuple <T1, T2, T3>

//Creates a new 4-tuple, or quadruple.
public class Tuple <T1, T2, T3, T4>

//Creates a new 5-tuple, or quintuple.
public class Tuple <T1, T2, T3, T4, T5>

//Creates a new 6-tuple, or sextuple.
public class Tuple <T1, T2, T3, T4, T5, T6>

//Creates a new 7-tuple, or septuple.
public class Tuple <T1, T2, T3, T4, T5, T6, T7>

//Creates a new 8-tuple, or octuple.
public class Tuple <T1, T2, T3, T4, T5, T6, T7, T8>

A Tuple can be instantiated in two ways:

1. Constructor


var tuple = new Tuple<int, string>(10, "Hello World");

2. Static method


var tuple = Tuple.Create(10.10, "Hello World", 50);

Tuples are commonly used in four ways:

1. To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.

2. To provide easy access to, and manipulation of, a data set.

3. To return multiple values from a method without using out parameters.

4. To pass multiple values to a method through a single parameter.

Example


Tuple<int, string> tuple = new Tuple<int, string>(10, "Hello World!");
Console.WriteLine(tuple.Item1); // will print 10
Console.WriteLine(tuple.Item2); // will print "Hello World!"

Sending E-mail Using ASP.NET


Description and steps:

1. I have created “EmailHelper” class which is very self explanatory.

2. Include the namespace “System.Net.Mail”.

using System.Net.Mail;

Please note: We can include “System.Web.Mail” or “System.Net.Mail“. These 2 namespaces contains classes used to send an email to a Simple Mail Transfer Protocol (SMTP) server for delivery.. But since “System.Web.Mail” is deprecated, It is recommended to use “”System.NET.Mail”.

Even if you can use “System.Web.Mail”, it is not a full .NET native implementation of the SMTP protocol. Instead, it uses the pre-existing COM functionality in CDONTS. System.Net.Mail, in contrast, is a fully managed implementation of an SMTP client.

3. In your Web.config file, include following lines.


<system.net>
<mailSettings>
<smtp from="defaultEmail@yourdomain.com" deliveryMethod="SpecifiedPickupDirectory">
<network host="localhost" port="25" userName="UserName" password="Password"/>
<specifiedPickupDirectory pickupDirectoryLocation="c:\Emails\"></specifiedPickupDirectory>
</smtp>
</mailSettings>
</system.net>

4. Create “Emails” folder on your C drive. P.S. You can create folder anywhere on your system, but path of the folder should be same as like in the web.config file.

5. Code snippet to send mail using “EmailHelper” class.


EmailHelper emailHelper = new EmailHelper("test@email.com", "recepient@email.com", null, null, "This email was sent from my asp.net application", string.Format("Email was sent on {0}<br/></b>This is bold text.</b><br/><I>This is italic</i>", DateTime.Now), true, System.Net.Mail.MailPriority.High);
emailHelper.SendMailMessage();

6. If you are running it locally, you need to configure SMTP on your system. If you don’t know how to do it, please refer the related article links at the bottom of this post.

EmailHelper Class Explained:

1. It contains 2 constructors. First one is default and other one is parameterised.

2. If you use the parameterised constructor while creating instance of the class, you can send mail as shows above by very simple way with only 2 lines of code.

3. It also contains a SendMailMessage method with 1 overload. First one with no input parameters and other one is with multiple parameters.

4. If you want to send emails to multiple users (e.g 2 users in TO, 2 users in CC, 3 users in Bcc etc), then SendMailMessage with multiple input parameter method is for you. Pass the list of persons as per your requirement and call the method.

5. It has one extra method called “IsValidEmailAdress”. It validates email ID’s using regular expressions.

Downloads:

Github [Repository Link]

Box.com [Direct Link to Zip file]

Access Modifiers In C#


It’s been always a confusion about the default access modifiers. Here is a small article which will make things clear.

Access Modifiers in C#:

public

The type or member can be accessed by any other code in the same assembly or another assembly.

private

The type or member can be accessed only by code in the same class or struct.

protected

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.

Default Access Modifiers in C#:

1. A class has default modifiers as Internal.

2. An enum has default modifier as public.

3. An interface has default modifier as public

4. Like class, A struct has default modifier as Internal.

5. A methods, fields, and properties has default access modifier as “Private” if no modifier is specified.