Saturday, December 4, 2010

Difference between .Net 4.0 and .Net 3.5, 2.0

.Net Framework 4.0 comes up with some of major changes as compare to previous versions of .Net Framework 3.5 and 2.0

Following are list of Major Changes in .Net 4.0
  • ControlRenderingCompatabilityVersion Setting in the Web.config File 
  • ClientIDMode Changes 
  • HtmlEncode and UrlEncode Now Encode Single Quotation Marks 
  • ASP.NET Page (.aspx) Parser is Stricter 
  • Browser Definition Files Updated 
  • System.Web.Mobile.dll Removed from Root Web Configuration File 
  • ASP.NET Request Validation 
  • Default Hashing Algorithm Is Now HMACSHA256 
  • Configuration Errors Related to New ASP.NET 4 Root Configuration 
  • ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications 
  • ASP.NET 4 Web Sites Fail to Start on Computers Where SharePoint Is Installed 
  • The HttpRequest.FilePath Property No Longer Includes PathInfo Values 
  • ASP.NET 2.0 Applications Might Generate HttpException Errors that Reference eurl.axd 
  • Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode Changes to the ASP.NET Code Access Security (CAS) Implementation 
  • MembershipUser and Other Types in the System.Web.Security Namespace Have Been Moved 
  • Output Caching Changes to Vary * HTTP Header 
  • System.Web.Security Types for Passport are Obsolete 
  • The MenuItem.PopOutImageUrl Property Fails to Render an Image in ASP.NET 4 
  • Menu.StaticPopOutImageUrl and Menu.DynamicPopOutImageUrl Fail to Render Images When Paths Contain Backslashes 
Link to find details of all the Major changes in .Net 4.0

Friday, December 3, 2010

C# and the Web: Writing a Web Client Application with Managed Code in the Microsoft .NET Framework

What is a Web Client?

      As you know, accessing data from the Internet can be accomplished in several ways. Browsers are one type of Web client that enable you to send requests to a particular Uniform Resource Identifier (URI) and receive the response in a standard format. Browsers are great Web clients for human-readable content; they display the results in HTML format allowing you to read the text and see the images. Performing more advanced tasks such as extracting a stock price from a Web page can be pretty difficult and techniques such as page scraping aren't trivial to implement. So how can applications connect to other applications via the Web?
      The answer to that is the XMLHttpRequest object, which is another kind of Web client. Using this object you can send and receive information to and from a Web resource in various formats, as shown in the following code:
var httpOb = new ActiveXObject("Microsoft.XMLHTTP");

httpOb.Open("POST","http://uddi.microsoft.com/inquire", false);
httpOb.send(MySOAPMessage);
var Ans = httpOb.GetResponseXML();
      The .NET Framework has a request/response model for accessing data from the Internet. Applications that use the request/response model can request data from the Internet in a protocol-agnostic manner—the application works with instances of a Web client (the WebRequest and WebResponse classes), while the details of the request are carried out by protocol-specific descendant classes. The .NET Framework provides a rich class structure for enabling the request/response model. The base classes for that are WebRequest and WebResponse. In my Web client, their descendants—the HTTPWebRequest and HTTPWebResponse classes—play a major role.

A Managed Web Client is Born

      The .NET Framework provides all the goodies you need to have full Web client functionality in the world of managed code, but it doesn't provide a full-featured client that can be reused in your projects, like the XMLHttpRequest object. I decided to wrap some managed classes and create a new managed class with identical behavior to the unmanaged XMLHttpRequest object. It turned out to be easier than I thought.
      In order to write the managed Web client, it's important to understand the common language runtime (CLR) and how to program against it. In addition, understanding the Unified Class Library (UCL) structure is even more important in my case so that I'm able to select the right class for the right job. I won't bore you with the technical details about the structure of the CLR and the exact implementation of the garbage collection, and I won't go through every class of the base classes and explain its interface. Instead I will explain only those classes that are relevant to my implementation of the Web client.
      Take a look at the .NET Framework structure in Figure 1. It provides a schematic overview of the UCL namespace structure. The base classes actually expose the operating system services. For example, the System.IO library enables services such as file streaming, reading, and writing, and the Net library allows you to handle Web requests, Web responses, sockets, and more. On top of it there are the System.Web services which are used to create Web Forms and Web Services, and the System.WindowsForms services which are used to create Windows®-based applications. My application will make extensive use of the System.Net and System.IO libraries for the XMLHttpRequest class.

Figure 1 The Unified Class Library Structure
Figure 1 The Unified Class Library Structure

      The first task is to create a WebRequest object for a specific network request schema—in my case, HTTP. In order to do that I'll use the System.Net.WebRequest class's CreateDefault method. However, instead of using the returned WebRequest object, I'll typecast it to the HttpWebRequest class, which is actually the HTTP-specific implementation of the WebRequest object.

http://msdn.microsoft.com/hi-in/magazine/cc301587%28en-us%29.aspx

Exception Handling in C#

Painful Procedural Error Handling

In the absence of exceptions the classic way to handle errors is to intertwine your statements with error checks. For example:
public sealed class Painful
{  
    ...  
    private static char[] ReadSource(string filename)
    {
        FileInfo file = new FileInfo(filename);
        if (errorCode == 2342) goto handler;
        int length = (int)file.Length;  
        char[] source = new char[length];
        if (errorCode == -734) goto handler;
        TextReader reader = file.OpenText();
        if (errorCode == 2664) goto handler;
        reader.Read(source, 0, length);
        if (errorCode == -5227) goto handler;
        reader.Close();
        Process(filename, source); 
        return source;

        handler:
        ...
    }
}
This style of programming is tedious, repetitive, awkward, complex, and obscures the essential functionality. And it's too easy to ignore errors (either deliberately or accidentally). There have to be better ways. And there are. But some are better than others.

Separation of Concerns

The fundamental thing that exceptions allow you to do is to separate the essential functionality from the error handling. In other words, we can rewrite the mess above like this:
...
public sealed class PainLess
{    
    public static int Main(string[] args)
    {
        try
        {
           string filename = args[0];
           char[] source = ReadSource(filename);
           Process(filename, source);
           return 0;
        }
        catch (SecurityException    caught) { ... }
        catch (IOException          caught) { ... }
        catch (OutOfMemoryException caught) { ... }
        ...
    }

    private static char[] ReadSource(string filename)
    {
        FileInfo file = new FileInfo(filename);
        int length = (int)file.Length;
        char[] source = new char[length];
        TextReader reader = file.OpenText();
        reader.Read(source, 0, length);
        reader.Close();
        return source;
    }
}
There are several things to notice about this transformation.
  • The numeric integer error codes that utterly failed to describe the errors they represented (e.g. what does 2342 mean?) are now descriptively named exception classes (e.g. SecurityException).
  • The exception classes are not tightly coupled to each other. In contrast, each integer code must hold a unique value thus coupling all the error codes together.
  • There is no throw specification on ReadSource. C# does not have throw specifications.
However, by far and away the most important thing to notice is how much cleaner, simpler and easier to understand ReadSource has become. It now contains only the statements required to implement its essential functionality. It makes no apparent concession to error handling. This is possible because if an exception occurs the call stack will unwind all by itself. This version of ReadSource is the "ideal" we are aiming it. It is as direct as we can make it.
Ironically, exceptions allow us to get close to this ideal version of ReadSource but at the same time prevent us from quite reaching it. ReadSource is an example of code that acquires a resource (a TextReader), uses the resource (Read), and then releases the resource (Close). The problem is that if an exception occurs after acquiring the resource but before releasing it then the release will not take place. The solution has become part of the context. Nevertheless, this "ideal" version of ReadSource is useful; we can compare forthcoming versions of ReadSource to it as a crude estimate of their "idealness".

finally?

The solution to this lost release problem depends on the language you're using. In C++ you can release the resource in the destructor of an object held on the stack (the misnamed Resource Acquisition Is Initialization idiom). In Java you can use a finally block. C# allows you to create user-defined struct types that live on the stack but does not allow struct destructors. (This is because a C# destructor is really a Finalize method in disguise and Finalize is called by the garbage collector. Structs, being value types, are never subject to garbage collection.) Therefore, initially at least, C# must follow the Java route and use a finally block. A first cut implementation using a finally block might look like this:
private static char[] ReadSource(string filename)
{
    try
    {
        FileInfo file = new FileInfo(filename);
        int length = (int)file.Length;
        char[] source = new char[length];
        TextReader reader = file.OpenText();
        reader.Read(source, 0, length);
    }
    finally
    {
        reader.Close();
    }
    return source;
}
This version has had to introduce a try block (since a finally block must follow a try block) which isn't in the ideal solution but apart from that it's the same as the "ideal" version of ReadSource. It would be a reasonable solution if it worked. But it doesn't. The problem is that the try block forms a scope so reader is not in scope inside the finally block and source is not in scope at the return statement.

finally?

To solve this problem you have to move the declarations of reader and source outside the try block. A second attempt might be:
private static char[] ReadSource(string filename)
{
    TextReader reader;
    char[] source;
    try
    {
        FileInfo file = new FileInfo(filename);
        int length = (int)file.Length;
        source = new char[length];
        reader = file.OpenText();
        reader.Read(source, 0, length);
    }
    finally
    {
        reader.Close();
    }
    return source;
}
This version has moved the declaration of reader and source out of the try block and consequently assigns to reader and source rather than initializing them. That's another difference (and two extra lines) from the "ideal" version of ReadSource. Nevertheless, you might consider it a reasonable solution if it worked. But it doesn't. The problem is that assignment is not the same as initialization and the compiler knows it. If an exception is thrown before reader is assigned then the call to reader.Close() in the finally block will be on reader which won't be assigned. C#, like Java, doesn't allow that.

finally?

Clearly you have to initialize reader. A third attempt therefore might be:
private static char[] ReadSource(string filename)
{
    TextReader reader = null;
    char[] source;
    try
    {
        FileInfo file = new FileInfo(filename);
        int length = (int)file.Length;
        source = new char[length];
        reader = file.OpenText();
        reader.Read(source, 0, length);
    }
    finally
    {
        reader.Close();
    }
    return source;
}
This version introduces null which isn't in the "ideal" version of ReadSource. Nevertheless, you might still consider it a reasonable solution if it worked. But it doesn't (although it does compile). The problem is the call to reader.Close() could easily throw a NullReferenceException.

finally?

One way to solve this problem is to guard the call to reader.Close(). A fourth attempt therefore might be:
private static char[] ReadSource(string filename)
{
    TextReader reader = null;
    char[] source;
    try
    {
        FileInfo file = new FileInfo(filename);
        int length = (int)file.Length;
        source = new char[length];
        reader = file.OpenText();
        reader.Read(source, 0, length);
    }
    finally
    {
        if (reader != null)
        {
            reader.Close();
        }
    }
    return source;
}
Of course, the guard on reader.Close() isn't in the "ideal" version of ReadSource. But this is a reasonable version if only because it does, finally, work. It's quite different from the "ideal" version but with a bit of effort you can refactor it to this:
private static char[] ReadSource(string filename)
{
    FileInfo file = new FileInfo(filename);
    int length = (int)file.Length;
    char[] source = new char[length];
    TextReader reader = file.OpenText();
    try
    {
        reader.Read(source, 0, length);
    }
    finally
    {
        if (reader != null)
        {
            reader.Close();
        }
    }
    return source;
}
In some cases you might be able to drop the null guard inside the finally block (you can in the above case) but in general this is the best you can do with a finally block solution. (Consider if file.OpenText returned null, or if reader was assigned to inside the try block, or reader was passed as a ref/out argument inside the try block.) You have to add a try block, a finally block, and an if guard. And if you are using Java you have to do those three things every time. And therein is the biggest problem. If this solution was truly horrible and completely and utterly different to the ideal solution it wouldn't matter a jot if we could abstract it all away. But in Java you can't. The Java road stops here, but the C# road continues.

using Statements

In C#, the nearest you can get to the "ideal" version is this:
private static char[] ReadSource(string filename)
{
    FileInfo file = new FileInfo(filename);
    int length = (int)file.Length;
    char[] source = new char[length];
    using (TextReader reader = file.OpenText())
    {
        reader.Read(source, 0, length);
    }
    return source;
}
This is pretty close. And as I'll explain shortly it has a number of features that improve on the "ideal" version. But first let's look under the lid to see how it actually works.

using Statement Translation

The C# ECMA specification states that a using statement:
using (type variable = initialization)
    embeddedStatement
is exactly equivalent to:
{
    type variable = initialization;
    try
    {
        embeddedStatement
    }
    finally
    {
        if (variable != null) 
        {
            ((IDisposable)variable).Dispose();
        }
    }
}
This relies on the IDisposable interface from the System namespace:
namespace System
{
    public interface IDisposable
    {
        void Dispose();
    }
}
Note that the cast inside the finally block implies that variable must be of a type that supports the IDisposable interface (either via inheritance or conversion operator). If it doesn't you'll get a compile time error.

using TextReader Translation

Not surprisingly, TextReader supports the Disposable interface and implements Dispose to call Close. This means that this:
using (TextReader reader = file.OpenText())
{
    reader.Read(source, 0, length);
}
is translated, under the hood, into this:
{
    TextReader reader = file.OpenText();
    try
    {
        reader.Read(source, 0, length);
    }
    finally
    {
        if (reader != null)
        {
            ((IDisposable)reader).Dispose();
        }
    }
}
Apart from the cast to IDisposable this is identical to the best general Java solution. The cast is required because this is a general solution.

Do It Yourself?

It's instructive to consider what would happen if TextReader didn't implement the IDisposable interface. The lessons from this will show us how to implement Disposability in our own classes. One solution is the Object Adapter pattern. For example:
public sealed class AutoTextReader : IDisposable
{
    public AutoTextReader(TextReader target)
    {
        // PreCondition(target != null);
        adaptee = target;
    }

    public TextReader TextReader
    {
        get { return adaptee; }
    }

    public void Dispose()
    { 
        adaptee.Close();
    }

    private readonly TextReader adaptee; 
}
which you would use like this:
using (AutoTextReader scoped = new AutoTextReader(file.OpenText()))
{
    scoped.TextReader.Read(source, 0, length);
}
To make things a little easier you can create an implicit conversion operator:
public sealed class AutoTextReader : IDisposable
{
    ...
    public static implicit operator AutoTextReader(TextReader target)
    {
        return new AutoTextReader(target);
    }
    ...
}
which would allow you to write this:
using (AutoTextReader scoped = file.OpenText())
{
    scoped.TextReader.Read(source, 0, length);
}

struct Alternative

AutoTextReader is a sealed class intended, as its name suggests, to be used as a local variable. It makes sense to implement it as a struct instead of class:
public struct AutoTextReader : IDisposable
{
    // exactly as before
}
Using a struct instead of a class also gives you a couple of free optimizations. Since a struct is a value type it can never be null. This means the compiler must omit the null guard from generated finally block. Also, since you cannot derive from a struct its runtime type is always the same as its compile time type. This means the compiler can usually omit the cast to IDisposable from the generated finally block and thus avoid a boxing operation. (specifically, it can avoid the cast if Dispose is a public Implicit Interface Implementation rather than a non-public Explicit Interface Implementation). In other words, this:
using (AutoTextReader scoped = file.OpenText())
{
    scoped.TextReader.Read(source, 0, length);
}
is translated into this:
{
    AutoTextReader scoped = new file.OpenText();
    try
    {
        scoped.TextReader.Read(source, 0, length);
    }
    finally
    {
        scoped.Dispose();
    }
}
It should come as no surprise that I prefer the using statement solution to the finally block solution. In fact, the using statement solution scores several extra points in comparison to the "ideal" solution. A using statement:
  • Works! It always releases the resource.
  • Is an extensible mechanism. It allows you to create an abstraction of resource release. Creating your own resource releaser types such as AutoTextReader is easy.
  • Allows you to pair up the resource acquisition with the resource release. The best moment to organize the resource release is the moment you acquire the resource. If you borrow a book from a library you're told when to return it as you borrow it.
  • Says explicitly, in syntax, that you are using a resource.
  • Creates a scope for the variable holding the resource. Look carefully at the compiler translation of a using statement and you'll see that it cleverly includes a pair of outer braces:
    using (AutoTextReader scoped = file.OpenText())
    {
        scoped.TextReader.Read(source, 0, length);
    }
    scoped.TextReader.Close(); // scoped is not in scope here
    This is reminiscent of C++ declarations in conditions. Both allow you to restrict the scope of a variable so it's only usable when in scope and is only in scope when usable.

Wednesday, December 1, 2010

Programming Microsoft LINQ

http://www.microsoft.com/learning/en/us/book.aspx?ID=10827Get comprehensive guidance for using the Microsoft Language Integrated Query (LINQ) Project—with in-depth insights from two experienced developers. Data-rich applications can be difficult to create because of the tremendous differences between query languages used to access data and the programming languages commonly used to write applications. This practical guide covers the intricacies of LINQ, a set of extensions to the Visual C# and Visual Basic programming languages. Instead of traversing different language syntaxes required for accessing data from relational and hierarchical data sources, developers will learn how to write queries natively in Visual C# or Visual Basic—helping reduce complexity and boost productivity.

You can download and read sample chapters from the follwing link


Link: http://programminglinq.com/


View More Detail: http://www.microsoft.com/learning/en/us/book.aspx?ID=10827http://www.microsoft.com/learning/en/us/book.aspx?ID=10827

How to Call a .NET-based Web Service Using the SOAP::Lite Perl Library

Let's say you have a WebMethod that takes no arguments and returns a string:


[WebMethod]
public string HelloWorld()
{
   return "Hello World";
}

use SOAP::Lite;

my $soap = SOAP::Lite
    -> uri('http://www.alfredbr.com')
    -> on_action( sub { join '/', 'http://www.alfredbr.com', $_[1] } )
    -> proxy('http://localhost/Example1/Service1.asmx');

print $soap->HelloWorld()->result; 
 
View More Detail: http://msdn.microsoft.com/en-us/library/ms995764.aspx 

Thursday, November 25, 2010

Advantage of HttpHandler - A Certificate example

Scenario

You are a developer at Grade Nineteen University. One of the recent requirments the management had is to create an online certificate.
So that the students that pass out should be able to view their Certificates online. This will definitely add some technological edge to the university.

Requirement
The student will be given his own certification url as following: http://www.cert19.edu/certificates/100.cert

On accessing the url, the following Certifcate image will be displayed for the student id: 100

(100.cert should be interpreted in server as "Show Certificate for Student Id as 100")

Easy Way of Implementation - But not the Best

The first thought of implementation would be to create jpg files for all the students and copy them into the cert folder of the website. This approach is feasible but the following overheads would exist:

  • For 1000 students that pass each year, 50 MB disk space would be required.
  • While backing up database of site, we have to do backup of jpg files too, which is tedious.
If we have to take a backup of the site, we have to copy the files separately and do the database backup separately.


Http Handlers for the Rescue - A better Approach

We can achieve the same behavior with little overheads รข€“ by avoiding files creation for certificates.

We can use the database records to dynamically create certificate based on the student url.

By default the ISAPI handlers, handle the .aspx url extensions. We have to create a new handler for .jpg file handling that would be redirected to our certificate creation code


View  more detail : http://www.c-sharpcorner.com/UploadFile/40e97e/3806/Default.aspx

Introducing Web Client Software Factory (WCSF)

The Web Client Software Factory is a framework for developing ASP.NET and Ajax applications implementing proven patterns and practices. This framework is part of Microsoft Patterns & Practices.

Advantages

Some of the core advantages of using the WCSF are:

Module based Development: We can create each business module as separate library and it provides reusability and easier maintainability.

Model View Presenter: Separation of User Interface giving more flexibility in manageability and unit testing.

Service Dependency Attribute: Allows injection of class instances to modules, resulting in instance reusability and less instance creation overheads

Overall it would be a good to have framework at the cost of learning.

Installation for Visual Studio 2010

It would be a two step process.

Step 1: First we have to install Guidance Automation Extensions for 2010. Guidance Automation provides the infrastructure for automated project creation actions inside Visual Studio IDE.

http://visualstudiogallery.msdn.microsoft.com/en-us/25e4b5e9-65e4-4950-967d-5f1e6a9dcbeb

image1.gif

Click on the Install button to proced.

View more Detail Click http://www.c-sharpcorner.com/UploadFile/40e97e/4402/