How to create asynchronous ASP.NET pages using C#

IIS combined with ASP.NET provides many technologies to improve performance and scalability.  IIS provides a pool of threads so that it can server many requests simultaneously.  The pool has a limited number of threads in it, and once they are used up additional requests can start to pile up.  Keeping the total number of active threads down is an attempt to prevent too many active threads from consuming all of the available CPU time.  However, with today's data intensive websites, much of the time threads are tied up waiting for an external resource such as a request from a web service or from a database.  Asynchronous pages in ASP.NET can boost performance in these situations by enabling threads in the pool to be used to serve additional requests while an operation is waiting for an external resource request to complete.

Suppose you have a website with two web pages.  One is your home page which display's a greeting, and the second page displays a large dataset from a database.  You have 25 threads in your thread pool.  25 people simultaneously are accessing the database query page, and one additional person comes onto the site to see the home page which has static content on it.

Compare these two scenarios:

Synchronous database driven page:  While everyone is waiting for the dataset to load, all available threads are in use so the 26th request for the home page becomes blocked.

Asynchronous database driven page:  While 25 requests are waiting for data from the database, those threads are returned to the pool for work.  When the 26th request comes in for the home page, that page is returned immediately.  As the datasets are returned the threads are drawn out of the thread pool to finish serving the pages.  The result is that the threads spend much more time available to serve requests.

Here are two good pages for getting started with asynchronous ASP.NET pages:

Asynchronous ASP.NET Page Processing by Peter Bromberg

http://www.eggheadcafe.com/articles/20060918.asp

Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code by Fritz Onion

http://msdn.microsoft.com/msdnmag/issues/03/06/threading/default.aspx

After reading these and some other articles, here is a piece of code to get you started.  I put this together to process a job in the background as a generic pattern.  I wrap my big job in a delegate so that I can get an IAsyncResult object back.  This simplifies things, because in most examples I read you get this by calling a web service asynchronously but this isn't always what you want done.

Step 1:  Make an empty asp.net page.  Add async="true" to the @Page tag in the .aspx file.

Step 2:  In the class code, declare a delegate

              public delegate void AsyncTaskDelegate();

Step 3:  Declare a member variable in the class to prevent the delegate from going out of scope

AsyncTaskDelegate _runnerDelegate = null;

Step 4:  Create a method that will be run asynchronously:

             public void DoJob()

            {

                 this.GridView1.DataSource = GetDatasetFromDatabase();        this.GridView1.DataBind();

           }

Step 5:  Tell the framework you want your job run.  You can put this in Page_Load or in a response to a button click / postback:

       // Register async methods

        AddOnPreRenderCompleteAsync(

            new BeginEventHandler(OnBegin),

            new EndEventHandler(OnEnd)

        );

Step 6:  Add the event to kick off the delegate and run the job asynchronously.

IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object state)

      {

        _runnerDelegate = new AsyncTaskDelegate(this.DoJob);

        IAsyncResult result = _runnerDelegate.BeginInvoke(cb, state);

        return result;

      }

Step 7:   Add an event handler for after the request finishes

void OnEnd(IAsyncResult ar)

      {

        _runnerDelegate.EndInvoke(ar);

      }

All together, it looks like this:

   1:  public partial class Async : System.Web.UI.Page
   2:  {
   3:      public delegate void AsyncTaskDelegate();
   4:   
   5:      AsyncTaskDelegate _runnerDelegate = null;
   6:   
   7:      IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object state)
   8:      {
   9:          _runnerDelegate = new AsyncTaskDelegate(this.DoJob);
  10:          IAsyncResult result = _runnerDelegate.BeginInvoke(cb, state);
  11:          return result;
  12:      }
  13:   
  14:      public void DoJob()
  15:      {
  16:          this.GridView1.DataSource = new AsyncTaskDelegate(this.DoJob); 
  17:          this.GridView1.DataBind();
  18:      }
  19:   
  20:      void OnEnd(IAsyncResult ar)
  21:      {
  22:          _runnerDelegate.EndInvoke(ar);
  23:      }
  24:   
  25:      protected void Button1_Click(object sender, EventArgs e)
  26:      {
  27:          // Register async methods
  28:          AddOnPreRenderCompleteAsync(
  29:              new BeginEventHandler(OnBegin),
  30:              new EndEventHandler(OnEnd)
  31:          );
  32:      }
  33:   
  34:  }

Original Source: http://davidjberman.com/blogs/csharp/archive/2007/08/13/how-to-create-asynchronous-asp-net-pages-using-c.aspx


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (279) 
  • RSS Feed for this post's comments Comment RSS
  •    


List of C# Tools

A collection of development tools and utilities for C# programming.

C# Build Tools

  • CruiseControl.NET - A .NET continuous integration tool and an extensible framework for creating a custom continuous build process. more
  • FinalBuilder - An automated build and release management solution for Windows software developers. more
  • Hippo.NET - A tool for streamlining the build process of .NET projects in a team environment. more
  • MegaBuild - An automated build utility. more
  • MSBuild - The build system for Microsoft and Visual Studio. more
  • NAnt - An open source .NET build tool. more
  • Visual Build Professional - Software for Windows that enables developers and build masters to easily create an automated, repeatable process for building and deploying software. more

C# Compilers and Frameworks

  • .NET Framework SDK - Contains the .NET Framework, runtime and compilers for C# (and other languages). more
  • ANTLR - ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, compilers, and translators from grammatical descriptions. more
  • Coco/R - A compiler generator, which takes an attributed grammar of a source language and generates a scanner and a parser for this language. more
  • DotGNU - DotGNU Portable.NET, a cross-platform implementation of the Common Language Infrastructure (CLI). more
  • Mono - A cross-platform, open-source .NET development framework. more
  • Script# - Brings the power and productivity of C# and .NET tools to AJAX development by compiling C# source code into regular JavaScript. more
  • Silverlight - Microsoft Silverlight 2 allows rich application experiences for the Web and mobile devices to be written in C#. more
  • Visual C# Express Edition - Free edition of Visual Studio for C# developers. more

Collaboration

  • AQdevTeam - A project control and management system. more
  • Ultra Apps - Free web-based bug tracking with source code in ASP and ASP.NET/C#. Features include: issue tracking, response history, Excel export, bookmarks, search and more... more
  • Visual Studio Team System - An integrated application life-cycle management (ALM) solution comprising tools, processes, and guidance to help everyone on the team improve their skills and work more effectively together. more

C# Decompilers

  • .NET Reflector - A class browser and analysis tool for .NET. It allows developers to navigate, search, disassemble and analyze .NET components. more
  • Anakrino/Exemplar - more
  • Dis# - A .NET decompiler. more
  • Spices.Decompiler - A powerful and flexible .NET decompiler that converts .NET assemblies from binary format to well-formed and optimized source code. more
  • Salamander .NET Decompiler - A .NET decompiler that converts executable files (.EXE or .DLL) from Intermediate Language (IL, MSIL, CIL) binary format to high-level source code, such as C#, managed C++, Visual Basic.NET, etc. more

C# Deployment

  • Thinstall - Application virtualization for .NET. more
  • Windows Installer XML - (WiX) A toolset that builds Windows installation packages from XML source code. The toolset supports a command line environment that developers may integrate into their build processes to build MSI and MSM setup packages. more

C# Design Tools

  • StarUML - An open source project to develop a fast, flexible, extensible, featureful and freely-available UML/MDA platform running on the Win32 platform. more
  • WithClass - A UML design tool that can generate and reverse engineer C# source code. more

C# Development Environments (IDEs)

  • Borland C#Builder for Microsoft .NET - Integrated development environment (IDE) for building .NET applications with C#. more
  • C# Studio - A simple IDE for a C#/Mono/GTK# developer. more
  • QuickSharp - QuickSharp 2008 is a simplified, free C# development environment for Microsoft .NET 2.0. It's open source and allows C# applications to be created instantly without having to create projects and solutions. Ideal for the beginner just wanting to try out some code. more
  • MonoDevelop - An open source integrated development environment for the Linux platform, primarily targeted for the development of software that uses both the Mono and Microsoft .NET framework. more
  • SharpDevelop - The Open Source Development Environment for .NET. #develop (short for SharpDevelop) is a free IDE for C# and VB.NET projects on Microsoft's .NET platform. more
  • Snippet Compiler - A tool for working with C# code snippets (perfect for when you just need to run a couple lines of code). more
  • Visual C# Express Edition - An integrated development environment designed for beginning programmers and non-professional developers interested in building Windows Forms, class libraries, and console-based applications. Visual C# 2005/2008 Express Edition includes many of the same productivity features found in Visual Studio, all streamlined to fit the needs of the non-professional Windows developer. more

C# Documentation

  • GhostDoc - A free add-in for Visual Studio that automatically generates XML documentation comments for C#, either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from the name and type of methods, properties or parameters. more
  • NDoc - Generates class library documentation from .NET assemblies and the XML documentation files generated by the C# compiler. more
  • Sandcastle - Produces MSDN style documentation by reflecting over the source assemblies and optionally integrating XML documentation comments. more

Database

  • ADO.NET Express - Add-in for Visual Studio that automates common tasks of writing repetitive data access code. more
  • Data Access Application Block for .NET - A reusable and extensible source code-based guidance that simplifies development of common data access functionality in .NET-based applications. more
  • DataLG - Generates a complete data layer for your VB and C# applications. more
  • DeKlarit - A model-driven tool that combines agile database modeling, declarative business rules, code generation and integration with Microsoft Visual Studio. more
  • NHibernate - An object-relational mapping (ORM) solution for the Microsoft .NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database. more
  • OlyMars - SQL Server Centric .NET Code Generator (code named OlyMars) is a code generator based on database modeling. more

C# Editors

C# Formatters and C# Code Beautifiers

  • Code Highlighter - A source code syntax highlighting component available for the .NET environment. more
  • NArrange - An open-source tool for arranging .NET source code. This code beautifier allows you to sort and organize C# and VB.NET code members into groups or regions. more
  • Semantic Designs: C# Source Code Formatter - Reorganizes C# source text files to neatly indent code blocks according to their nesting level, or, conversely, obfuscates the code to make it difficult to understand by renaming variables. more
  • Uncrustify - Source code beautifier for many languages, including C#. more
  • Regionerate - An open-source tool for developers and team leaders that allows you to automatically apply layout rules on C# code. more

C# Graphics and Games

  • CadLib - DXF 3D .NET component and viewer. more
  • ExoEngine - An open source C# 3D game engine for Microsoft .NET, based upon OpenGL and NVIDIA's Cg. more
  • OpenGL & SDL for C# - An open source implementation of OpenGL in C#. more
  • VG.net - Animated vector graphics in Visual Studio .NET. more
  • XNA Game Studio - Enables hobbyists, academics, and independent game developers to easily create video games for Microsoft Windows and the Microsoft Zune digital media player using optimized cross-platform gaming libraries based on the Microsoft .NET Framework. more

C# Libraries and Components

  • C# Math Expression parser assembly - Math expression parser written in C#. It evaluates mathematical expressions such as "cos(x)+cos(y)-2", with given values. more
  • C-Sharpener For VB - Code converter tool from VB.NET to C#. more
  • Castle .NET - An open-source project to create a set of .NET tools/frameworks to ease enterprise and web application development. more
  • CenterSpace Software - C# libraries that provide building blocks for .NET mathematical and financial applications, including matrix and vector classes, and object-oriented interfaces to public domain computing packages such as the BLAS (Basic Linear Algebra Subprograms) and LAPACK (Linear Algebra PACKage). more
  • Enterprise Library - A collection of reusable software components (application blocks), provided by Microsoft, that assist enterprise .NET developers with common application development scenarios. more
  • Evolutility - Dual-licensed, open-source web UI framework for CRUD applications. Free for use in open-source projects. more
  • Glacial Components - Free .NET components. more
  • IE Web Controls - The Internet Explorer Web Controls including C# source code. more
  • LibCheck - This tool allows you to compare two versions of an assembly and determine the differences. more
  • Neural Network Library in C# - A neural network library written in C#. more
  • Sharp3D.Math - Fundamental classes for dealing with numerics on the .NET platform. more
  • Spring.NET: Application Framework - Spring.NET is a port and extension of the Spring Framework for .NET. more
  • Visual Guard - Security solution for .NET Applications. Allows management of users, memberships, roles and password policy. more

C# Logging

  • Log4Net - A tool to help the programmer output log statements to a variety of output targets. log4net is a port of the log4j framework to the .NET runtime more
  • SmartInspect - Logging tool for debugging and monitoring .NET applications. more

Miscellaneous

  • CSharpTelnet - Telnet client for C#. more
  • IntelliSpell - Spell-checking add-in for Microsoft Visual Studio. A free, community edition is available. more
  • Ora Visual Studio Add-In - A Visual Studio 2008 add-in that provides an instant grouped overview of the class, interface or struct you are viewing or editing. more
  • PostSharp - An aspect weaver for .NET. It can can reduce the number of lines of code and improve the logical decoupling of your programs. more
  • Resourcer - Resourcer is an editor for .resources binaries and .resx XML file formats used with the .NET platform. Resourcer allows editing of name/string pairs, import of bitmaps/icons and and merging of resources from different sources. By Lutz Roeder. more
  • StudioSpell - A Visual Studio spell check add-in. more

C# Obfuscators

  • C# Source Code Obfuscator - by Semantic Designs. Scrambles C# source code to make it very difficult to understand or reverse-engineer. more
  • .NET Reactor - A .NET code protection and licensing system which assists developers in protecting their .NET software. more
  • {smartassembly} - A .NET obfuscation, protection and improvement tool. more
  • Demeanor for .NET - Protects your intellectual property by making it difficult to reverse engineer your .NET applications. more
  • Dotfuscator - A .NET Obfuscator. more
  • Salamander .NET Obfuscator - A .NET code protection tool that offers sophisticated technologies to protect your .NET code and intellectual properties. more

Object Browsers

C# Profiling Tools and C# Optimization

  • .NET Memory Profiler - A tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language. more
  • ANTS Profiler - Performance profiling and memory profiler for .NET code. more
  • AQtime - Performance profiling and memory/resource debugging toolset for Microsoft, Borland, Intel, Compaq and GNU compilers. more
  • CLR Profiler - The CLR Profiler allows developers to see the allocation profile of their managed applications. more
  • DevPartner Studio Professional Edition - A suite of software development and testing tools that enable Windows application teams to build reliable, high-performance applications, components and web services for Microsoft .NET and native Windows platforms. more
  • ILMerge - A utility for merging multiple .NET assemblies into a single .NET assembly. more
  • NCover - .NET code coverage tool. Commercial, but a disontinued free version is also available. more
  • NGen - The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. more
  • NProf - .NET profiler application and API. more
  • PartCover - An open-source .NET code coverage tool. more
  • Prof-It for C# - A standalone profiler for C# that measures execution frequencies for each statement, while keeping the instrumentation of the source code to a minimum. more

C# Refactoring

  • devAdvantage - C# source code analyzer for Visual Studio.NET - A Microsoft Visual Studio .NET add-in that provides C# static source code analysis to automate code reviews and detects errors, bugs and issues. The community edition is free. more
  • dotEASY - A Visual Studio .NET add-in that evaluates C# source code and performs “advices” in order to improve software quality. more
  • ReSharper - A powerful productivity suite for Visual Studio. Refactoring, code analysis, code generation... more

Regular Expressions

  • Expresso - A regular expression development tool. more
  • RegexDesigner.NET - A visual tool for helping you construct and test .NET regular expressions. more
  • The Regulator - An advanced regular expressions testing tool, featuring syntax highlighting and web-service integration with Regexlib.com's database of online regular expressions. more

C# Reporting

  • ActiveReports - Reporting solution for .NET that is written in fully managed Visual C# and provides complete integration into the Visual Studio .NET IDE. more
  • Crystal Reports - Professional .NET reporting. more
  • Report Generator List & Label - Equip your applications with classic printing, fast preview and comprehensive export functions. more

C# Standards Verifiers

  • Code Style Enforcer - A DXCore plug-in for Microsoft Visual Studio 2005/2008 that provides code style enforcement against configurable coding standards. more
  • devAdvantage - C# source code analyzer for Visual Studio .NET - A Microsoft Visual Studio .NET add-in that provides C# static source code analysis to automate code reviews and detects errors, bugs and issues. The community edition is free. more
  • FxCop - FxCop is an application that analyzes managed code assemblies and reports information about the assemblies, such as possible design, localization, performance and security improvements. more
  • StyleCop - Analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. more

C# Testing and C# Test Frameworks

  • .NETUnit - An implementation of Kent Beck's XUnit testing framework designed specifically for unit testing components written for the .NET platform. more
  • csUnit - Inspired by JUnit, csUnit brings the power of unit testing to the .NET framework. csUnit is your key to unit testing and test-driven development using .NET languages such as C#, Visual Basic .NET, Visual J#, or Managed C++. more
  • MbUnit - A generative unit test framework for the .NET Framework. more
  • NMock - A dynamic mock object library for .NET. more
  • NUnit - A unit-testing framework for all .NET languages; initially ported from JUnit. more
  • Pex - Automated white box testing for .NET. more
  • POCMock - A tool for creating mock classes. more
  • Rhino Mocks - A dynamic mock object framework for the .Net platform. Its purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing. more
  • Silverlight Unit Test Framework (Ignite) - A simple, extensible unit testing solution for rich Silverlight 2 applications, controls and class libraries. more
  • TestComplete - A full-featured environment for automated testing of Windows, .NET, WPF (XAML) applications, web pages, web servers and web services. more
  • TestDriven.NET - Unit-Testing add-in for Visual Studio .NET that is fully integrated with all major unit testing frameworks including NUnit, MbUnit, csUnit and Visual Studio Team System. more
  • TestMatrix for Visual Studio - Adds test driven development support to Visual Studio with unit testing, code coverage analysis, and test profiling. more
  • WatiN - Write automated web application tests in C#. more
  • XtUnit - Extend NUnit or MbUnit with new test attributes. more
  • xUnit.net - Unit testing for .NET. more
  • X-Unity - A suite of development tools enabling unit testing and continuous integration activities on Microsoft .NET projects. more

Source: http://www.csharptools.com


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (813) 
  • RSS Feed for this post's comments Comment RSS
  •    


Web Forms model in ASP.NET 4.0

ASP.NET 4.0 platform is built up with various components Web Forms,ASP.NET MVC, Dynamic Data Controls and ASP.NET AJAX. It has the same foundation as in ASP.NET 3.5 SP1 but refined the above features. This post speaks about features in the Web Form model.


ASP.NET 4.0 features are nothing new, all are in 3.5 but this version gives more control over frequently used features.

Example: ASP.NET 4.0 Web Forms give developers more control over viewstate management, generation of Control ID’s, and HTML generated by some template based controls.

Control Over the Viewstate

Every developer knows that ASP.NET Viewstate burdens the page and waste of bandwidth. Same developers welcomed the ASP.NET MVC because of its complete absence of viewstate. If you ignore the viewstate on your page then you need to reload the data from server to controls.

The Viewstate is functional to Web Forms model, as it caches the contents from cache for control in the page.The overlooked feature is we can turnoff the viewstate for the page or control.The viewstate support is turned on for each page by default. The property EnableViewstate is defined is System.Web.UI.Control class and can be used to turn it on or off.

You can turn off the viewstate for ASP.NET page either declaratively or programmatically during the page’s life cycle.

void Page_Load(object sender,EventArgs e)
{
//Disable viewstate for the page and all of its child controls
 
this.EnableViewState = false;
 
....
 
}

Viewstate setting in ASP.NET has hierarchical nature, which means if the viewstate is enabled on the parent control, it can not be disabled on any of its child controls. You can disable the viewstate at page level and enable it in control level wherever it required.

ASP.NET 4.0 feature is you can enable viewstate at control level. In ASP.NET 4.0, the System.Web.UI.Control class exposes a new property named ViewStateMode:

public virtual ViewStateMode {get; set; }

ViewStateMode enumeration has the following values

 

Value Description
Inherit Inherits the value of ViewStateMode property from the parent control
Enabled Enables viewstate for this control even if the parent control has set the viewstate property disabled.
Disabled Disables viewstate for this control even if the parent control has set the viewstate property enabled.

 

Auto-Generated IDs

It is possible that rendered HTML can contain the same ID. When search for an element using getElementById, you will simply get an array of elements.Most data-bound controls generate their output by repeating the HTML for every data-bound item.

The sample generated Id string look like the following

ctl00$ContentPlaceHolder2$Gridview11$TextBox1

First issue might be with the length of the string, which repeated for several elements, makes the downloaded larger. Predicting the ID of a given control from script is difficult.

A frequently used technique for the above issue is

var btn = document.getElementById("<%=Button1.ClientID %> ");

ASP.NET 4.0 supports another option for autogenerated ids problem and developer can has greater control over generating the clientid of a control.

The System.Web.UI.Control Class now has a brand new property named ClientIDMode.

The ClientIDMode property values can be

Value Description
Legacy Indicates that ID should be generated as in earlier versions of ASP.NET
Static ASP.NET doesn’t make any attempt to scope the client ID. The ID is assigned as-is.
Predictable The ID is obtained by simply concatenating the ID of parent controls and ignoring master page’s parent elements.
Inherit The control will use the same algorithm as its parent.

Consider the following code:

<asp:GridView ID="GridView1" runat="server"
              ClientIDMode = "Predictable"
              RowClientIdsuffix="CustomerID">
  ......
 
</asp:GridView>

In this case, each row of the grid is identified by one or more columns in the data source with a trailing index. example

Panel1_GridView1_ALFKI_1

Finally, note that the ClientIDMode property affects only the ID attribute of the resulting HTML. The more about clientids in ASP.NET 4.0 can read here

HTML Enhancements

In the early version of ASP.NET developer didn’t have much control over programmatically accessing the HTML tags of a Web Page.

In ASP.NET 4.0, the Page class exposes two new string properties to set some common tags in the <head> section of a page. The two properties are Keywords and Description. The Keywords and Description properties can also be set directly as attributes of the @Page directive as shown below

 
<%@ Page Language="c#"
    AutoEventWireup="true"
    CodeFile="Default.aspx.cs"
    Inherits="_Default"
    Keywords="ASP.NET, AJAX "
    Description="ASP.NET 4.0 WebForms" %>
 
 

permanently redirecting the page feature can be found here

More Control over Output Caching here

Conclusion

ASP.NET 4.0 Web Forms contains a number of features that together can make it a bigger development platform. It is moreover a refinement of existing features.

Source: MSDN Magazine

Backtrack: http://www.techbubbles.com/aspnet/web-forms-model-in-asp-net-4-0/


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (117) 
  • RSS Feed for this post's comments Comment RSS
  •    


Difference between Early Binding and Late binding

Binding refers the object type definition. You are using Early Binding if the object type is specified when declaring your object.
E.g. if you say Dim myObject as ADODB.Recordset that is early binding (VB example).

If on the other hand you declare your object as a generic type you are late binding.
E.g. if you Dim myObject as Object (VB example).

One should note that binding is determined at object declaration and not at object instantiation. Therefore it does not matter if you later go on to Set myObject = New ADODB.Recordset or Set myObject = CreateObject(”ADODB.Recordset”).

Early binding allows developers to interact with the object’s properties and methods during coding. You can enjoy the benefits of intellisense. Also, early binding permits the compiler to check your code. Errors are caught at compile time. Early binding also results in faster code. It’s disadvantage is that you cannot create a generic object which may be bound to different types of objects.

Late binding on the other hand permits defining generic objects which may be bound to different objects. Eg you could declare myControl as Control without knowing which control you will encounter. You could then query the Controls collection and determine which control you are working on using the TypeOf method and branch to the section of your code that provides for that type. This is the only benefit of late binding. It’s disadvantages are that it is error prone and you will not enjoy much intellisense whilst coding.

Early binding is just simply explicitly invoking a member, as in

string s = "Hello";
s.Trim();  // Early bound call to the Trim() method

There are lots of late binding mechanisms in .NET, including delegates and reflection. For example, you could use

class Test {

   public void Foo( int i ) {
     ...
   }
}
// Code somewhere else
Test t = new Test();
Type ty = t.GetType();
System.Reflection.MethodInfo mi = ty.GetMethod( "Foo" );
mi.Invoke( t, new object[] { 10 } );

or (via a delegate)

public delegate void FooInvoker( int i );
// code somewhere else
Test t = new Test();

FooInvoker fi = (FooInvoker) Delegate.CreateDelegate( typeof( FooInvoker ), t, "Foo" );
fi( 10 ); // although you could use asynch invoke pattern

Remember that these late binding calls can fail because you might misspell the method name, or pass in the wrong parameters. And please note that there are a lot of ways of invoking a member on an object (or a static member of a type), not just the two shown here.

Also note that some people also use the term late binding to describe virtual function resolution at run-time, as opposed to full early binding where a method is invoked without any virtual lookup being required.

Generally (but see below), early binding is done at compile time (with some work at load time to verify):

int a = 1;
string b = a.ToString();

The call to ToString is completely determined by the compile.

Late binding is done dynamically at runtime (usually via Reflection). Overall, it is more a qualitative statement about performance (direct compiled method calls are orders of magnitude faster than calls via reflection), and dynamism (reflection allows decisions to be made

However, there are many intermediate steps and the whole thing is far from binary. Many different methods exist to call methods which give different performance and flexibility tradeoffs. Including

  • non-virtual method calls
  • virtual method calls
  • delegates
  • Expression Trees
  • reflection
  • dynamically created code (emit and CodeDOM)

It is the ability to do things at runtime you would otherwise have to do at coding time by reading the assembly metadata. This includes working with types that do not exist at compile time (or deployment time even).

Consider how to call each public method (which takes no arguments) on an instance of a type that has a particular attribute ("RunThisAttribute"):

public void RunAnnotatedMethods(object target) {
   Type targetType = target.GetType();
   MethodInfo[] methods
     = targetType.GetMethods()
                 .Where(m => m.GetParameters().Length == 0
                             && m.GetCustomAttributes(typeof(RunThisAttribute), false).Length > 0);
   foreach (MethodInfo m in methods) {
     m.Invoke(target, new object[] {});
   }
}

  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (334) 
  • RSS Feed for this post's comments Comment RSS
  •    
  • Tags:
  •    Categories: C#


Facade Design Pattern

This article provides a brief introduction to Facade Design Patterns.  Facade Design pattern provides an easy to use interface to an otherwise complicated collection of interfaces or subsystems.  It makes things easier by hiding the details of the implementation.

When designing good programs, programmers usually attempt to avoid excess coupling between module/classes.  Using this pattern helps to simplify much of the interfacing that makes large amounts of coupling complex to use and difficult to understand.

In a nutshell, this is accomplished by creating a small collection of classes that have a single class (Facade) that is used to access them.

The facade pattern is an object-oriented design pattern.  A facade is an object that provides a simplified interface to a larger body of code, such as a class library.  A facade can accomplish all of the following.

  • It can make a software library easier to use and understand since the facade has convenient methods for common tasks.
  • It makes code that uses the library more readable for the same reason.
  • It can reduce dependencies of outside code on the inner workings of a library since most code uses the facade.  This allows for more flexibility in developing the system.
  • It can wrap a poorly designed collection of APIs with a single well-designed API.

Class Diagram

ClassDiagram2

Code in C#

This structural code demonstrates the Facade pattern which provides a simplified and uniform interface to a large subsystem of classes.

// Facade pattern -- Structural example  


using System;



namespace GangOfFour.Facade.Structural
{

    /// <summary>

    /// MainApp startup class for Structural

    /// Facade Design Pattern.

    /// </summary>

    class MainApp
    {

        /// <summary>

        /// Entry point into console application.

        /// </summary>

        public static void Main()
        {

            Facade facade = new Facade();



            facade.MethodA();

            facade.MethodB();



            // Wait for user

            Console.ReadKey();

        }

    }



    /// <summary>

    /// The 'Subsystem ClassA' class

    /// </summary>

    class SubSystemOne
    {

        public void MethodOne()
        {

            Console.WriteLine(" SubSystemOne Method");

        }

    }



    /// <summary>

    /// The 'Subsystem ClassB' class

    /// </summary>

    class SubSystemTwo
    {

        public void MethodTwo()
        {

            Console.WriteLine(" SubSystemTwo Method");

        }

    }



    /// <summary>

    /// The 'Subsystem ClassC' class

    /// </summary>

    class SubSystemThree
    {

        public void MethodThree()
        {

            Console.WriteLine(" SubSystemThree Method");

        }

    }



    /// <summary>

    /// The 'Subsystem ClassD' class

    /// </summary>

    class SubSystemFour
    {

        public void MethodFour()
        {

            Console.WriteLine(" SubSystemFour Method");

        }

    }



    /// <summary>

    /// The 'Facade' class

    /// </summary>

    class Facade
    {

        private SubSystemOne _one;

        private SubSystemTwo _two;

        private SubSystemThree _three;

        private SubSystemFour _four;



        public Facade()
        {

            _one = new SubSystemOne();

            _two = new SubSystemTwo();

            _three = new SubSystemThree();

            _four = new SubSystemFour();

        }



        public void MethodA()
        {

            Console.WriteLine("\nMethodA() ---- ");

            _one.MethodOne();

            _two.MethodTwo();

            _four.MethodFour();

        }



        public void MethodB()
        {

            Console.WriteLine("\nMethodB() ---- ");

            _two.MethodTwo();

            _three.MethodThree();

        }

    }

}

Conclusion

Thus, Facade is a design pattern that hides the details and complexities of the lower-level software services for which it is written, making the service easier to use.  In fact, the lower-level classes need not be classes at all; they can be an API in the form of a code library or a Web service.

A Facade also provides a unified entry point into the layers of the software.  This reduces the application's dependency on the software service details and allows the Facade to hide future changes in the software service itself.

References:

http://www.dofactory.com/patterns/patternfacade.aspx
http://aspalliance.com/970_Facade_Design_Pattern.4
  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (373) 
  • RSS Feed for this post's comments Comment RSS
  •    


SOA Enabled DAL

Introduction

Traditional applications using relational data sources such as Oracle, SQL Server and DB2 to expose their business logic to external world in a tightly coupled manner. This tightly coupled approach leads to the performance\scalability issues. This post discusses the Designing a SOA enabled DAL with example.

Traditional Service Data Access

clip_image002

Above figure shows the set of web services accessing the same relational database. Every request from the client requires data access which creates the performance issue when multiple concurrent users are trying to access the database.

Traditional applications having their own databases and when we migrate to the SOA data integrity issues will arise.

SOA Model Data Access

clip_image004

SOA model represents the loosely coupled architecture where business logic and Data access logic are no longer integrated. We are using LINQ-SQL as an interface for the SOA DAL.

SOA DAL only exposes the DTO’s[Data Transfer Objects] to the services

DTO representing the Employee looks like the following

Data Transfer Objects

clip_image006

This DAL is a provider independent and can be pluggable to different databases by reading the provider from the configuration file.

The Data provider using LINQ to SQL looks as follows

Data Provider

clip_image008

clip_image010

The DataService that exposed through service layer looks like

clip_image012

Now You can call the above service in windows or web application. We have seen how we decoupled the application from data access logic.

More information on building the SOA data access at http://msdn.microsoft.com/en-gb/magazine/dd263098.aspx.


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (64) 
  • RSS Feed for this post's comments Comment RSS
  •    


Singleton - Creational Design Pattern

Introduction

There are times, when one need to have a class which can be only instantiated once. Singleton Design Pattern addresses to such situation by providing a design for such classes (known as Singleton class).

Description:
There are at least two solutions or scenario for implementing Singleton Class. The first solution says that there should be only one shared object and reference to that object should be available only through static method like GetInstance() while making the constructor private. A number of clients can be awarded the reference to such shared object. The second solution says that the constructor should be public (as it appears in most cases) but once an object has been instantiated, an exception should be thrown for each successive constructor call; thus limiting the class to only one object.

An Example:

First case Singleton can be used in a data repository or data collection where creation of more than one object can be resource wastage. Hence each client is given a reference to a single shared object to operate on. While the second case Singleton can be used in locking mechanisms. Once a client has got the object, no other client can have an object.

Class Diagram:

ClassDiagram1

Implementation:

Let us first discuss the code of first case Singleton which is like:

 class Singleton
    {
        private static Singleton instance;
        private static int numOfReference;
        private string code;
        private Singleton()
        {
            numOfReference = 0;
            code = "Deepak Kamboj";
        }
        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            numOfReference++;
            return instance;
        }
        public static int Reference
        {
            get { return numOfReference; }
        }
        public string Code
        {
            get { return code; }
            set { code = value; }
        }
    }

There are 3 fields in the Singleton class. Static field instance is a reference to shared object in this Singleton class. Static field numOfReference is an integer variable to hold the number of current references to the single shared object of Singleton class. Code is a string value, it is used to demonstrate that the object is shared b/w references and change made to this field through one reference can be realized through other reference.

The constructor is made private and used to initialize the numOfReference and default value of code. GetInstance() method checks the instance, if it is null then it assign it an instance of Singleton otherwise return the old reference. GetInstance() also increments the numOfReference each time it is called to keep track of current number of reference to our shared instance. Property Reference returns the number of reference referencing our shared object while Code property can be used to set/get the code string of shared object.

The second case Singleton class (Singleton2) looks like:

 public class Singleton2
    {
        private static int numOfInstance = 0;
        public Singleton2()
        {
            if (numOfInstance == 0)
            {
                Console.WriteLine("\r\nCreating First " 
                                + "Object of Singleton2 class...");
                numOfInstance++;
            }
            else
            {
                throw new Exception("This class is Singleton" +
                    ", so only one object of it can be instantiated.");
            }
        }
    }

Here we make the constructor public and use a private field numOfInstance which is incremented for each constructor call. If numOfInstance is zero (no object is yet instantiated), a new object is allowed to made. But, if this value is not zero (there is already an object of Singleton2 class, an exception is thrown.

Now let us try these with Main() method, the code in main is like:

 

class Program
    {
        static void Main(string[] args)
        {
            Singleton obj1 = Singleton.GetInstance();
            obj1.Code = "Deepak Kamboj";
            Console.WriteLine("No. of references : " + Singleton.Reference);
            Console.WriteLine("First Objects code: " + obj1.Code);
            Singleton obj2 = Singleton.GetInstance();
            Console.WriteLine("No. of references : " + Singleton.Reference);
            Console.WriteLine("Second Objects code: " + obj2.Code);
            Singleton2 obj3 = new Singleton2();
            Singleton2 obj4 = new Singleton2();

        }
    }

First we called GetInstance() and took the reference to the new object in obj1. The code for this object is changed to Faraz Rasheed which was Maasoom Faraz by default. Then, we check for number of references to this object and code set for this. Next, we get another reference to this object through GetInstance() in obj2. We again check the number of references and code using this reference. If both the references are pointing to the same shared object, the number of references now should be 2 while the code should also be Faraz Rasheed (remember if obj2 points to a new object then code would have been Maasoom Faraz, the default one) which is shown in the output.

We also made an object of Singleton2. When constructor is called for the first reference (obj3), the new object is instantiated printing the message on Console. But when another instance of Singleton2 is attempted to be made through obj4, an exception is thrown saying Singleton class can only be instantiated once.

Sample output from the program is:

No. of references : 1
First Objects code: Deepak Kamboj
No. of references : 2
Second Objects code: Deepak Kamboj
Creating First Object of Singleton2 class...

Unhandled Exception: System.Exception: This class is Singleton,so only one object of it can be instantiated. 
at Singleton.Singleton2..ctor() in c:\documents and settings\msff\my documents\visual studio projects\singleton\class1.cs:line 75 
at Singleton.Client.Main(String[] args) in c:\documents and settings\msff\my
documents\visual studio projects\singleton\class1.cs:line 20
Press any key to continue

The complete source code is also attached with the article. Take a look at it to understand it to full. 

Conclusion:

By using Singleton Design Pattern, it is possible for a programmer to control the instantiation of class by allowing only single object to be instantiated when desirable.

Backtrack: http://www.c-sharpcorner.com/UploadFile/faraz.rasheed/SingletonPattern12052005063955AM/SingletonPattern.aspx


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (57) 
  • RSS Feed for this post's comments Comment RSS
  •    


Factory Design Pattern using C#

The factory method pattern is a creational design pattern used in software development to encapsulate the process of creating the objects.

Concerns:

  • Which object needs to be created.
  • Managing the life time of the object.
  • Managing the build-up and tear down concerns of the object.

Definition:

“Define an interface for creating an object, but let subclasses decide which class to instantiate”

C# Implementation of Factory method

abstract class Factory 
              { 
	//Factory Method Declaration 
              public abstract Product GetProduct(); 
              }

——————————————————————————————-         

           class concreteFactoryforProcuct1 : Factory 
              { 
	//Factory Method Implementation
              public override Product GetProduct()  
                       { 
                           return new Product1(); 
                       } 
               } 

——————————————————————————————–            

           class concreteFactoryforProcuct2 : Factory 
              { 
	//Factory Method Implementation 
              public override Product GetProduct() 
                     { 
                          return new Product2(); 
                     } 
              } 

——————————————————————————————–

            interface Product 
                { 
                 void GetDetails(); 
                } 

              class Product1 : Product 
               { 
                public void GetDetails() 
                { 
                  Console.WriteLine("Product1 Details are Called"); 
                } 
               } 
              class Product2 : Product 
              { 
                public void GetDetails() 
                { 
                 Console.WriteLine("Product2 Details are called"); 
                } 
              }

——————————————————————————————–

        protected void Page_Load(object sender, EventArgs e) 
        { 

            Factory[] objFactories = new Factory[2]; 
            objFactories[0] = new concreteFactoryforProcuct1(); 
            objFactories[1] = new concreteFactoryforProcuct2(); 
            foreach (Factory objFactory in objFactories) 
            { 
                Product objProduct = objFactory.GetProduct(); 
                objProduct.GetDetails(); 
            } 
        }


——————————————————————————————–

References: dofactory.com


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (131) 
  • RSS Feed for this post's comments Comment RSS
  •    


Using If/Else activity in Workflow Foundation

Introduction

In this post I will explain how to utilize the IF\Else activity and a declarative condition in the workflow to perform the conditional processing.

This workflow evaluates the order by taking the order value and if the order value  < $1000 then it will approved by Manager other wise it requires vice president  approval.

1. Create a new workflow project by selecting File->New->Project menu command visual studio displays the New Project dialogue window.

2. Select the Empty Workflow Project template from the dialogue box and say ok.

IfElse

3. Add the new item to the empty workflow project and select the Sequential Workflow (with code separation) template from the above dialogue box.

4. Start the workflow by writing the following code in Main program.cs file.

program

In above code we have started the workflow runtime and loaded the workflow type that we are going to design in the next step.

Notice that we are also passing the OrderValue as the parameter to the workflow.

5. Add the IF/ELSE activity to the workflow designer from the toolbox.

Ifelseworkflow

6. Add the condition to the ifElseBranch1 by selecting the ConditioName from the properties window.

condition

7. Similarly Add the condition to the ifElseBranch2 by selecting the condition name from the properties window.

8. Add the code activities below the both ifElseBranch1 and ifElseBranch2 branches and attach the event handlers to the ExecuteCode property.

9.  The code besides file of the workflow will look like

workflowcode

10. You can attach the ManagerApprovalHandler to one branch and VPApprovalHandler to another branch by selecting the code activities and assign the value to the Executecode property.

11.  You will see the following output after executing the application

console

Conclusion

We discussed about using the If/Else activity in workflow and evaluating the conditions using the activity. In the next post we discuss about other important activities in the workflow.


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (189) 
  • RSS Feed for this post's comments Comment RSS
  •    


Introducing the WCF Security

Windows Communication Foundation (WCF) is a secure, reliable, and scalable messaging platform for the .NET Framework 3.0. With WCF, SOAP messages can be transmitted over a variety of supported protocols including IPC (named pipes), TCP, HTTP and MSMQ. Like any distributed messaging platform, you must establish security policies for protecting messages and for authenticating and authorizing calls. This article will discuss how WCF accomplishes this.

The core of WCF security is to address four important features:

  • Confidentiality: Is the information confidential between the sender and the receiver? This feature will ensure that “unauthorized” parties do not get the opportunity to view the message. You usually achieve this by utilizing encryption algorithms.
  • Integrity: This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering. You usually sign messages using digital signatures to achieve integrity.
  • Authentication: This is to verify who the sender is and who the receiver is. Are they known to the system or the application? Authentication is the process of establishing a clear identity for an entity, for example, by providing evidence such as username and password. Although this is clearly important for a service to understand of its callers, it is equally important that callers have an assurance that the service being called is the expected service and not an impostor.
  • Authorization: At the authorization stage, you know who the sender or the receiver is. However, you also need to know whether they are authorized to perform the action they are requesting from the application. Authorization can be performed by custom code in the service, native or custom authorization providers, ASP.NET roles, Windows groups, Active Directory, Authorization Manager, and other mechanisms.

These are the key features the WCF security model attempts to address. You achieve the physical implementation of addressing these issues by configuring bindings in WCF. WCF offers a rich set of binding to address these security issues. You also have the flexibility of extending or creating custom bindings to address specific security needs if necessary.

There are two major classifications of security within WCF; both are related to the security of what is transferred between a service and caller (sometimes called transfer security). The first concept is of protecting data as it is sent across the network, or “on the wire.” This is known as transport security. The other classification is called message security and is concerned with the protection that each message provides for itself, regardless of the transportation mechanism used.

Default Security Settings
Each binding has a default set of security settings. Consider the following service endpoint that supports NetTcpBinding.

   <system.serviceModel>
     <services>
      <service name="HelloIndigo.HelloIndigoService" >
        <endpoint contract="HelloIndigo.IHelloIndigoService" 
          binding="netTcpBinding" />
      </service>
     </services>
   </system.serviceModel>

 

Transport security provides protection for the data sent, without regard to the contents. A common approach for this is to use Secure Sockets Layer (SSL) for encrypting and signing the contents of the packets sent over HTTPS. There are other transport security options as well, and the choice of options will depend on the particular WCF binding used. In fact, you will see that many options in WCF are configured to be secure by default, such as with TCP.

One limitation of transport security is that it relies on every “step” and participant in the network path having consistently configured security.

Message security focuses on ensuring the integrity and privacy of individual messages, without regard for the network. Through mechanisms such as encryption and signing via public and private keys, the message will be protected even if sent over an unprotected transport (such as plain HTTP).

 <bindings>
      <basicHttpBinding>
          <binding name="MyBinding">
              <security mode="TransportCredentialOnly">
                  <transport clientCredentialType="Windows" />
              </security>
          </binding>
      </basicHttpBinding>
  </bindings>

  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (185) 
  • RSS Feed for this post's comments Comment RSS
  •    


About Me

Deepak Kamboj

Deepak Kamboj, MCTS, JCP
ASP.NET/C# Web Developer
Chandigarh, India

RSS Contact Twitter Facebook LinkedIn

Yahoo: DeepakKamboj@yahoo.com
GTalk: DeepakKamboj@gmail.com
Skype: DeepakKamboj

Recent Comments