I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label .NET. Show all posts
Showing posts with label .NET. Show all posts

Generate unique random string with desired length using GUID

GUID, also known as Globally Unique Identifier, is an 128-bit integer (16 bytes) that can be used to uniquely identify a record in the database (other than the auto-increase number). It is best used as a primary key as well.
But in some occasion, what you need is not really a GUID, but a random string that is "unique enough" to be used by your system. And you might want to store it as a string in your database (for whatever reason).
In C#, you can do this by using the GUID hash code. Here is the function that returns a "unique enough" string with a desired length:

        /// <summary>         
        /// Gets a unqiue key based on GUID string hash code.
        /// </summary>
         /// <param name="length">The length of the key returned.</param>
         /// <returns>Unique string</returns>
         private static string GetUniqueString(int length)
             StringBuilder uniqHashKey = new StringBuilder();
             while (uniqHashKey.Length < length)
                 // Get the GUID.
             return uniqHashKey.ToString();

Encrypting and Decrypting Query Strings in asp.net


We often pass values between pages in the form of a query string as key-value pairs. Query string is the easiest way and most widely practiced mechanism of transferring small pieces of data between web pages. The end-user may change the value in the query string to play around with the application, and at the same time, it leads to compromising the security and data integrity of the system. So the solution is encrypting the query strings.

Following is the simple way of encryption and decryption mechanism in asp.net

First I created two methods for encryption and decryption

Encrypt the string

        private string Encrypt(string stringToEncrypt)
             byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
             byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
             byte[] key = { };
                 key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                 MemoryStream ms = new MemoryStream();
                 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 return Convert.ToBase64String(ms.ToArray());
             catch (Exception e)
                 return e.Message;

Decrypt the encrypted string

        private string Decrypt(string EncryptedText)
byte[] inputByteArray = new byte[EncryptedText.Length + 1];
byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
byte[] key = { };

key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(EncryptedText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
catch (Exception e)
return e.Message;

It is better practice to encode the encrypted string before adding it to the URL like following, you can pass any number of parameters as you can (ex: OrderId=1&Name=RV )

   var addressLink = "http://abcxyz.com/abc.aspx?" + HttpUtility.UrlEncode(Encrypt(string.Format("OrderId={0}", orderId)));

Encryption is done, now we have to decrypt the encrypted string whenever we need, like following

   string str = "";
str = Request.RawUrl;
   var qs = Decrypt(HttpUtility.UrlDecode(str.Substring(strReq.IndexOf('?') + 1)));

Parse the returned string according to the parameters you have passed in above expression.

.NET interview Question for Fresher

Questions : 1
What is Code Access Security (CAS)? How does CAS work?

Answers : 1

CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

Questions : 2
What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling?

Answers : 2

Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class. Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached.

Following are important differences between object pooling and connection pooling:

1. Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long.

2. Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.)

COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced.

Questions : 3
What is a WebService and what is the underlying protocol used in it? Namespace?

Answers : 3

Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.

Questions : 4
What is serialization in .NET? What are the ways to control serialization?

Answers : 4

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

1. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.

2. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.

Questions : 5
Explain SOAP, WSDL, UDDI in brief.Namespace?

Answers : 5

SOAP:-SOAP is an XML-based messaging framework specifically designed for exchanging formatted data across the Internet, for example using request and reply messages or sending entire documents. SOAP is simple, easy to use, and completely neutral with respect to operating system, programming language, or distributed computing platform.After SOAP became available as a mechanism for exchanging XML messages among enterprises (or among disparate applications within the same enterprise), a better way was needed to describe the messages and how they are exchanged.

WSDL :-The Web Services Description Language (WSDL) is a particular form of an XML Schema, developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL spec describes how to map messages and operations to SOAP 1.1, HTTP GET/POST, and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols (using "ports").

UDDI :-The Universal Description, Discovery, and Integration (UDDI) framework defines a data model (in XML) and SOAP APIs for registration and searches on business information, including the web services a business exposes to the Internet. UDDI is an independent consortium of vendors, founded by Microsoft, IBM, and Ariba, for the purpose of developing an Internet standard for web service description registration and discovery. Microsoft, IBM, and Ariba also are hosting the initial deployment of a UDDI service, which is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses). UDDI uses a private agreement profile of SOAP (i.e. UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use the SOAP APIs to register themselves with UDDI, and other businesses search UDDI when they want to discover a trading partner, for example someone from whom they wish to procure sheet metal, bolts, or transistors. The information in UDDI is categorized according to industry type and geographical location, allowing UDDI consumers to search through lists of potentially matching businesses to find the specific one they want to contact. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes. .

Questions : 6
What is Method Overriding? How to override a function in C#?

Answers : 6

An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.

Use the override modifier to modify a method, a property, an indexer, or an event. You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

Questions : 7
7. How can we check if all validation and controls are valid or proper?How can we force to run all validation control to run?

Answers : 7

By using Page.IsValid() property we can check if all validation and controls are valid or proper by using Page.Validate we can force to run all validation control to run

Questions : 8
What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Answers : 8

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

Questions : 9
What is JIT (just in time)? how it works?

Answers : 9

Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.

Questions : 10
Difference between DataReader and DataAdapter / DataSet and DataAdapter?

Answers : 10

You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory. After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example. SqlDataReader myReader = myCommand.ExecuteReader(); You use the Read method of the DataReader object to obtain a row from the results of the query. while (myReader.Read()) Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); myReader.Close(); The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema. The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.

Questions : 11
Differences between dataset.clone and dataset.copy?

Answers : 11

Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
Copy - Copies both the structure and data for this DataSet.

Questions : 12
What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state?

Answers : 12

Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip. To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips. However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options:
View State
Hidden Form Fields
Query Strings
Server-Based State Management Options
Application State
Session State
Database Support

Questions : 13
Difference between web services & remoting? Namespace?

Answers : 13

ASP.NET Web Services .NET Remoting Protocol Can be accessed only over HTTP Can be accessed over any protocol (including TCP, HTTP, SMTP and so on) State Management Web services work in a stateless environment Provide support for both stateful and stateless environments through Singleton and SingleCall objects Type System Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized. Using binary communication, .NET Remoting can provide support for rich type system Interoperability Web services support interoperability across platforms, and are ideal for heterogeneous environments. .NET remoting requires the client be built using .NET, enforcing homogenous environment. Reliability Highly reliable due to the fact that Web services are always hosted in IIS Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application. Extensibility Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages. Very extensible by allowing us to customize the different components of the .NET remoting framework. Ease-of-Programming Easy-to-create and deploy. Complex to program.

Questions : 14
What is MSIL, IL?

Answers : 14

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

Questions : 15
What is strong name?

Answers : 15

A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.

Questions : 16
What is exception handling?

Answers : 16

When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.

Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

Questions : 17
What is the managed and unmanaged code in .net?

Answers : 17

The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

Questions : 18
What is the namespace threading in .net?

Answers : 18

System.Threading.Thread How to encode string string ss="pervej"; string encode=Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ss)); Response.Write(encode);

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers.

  • What is IL code, CLR, CTS, GAC & GC?
  • How can we do Assembly versioning?
  • can you explain how ASP.NET application life cycle and page life cycle events fire?
  • What is the problem with Functional Programming?
  • Can you define OOP and the 4 principles of OOP?
  • What are Classes and Objects?
  • What is Inheritance?
  • What is Polymorphism, overloading, overriding and virtual?
  • Can you explain encapsulation and abstraction?
  • What is an abstract class?
  • Define Interface & What is the diff. between abstract & interface?
  • What problem does Delegate Solve ?
  • What is a Multicast delegate ?
  • What are events and what's the difference between delegates and events?
  • How can we make Asynchronous method calls using delegates ?
  • What is a stack, Heap, Value types and Reference types ?
  • What is boxing and unboxing ?
  • Can you explain ASP.NET application and Page life cycle ?
  • What is Authentication, Authorization, Principal & Identity objects?
  • How can we do Inproc and outProc session management ?
  • How can we windows , forms and passport authentication and authorization in ASP.NET ?
  • In a parent child relationship which constructor fires first ?

MVC ASP.NET Q & A series

  • How to create a simple "Hello World" using ASP.NET MVC template?
  • How to pass data from controller to views?
  • Can we see a simple sample of model using MVC template?
  • How can we create simple input screens using MVC template?
  • How can we create MVC views faster and make them strong typed by using HTML helper?
  • Can we see how easy it is do unit testing for MVC application?
  • What is MVC routing?
  • How can we set default values & validate MVC routes?
  • How we can define actions & navigate from one page to other page?

WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview question and answers

  • What is SOA, Services and Messages ?
  • What is the difference between Service and Component?
  • What are basic steps to create a WCF service ?
  • What are endpoints, address, contracts and bindings?
  • What are various ways of hosting WCF service?
  • What is the difference of hosting a WCF service on IIS and Self hosting?
  • What is the difference between BasicHttpBinding and WsHttpBinding?
  • How can we do debugging and tracing in WCF?
  • Can you explain transactions in WCF (theory)?
  • How can we self host WCF service ?
  • What are the different ways of implementing WCF Security?
  • How can we implement SSL security on WCF(Transport Security)?
  • How can we implement transport security plus message security in WCF ?
  • How can we do WCF instancing ?
  • How Can we do WCF Concurency and throttling?
  • Can you explain the architecture of Silverlight ?
  • What are the basic things needed to make a silverlight application ?
  • How can we do transformations in SilverLight ?
  • Can you explain animation fundamentals in SilverLight?
  • What are the different layout methodologies in SilverLight?
  • Can you explain one way , two way and one time bindings?
  • How can we consume WCF service in SilverLight?
  • How can we connect databases using SilverLight?
  • What is LINQ and can you explain same with example?
  • Can you explain a simple example of LINQ to SQL?
  • How can we define relationships using LINQ to SQL?
  • How can we optimize LINQ relationships queries using ‘DataLoadOptions’?
  • Can we see a simple example of how we can do CRUD using LINQ to SQL?
  • How can we call a stored procedure using LINQ?
  • What is the need of WPF when we had GDI, GDI+ and DirectX?
  • Can you explain how we can make a simple WPF application?
  • Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?
  • Can you explain the Architecture of WPF?
  • What is Azure?
  • Can you explain Azure Costing?
  • Can we see a simple Azure sample program?
  • What are the different steps to create a simple Worker application?
  • Can we understand Blobs in steps, Tables & Queues ?
  • Can we see a simple example for Azure tables?
  • What is Package and One click deploy(Deployment Part - 1) ?
  • What is Web.config transformation (Deployment Part-2)?
  • What is MEF and how can we implement the same?
  • How is MEF different from DIIOC?
  • Can you show us a simple implementation of MEF in Silverlight ?

WCF Architecture

The following figure illustrates the major components of WCF.

Figure 1: WCF Architecture


Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

- It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.


- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels

    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

  • Protocol Channels

    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS

    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.

  • Windows Activation Service

    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.

  • Self-Hosting

    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.

  • Windows Service

    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

Introdution to WCF 4.0

This article explains about the new features introduced in WCF 4.0.

.Net framework comes with new features and improved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF.

The following items specifies the new features of WCF 4.0

Simplified configuration

This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible to host configuration-free services.

Discovery service

There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can be achieved using WS-Discovery protocol.

Routing service

This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

REST Service

There are few features helps while developing RESTful service.

  • Automatic help page that describes REST services to consumer
  • Support for declarative HTTP catching

Workflow service

  • Improves development experience
  • Entire service definition can be define in XAML
  • Hosting workflow service can be done from .xamlx file, without using .svc file
  • Introduce new “Context” bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding
  • In .Net4.0, WorkflowServiceHost class for hosting workflow services was redesigned and it is available inSystem.ServiceModel.Activities assembly. In .Net3.5, WorkflowServiceHost class is available inSystem.WorkflowServices assembly
  • New messaging activities SendReply and ReceiveReply are added in .Net4.0

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

Introduction to WCF

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Below figures shows the different technology combined to form WCF.

  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Making right design for your requirement is little bit difficult.

Introduction to Language Integrated Query (LINQ)

If you are developing .NET applications from some time, you may already know how to connect databases and performs operations using either hard coded SQL queries or stored procedures. You may also know how to query the in memory collection of objects using traditional programming constructs such as loops and conditions. In this tutorial, I will give you introduction to Microsoft’s new technology called LINQ that enables you to integrate query processing features into your programming language such as C# or Visual Basic. More specifically I will show you how you can query in memory object collections or Arrays using some basic LINQ query operators.

What is LINQ?
Language Integrated Query (LINQ) provides .NET developers some new and exciting features to query and manipulate data in a consistent and uniform way. It enables them to work with different type of data sources such as Arrays, collection of objects, XML documents, a relational databases, Active Directory or even Microsoft Excel sheets by writing or embedding queries in C# or Visual Basic language.
Microsoft has introduced many new keywords and features in both C# and Visual Basic languages to integrate LINQ technology. Microsoft has also added new namespaces in .NET Framework Library that contains new interfaces and hundreds of extension methods also called LINQ query operators. These methods perform different operations on different type of data sources in LINQ.
The following figure shows you the overall architecture of LINQ building blocks.

LINQ Architecture

In the above architecture you can see that many new features are introduced in both C# and Visual Basic to integrate LINQ queries into language. You can also notice how different type of data sources can be accessed using LINQ providers and related language enhancements in a unified way.
One common question that comes in everybody’s mind is that if we are already using almost all the above data sources in the applications we are created then why we need to use LINQ. The answer of this question is that you need to learn different object models and technologies to connect all the above data sources. For example, if you want to connect relational databases you need to learn ADO.NET data provider object such asSqlConnection, SqlCommand, SqlDataReader along with the knowledge of SQL language. Similarly if you want to manipulate XML documents you should have knowledge of DOM or Simple API for XML (SAX).
To give you some idea about how you can write simple LINQ queries I am giving you a simple LINQ example in C# in the following code. I am creating a simple array of strings which I will query using some new C# keywords and standard LINQ query operators.

string[] monthNames = { "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};

I will query the above array of strings in such a way that I only get month names which are shorter than 6 letters. Here is the query that will perform this task:

var shortNames = from name in monthNames
where name.Length < 6
select name;

In the above query, Notice how the new keywords such as from, where and select are used. They look similar to the keywords used in SQL language and they provide the basis for writing LINQ queries. The order of the query looks rather reverse and it may feel strange to you if you have SQL query syntax in mind.
The first keyword from determines the data source used to query and select information in this example it is an array of strings. In LINQ world, the data source is called sequence. The variable name is declared just after the keyword from to hold the current enumerated value temporarily. This temporary variable is used in the second line in the above code alone with another new keyword where that performs filtering. Most of the LINQ queries you will write require some sort of filtering on the data so you can use where keyword to filter data source depending on the needs of your application. Finally I am using the select keyword to actually select the value I want to include in the query results. Notice the results of the query are stored in an implicitly typed variable shortNames which is defined using var keyword.
To display the results of the query you can use simple foreach loop:

foreach (var item in shortNames)

If you will compile and run the above foreach loop, here is the output you’d see:


Let’s say you also want to display data in specific order, You can add another new operator orderby in the above query to perform this task as shown below:

var shortNames = from name in monthNames
where name.Length < 6
orderby name.Length
select name;

The orderby keyword changes the order of the data according to your own criteria. In the example here I have ordered the months names according to their length so the shortest month name will come on top of the results. Here is the output you will get after running the above query.


So far, the queries I wrote look very straight forward and I haven’t introduced you another important building block of LINQ technology called query operators.
What are LINQ Query Operators?
LINQ Query operators are not a language extension, but an extension to the .NET Framework Class Library. These are a set of extension methods to perform operations in the context of LINQ queries. These operators are at the heart of the LINQ foundation and they are the real elements that make LINQ possible. It is not possible to cover all the query operators in one tutorial because there are hundreds of them but I will give you some easy examples of some operators which we have already used above without even knowing that they are operators. For example, when we useselect, where and orderby keywords above we were actually using query operators. These query operators are extension methods available in many new namespaces added in .NET Framework to facilitate LINQ technology.
The following is the list of standard query operators along with their category:

Category Operators


Select, SelectMany
Filtering OffType, Where
Sorting OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Set Distinct, Except, Intersect, Union
Concatenation Concat
Aggregation Aggregate, Average, Count, LongCount, Max, Min, Sum
Element ElemenatAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault
Conversion AsEnumerable, AsQuerable, Cast, OfType, ToArray, ToDictionary, ToList, ToLookup
Equality SequenceEqual
Generation DefaultifEmpty, Empty, Range, Repeat
Grouping GroupBy, ToLookup
Join Join, GroupJoin
Quantifiers All, Any, Contains
Partitioning Skip, SkipWhite, Take, TakeWhite

The code below shows you how you can map the keywords you have used in above query examples to standard query operators. I am using same example I have used above to give you better comparison of operators and their use.

var shortNames = monthNames
.Where(name => name.Length < 6)
.OrderBy( name => name.Length)
.Select(name => name);

The output of the above query will be similar to the above queries.


Notice how I have used three query operators Where, OrderBy and Select in the above syntax. Also notice the use of lambda expressions inside the methods. Some C# developers found this query operator syntax easier to understand than the above mentioned syntax because it is calling simple methods from the classes available in .NET Framework. Every method performs its operation on the query result it gets and then passes the results to another extension method. Almost all query operators return the object of type IEnumerable<T> which is a sequence of objects and can be queried further by using another operator. For example, you can perform the above three operations using three separate C# statements using one query operator at a time.

var shortNames = monthNames.Where(name => name.Length < 6);
var shortNamesWithOrder = shortNames.OrderBy( name => name.Length);
var finalResults = shortNamesWithOrder.Select(name => name);

Now if you can query the finalResults variable using foreach loop

foreach (var item in finalResults)


Display Photos in ASP.NET using Flickr.NET API

One of the most common ingredients of any successful website is to display photos to the site visitors along with photos and their metadata search facility. There are number of photo sharing web sites and services providing the large number of photos for websites and blogs. The most popular and commonly used site is Flickr.com, which provides very flexible and powerful API to web developers and exposes almost all the data stored on the site to offer web developers limitless possibilities for creating mashups, widgets, etc. Due to the popularity of Flickr API, many client libraries are available for almost all programming languages such as .NET, Java or PHP. These libraries make development with Flickr API even easier by hiding lower level API details and also allows you to work with your favorite programming language and environment. In this tutorial, I will show you how you can use one such library Flickr.NET to search and display photos using C# and ASP.NET.
Using Flickr.NET API in ASP.NET
Before I start this tutorial, please keep in mind that the developer key and shared secret is required to make requests to the Flickr API so make sure you have got your developer key and shared secret from the Flckr website at the following URL.
You also make sure that you have downloaded the latest version of Flickr.NET API from codeplex website.
To get started, create a new ASP.NET website in Visual Studio and add the reference of FlickrNet.dll you just downloaded from codeplex. To create an interface shown in the above figure, you need to add a table with three rows and two columns. Inside that table, you need to add search textbox, go button, some labels and a DataList control to show thumbnails. Following is the complete markup of the page used in this tutorial.
<div style="text-align: center">
<table cellpadding="5" cellspacing="0" style="border: 2px solid #0066CC; width: 60%;">
<td style="width: 40%;">
<asp:TextBox ID="SearchTextBox" runat="server"></asp:TextBox>
<asp:Button ID="GoButton" runat="server" Text="GO"
OnClick="GoButton_Click" />
<td style="vertical-align: top">
<asp:Label ID="PhotoDateTaken" runat="server"></asp:Label>
<td style="vertical-align: top">
<asp:DataList ID="ThumbnailsList" runat="server" HorizontalAlign="Center"
RepeatColumns="3" Width="100%"
<ItemStyle HorizontalAlign="Center" />
<asp:ImageButton ID="ThumbnailImage" runat="server"
ImageUrl='<%# Eval("SquareThumbnailUrl") %>'
AlternateText='<%# Eval("Title") %>'
ToolTip='<%# Eval("Title") %>
<asp:Literal ID="HiddenPhotoId" runat="server"
Text='<%# Eval("PhotoId") %>' Visible="false" />
<asp:Literal ID="HiddenPhotoUrl" runat="server"
Text='<%# Eval("MediumUrl") %>' Visible="false" />
<td style="vertical-align: top">
<asp:Image ID="PreviewImage" runat="server" />
<td style="vertical-align: top">&nbsp;</td>
<td style="vertical-align: top">
<asp:Label ID="PhotoDescription" runat="server"></asp:Label>
The DataList control used in the above markup is using an ImageButton control to display image thumbnails inside the ItemTemplate. Notice how the ImageUrl property of the ImageButton is bound with SquareThumbnailUrl property of the Flickr.NET API Photo class. Furthermore, notice the AlternateText and ToolTip properties are bound with Title property. I also used two hidden literal controls to store PhotoId and itsMediumUrl properties, which will be used to display photo preview and to get more details like its description or date the photo is taken from Flickr website.
It is now time to show you the Flickr.NET API in action by moving to the page code behind file. Declare the following two variables on top of the class and store your developer key and shared secret in them.
string flickrKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string sharedSecret = "xxxxxxxxxxxxxxx";
Define the following GetPhotos method to search photos from Flickr website using Flickr.NET API and to bind the DataList with the photos returned from Flickr. This method will be called in Page Load event with default keyword and then from Go button click with the keyword user will specify in the search textbox.
private void GetPhotos(string tag)
PhotoSearchOptions options = new PhotoSearchOptions();
options.PerPage = 12;
options.Page = 1;
options.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
options.MediaType = MediaType.Photos;
options.Extras = PhotoSearchExtras.All;
options.Tags = tag;
Flickr flickr = new Flickr(flickrKey, sharedSecret);
PhotoCollection photos = flickr.PhotosSearch(options);

ThumbnailsList.DataSource = photos;
The method GetPhotos first declares an object of PhotoSearchOptions class that allows us to set all the search related parameters in a single place. You can set how many photos you want to retrieve per page along with the current page index. You can set the sort order, media type (photos, videos etc.) to fetch from Flickr website. You need to set the Tags property with any string value you want to search. Flickr.NET API also exposes Flickr class that have PhotoSearch method to actually search photos from Flickr. It takes PhotoSearchOptions object as parameter and returns PhotoCollection returned by using the search options specified. Finally, I bind the photos collection with the DataList control on the page. Similar to the above method is the GetDescription method which takes photoId as parameter and returns Photo description and other useful information from Flickr website.
private void GetDescription(string photoId)
Flickr flickr = new Flickr(flickrKey, sharedSecret);
PhotoInfo info = flickr.PhotosGetInfo(photoId);

PhotoDescription.Text = info.Description;
PhotoDateTaken.Text = info.DateTaken.ToString("MMMM dd, yyyy");
Call the above methods in the Page Load event as shown in the code below. Notice how I am getting hidden photoId and photoUrl from the first Item shown in the DataList to make sure user see the first image preview and its description when the page loads first time.
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
string defaultKeyword = "nature";
SearchTextBox.Text = defaultKeyword;
Literal HiddenPhotoId =
ThumbnailsList.Items[0].FindControl("HiddenPhotoId") as Literal;
Literal HiddenPhotoUrl =
ThumbnailsList.Items[0].FindControl("HiddenPhotoUrl") as Literal;
string photoId = HiddenPhotoId.Text;
string photoUrl = HiddenPhotoUrl.Text;
PreviewImage.ImageUrl = photoUrl;
The same GetPhotos method will be called from the Go button click event to search photos with the user given keyword.
protected void GoButton_Click(object sender, EventArgs e)
string keyword = SearchTextBox.Text.Trim();
Finally, I am using SelectedIndexChange event of the DataList control to allow user to select any photo by clicking the thumbnail and showing the user selected photo preview and description on the right hand side of the thumbnails.
protected void ThumbnailsList_SelectedIndexChanged(object sender, EventArgs e)
Literal HiddenPhotoId =
ThumbnailsList.SelectedItem.FindControl("HiddenPhotoId") as Literal;
Literal HiddenPhotoUrl =
ThumbnailsList.SelectedItem.FindControl("HiddenPhotoUrl") as Literal;
string photoId = HiddenPhotoId.Text;
string photoUrl = HiddenPhotoUrl.Text;
PreviewImage.ImageUrl = photoUrl;
Download Source Code

Using ASP.NET ImageMap Control

Many web designers try to impress their website visitors with animated flash buttons or crazy JavaScript navigation menus, but they forget the old HTML Image maps. Image maps are images with clickable areas called hotspots, which allow a user to navigate to another page or website. Following the same old HTML concept of image maps, Microsoft introduced the server side ImageMap control for ASP.NET developers that let you convert any image into a navigation menu by just setting few properties. In this tutorial, I will show you how to use ASP.NET server side ImageMap control with Rectangular, Circular or even free form Polygon style hotspots.

Before you start this tutorial, you need to make sure that you have an image ready which you want to use as ImageMap. It can be a toolbar image created in any graphic tool such as Photoshop, or it can be a map of your or home or country. I have created the following image, especially for this tutorial to show you all types of hotspots ASP.NET ImageMap control supports. You can save this image on your desktop and use it for playing with ASP.NET ImageMap control.

ASP.NET ImageMap Control

To get started, create an ASP.NET website project in Visual Studio and add the image in your project root or images sub directory. Next, drag theImageMap control on the page from the left hand side toolbox. Set the ImageUrl property of the control and you will be able to see your image appear on the designer area of the page. If you see the properties of this control in the properties window, you will notice that all the basic properties like BackColor, BorderColor, etc. are available along with ImageAlign and AlternateText properties to fine tune your image look and feel on the page. The properties which need more explanations are HotSpotMode and HotSpots.
HotSpotMode property let you specify the default click behavior of the hotspot inside the ImageMap control. It can be set to one of the followings:
Inactive: This value means that HotSpots does not have any behavior so nothing will happen if the user will click on image.
Navigate: This value allows you to navigate user to any URL.
PostBack: This property allows you to generate post back behavior on user clicks and very useful if you want to execute code on the server side based on the user clicks.
NotSet: This property checks the behavior set by the HotSpotMode property and if none of the above three values are set then all HotSpots navigate to a URL.
Next you need to define the hotspots to divide your image into clickable areas. If you will click the ellipse next to the HotSpots property in the properties window you will see the following HotSpot Collection Editor dialog appear on the screen that lets you specify different types of hotspots. You can add Rectangle, Circle or Polygon hotspots to your image depending upon your image and requirement.

ASP.NET ImageMap Controls Hotspots

All these hotspots types have some properties to customize the hotspot region and behavior. You can specify Left, Top, Right and Bottom for Rectangle hotspot and X, Y and Radius properties for Circle hotspot. The Polygon hotspot requires a serious of X and Y coordinates to create a free form hotspot. All these hotspots types also have HotSpotMode property available to specify their click behavior individually so you can have one hotspot that navigates the user to another page and other hotspot which generate postback to the server and yet another hotspot which does nothing when user click on it. You also have PostBackValue property to send different values to the server on postback. You also haveTarget property to open the URL in a new window if you want and other basic properties such as NavigateUrl to specify the URL to navigate to on user click and AlternateText that will show a nice tool tip when the user will move the mouse over that particular hotspot.
In the sample image I used in this tutorial, the facebook and twitter logos will use navigate behavior while the other four will generate postback to the server. The facebook and twitter logos will use Rectangle hotspots, Wordpress, BMW and Windows logos will use Circle hotspots and the star will show you how to use Polygon hotspot. Following is the complete HTML markup used in this tutorial.

<asp:ImageMap ID="ImageMap1" runat="server" ImageUrl="~/images/aspnet_imagemap.jpg"
<asp:RectangleHotSpot AlternateText="Facebook" Bottom="62"
HotSpotMode="Navigate" Left="14" NavigateUrl="http://www.facebook.com"
Right="152" Target="_blank" Top="11" />
<asp:RectangleHotSpot AlternateText="Twitter" Bottom="61"
HotSpotMode="Navigate" Left="156" NavigateUrl="http://www.twitter.com"
Right="306" Target="_blank" Top="11" />
<asp:CircleHotSpot AlternateText="WordPress" HotSpotMode="PostBack"
PostBackValue="WordPress" Radius="41" X="50" Y="118" />
<asp:CircleHotSpot AlternateText="BMW" HotSpotMode="PostBack"
PostBackValue="BMW" Radius="41" X="155" Y="121" />
<asp:CircleHotSpot AlternateText="Windows" HotSpotMode="PostBack"
PostBackValue="Windows" Radius="44" X="266" Y="122" />
<asp:PolygonHotSpot AlternateText="Star" HotSpotMode="PostBack"
PostBackValue="Star" Coordinates="108,217, 141,210, 157,181, 173,210, 207,217, 184,242, 188,276, 158,261, 127,275, 131,243" />
<br />
<asp:Label ID="Label1" runat="server" Width="322px" BackColor="#FFFFCC" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px"></asp:Label>

Note, I have also added a Label control at the bottom that will be used to display hotspots PostBackValue on user clicks. The ImageMap control supports click event that allows you to capture the user clicks on different hotspot areas in a single place. It gets the ImageMapEventArgs type object as one of its argument that has PostBackValue property which you can use in the server side code on postback. The following code shows the ImageMap click event handler used in this tutorial.

protected void ImageMap1_Click(object sender, ImageMapEventArgs e)
Label1.Text = e.PostBackValue.ToString();

Now, It’s the time to test our ImageMap control in the browser, press F5 and try to click different logo hotspots and you will see the Label control showing you the PostBackValue as you will click the logo that has PostBack behavior defined.

ASP.NET Image Map with Postback

SourceCode             Demo

Binding Repeater Control with XML Documents using XmlDataSource

The Extensible Markup Language (XML) is the universal format for structured documents and data on the Web. Developers are using XML based RSS feeds and XML Web Services in their web applications on quite regular basis these days. ASP.NET version 1.1 was lacking built in capability to handle XML data that’s why ASP.NET version 2.0 is shipped with dedicated data source control called XmlDataSource. In this tutorial I will show you how you can use XmlDataSource control to handle and display XML data with very famous ASP.NET Repeater control. This tutorial will also show you how to bind XML elements with Repeater control using XPath binding expressions.

The XmlDataSource control usually used to display read only XML data but it still allows user to edit, delete or update XML data using custom code as there is no built in support for automatic edit/update in the control. The XmlDataSource control supports declarative data binding to XML files and because of hierarchical nature of XML data, developers usually bind this control with hierarchical data bound controls such as TreeView or Menu. However this control can also be used with tabular data bound controls such as GridView, Repeater or DataList controls.
The XmlDataSource control has following important properties which can be set either through the Configure DataSource dialog box or programmatically using code behind file.
DataFile: This property specifies the absolute or relative file path of XML file which you want to use for data binding.
Data: This property gets or sets the block of XML data for data binding. If both DataFile and Data properties are set, the DataFile property takes precedence and data in the XML file will be used for binding.
XPath: This property specifies an XPath expression which acts as filter to XML data. Actually XPath is a language used to retrieve information from XML documents and by using XPath you can traverse through the nodes and attributes of XML documents.
For the purpose of this tutorial, I have created the following sample XML file. It has list of employees with their departments available as attributes and their names and salaries available as elements. Create the following XML file and save it with the name Employees.xml in your website root directory.

<?xml version="1.0" encoding="utf-8" ?>
<Employee Department="Sales">
<Employee Department="Finance">
<Employee Department="Accounts">

Now create a web form in your website and drag the XmlDataSource control from the Data category in the toolbox. Click the arrow on the right side of the XmlDataSource Control to open the XmlDataSource smart tasks options and click Configure Data Source link to open the Configure Data Source dialog box. Click Browse button available next to Data File property and select the Employees.xml file stored in your website. In the XPath expression property type Employees/Employee to traverse to Employee elements in the XML file. Following figure shows all the above mentioned steps for your reference.

XmlDataSource Control
Configure Data Source dialog box for XmlDataSource configuration

Next, add a Repeater control on your web page and set its DataSourceID property to XmlDataSource1. This property will bind the Repeater control with XmlDataSource control which is linked with XML file. The following code shows you how you can bind the Department attribute andName and Salary elements inside Repeater ItemTemplate using XPath binding expressions.

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="XmlDataSource1">
<%# XPath("@Department")%><br />
- Name: <%#XPath("Name")%><br />
- Salary: <%#XPath("Salary")%><br />

If you have configure both Repeater and XmlDataSource controls properly as described in this tutorial you should be able to see the following output rendered in browser.

Binding Repeater Control with XmlDataSource

Repeater control displaying XML File data

Download SourceCode

Creating Custom Configuration Sections in ASP.NET

Almost all ASP.NET Web Applications require some sort of configuration settings to be stored in the web.config files. These settings can be application settings, database connection strings, user authentication settings, page specific settings and so on. ASP.NET also provides very powerful Configuration API to work with configuration settings defined in web.config files. The Configuration API not only allows us to read/write settings in configuration files with ease but also allow us to define our own custom configuration sections in web.config. These custom sections are very useful in large web applications where you have a lot of application settings to store in the configuration file. In this tutorial, I will show you how to create and use custom configuration sections in ASP.NET.

I am sure many of you are using the following appSettings section of web.config to define your application specific settings.

   <add key="DefaultLanguage" value="English-US"/>
   <add key="WebsiteTitle" value="Microsoft Corporation"/> 
   <add key="MaximumTransactionLimit" value="100000"/>

However, in large projects you end up having an endless list of key/value pairs in your web.config file. This makes life little difficult as you have to make sure when you are reading these values you are typing the spellings of all keys correctly e.g. DefautlLanguage is not same as DefaultLanguage. You also need to do lot of type casting when you are reading all types of values such as numbers, Booleans, dates, etc.

To solve these problems, ASP.NET allows us to create a custom configuration section in web.config. A custom configuration section can be defined in the element in web.config. You need to specify the name of the section and the class name that is responsible for serialization and de-serialization of attributes of custom configuration section into class properties. Following is an example of custom configuration section defined for a typical ecommerce web application.

      <section name="ShoppingCartSettings" type="ShoppingCartSection"/>


Please keep in mind that the value given for the type attribute above is the fully qualified name of the class. If the class is in App_Code folder of your project, you can simply use its name as used in the above example. If the class is in another assembly (.dll) then you need to use"Namespace.ClassName, AssemblyName" as the value of the type attribute. Once you have defined the custom configuration section you can use it in web.config file anywhere inside root configuration element as shown in the following code.

paypalCheckoutEnabled="true" />


You can define any number of properties in the ShoppingCartSettings section but keep in mind that these properties need to be defined in the class named ShoppingCartSection as mentioned above in the type attribute. ShoppingCartSection class will be a simple C# class inherited from the System.Configuration.ConfigurationSection class. To define this class, add the reference of System.Configuration in your project and import the namespace on the top of the file with using statement.

using System.Configuration;
public class ShoppingCartSection : ConfigurationSection

The ShoppingCartSection class represents the root ShoppingCartSettings element of the custom configuration section defined in web.config file. Next you need to define the properties of the class as shown in the following code.

public class ShoppingCartSection : ConfigurationSection
[ConfigurationProperty("defaultCurrency", IsRequired = true, DefaultValue="USD")]
[StringValidator(MinLength=1, MaxLength=100)]

public string DefaultCurrency
get { return (string)this["defaultCurrency"]; }
set { this["defaultCurrency"] = value; }
[ConfigurationProperty("maxItemsInCart", IsRequired = true, DefaultValue = "5")]
[IntegerValidator(MinValue=1, MaxValue=10)]

public int MaxItemsInCart
get { return Convert.ToInt32(this["maxItemsInCart"]); }
set { this["maxItemsInCart"] = value; }
[ConfigurationProperty("paypalCheckoutEnabled", IsRequired = false, DefaultValue = false)]
public bool PaypalCheckoutEnabled
get { return Convert.ToBoolean(this["paypalCheckoutEnabled"]); }
set { this["paypalCheckoutEnabled"] = value; }

Notice how the class properties MaxItemsInCart, DefaultCurrency etc. are mapped with the attributes defined in custom configuration element in web.config using the ConfigurationProperty attribute declaration on top of the properties. The ConfigurationProperty attribute is also using some other parameters such as DefaultValue and IsRequired. The DefaultValue parameter specifies the default value of the property if it is not defined in the web.config. The IsRequired parameter specified whether the attribute defined in web.config is required or optional. I have also used the StringValidator and IntegerValidator attributes in the above code to show you how to validate the values specified in the web.config.
To read the custom configuration section data in your web pages you can use the static GetSection method of ConfigurationManager class as shown below:

ShoppingCartSection settings =
ConfigurationManager.GetSection("ShoppingCartSettings") as ShoppingCartSection;

Label1.Text = "Default Currency: " + settings.DefaultCurrency;
Label2.Text = "Max Allowed Items in Shopping Cart: " + settings.MaxItemsInCart.ToString();
Label3.Text = "Paypal Checkout Enable: " + settings.PaypalCheckoutEnabled.ToString();

Using Multiple Programming Languages in ASP.NET Website

Source: ezzylearning

ASP.NET websites do not allow you to use multiple programming languages such as C# and Visual Basic in the App_Code folder of the website project. If you are creating a C# web site and you have copied a Visual Basic source file in App_Code folder, you won’t be able to compile your ASP.NET website. Off course, if it is a small source file, then you can convert it into C# source code either yourself or by using any code converter but it is time wasting practice if you have a large file or you want to use multiple source files. In this tutorial, I will show you how you can use multiple programming languages source files in a single website project by just doing some simple modifications in the configuration settings of the website.

To get things started, create an ASP.NET website project using either Visual Basic or C# in Visual Studio. I am creating a C# website project for this tutorial. Now right click the website project name in Solution Explorer and add the Add App_Code folder in the website from the "Add ASP.NET Folder" menu option. Next you need to create a separate subfolder for each of the programming language you want to support in your website. For the purpose of this tutorial I am adding CS and VB subfolders to support C# and Visual Basic source files. For this tutorial I am creating two simple code files named "ClassOne.cs" and "ClassTwo.vb" in CS and VB subfolders respectively. Your website structure should look like the following figure after the files are created.

Multiple Programming Languages in ASP.NET website

To check whether these files compile and work properly, I am adding a field and a function in both files. The source code of both files is shown below:


public class ClassOne
   public string Message;
   public string GetMessage()
      return this.Message;


Public Class ClassTwo
    Public Message As String
    Public Function GetMessage() As String
        Return Me.Message
    End Function
End Class

After creating separate subfolders for each programming language and creating multiple source files, all you need is simple modification in your website web.config file to tell ASP.NET to compile the files located in those subfolders separately. Open the web.config file of the website project and locate <compilation> the section in the file. You need to add the following <codesubdirectories> section inside the <compilation>section.

      <add directoryName="CS"/>
      <add directoryName="VB"/>


That’s all is required to support multiple languages in ASP.NET website project. You can now use both classes as normally in your website. To test these classes, create a Default.aspx page if it is not already created in your project. Add Two buttons and a label control on it and you can use those two classes on the button click events of both buttons as shown in the code below:


protected void Button1_Click(object sender, EventArgs e)
   ClassOne obj = new ClassOne();
   obj.Message = "C# Function is called...";
   Label2.Text = obj.GetMessage();
protected void Button2_Click(object sender, EventArgs e)
   ClassTwo obj = new ClassTwo();
   obj.Message = "VB Function is called...";
   Label2.Text = obj.GetMessage();

Following is the output of the page.

Multiple Programming Languages in ASP.NET website

Developers commonly include multiple programming languages in Web applications to support multiple development teams that operate independently and prefer different programming languages. I hope I am able to teach you how you can support multiple programming languages in ASP.NET website project.

Download SourceCode

String Format for DateTime


This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator andDateTimeForma­tInfo.TimeSepa­rator.

// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
Here are some examples of custom date and time formatting:

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008" // day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008" // two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
DateTimeFormatInfo property
Pattern value (for en-US culture)
h:mm tt
h:mm:ss tt
dddd, MMMM dd, yyyy
(combination of D and t)
dddd, MMMM dd, yyyy h:mm tt
dddd, MMMM dd, yyyy h:mm:ss tt
(combination of d and t)
M/d/yyyy h:mm tt
(combination of d and T)
M/d/yyyy h:mm:ss tt
m, M
y, Y
MMMM, yyyy
r, R
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.

String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

.NET Framework 4

The .NET Framework is an application development platform that provides services for building, deploying, and running desktop, web, and phone applications and web services. It consists of two major components: the common language runtime (CLR), which provides memory management and other system services, and an extensive class library, which includes tested, reusable code for all major areas of application development.

The .NET Framework for Users

If you do not develop .NET Framework applications, but you use them, you do not need specific knowledge about the .NET Framework or its operation. For the most part, the .NET Framework is completely transparent to users.
If you are using the Windows operating system, the .NET Framework may already be installed on your computer. In addition, if you install an application that requires the .NET Framework, the application's setup program might install a specific version of the .NET Framework on your computer. In some cases, you may see a dialog box that asks you to install the .NET Framework. If you have just tried to run an application when this dialog box appears and if your computer has Internet access, you can go to a webpage that lets you install the missing version of the .NET Framework.
In general, you should not uninstall any versions of the .NET Framework that are installed on your computer, because an application you use may depend on a specific version and may break if that version is removed. Note that multiple versions of the .NET Framework can be loaded on a single computer at the same time. This means that you do not have to uninstall previous versions in order to install a later version.

The .NET Framework for Developers

The .NET Framework provides the following services for application developers:
  • Memory management. In many programming languages, programmers are responsible for allocating and releasing memory and for handling object lifetimes. In .NET Framework applications, the CLR provides these services on behalf of the application.
  • A common type system. In traditional programming languages, basic types are defined by the compiler, which complicates cross-language interoperability. In the .NET Framework, basic types are defined by the .NET Framework type system and are common to all languages that target the .NET Framework.
  • An extensive class library. Instead of having to write vast amounts of code to handle common low-level programming operations, programmers can use a readily accessible library of types and their members from the .NET Framework Class Library.
  • Development frameworks and technologies. The .NET Framework includes libraries for specific areas of application development, such as ASP.NET for web applications, ADO.NET for data access, and Windows Communication Foundation for service-oriented applications.
  • Language interoperability. Language compilers that target the .NET Framework emit an intermediate code named Common Intermediate Language (CIL), which, in turn, is compiled at run time by the common language runtime. With this feature, routines written in one language are accessible to other languages, and programmers can focus on creating applications in their preferred language or languages.
  • Version compatibility. With rare exceptions, applications that are developed by using a particular version of the .NET Framework can run without modification on a later version.
  • Side-by-side execution. The .NET Framework helps resolve version conflicts by allowing multiple versions of the common language runtime to exist on the same computer. This means that multiple versions of applications can also coexist, and that an application can run on the version of the .NET Framework with which it was built.
  • Multitargeting. By targeting the .NET Framework Portable Class Library, developers can create assemblies that work on multiple .NET Framework platforms, such as the .NET Framework, Silverlight, Windows Phone 7, or Xbox 360.
You can choose any programming language that supports the .NET Framework to create your application. Because the .NET Framework provides language independence and interoperability, you can interact with other .NET Framework applications and components regardless of the language with which they were developed.