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
  •    


Do you Know : The world's most widely used software is now available in the cloud

Steve Ballmer, Microsoft CEO sees the cloud as one of the biggest opportunities in decades for the tech industry and for Microsoft. Twenty million businesses and over a billion people use Microsoft cloud services.  The following products are already in the cloud.

  1. SQL Server :            http://www.microsoft.com/windowsazure/sqlazure/
  2. Exchange   :            http://www.microsoft.com/online/exchange-online.mspx
  3. SharePoint :            http://www.microsoft.com/online/sharepoint-online.mspx
  4. Office  [Live Meeting / Communications / Office WebApps] :            http://www.microsoft.com/online/office-live-meeting.mspx ; http://www.microsoft.com/online/office-communications-online.mspx; http://technet.microsoft.com/en-us/office/ee815687.aspx
  5. Dynamics CRM :            http://www.microsoft.com/online/dynamics-crm-online.mspx

  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (179) 
  • 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
  •    


Performance tuning For .NET Applications

Performance tuning is one of the daunting task for making your applications run faster. There are several factors that can cause your application run slow. One of the factor is memory which can directly impact on your program execution. This post discusses the basics of memory optimization for .NET programs. If we outline the cases where memory access is bottleneck then it is easier for tune them. I also discuss the tools and strategies to determine the bottlenecks of memory in .NET Applications.

dot_net_memory_profiler_graph

Bottlenecks

Memory Usage and Speed

Case1:

Memory consumption is matter when your application manipulates the large amount of data. The speed is limited by how long it takes for CPU to bring the instructions from memory. More data then more time……

Case2:

Memory consumption also matter is during an application startup. Hard disk access is much slower than main memory access. When the application launched second time then it will be faster.

Case3:

Memory consumption matter is during application switching. When your application switches to the other applications , there is a chance of stealing the physical memory of your applications. When user returns to your application, these stolen pages needs to be fetched back from the desk, which makes your application very slow.

Solution

A feasible solution could be minimizing the amount of memory used. This reduces the load on the fast cache and makes program execution faster.

You can execute less code while program startup. Efficiently using the data structures. These things needs to be done in the early stages of the development.

Task Manager

You can use Task Manager to know how much of memory your application currently used. You can invoke it by (Winkey + R). If the columns don’t include PID, Memory-Working Set, use the View->Select Columns menu option to add them to the display.

Working Set is the physical memory currently being used by the process.

Application Size

Depending on memory usage application can be categorized small, medium or large. A simple and quick way to monitor memory usage and check for leaks is by running a test on your application. Run the application and monitor its working set usage; if the working set grows unbounded then it can mean a memory leak.

VADump: A More Detailed View

Task Manager just provides the summary of the memory usage of an application. To get more detail you need a tool called VADump. This can be invoked by typing VADump –sop processID in the command prompt under the directory in which it is installed. It prints a breakdown of memory within a single process down to DLL level. You can download the tool from here.

The .NET Garbage Collector

The .NET runtime supports automatic memory management. Garbage Collector in runtime finds memory that is no longer in use and reuses it for new allocations. Garbage Collector partitions the heap into three generations(0,1, and 2).

PerfMon

VADump gives the first level of breakdown of memory usage in the process. It does not tell you how much GC memory we are using and also whether we are having a healthy ration of GC generations. You can invoke it by typing PerfMon in run command. After PerfMon comes up, we need to configure it to display information about the GC. A healthy number for GC is less than 10 percent of total application time.

Conclusion

Memory issues are difficult to debug. If your application is large enough to care about memory, the key is to control memory usage in early stages of the development.

Source: MSDN magazine

Backtrack: http://www.techbubbles.com/microsoft/performance-tuning-for-net-applications/


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


Windows Workflow Foundation Key Concepts with example

Introduction

This post discusses the key concepts of workflow foundation, authoring the sequential workflow using the visual studio 2008 designer for WF and debugging the workflows using visual studio 2008 designer.

You can Get the overview on windows workflow foundation before going to read this post.

1. Create the new workflow project by selecting the File->New->Project in

    VS 2008 it displays the following dialogue box

new

select the Sequential Workflow Console Application template and say ok.

2. We now have a workflow project with workflow1.cs file in the solution. You delete this file and right click on the project and say Add->New Item from the context menu.

WFnew

Select the Sequential Workflow (with code separation) template from the above dialogue box.

3. Drag and drop the Code activity to the design surface of the workflow.

WFSeq

Enter the value codeActivity1_CodeHandler for the ExecuteCode property.

4. Notice that codebeside class is a partial class and inheriting from the SequentialWorkflowActivity Base class.

codebeside

5. Right click the codeactivity in workflow design and select the insert break point option from the context menu.

6. Compile and run the application by pressing F5 then it starts the workflow instance and that instance will break in the debugger when it gets in to the code activity.

clip_image002

Conclusion

This post discussed the basic workflow application and concepts and next post am going to explain using the if else activity in workflow designer.


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


WCF vs ASP.NET Web services

In this post I will explain the Difference between ASP.NET web service and programming WCF services like ASP.NET web services. It also discusses how we use the both technologies for developing the web services.

The development of web service with ASP.NET relies on defining data  and relies on the XmlSerializer to transform data to or from a service.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML.
  • Only the classes which implement IEnumerable interface.
  • Classes that implement the IDictionary interface, such as Hash table can not be serialized.

The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types in to XML.

[DataContract]
public class Item
{
    [DataMember]
    public string ItemID;
    [DataMember]
    public decimal ItemQuantity;
    [DataMember]
    public decimal ItemPrice;

}

The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.

Important difference between DataContractSerializer and XMLSerializer.

  • A practical benefit of the design of the DataContractSerializer is better performance over XMLserialization.
  • XMLSerialization does not indicate the which fields or properties of the type are serialized into XML where as DataCotratSerializer Explicitly shows the which fields or properties are serialized into XML.
  • The DataContractSerializer can translate the HashTable into XML.

Developing Service

To develop a service using ASP.NET we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.

Example

[WebService]
public class Service : System.Web.Services.WebService
{
    [WebMethod]
    public string Test(string strMsg)
    {
       return strMsg;
    }
}

To develop a service in WCF we will write the following code

[ServiceContract]
public interface ITest
{
    [OperationContract]
    string ShowMessage(string strMsg);
}
public class Service : ITest
{
    public string ShowMessage(string strMsg)
    {
        return strMsg;
    }
}

The ServiceContractAttribute specifies that a interface defines a WCF service contract, OperationContract Attribute indicates which of the methods of the interface defines the operations of the service contract.

A class that implements the service contract is referred to as a service type in WCF.

Hosting the Service

ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assembly will be copied to the bin directory. The application is accessible using url of the service file.

WCF Service can be hosted within IIS or WindowsActivationService.

  • Compile the service type into a class library
  • Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.
  • Copy the web.config file into the virtual directory.

Client Development

Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.

WCF uses the ServiceMetadata tool(svcutil.exe) to generate the client for the service.

Message Representation

The Header of the SOAP Message can be customized in ASP.NET Web service.

WCF provides attributes MessageContractAttribute , MessageHeaderAttribute and MessageBodyMemberAttribute to describe the structure of the SOAP Message.

Service Description

Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as response to the request.

The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.

Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated by WCF can customized by using ServiceMetadataBehavior class.

Exception Handling

In ASP.NET Web services, Unhandled exceptions are returned to the client as SOAP faults.

In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

Backtrack: http://www.techbubbles.com/wcf/wcf-vs-aspnet-web-services/


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


Understanding Garbage Collection in C#

All the garbage collection mechanisms have one thing in common, that is they take the responsibility of tracking memory usage.

Understanding Garbage Collection


The .NET garbage collector is optimized for the following assumptions:
  1. Objects that were recently allocated are most likely to be freed.
  2. Objects that have lived the longest are least likely to be become free.
  3. Objects allocated together are often used together.

The .NET garbage collector is known as generational garbage collector. The objects allocated are categorized into three generations. Most recently allocated objects are placed in generation 0.
Objects in generation 0, that survive a garbage collection pass are moved to generation 1.
generation 2 contains long-lived objects, that survive after the two collection passes.
A garbage collection pass for generation 0 is the most common type of collection. Generation 1 collection pass is performed if generation 0 collection pass is not sufficient to reclaim memory.
Atlast, generation 2 collection pass is peformed if collection pass on generation 0 and 1 are not sufficient to reclaim memory. If no memory is available, after all the collection passes, an
OutOfMemoryException is thrown.

Finalizers


A class could expose a finalizer, which executes when the object is destroyed. In C#, the finalizer is a protected method as shown below.

protected void Finalize()
{
    base.Finalize();      // clean external resources
}

The method Finalize(), is only called by the .NET framework.
C#, will generate a code to a well formed Finalizer, if we declare a destructor as shown

~class1
{    
	// Clean external resources.
}

Declaring a Finalize method and destructor in a class, will lead to an error.

Dispose


Instead of declaring a Finalizer, exposing a Dispose method is considered as good.
If we clean up a object, using Dispose or Close method, we should indicate to the runtime that the object is no longer needed finalization, by calling GC.SuppressFinalize() as shown below:

public void Dispose()
{    
	// all clean up source code here..
	GC.SuppressFinalize(this);
}

If we are creating and using objects that have Dispose or Close methods, we should call these methods when we’ve finished using these objects. It is advisable to place these calls in a finally clause, which guarantees that the objects are properly handled even if an exception is thrown.

Summary


The System.GC class provides methods that control the system garbage collector. We have to use methods from this class in our application with extreme caution.

Backtrack: http://www.dotnetspider.com/resources/1149-Understanding-Garbage-Collection-C.aspx


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


How to sort GridView?

In this article I will discuss how to sort columns in grid and more. At the end it will help answer some very frequently asked questions like following.

  • How to sort DataGrid in ASP.Net?
  • How to sort GridView?
  • How to show sort direction image in column header of GridView or DataGrid?
  • How to keep track of sorting direction and sort expression while sorting GridView?

Along with getting answers to these question I will also discuss some of the issues with implementation of sorting in GridView. And one of the very frequently brought up issue is that SortDirection property of GridViewSortEventArgs is always set to Ascending.

Specifying Sorting Attributes For GridView

To enable sorting for GridView set Sorting attribute for the control to True and if you are specifying event handlers for controls on page itself then set the event handler function for OnSort event of the control. The following code snippet from ASPX page shows how these attributes are set.


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


Static Classes and Static Class Members

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member.

Interview Questions for Static Class

What is a static class?

A static class is a class which can not be instantiated using the “new” keyword. They also only contain static members, are sealed and have a private constructor.

What is static member?

A static member is a method, field, property or event that can be called without creating an instance of its defining class. Static members are particularly useful for representing calculations and data that are independent of object state.

3. What is static function?

A static function is another term for a static method. It allows you to execute the function without creating an instance of its defining class. They are similar to global functions. An example of a static function could be: ConvertFromFarenheitToCelsius with a signature as follows:

public static double ConvertFromFarenheitToCelsius (string valToConvert)
{
//add code here
}

 

4. What is static constructor?

A static constructor has a similar function as a normal constructor i.e. it is automatically called the first time a class is loaded. The differences between a conventional constructor are that it cannot be overloaded, cannot have any parameters nor have any access modifiers and must be preceded by the

keyword static. In addition, a class with a static constructor may only have static members.

5. How can we inherit a static variable?

6. How can we inherit a static member?

When inheriting static members there is no need to instantiate the defining class using the “new”keyword.

public class MyBaseClass
{
MyBaseClass()
{
}

public static void PrintName()
{
}

}

public class MyDerivedClass : MyBaseClass
{
	MyDerivedClass ()
{
}

public void DoSomething()
{
MyBaseClass.GetName();
}
}

 

7. Can we use a static function with a non-static variable?

No.

8. How can we access static variable?

By employing the use of a static member field as follows:

public class CashSales

{

//declare static member field

private static int maxUnitsAllowed = 50;

//declare method to return maximum number of units allowed

public static int GetMaxUnitsAllowed ()

{

Return maxUnitsAllowed;

}

}

The static field can now be accessed by simply doing CashSales.GetMaxUnitsAllowed(). No need to create an instance of the class.

9. Why main function is static?

Because it is automatically loaded by the CLR and initialised by the runtime when the class is first loaded. If it wasn’t static an instance of the class would first need to be created and initialised.


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


.Net Projects

In this section, you can find a few projects I have worked on to learn C# and the .NET Framework.

  • With NDoc, create great looking C# code documentation. This is an open source project I've been involved with since 2001.
  • Publish great looking C#, VB, HTML, ASP.NET, XML and T-SQL source code on your web site or in your blog with this source code html formatter.

Check those useful development tools for .NET from other developers:

  • Roland Weigelt's GhostDoc, a great Visual Studio add-in to automatically generate code documentation.
  • NUnit, a simple framework to write repeatable tests in any .NET language.
  • NUnitAsp, for unit testing ASP.NET pages.
  • NAnt, a .NET build tool.

  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (103) 
  • 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