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

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

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

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.

Overview:

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

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

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

What’s New in Visual Studio 2013 RC


In this article, let’s discuss about the new and enhanced features in Visual Studio 2013 Release Candidate (RC).

The official release date for Visual Studio 2013 is November 13, 2013. In preparation, the Release Candidates of VS2013, Team Foundation Server 2013, and .NET Framework 4.5.1 are available for download now. Here is the official announcement for Visual Studio 2013 RC.

Features:

1. Visual studio 2013 comes with .NET Framework 4.5 and 4.5.1 framework with some new features, see What’s New in the .NET Framework 4.5.

2. New javascript features are added like Block scoped variables, container object etc. See What’s New in JavaScript.

3. Visual studio support windows 8.1 app development also it allows you to submit newly developed windows app to App store. See Windows 8.1 Preview: New APIs and features for developers.

4. Productivity improvements for managed apps include return values in the debugger, Edit and Continue support for 64-bit apps, and better exception handling in Windows Store apps.

5. MSBuild 12.0 is now installed as part of Visual Studio rather than as part of the .NET Framework, see What’s New in MSBuild 12.0.

6. The Visual Studio IDE has some important changes—improved icons, more contrast in the user interface, the ability to search the Options window directly, and other enhancements.

7. First time, when you start the visual studio, you can select one of the three Visual Studio themes—Black, White, or Blue.

8. The new connected IDE uses your Microsoft account to connect to your Visual Studio profile, including your Team Foundation Service (TFS) account.

9. You can use the new MVC (model-view-controller) pattern in Office and SharePoint 2013 to create apps. You can also publish apps to Windows Azure websites.

Download Visual Studio 2013 RC here.

What is the future of ASP.NET and MVC?


There are lots of articles on the internet that will put some thoughts on “What is the future of ASP.NET?”

Some thoughts:

As a developer, do you know Silverlight? Yes/No ?

Few years back, Microsoft marketing team promoted it. They promoted it in such a way that developers thought Silverlight will be the next Adobe Flash. A very popular companies such as Netflix, Renault Megane, NBC etc developed their websites using Silverlight.

But Where is Silverlight today? What is the share of Silverlight today in the market? What is the trend?

Now what about upcoming things like HTML 5TypeScriptMVC etc.. etc..?

Back to the main point, what is the future of ASP.NET and MVC?

It is true that, there is a shift to MVC from ASP.NET web forms. ASP.Net MVC is on the rise and growing more popular everyday. Another reason, ASP.Net MVC is becoming very popular, since it can take advantage of all the fantastic features coming with HTML 5 as well as new client-side libraries with ease . But they are much harder to integrate in ASP.NET webForms than MVC.

As the technologies are advancing, things are getting better and better with every advancements. So it’s the trend which will lead us the way we develop the sites.

So I don’t think that a technology is coming that would replace everything, rather think that new improvements would be made in the existing technology and knowledge of current technology would help you adapt to those new changes.

What do you think the future of ASP.NET and MVC should be? Thumbs up, or thumbs down? Share your thoughts please.