WCF programming for Beginners Wednesday, Aug 25 2010 

Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is a dedicated communication frame work provided by the Microsoft. WCF is a part of .NET 3.0. The runtime environment provided by the WCF enables us to expose our CLR types as services and to consume other existing services as CLR types.

Background:

In the world there are lot of distributed communication technologies exist. Some of them are:

  • ASP.NET Web Services (ASMX)
  • Web Services Enhancements (WSE)
  • Messaging (MSMQ)
  • .NET Enterprise Services (ES)
  • .NET Remoting

Creating and Consuming a Sample WCF Service:

Three major steps are involved while creating and consuming the WCF services. Those are:

  1. Create the Service.(Creating)
  2. Binding an address to the service and host the Service. (Hosting)
  3. Consuming the Service.(Consuming)

Step 1: Creating the Service

In WCF, all services are exposed as contracts. Contract is a neutral way of describing the service what it does. Mainly we have four types of contracts:

  1. Service Contract

    This contract describes all the available operations that client can perform on the service.

    .Net uses “System.ServiceModel” Name space to work with WCF services.

    ServiceContract attribute is used to define the service contract. We can apply this attribute on class or interface. Servicecontract attribute exposes a CLR interface (or a class) as a WCF contract.

    OperationContract attribute, is used to indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods, not on properties or indexers.

    [ServiceContract] applies at the class or interface level.
    [OperatiContract] applies at the method level.

  2. Data Contract

    This contract defines the data types that passed in and out to the service.

    [DataContract] attribute is used at the custom data type definition level, i.e. at class or structure level.
    [DataMember] attribute is used to fields, properties, and events.

  3. Fault Contract

    This contract describes about the error raised by the services.

    [FaultContract(<<type of Exception/Fault>>)] attribute is used for defining the fault contracts.

  4. Message Contracts

    This contract provides the direct control over the SOAP message structure. This is useful in inter operability cases and when there is an existing message format you have to comply with.

    [MessageContract] attribute is used to define a type as a Message type.
    [MessageHeader] attribute is used to those members of the type we want to make into SOAP headers
    [MessageBodyMember] attribute is used to those members we want to make into parts of the SOAP body of the message.

Sample Service Creation :

[ServiceContract]

public interface IFirstWCFService

{

[OperationContract]

int Add(int x, int y);

[OperationContract]

string Hello(string strName);

int Multiplication(int x, int y);

}

Here “IFirstWCFService” is a service exposed by using the servicecontract attribute. This service exposes two methods “Add”,”Hello” by using the [OperationContract] attribute. The method “Multiplication” is not exposed by using the [OperationContract] attribute. So it wnt be avlible in the WCF service.

public class FrtWCFService : IFirstWCFService

{

public int Add(int x, int y)

{

return x + y;

}

public string Hello(string strName)

{

return “WCF program  : ” + strName;

}

public int Multiplication(int x, int y)

{

return x * y;

}

}

“FrtWCFService” is a class,which implements the interface “IFirstWCFService”. This class definse the functionality of methods exposed as services.

STEP 2:  Binding and Hosting

Each service has an end point. Clients communicates with this end points only. End point describes 3 things :

  1. Address
  2. Binding type
  3. Contract Name (which was defined in STEP 1)

Address

Every service must be associated with a unique address. Address mainly contains the following  two key factors :

  1. Transport protocal used to communicate between the client proxy and service.

    WCF supports the following transport machinisams:

    • HTTP   (ex : http://  or https:// )
    • TCP     (ex :  net.tcp :// )
    • Peer network   (ex: net.p2p://)
    • IPC (Inter-Process Communication over named pipes) (ex: net.pipe://)
    • MSMQ  (ex: net.msmq://)
  2. Location of the service.

    Location of the service describes the targeted machine(where service is hosted) complete name (or) path  and optionally port / pipe /queue name.

    Example :   localhost:8081
    Here local host is the target machine name.
    8081 is the optional port number.

    Example 2:  localchost
    This is with out optional parameter.

Here are a few sample addresses:

http://localhost:8001

http://localhost:8001/MyFirstService

net.tcp://localhost:8002/MyFirstService

net.pipe://localhost/MyFirstPipe

net.msmq://localhost/MyFirstService

net.msmq://localhost/MyFirstService

Binding is nothing but a set of choices regarding the  transport protocol (which transport protocal we have to use : http /tcp /pipe etc.) ,message encoding (tells about the message encdong / decoidng technique)  ,communication pattern (whether communication is asynchronous, synchronous,  message queued etc.) , reliability, security, transaction propagation, and interoperability.

WCF defines the nine basic bindings:

Binding Type .Net Class implements this binding Transport Encoding Inter operable Comments
Basic Binding BasicHttpBinding Http / Https Text / MTOM Yes Used to expose a WCF service as a legacy ASMX web service.
TCP binding NetTcpBinding TCP Binary NO TCP is used for cross-machine communication on the intranet.
Peer network binding NetPeerTcpBinding P2P Binary NO In this peer network transport schema is used to communicate.
IPC binding NetNamedPipeBinding IPC Binary NO This uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine.
WSbinding WSHttpBinding Http / Https Text / MTOM Yes This uses Http / Https as a communication schema.
Federated WS binding WSFederationHttpBinding Http / Https Text / MTOM Yes This is a specialization of the WS binding. This offers the support for federated security
Duplex WS binding WSDualHttpBinding Http Text / MTOM Yes This is a WS binding with bidirectional communication support from the service to the client.
MSMQ binding NetMsmqBinding MSMQ Binary NO This supports for disconnected queued calls
MSMQ integration binding MsmqIntegrationBinding MSMQ Binary Yes This is designed to interoperate with legacy MSMQ clients.

Hosting:

Every service must be hosted in a host process. Hosting can be done by using the

  • IIS
  • Windows Activation Service (WAS)
  • Self hosting
Hosting Type Advantages Limitations
IIS Hosting IIS manages the life cycle of host process. ( like application pooling, recycling, idle time management, identity management, and isolation) Only HTTP transport schemas WCF service are hosted in IIS.
WAS Hosting
  • WAS supports for all available WCF transports, ports, and queues.
  • WAS manages the life cycle of host process.
Some adv of self hosted processing is missing.
Self Hosting
  • Developer can have explicit control over opening and closing the host.
  • In-Proc hosting can be done.
Missing the host process life cycle management.

IIS Hosting

IIS hosting is same as hosting the traditional web service hosting. Create a virtual directory and supply a .svc file.

In Vs2008 select a project type: “WCF Service Application”.

In the solution explorer, under the App_code folder you can find the two files: “IService.cs” and “Service.cs”.

“IService.cs” class file defines the contracts. “Service.cs” implements the contracts defined in the “IService.cs”. Contracts defined in the “IService.cs” are exposed in the service.

Check in the Web.Config file, under <system.serviceModel> section:

<services>

<service name=”Service” behaviorConfiguration=”ServiceBehavior”>

<!– Service Endpoints –>

<endpoint address=”” binding=”wsHttpBinding” contract=”IService”>

<!–

Upon deployment, the following identity element should be removed or replaced to reflect the

identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity

automatically.

–>

<identity>

<dns value=”localhost”/>

</identity>

</endpoint>

<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange”/>

</service>

</services>

In this one , end point node specifies the : address, binding type, contract (this is the name of the class that defines the contracts.)

Another end point node endpoint address=”mex” specify about the Metadata end point for the service.

Now host this serivce by creating the virtual directory and browse the *.SVC file:

Hosting with Windows Activation Service (WAS)

WAS is a part of IIS 7.0. It comes with VISTA OS. The hosting with the Windows Activation Service is same as hosting with IIS. The only difference between these two is, IIS supports for HTTP binding only. Whereas WAS supports for all transport schemas.

Self Hosting

In this technique developer is only responsible for providing and managing the life cycle of the host process. In this one host service must be running before the client calls the service.  To host the service we use the .NET class ServiceHost.  We have to create an instance of the “ServiceHost”.  Constructor of this class takes two parameters: service type, base address. (Base address can be empty set.)

Uri baseaddress = new Uri(“http://localhost:8080&#8221;);

ServiceHost srvHost = new
ServiceHost(typeof(WCFService.FrtWCFService),baseaddress);

Add the Service End points to the host :

We will use the AddServiceEndpoint() to add an end point to the host. As we awre that end point contains thress things:  type of service, type of binding, service Name.

So, AddServiceEndpoint() method accepts these three as the required parameters.

srvHost.AddServiceEndpoint(typeof(WCFService.IFirstWCFService), new BasicHttpBinding(), “FirstWCFService”);

Adding the Meta Data End points to the host:

For the Meta data, service type will be: typeof(IMetadataExchange)

srvHost.AddServiceEndpoint(typeof(IMetadataExchange), httpBinding, “MEX”);

Up to Now, we have created the host process and add the end points to it. Now call the open() method on the host. By calling the Open( ) method on the host, we allow calls in, and by calling the Close( ) method, we stylishly exit the host instance, that means, allowing calls in progress to complete, and yet refusing future new client calls even if the host process is still running

srvHost.Open();

STEP 3: Consuming the Service

With WCF, the client always communicates with the proxy only. Client never directly communicates with the services, even though the service is located on the same machine. Client communicates with the proxy; proxy forwards the call to the service.  Proxy exposes the same functionalities as Service exposed.

Consuming WCF Service Hosted by IIS/WAS

Consuming WCF service is very similar way of consuming a web service by using the proxy. To consume the service, in the solution explorer click on “Add service Reference” and add the service created in the STEP1.

A service reference is created under the service reference folder. Use this proxy class to consume the WCF service as we are doing with web services.

ServiceReference1.FirstWCFServiceClient obj = new

UsingWCFService.ServiceReference1.FirstWCFServiceClient();

Console.WriteLine(obj.Add(2, 3).ToString());

obj.Close();

Alternatively: We can create  the proxy class by using the following command

svcutil.exe [WCFService Address]

This generates a service proxy class, just include this class in to the solution and consume the service.

Consuming by creating the channel factory:

We can consume the service by creating the channel factory manually. While creating the channel, we have to provide the same binding type and end point address where the service is hosted.

IFirstWCFService chnl = new ChannelFactory<IFirstWCFService>

(new BasicHttpBinding(), new EndpointAddress(“http://localhost:8080/MYFirstWCFService&#8221;)).CreateChannel();

Here IFirstWCFService is the service contract interface, that is exposed.

Source is taken from: http://www.c-sharpcorner.com/uploadfile/sunilbabuylv/wcf4beginners08132008040537am/wcf4beginners.aspx

Advertisements

Exploring Windows Communication Foundation Wednesday, Aug 25 2010 

Two easy way to explore your WCF skills:

1: http://www.codeproject.com/KB/WCF/edujini_wcf_scart_01.aspx

2. http://www.codeproject.com/KB/WCF/edujini_wcf_scart_02.aspx

C# Tutorial for Beginners: Wednesday, Aug 25 2010 

Chapter 1:   About Microsoft. NET

All About Microsoft. NET

Microsoft. NET is one of the latest and new technologies introduced by Microsoft Corporation. Nowadays we use to connect to the internet using a computer and a remote computer responses via a web page and a collection of web pages are called as Web Sites. The Concept in .NET is that these websites can integrate with other sites and services using Standard Protocols like HTTP.

Microsoft .NET Platform comprises of  four core components such as:

  • NET Building Block Services such as file storage, calendar called Passport. NET
  • NET Device Software which will run on latest Internet Devices like Mobile Phones.
  • NET user experience such as integrating this technology to user created documents (integrates with XML). For example if you code XML via a  .NET Language like C#, it will  automatically create XML document.
  • NET infrastructure which includes  NET Framework (Common Language Runtime & .NET Framework Class Libraries) Microsoft Visual Studio.NET such as Visual Basic.NET ,Visual C++.NET etc  NET Enterprise Servers and Microsoft Windows. NET.

We can build robust, scalable, distributed applications with the help of .NET and the part that helps us to develop these applications is called the .NET Framework. The .NET Framework contains Common Language Runtime (CLR) and the .NET Framework class libraries also called as Base Class Libraries.

All the .NET languages (like C-sharp, VisualBasic.NET, Visual C++. NET etc) have the .NET Framework class libraries built into them. The .NET class Libraries also supports File I/O, database operations, XML (Extensible Markup Language) and SOAP (Simple Object Access Protocol). For example you can develop XML Pages by using C-sharp language.

When someone talks about .NET development, then you should understand that they are talking about .NET Framework. It includes a Runtime environment and a set of Class Libraries which is being used by a new language called C-sharp abbreviated as C# (more or less similar to  C/C++/Java family of languages) and all other .NET Languages. Simply speaking C-sharp is a new language for developing custom solutions for Microsoft’s .NET Platform.

The runtime which we discussed just now  is also used by VisualStudio.NET. Visual Studio.NET Provides us with a visual environment to design and develop .NET Applications. Every language in VisualStudio.NET uses this runtime to execute its applications. Moreover these languages compiles its source code into an intermediate language upon compilation. Hence you can very well use a module written using C-sharp in a Visual Basic Application. For example you can design a user interface with Visual Basic.NET and write a DLL function using C-sharp.

.NET Framework Process

Terms Associated with Microsoft .NET

Common Language Runtime

Common Language Runtime also called CLR Provides a universal execution engine for developers code. It generates SOAP when it makes remote procedure calls. CLR is independent and is provided as part of the .NET Framework. The main features of CLR are as follows:

  1. Managed Code
  2. Automatic application installation
  3. Memory Management
  4. Automatic Garbage Collection
  5. Very high level of Security while executing

.NET Framework Class Libraries

These class libraries works with any language under the common language runtime environment. It includes Visual Studio.NET, C-Sharp. Therefore if you are familiar with  one .NET language then you can easily migrate to other .NET Languages. The figure given below shows the .NET Framework hierarchy

Note:

  1. All namespaces should have to be called in your Program by applying the keyword using. For example if your programs needs to call System namespace, then it should be applied in the program as using System.
  2. Classes cannot be called along with the using directive.
  3. The using directive applies only to namespaces, just like importing packages in Java. Hence the following code will result in compilation error, usingSystem.Console.

However you can create an alias like the following using mysys = System.Console. Then you have to apply the alias in your program as followsmysys.writeLine(“Hello C#”);

Common Language Specification (CLS)

It is a set of rules that a language compiler must adhere to in order to create .NET Applications that run in the CLR. If you are going to create a compiler for .NET, you have to adhere to the rules enumerated in the common language specification and this enables us to create a club of CLS compliant languages.

Each such compiler will have the following features:

  • Complete access to .NET Framework hierarchy
  • High level of interoperability with other compliant languages like Visual Basic. NET etc.

For example a Visual Basic class can inherit from a C# Class.

You should note that the syntaxes and other programming structures differ from each of these languages. The only difference is that a developer well versed with a language such as C-sharp can easily program in Visual Basic.NET or Visual C++.NET without investing a lot or spending too long to learn a new language.

Chapter 2: Begin C-Sharp Programming

Getting Started with C-sharp

First of all let me welcome you to the world of this new programming language. I hope you will have a basic idea about Object Oriented Programming languages because many languages like Java, C++ have come by the past 5 years. However there will be no difficulty in learning this language if you are a fresher, because this tutorial and the coming ones will explain all the concepts and features right from the beginning.

Wherever required I explained the features involved in C-sharp by comparing them with Java. This will ensure smooth progress for experienced Programmers. I recommend you to install the appropriate software’s outlined in the next section before learning this new language.

Basic Requirements needed to begin C-sharp Programming

  1. .NET Framework Software Development Kit and
  2. An Editor (like Notepad or DOS Editor) to write source codes.

Optional Requirements:

  1. Visual C#. NET or
  2. Visual C++ 6.0 included with VisualStudio 6.0

Installing .NET Framework SDK

As a first step you should install .NET SDK on your computer to begin C-sharp Programming. It can be downloaded from the Microsoft’s Website. It is also available with almost all the popular computing magazine CD’S. It also comes with the complete documentation in the form of HTML Help.

At the time of this writing only beta version of the kit is available. This kit enables you to compile & execute the source code in C#, Visual Basic by using its built-in Command line Compiler (csc and vbc) and runtime Just In Time (JIT) Compiler. This is similar to Java Compiler (javac) and Java Interpreter (java) included
with Java Development Kit.

You can also develop applications with C-sharp and Visual Basic by using Visual Studio.NET languages like Visual C#.NET and Visual Basic.NET. This will help you to develop windows based applications easily and with limited effort because you don’t have to devote too much time in designing the user interface (Usage of WinForms). The only work left for you to do is to write the codings appropriately as per the .NET Standards.

About the Editors

Notepad is the best choice among developers using .NET SDK to develop C# applications. However it is not the most suitable editor since it does not support syntax coloring, code numberings etc.

Developers can use Visual C++ 6.0 included with Visual Studio 6.0. However they should make some tweaking in the registry before using the same. It supports syntax colorings and other features such as finding line numbers (Ctrl+G). However it is dangerous for a new user to make changes in registry. Hence only advanced and experienced users can be able to use Visual Studio 6.0 for developing C#. It is not possible to compile and execute the applications from the Visual C++ 6.0 Environment. Hence there is not much use except some of the features listed above.

VisualStudio.NET provides all the integrated tools and wizards for creating C# and Visual Basic applications. It also supports features such as intellisense, Dynamic help. Moreover you can compile and execute your applications from the IDE itself.  Hence in order to experience the power of developing the .NET applications, you should try VisualStudio.NET.

Many Third Party editors are now available either from magazine’s CD’S or can be downloaded from the internet. However it is up to you to decide upon which editor to use. I recommend you to try one common editor and learn the language in full.

Chapter 3: Your First Hello C# Program

Getting Started with Hello C-Sharp

After understanding the fundamentals of .NET and its Structure, let us now move on to look at a classic Hello C# Program. As I mentioned in the previous tutorial, you can use any text editor as per your Convenience.

Listing 3.1 gives the coding for this simple Hello C# Program.

using System ;
Class Hello
{
Public
static void Main ()
{
Console.writeLine (“Hello C#”);
}
}
//end of the main

What to do next: –

Save the following file as Hello.cs. cs is an extension to indicate C-sharp like .java for a Java Source File. You have to supply this extension while saving your file, otherwise the code will not compile correctly. The saved file will be of .cs.txt extension.

Compile the above Code by giving the following Command at the Command Prompt csc Hello.cs

If there are compile errors then you will be prompted accordingly, otherwise you will be getting a command prompt with the copyright information. Keep in mind that the compiler generates MSIL.

Your next job is to execute the program to view the final Output. For that purpose you have to simply give Hello at the command Prompt. If everything goes on well, a message Hello C# will be printed on the Screen.

You can view the MSIL Code generated by any .NET Language with the help of an Utility called Intermediate Language Disassembler or shortly ILDASM. This utility will display the application’s information in a tree like fashion. Since the contents of this file is read only, a Programmer or anybody accessing these files cannot make any modifications to the output generated by the Source Code.

To view the MSIL Code for the above Hello C# Program, open Hello.exe file from the ILDASM tool. In Windows 98, ME & NT this tool can be accessed via  start – programs – Microsoft .NET Framework SDK – Tools – IL Disassembler

Detailed Review of the above Program: –

I am giving below the process occurring to the source code, during the compilation and execution stages once again for your reference.

Compilation Stage:

C# Compiler produces MSIL as output after compilation. It is itself a complete language and it is more or less similar to Assembly language. MSIL stands for Microsoft Intermediate Language. The same thing happens to any application written in any CLR Compliant Language like Visual Basic.NET, Visual C++.NET etc.

Execution Stage: –

The MSIL is then compiled into native CPU instructions by using JIT (Just in Time) compiler at the time of the program execution. The Source Code is recompiled and executed only after making any changes to it .

Now let us analyze the Hello C# Program as a whole. I am giving below the code once again for your reference. Please note that the line numbers are given for clarification and explanation and is not a part of the Source Code.

using System ;
class
Hello
{
public static void
Main ()
{
Console.writeLine (“Hello C#”);
}
}
//end of the main

Line Number wise Analysis

Line  – 1: – It is called as the namespace. Simply speaking, a namespace is a collection of .NET Classes similar to packages in Java.

Line – 2: – It is the class declaration similar to Java & C++

Line – 3: – This is the main method which is required in all C# applications.

Line – 4: – This code will print Hello C# onto the Console. Here Console is the class belonging to System namespace and writeLine is the static method belonging to Console Class.

Line – 5:- The Opening and Closing curly races are similar to that of C++/Java.

Source from: http://www.c-sharpcorner.com/uploadfile/anandnarayanswamy/cstutorial1an11282005015140am/cstutorial1an.aspx

Managed, Unmanaged, Native: What Kind of Code Is This? Wednesday, Aug 25 2010 

With the release of Visual Studio .NET 2003 (formerly known as Everett) on April 24th, many developers are now willing to consider using the new technology known as managed code. But especially for C++ developers, it can be a bit confusing. That’s because C++, as I pointed out in my first column here, is special.

What Is Managed Code?

Managed Code is what Visual Basic .NET and C# compilers create. It compiles to Intermediate Language (IL), not to machine code that could run directly on your computer. The IL is kept in a file called an assembly, along with metadata that describes the classes, methods, and attributes (such as security requirements) of the code you’ve created. This assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to another server to deploy the assembly there—and often that copying is the only step required in the deployment.

Managed code runs in the Common Language Runtime. The runtime offers a wide variety of services to your running code. In the usual course of events, it first loads and verifies the assembly to make sure the IL is okay. Then, just in time, as methods are called, the runtime arranges for them to be compiled to machine code suitable for the machine the assembly is running on, and caches this machine code to be used the next time the method is called. (This is called Just In Time, or JIT compiling, or often just Jitting.)

As the assembly runs, the runtime continues to provide services such as security, memory management, threading, and the like. The application is managed by the runtime.

source from: http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

How to make a Visual C# class usable in a foreach statement Tuesday, Aug 24 2010 

This step-by-step article demonstrates how to use the IEnumerable and the IEnumeratorinterfaces to create a class that you can use in a foreach statement. IEnumerable andIEnumerator are frequently used together. Although these interfaces are similar (and have similar names), they have different purposes.

IEnumerator interface

The IEnumerator interface provides iterative capability for a collection that is internal to a class. IEnumerator requires that you implement three methods:

  • The MoveNext method, which increments the collection index by 1 and returns a bool that indicates whether the end of the collection has been reached.
  • The Reset method, which resets the collection index to its initial value of -1. This invalidates the enumerator.
  • The Current method, which returns the current object at [position].
public bool MoveNext()
      {
         position++;
         return (position < carlist.Length);
      }

      public void Reset()
      {position = 0;}

      public object Current
      {
         get { return carlist[position];}
      }

IEnumerable interface

The IEnumerable interface provides support for the foreach iteration. IEnumerablerequires that you  implement the GetEnumerator method.
 public IEnumerator GetEnumerator()
      {
         return (IEnumerator)this;
      }

When to use which interface

Initially, you may find it confusing to use these interfaces. The IEnumerator interface provides  iteration over a collection-type object in a class. The IEnumerable interface permits enumeration by  using a foreach loop. However, the GetEmunerator method of theIEnumerable interface returns an  IEnumerator interface. Therefore, to implementIEnumerable, you must also implement IEnumerator.  If you do not implementIEnumerator, you cannot cast the return value from the GetEnumerator method  ofIEnumerable to the IEnumerator interface. In summary, the use of IEnumerable requires that the class implement IEnumerator. If you want to provide support for foreach, implement both interfaces.

Step by step example

The following example demonstrates how to use these interfaces. In this example, theIEnumerator and  the IEnumerable interfaces are used in a class named cars. The carsclass has an internal array of car  objects. Client applications can enumerate through this internal array by using a foreach construct  because of the implementation of these two interfaces.
  1. Follow these steps to create a new Console Application project in Visual C#:
    1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
    2. On the File menu, point to New, and then click Project.
    3. Click Visual C# Projectsunder Project Types, and then click Console Application under Templates. Note In Visual Studio 2005, click Visual C# under Project Types.
    4. In the Name box, type ConsoleEnum.
  2. Rename Class1.cs to host.cs, and then replace the code in host.cs with the following code:

using System;

namespace ConsoleEnum
{
  class host
  {
    [STAThread]
    static void Main(string[] args)
    {
      cars C = new cars();
      Console.WriteLine("\nInternal Collection (Unsorted - IEnumerable,Enumerator)\n");
      foreach(car c in C)
      Console.WriteLine(c.Make + "\t\t" + c.Year);

      Console.ReadLine();
    }
  }
}
   3. On the Project menu, click Add Class, and then type car in the Name box.
   4. Replace the code in car.cs with the following code:
using System;
using System.Collections;
namespace ConsoleEnum
{

  public class car
  {
    private int year;
    private string make;

    public car(string Make,int Year)
    {
      make=Make;
      year=Year;
    }
    public int Year
    {
      get  {return year;}
      set {year=value;}
    }
    public string Make
    {
      get {return make;}
      set {make=value;}
    }
  }//end class
}//end namespace

  5. On the Project menu, click Add Class to add another class to the project, and then type cars in the 
Name box.

6. Replace the code in cars.cs with the following code:

using System;
using System.Collections;
namespace ConsoleEnum
{
   public class cars : IEnumerator,IEnumerable
   {
      private car[] carlist;
      int position = -1;

      //Create internal array in constructor.
      public cars()
      {
         carlist= new car[6]
      {
         new car("Ford",1992),
         new car("Fiat",1988),
         new car("Buick",1932),
         new car("Ford",1932),
         new car("Dodge",1999),
         new car("Honda",1977)
      };
      }

      //IEnumerator and IEnumerable require these methods.
      public IEnumerator GetEnumerator()
      {
         return (IEnumerator)this;
      }

      //IEnumerator
      public bool MoveNext()
      {
         position++;
         return (position < carlist.Length);
      }

      //IEnumerable
      public void Reset()
      {position = 0;}

      //IEnumerable
      public object Current
      {
         get { return carlist[position];}
      }
   }
}

Run the project. Notice that the following output appears in the Console window:

Ford            1992
Fiat            1988
Buick           1932
Ford            1932
Dodge           1999
Honda           1977

Best practices

The example in this article is kept as simple as possible to better explain the use of these interfaces.

To make the code more robust and to make sure that the code uses the current best practice guidelines,

modify the code as follows:

  • Implement IEnumerator in a nested class so that you can create multiple enumerators.
  • Provide exception handling for the Current method of IEnumerator. If the contents of the collection

change, the reset method is called. As a result, the current enumerator is invalidated, and you  receive an IndexOutOfRangeException exception. Other circumstances may also cause this exception.  Therefore, implement a Try...Catch block to catch this exception and to raise an  InvalidOperationException exception.

    using System;
    using System.Collections;
    namespace ConsoleEnum
    {
      public class cars : IEnumerable
      {
        private car[] carlist;
    
        //Create internal array in constructor.
        public cars()
        {
          carlist= new car[6]
        {
          new car("Ford",1992),
          new car("Fiat",1988),
          new car("Buick",1932),
          new car("Ford",1932),
          new car("Dodge",1999),
          new car("Honda",1977)
        };
        }
    
            //private enumerator class
            private class  MyEnumerator:IEnumerator
            {
              public car[] carlist;
              int position = -1;
    
            //constructor
            public MyEnumerator(car[] list)
            {
              carlist=list;
            }
            private IEnumerator getEnumerator()
            {
              return (IEnumerator)this;
            }
    
            //IEnumerator
            public bool MoveNext()
            {
              position++;
              return (position < carlist.Length);
            }
    
            //IEnumerator
            public void Reset()
            {position = -1;}
    
            //IEnumerator
            public object Current
            {
              get
              {
                try
                {
                  return carlist[position];
                }
    
                catch (IndexOutOfRangeException)
                {
                  throw new InvalidOperationException();
                }
              }
            }
          }  //end nested class
        public IEnumerator GetEnumerator()
        {
          return new MyEnumerator(carlist);
        }
      }
    }
    
    Source is taken from: http://support.microsoft.com/kb/322022

    ASP.NET ViewState related Interview Questions Friday, Aug 20 2010 

    What is ViewState?
    Web forms have very short lifetimes.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.The data that ASP.NET preserves between requests is called the Web form’s view state.

    How do you enable or disable a ViewState for a control on the page?
    Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If EnableViewState is set to false ViewState is disabled for the control.

    How do you enable or disable a ViewState at the page level?
    At the page level you can enable or disable ViewState using EnableViewState property of the page.

    What is the name of the hidden form field in which ViewState of the page is saved?
    __ViewState

    What are the performance implications of ViewState?
    ViewState is usually good to retain the state of the controls on the webform across postbacks. If you have a huge DataGrid with tons of data being loaded on every page load. It is a good idea to disable the ViewState of the DataGrid for the page to load faster. If the ViewState of a large DataGrid is not disabled, ViewState can easily get very large, on the order of tens of kilobytes. Not only does the __ViewState form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.

    When does ViewState restoration happens?
    During the Page_Init event

    What are the disadvantages of using ViewState?
    1. On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __ViewState form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.

    2. The __ViewState hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __ViewState form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.

    Is ViewState encoded?
    Yes, ViewState is base-64 encoded.

    Can you encrypt ViewState of Page?
    Yes, we can use the LosFormatter class to encrypt ViewState of Page

    Can the HTML controls retian State accross postbacks?
    No, by default HTML controls donot retain state accross postbacks.

    Can you make HTML controls retain State accross postbacks?
    Yes, HTML controls can retain State accross postbacks, if you convert HTML controls to Server Controls. There are 2 ways to convert HTML control to Server Controls.

    1. Right click on the HTML Control and then click “Run As Server Control”
    Or
    2. Set runat=”server” attribute for the Control.

    Is ViewState supported in classic ASP?
    No,ViewState is introduced in asp.net, it was not in classic asp.

    When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens…….ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.

    When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server.

    Is ViewState of one page available to another page?
    No, ViewState of a Page is available only in that page. You cannot access ViewState of one page from another page.

    Can you programatically store and retrieve data from ViewState?
    Yes. In ASP.NET you can programatically store and retrieve data from ViewState.See the example below

    //Save the value in ViewState object
    ViewState(“SomeVar”) = txtFirstName.text;

    //Retrieve the value from ViewState object
    String strFirstName = ViewState(“SomeVar”).ToString();

    Can someone view the Page HTML source and read ViewState?
    No. ViewState is base-64 encoded. Hence you cannot read ViewState. If you right click on the Page and View Source you will find __ViewState is base-64 encoded.

    What happens during the Page_Init event?
    The server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.

    Source: http://venkataspinterview.blogspot.com/2008/07/aspnet-viewstate-related-interview.html

    SSL and HTTPS related ASP.NET Interview Questions Friday, Aug 20 2010 

    How do you provide Secure Communication over the world wide web?
    Security is not just a matter of identifying users and preventing unauthorized users from accessing your Web applications, but it’s just as important to ensure that sensitive data sent across the Internet can’t be read by others.

    To provide secure communication across the Internet, IIS supports a standardized means of encrypting and decrypting Web requests and responses. This cryptography requires that you request an encryption key called a server certificate from an independent third party called a certificate authority.

    What is Secure Sockets Layer (SSL)?
    The Secure Sockets Layer (SSL) is the standard means of ensuring that data sent over the Internet can’t be read by others. When a user requests a secure Web page, the server generates an encryption key for the user’s session and then encrypts the page’s data before sending a response. On the client side, the browser uses that same encryption key to decrypt the requested Web page and to encrypt new requests sent from that page.

    Explain the process of secure communication using SSL?
    Using SSL in your application requires special authorization from a recognized certificate authority. This authorization comes in the form of a server certificate, which you install in IIS to identify your server. The certificate authority licenses server certificates (for a fee) and acts as a clearinghouse to verify your server’s identity over the Internet.

    When a user’s browser begins secure communications, it requests the server certificate and checks it against a list of trusted sites provided by the certificate authority. If the server certificate does not match one of the sites already authorized by the user, or if the server certificate does not match the Web address for which it was registered, or if there are any other problems with the server certificate, the browser displays a warning.

    In this way, the certificate authority not only provides encryption for secure data transmission, but it also provides assurance to users that your Web site is authentic.

    What is the largest certificate authority?
    The largest certificate authority is VeriSign.

    What are the steps to follow to use SSL in your Web application?
    1. Generate a certificate request from IIS.
    2. Request a certificate from a certificate authority.
    3. Install the certificate on the server using IIS.
    4. Install the certificate on browsers if you are using a test certificate.
    5. Use the Secure Hypertext Transfer Protocol (HTTPS) when accessing secure pages in your application.

    What should you do before you can request a server certificate from a certificate authority?
    Before you can request a server certificate from a certificate authority, you must generate a certificate request from IIS. The certificate request contains encrypted information about your server that the certificate authority uses to identify your server over the Internet.

    What are the steps to follow to generate a certificate request from the IIS?
    1. Select Default Web Site in the console tree of the IIS, and then choose Properties from the Action menu. IIS displays the Default Web Site Properties dialog box.
    2. Click the Directory Security tab in the Properties dialog box, and then click Server Certificate. IIS starts the Web Server Certificate Wizard.
    3. Step through the wizard by reading each screen and clicking Next. The wizard instructions are straightforward.
    4. When you click Finish at the end, the wizard creates an encrypted text file with the .cer file extension. That file is the certificate request that you send to the certificate authority.

    Why do you have to select Default Web Site when generating a Certificate Request from IIS?
    IIS requires that a certificate be created at the server root before secure communications can be created or configured for subordinate sites on the server. That’s why you have to select Default Web Site (or the root Web site if you have renamed it). After you have installed a server certificate at the root, you can repeat the process for subordinate sites if you want separate certificates for those sites.

    What is the file extension of a server certificate?
    .cer

    What are the steps to follow to install the Certificate to enable SSL for your Web applications?
    To install a server certificate in IIS:
    1. Select Default Web Site in the console tree of the IIS snap-in, and then choose Properties from the Action menu. IIS displays the Default Web Site Properties dialog box.
    2. Click the Directory Security tab in the Properties dialog box, and then click Server Certificate. IIS starts the Web Server Certificate Wizard.
    3. Click Next, and select Process The Pending Request And Install The Certificate.
    4. Click Next, and enter the name of the certificate file.
    5. Click Next, and then click Finish to complete the installation.

    What is the protocol on which secure pages are generally requested?
    HTTPS, the protocol HTTPS is what initializes the secure communication. When you’ve begun secure communication, it continues until you specify a nonsecure site.

    What are the steps to follow to make a web page secure in a web application?
    To require secure communication for a Web page using IIS, follow these steps
    1. Select the folder or file that requires secure communication, and then choose Properties from the Action menu. IIS displays the Properties dialog box.
    2. Click the Directory Security tab, and then click Edit in the Secure Communications group. IIS displays the Secure Communications dialog box.
    3. Select the Require Secure Channel (SSL) check box, and click OK.

    Can a user access secure web page over HTTP protocol instead of HTTPS?
    No, When you require secure communication for a Web page, that page can’t be viewed using HTTP. The user must type in or click a link using HTTPS, otherwise, access will be denied.

    Source: http://venkataspinterview.blogspot.com/2008/10/ssl-and-https-related-aspnet-interview.html#comment-form

    Wednesday, Aug 11 2010 

    free counters

    Sharepoint Object Model Tuesday, Aug 10 2010 

    There are several namespaces(around 50) that house the SharePoint object model. Out of these 50 namespaces we are using only 16 namespaces, rest of the namespaces are reserved for Microsoft internal use.

    1. Document Library

    Document libraries are a special type of list designed to store documents.To access a document library through object model we need to use Microsoft.Sharepoint namespace. To use this namespace in ASP.net we need to add a reference of Microsoft.Sharepoint.dll. This dll we can find from the below mentioned path:

    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

    Let’s take each and every class in this namespace:

    • SPDocumentLibrary Class:This class represents a document library in Windows Sharepoint Services.
      In C# code: SPDocumentLibrary obj = (DocumentLibrary)oList
      oList is an object for list. The above code will cast the list object into Document Library.
    • SPPictureLibrary Class:This class represents a picture library in Windows Sharepoint Services. Both classes are used in the sane manner. The only difference is: As the name indicates SPDocumentLibrary is used for Document Library and SPPictureLibrary is used for Picture Library.

    2. Features:

    For using the features through Sharepoint object model we need Microsoft.Sharepoint dll and you can get the dll from the above mentioned path.

    • SPFeatureDefinition Class: Contains the base definition of an SPFeature, including its name, identifier, scope, and version
    • SPFeatureScope Class : Specifies the scope to which the feature applies.
    • SPElementDefinition Class: Serves as the base class for implementing element types within Windows SharePoint Services
    • SPFeature Class: Represents the state of a feature at its corresponding scope
    • SPFeatureProperty Class: Represents a single Feature property.

    Code Example:

    SPSite oSpSite = new SPSite(“http://YourServer&#8221;);
    SPFeatureCollection oSPfeatureCollection = oSpSite.Features;

    foreach (SPFeature oSPFeature in oSPfeatureCollection)
    {
    SPFeatureDefinition featureDefinition = oSPFeature.Definition;
    SPElementDefinitionCollection elementDefinitionCollection =
    featureDefinition.GetElementDefinitions(System.Globalization.CultureInfo.InvariantCulture);

    foreach (SPElementDefinition elementDefinition in elementDefinitionCollection)
    {
    Console.WriteLine(elementDefinition.Id);
    }
    }

    Ref: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfeatureproperty.aspx

    3.

    For using meetings through object model we need to add Microsoft.Sharepoint dll as mentioned above. The classes under this category are explained as below:

    SPMeeting Class:- Provides methods and properties that can be used to work with a Meeting Workspace. Suppose if you want to create a meeting workspace through object model then we need to use this class. There are different kind of meeting template that can be handled like Basic meeting, Decision Meeting, Multiple meeting etc.

    MtgUtility:- Initialize a new instance of the MtgUtility class. To access the MtgUtility service and its methods, set a Web reference tohttp://Server_Name/[sites/][Site_Name/]_vti_bin/xxx.asmx.

    Microsoft.SharePoint.Meetings.MtgUtility – System.Object

    4.

    Sites objects are used to access the sharepoint site, The classes under this category of Sharepoint Object model are explained as below:

    SPSite: . Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.

    SPWeb: Represents a Windows SharePoint Services Web site.

    CODE Example:

    using(SPSite oSite = new SPSite(“http://Server_Name&#8221;))
    {
    using(SPWeb oWebsite = oSite.OpenWeb(“Website_URL”))
    {
    using(SPWeb oWebsiteRoot = oSite.RootWeb)
    {
    …//Your Code
    }
    }
    }

    5.

    Provides administrative types and members for managing a Windows SharePoint Services deployment. There are so many classes, delegates, interface under this namespace but only few classes I am going to explain.

    SPSolution : Represents a solution on a farm.

    Namespace: Microsoft.SharePoint.Administration

    Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

    SPFeatureReceiver:

    Base abstract class that can be overridden to trap the activation, deactivation, installation, or uninstallation of a Feature.

    Namespace: Microsoft.SharePoint

    Assembly: Microsoft.SharePoint

    Use the SPFeatureReceiver class to trap events that are raised after the Feature installation, uninstallation, activation, or deactivation action has been performed.

    It is not possible to cancel an installation or uninstallation through Feature events.

    SPSolutionCollector:

    Represents a collection of SPSolution objects.

    Namespace: Microsoft.SharePoint.Administration

    Assembly: Microsoft.SharePoint

    6.


    SPList object represent a List, SPListItem represent a List Item in the List and SPListItemCollection object represent a full item collection in the SPLIST.

    Code Example:

    SPList mylist_Name = myweb.Lists[“Category”];
    SPListItemCollection itmcln = mylist_Name.Items;
    foreach (SPListItem itm in itmcln)
    {
    if (itm[“ItemCategory”] != null)
    {
    ddlCategory.Items.Add(itm[“ItemCategory”].ToString());

    }
    }

    7.


    8.


    This is all about Sharepoint Object Model.

    Reference: http://www.c-sharpcorner.com/UploadFile/Ravish001/1376/

    C# 2.0 Anonymous Methods Friday, Aug 6 2010 

    C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.

    Here is a simple example of using an anonymous method to find all the even integers from 1…10:

    private int[] _integers =
          { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    int[] evenIntegers = Array.FindAll(_integers,
                               delegate(int integer)
                               {
                                   return (integer%2 == 0);
                               }
        );

    The Anonymous Method is:

    delegate(int integer)
        {
            return (integer%2 == 0);
        }

    which is called for each integer in the array and returns either true or false depending on if the integer is even.

    If you don’t use an anonymous method, you will need to create a separate method as such:

    private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    int[] evenIntegers = Array.FindAll(_integers, IsEven);
    
    private bool IsEven(int integer)
    {
        return (integer%2 == 0);
    }

    When you have very simple methods like above that won’t be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.

    Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):

    List<City> citiesInFlorida =
    cities.FindAll(delegate(City city)
         {
             return city.State.Name.Equals(States.SelectedValue);
         }
    );

    You can also use anonymous methods as such:

    button1.Click +=
    
        delegate
            {
                MessageBox.Show("Hello");
            };

    which for such a simple operation doesn’t “deserve“ a separate method to handle the event.

    Other uses of anonymous methods would be for asynchronous callback methods, etc.

    Anonymous methods don’t have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.

    Source: http://davidhayden.com/blog/dave/archive/2006/05/28/2974.aspx


    Next Page »