Tag Archives: .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

<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.

Advertisements

Book Review: “Nuget 2 Essentials” from Packt Publisher


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

Review

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

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!"

Bundling and Minification in ASP.NET 4.5


Background:

Aa developer always requires to use multiple Javascript (Js) and CSS files for readability and maintainability of code. But such practice leads to degradation of the overall performance of the website. Because multiple Js and CSS files require multiple HTTP requests from a browser leads to degrade the performance & load time of your web pages.

Bundling and Minification is new feature in ASP.NET 4.5. This feature can help to reduce the size of javascript and css files and make the site perform faster.

Bundling

This feature makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve the page load  performance.

Minification

This feature performs a variety of different code optimizations to scripts or CSS, such as removing unnecessary white spaces and comments and shortening variable names to one character.

Bundling and minification is performed at runtime. They identify the user agent (e.g Firefox, Chrome, IE etc) and improve the compression by targeting the user browser (browser specific changes).

Normal Web application approach (Without Bundling and Minification)

1. Let’s start with a sample project, we will add some sample js and css files to our Default.aspx page.


<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/jquery-ui-1.10.3.custom.js"></script>
 <script src="Scripts/jquery-1.10.2.min.js"></script>
 <script src="Scripts/require.js"></script>
 <script src="Scripts/shadowbox.js"></script>
 <script src="Scripts/jquery.mixitup.js"></script>

<link href="Styles/bootstrap-responsive.min.css" rel="stylesheet" />
 <link href="Styles/bootstrap.min.css" rel="stylesheet" />
 <link href="Styles/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
 <link href="Styles/shadowbox.css" rel="stylesheet" />

2. Let’s add a script code on the page. It will display “Page loaded” message on our page.


<script type="text/javascript">
 $(document).ready(function () {
 $('#span1').text('Page loaded');
 });
 </script>

<h1><b><span id="span1" style="color:blue;"></span></b></h1>

Let’s run this project and inspect it with developer tool plugin of the browser (F12). Switch to Network tab, it will show the timing for assets required by our sample application. As shown below.

3. If you observe Default.aspx page carefully, you can see that client has 15 requests to server, 1.5 KB of data is transfered and it takes 665 ms to complete the request.

Bundling and Minification Approach:

1. First, install the Bundling and Minification Package from NuGet. Open the Package Manager Console, type Install-Package Microsoft.AspNet.Web.Optimization

The command will add references to required assemblies automatically.

2. Create script and style bundles using a class called “BundleConfig”. The following code shows the complete class:


using System.Web.Optimization;

public class BundleConfig
 {
 public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new ScriptBundle("~/bundles/js").Include(
 "~/Scripts/*.js"));

bundles.Add(new StyleBundle("~/bundles/css").Include(</span>
 "~/Styles/*.css"));

            //Files can be added to bundle by different ways like shown below
            //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //        "~/Scripts/jquery.unobtrusive*",
            //        "~/Scripts/jquery.validate*"));

            //bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
            //      "~/Scripts/WebForms/WebForms.js",
            //      "~/Scripts/WebForms/WebUIValidation.js",
            //      "~/Scripts/WebForms/MenuStandards.js",
            //      "~/Scripts/WebForms/Focus.js",
            //      "~/Scripts/WebForms/GridView.js",
            //      "~/Scripts/WebForms/DetailsView.js",
            //      "~/Scripts/WebForms/TreeView.js",
            //      "~/Scripts/WebForms/WebParts.js"));

 }
 }

3. As shown in the code, Wildcard Character (*) can also be used to Select Files.

4. Once a “BundleConfig” class is created, we need to register a bundle in the Application_Start method in the Global.asax.


void Application_Start(object sender, EventArgs e)
{
 BundleConfig.RegisterBundles(BundleTable.Bundles);
}

5. Once it is done, we need to add reference to these bundles in the Default.aspx page.


<%: System.Web.Optimization.Scripts.Render("~/bundles/js") %>
 <%: System.Web.Optimization.Styles.Render("~/bundles/css") %>

6. Now comment out the javascript and css references from the code.

7. Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element  in the Web.config file.


<system.web>
 <compilation debug="true" />
</system.web>

8. To enable bundling and minification, set the debug value to “false”. You can override the Web.config setting with the EnableOptimizations property on the BundleTable class.


void Application_Start(object sender, EventArgs e)
{
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 BundleTable.EnableOptimizations = true;
}

9. Let’s rebuild the solution now and run it and compare the result of Bundling and Minification approach with the normal approach as shown below.

Now, If you observe Default.aspx page carefully implemented with Bundling and Minification, you can see that client has only 7 requests to server, 1.2 KB of data is transfered and it takes 467 ms to complete the request.

Source Code Download:

Github [Repository Link]

Box.com [Direct Link to Zip file]

New TextMode Properties in ASP.NET 4.5


While working on an open source project called “Link Shortner“, I came to know about a new enumerations of Texbox server control under the property “TextMode”. So let’s discuss about it.

Basically it specifies the behaviour mode of the text box. The TextBoxMode enumeration represents the different display options for textbox server controls.

Note: ASP.NET 4.5 provides full HTML5 support.

e.g If the TextMode of the TextBox control is set to “Password”, then all characters entered in the TextBox control are masked and are not saved in view state.

Following is a list of all the available values for this property and short description in ASP.Net 4.5:

SingleLine Represents single-line entry mode
MultiLine Represents multiline entry mode
Password Represents password entry mode
Color Represents color entry mode
Date Represents date entry mode
DateTime Represents date-time entry mode
DateTimeLocal Represents local date-time entry mode
Email Represents email address entry mode
Month Represents month entry mode
Number Represents number entry mode
Range Represents numeric range entry mode
Search Represents search string entry mode
Phone Represents phone number entry mode
Time Represents time entry mode
Url Represents URL entry mode
Week Represents week entry mode

I request developers to explore the different properties on different browser.

Let’s see some textmode property values:

1. DateTimeLocal

<asp:TextBox ID="textBox1" runat="server" TextMode="DateTimeLocal"></asp:TextBox>

2. Email


<asp:TextBox ID="textBox" runat="server" TextMode="Email"></asp:TextBox>

If you see here, validation was automatically fired when I click on “Submit” button, because of the invalid email address.

3. Month


<asp:TextBox ID="textBox3" runat="server" TextMode="Month"></asp:TextBox>

4. Time


<asp:TextBox ID="textBox5" runat="server" TextMode="Time"></asp:TextBox>

5. Range


<asp:TextBox ID="textBox7" runat="server" TextMode="Range"></asp:TextBox>

6. URL


<asp:TextBox ID="textBox8" runat="server" TextMode="Url"></asp:TextBox>

If you observe here, validation was automatically fired when I click on “Submit” button, because of the ‘url’ is not a valid URL.

7. Week


<asp:TextBox ID="textBox6" runat="server" TextMode="Week"></asp:TextBox>

Hope you understand everything here. Comments and questions are welcome.

CryptSharp – A Password Crypt Algorithms Library for .NET


Safely store a password:

Why Not (SHA-1, SHA-3, MD5 etc etc)?

These are all general purpose hash functions, designed to calculate a digest of huge amounts of data in a short period of time as possible. This means that they are fantastic for ensuring the integrity of data and utterly rubbish for storing passwords.

A modern server can calculate the MD5 hash of about 330MB every second. If your users have passwords which are lowercase, alphanumeric, and 6 characters long, you can try every single possible password of that size in around 40 seconds.

Modern supercomputer can process around 700,000,000 passwords a second. And that rate you’ll be cracking those passwords at the rate of more than one per second.

It’s important to note that salts are useless for preventing dictionary attacks or brute force attacks.

Bcrypt Solves These Problems:

It uses a variant of the Blowfish encryption algorithm’s keying schedule, and introduces a work factor, which allows you to determine how expensive the hash function will be. Because of this, bcrypt can keep up with Moore’s law. As computers get faster you can increase the work factor and the hash will get slower.

Why CryptSharp?

It’s been always a challenge for .NET developers to securely store the passwords in the database.

CryptSharp provides a number of password crypt algorithms like BCrypt, LDAP, MD5 (and Apache’s htpasswd variant), PHPass (WordPress, phpBB, Drupal), SHA256, SHA512, and Traditional and Extended DES. Additionally it includes Blowfish, SCrypt, and PBKDF2 for any HMAC (.NET’s built-in PBKDF2 implementation supports only SHA-1).

If you are looking to store passwords, odds are CryptSharp has the algorithm you want.

To install CryptSharp, run the following command in the package manager console in visual studio.


Install-Package CryptSharpOfficial

OR You can download it from It’s official site and add a reference to your project.

Using CryptSharp is very simple. To crypt a password, add the assembly to References and type:


using CryptSharp;

 // Crypt using the Blowfish crypt ("BCrypt") algorithm.
 string cryptedPassword = Crypter.Blowfish.Crypt(password);

To test the crypted password with plain text password use following lines of code:


using CryptSharp;

 // Do the passwords match?
 // You can also check a password using the Crypt method, but this approach way is easier.
 bool matches = Crypter.CheckPassword(testPassword, cryptedPassword);

If you choose the BCrypt algorithm, be aware that it only uses the first 72 bytes of a password.

Here is the sample output of CryptSharp from my code:

Source Code Download:

Github [Repository Link]

Box.com [Direct Link to Zip file]

Business Layer (BL) Class Generator


While working on n-tier architecture, you always need to create a Business Layer (BL) class by writing properties and methods by mapping the column names from the table.

To make this process faster, I try to develop this small window based application called – Business Layer (BL) class generator. It is developed in C# and .NET 4.5 framework is used.

How to use:

1. Open the exe file.

2. Enter the information like”User ID”, “Password” and Server. Click on “Connect” button. It will fill the databases available on the server and fill the Tables dropdown for the respective database.

3. Select the “Database” and the “Table” from the respective dropdown list. Click on “Save to” button to pick a directory where the generated BL class is saved. e.g the ProductsBL class is stored in “D” drive.

4. Click on “Generate Class” button. It will generate BL class for the respective table. Once process is completed, you will see following screen.

5. Click on “Ok” to view the generated class file, else click on “Cancel” to continue.

If you open the generated class, it will look like this. e.g I have opened generated ProductsBL class in Visual studio.

Download source code here: [164 KB]

http://www.4shared.com/zip/9DLkEwpV/BLDALGenerator-Source_Code.html

Download application here: [25 KB]

http://www.4shared.com/zip/HmgBQEdY/BLGenerator-Utility.html

Please let me know your feedbacks, suggestions and bugs if any. You can comment below this post.