Search This Blog

2009-06-28

Static Constructor

What is Static Constructor:
C# supports two types of Constructor
1.Class Constructor or Static Constructor-used to initialize static data members as soon as the class is referenced first time
2.Instance Constructor or non-Static Constructor-used to create an instance of that class with new keyword.
Static Data Member can be initialized at the time of their declaration(clsWithoutStaticConstructor in the following example) but there are times when value of one static member (clsWithStaticConstructor in the following example)may depend upon the value of another static member.

using System;
using System.Collections.Generic;
using System.Text;

namespace StaticConstructor
{
class clsWithoutStaticConstructor
{
private static int numStatData = 8;
public static int StatData
{
get { return numStatData; }
}
public static void print()
{
Console.WriteLine("Static Data :" + StatData);
}
}
class clsWithStaticConstructor
{

private static int numStatData2;
static clsWithStaticConstructor()
{

if (clsWithoutStaticConstructor.StatData < 10)
{
numStatData2 = 10;
}
else
{
numStatData2 = 100;
}
Console.WriteLine("Static Constructor is called...");
}
public static void print2()
{
Console.WriteLine("Static Data :" + numStatData2);
Console.ReadLine();
}
}
class Program
{

static void Main(string[] args)
{
clsWithoutStaticConstructor.print();
clsWithStaticConstructor.print2();
}
}
}

Output :


In the above example "numStatData2" in "clsWithStaticConstructor" is initialized based on the value of clsWithoutStaticConstructor.StatData .since StatData in the clsWithoutStaticConstructor is initilized to 8 so the value of numStatData2 is set to 10.

Static Constructor executes:
-before any instance of the class is created.
-before any of the static members for the class are referenced.
-after the static field initializers(if any) for the class.
-atmost one time.

and a static constructor does not take access modifiers or have parameter

2009-06-22

What is new in .NET 2.0

The following new features have been added to C# language with version 2.0 of .NET.

Generics
Iterators
Anonymous methods
Partial classes

generics :It is a programming language mechanism by which a single piece of code (function, object, interface, etc.) can manipulate many different data types.

Code Snippent:
class MyArrayList<ItemType>
{
private ItemType[] items = new ItemType[10];
private int count;
public void Add(ItemType item)
{
items[count++] = item;
}
public ItemType GetItem(int index)
{
return items[index];
}
}

To Call this method:
MyArrayList<int> iList = new MyArrayList();
MyArrayList<string> sList = new MyArrayList();

iList.Add(25);
int iValue = iList.GetItem(0);

sList.Add("Manab");
string sValue = sList.GetItem(0);

Using Methods:
Generic methods will allow you to pass one or more data types. An Example is given below.

public class MyClass
{
public ItemType MyMethod<ItemType>(ItemType item)
{
return item;
}
}

To Call the method
MyClass mc = new MyClass();
int i= mc.MyMethod<int>(32);
Response.Write(i.ToString());

C#Generics has the following advantages:
1.The Program becomes statically typed, so errors are discovered at compile-time.
2.No runtime casts are required and the program runs faster.
3.Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.

iterator : An iterator is an object that allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation.
foreach Loops Based on an Enumerator Pattern

// Implementation
ArrayList list = new ArrayList();
// ...
foreach(object obj in list)
{
DoSomething(obj);
}
// Translation through compiler
Enumerator e = list.GetEnumerator();
while(e.MoveNext())
{
object obj = e.Current;
DoSomething(obj);
}

Anonymous Methods:Anonymous methods let you define methods, usually delegates, inline with the declaration of the event.

You can replace this code:

button.Click += new EventHandler (this.bClick);
// elsewhere
private void bClick (sender, e)
{
MessageBox.Show ("click");
}

with the code given below:

button.Click +=new EventHandler (object sender, EventArgs e)
{
MessageBox.Show ("click");
}

Partial Classes:This feature allows you to split a particular class into two or more separate files. For this purpose, every part of the class is marked with the new modifier partial. The compiler looks for the marked parts and merges them into one complete implementation. You'll see no difference at run time. The assembly of the code parts requires all elements be in the same project and a parallel compilation. In addition, the classes have to match logically and must be identical regarding their modifiers, supported interfaces, and so on.

using System;
public partial class Foo
{
public void SomeMethod()
{
}
}
// foo2.cs
using System;
public partial class Foo
{
public void SomeOtherMethod()
{
}
}

Web Editor for ASP.NET

Most blog, forum, and Wiki applications use an HTML editor as the primary authoring tool for site content. With this type of a control, an online user can create and edit an HTML document. The user is able to modify the text — including its format, fonts, and colors — as well as add links and images. Often, the user can also view and/or edit the HTML source.

Microsoft AJAX (ASP.NET AJAX Extensions) introduces a new implementation model for server controls with related scripts. This article discusses how to create an HTML editor server control specifically for the Microsoft AJAX environment. The reader can also download the source code, including a sample web page, and view an online demo from the following URL.

http://69.10.233.10/KB/ajax/HtmlEditor.aspx?display=Print



2009-06-18

Basics Of Windows Communication Foundation

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.
WCF is a unification of .NET framework communication technologies which unites the following technologies:-

-NET remoting
-MSMQ
-Web services
-COM+

What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

What is ABCs Of WCF?
Hosts and Clients communicate with each other by agreeing on the ABCs.ABC indicates three things:
-Address:The location Of the service
-Binding:WCF Ships with a number of different bindings that specify network protocols
-Contract:A description of each method exposed from the WCF Service.

<system.serviceModel>
<services>
<service name="MyNameService" behaviorConfiguration="MyNameServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="IMyService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyNameServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.
The Endpoint is the fusion of Address, Contract and Binding.

What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.
WCF supports following transport schemas
-HTTP
-TCP
-Peer network
-IPC (Inter-Process Communication over named pipes)
-MSMQ
The sample address for above transport schema may look like
http://localhost:85
http://localhost:85/MyService
net.tcp://localhost:85/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.
-Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

-TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

-Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

-IPC binding
Offered by the NetNamedPipeBinding class, 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 and it supports a variety of features similar to the TCP binding.

-Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

-Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

-Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

-MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

-MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

-1.Service contracts:
Describe which operations the client can perform on the service.
There are two types of Service Contracts.
--a)ServiceContract - This attribute is used to define the Interface.
--b)OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod( );
}
class MyService : IMyContract
{
public string MyMethod( )
{
return "Hello World";
}
}

-2.Data contracts:Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
--a)DataContract - attribute used to define the class
--b)DataMember - attribute used to define the properties.
[DataContract]
class Contact
{
[DataMember]
public string FirstName;

[DataMember]
public string LastName;
}
If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

-3.Fault contracts:Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

-4.Message contracts :Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

-1. IIS
-2. Self Hosting
-3. WAS (Windows Activation Service)

How to deal with operation overloading while exposing the WCF services?
By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator
{
[OperationContract(Name = "AddInt")]
int Add(int arg1,int arg2);

[OperationContract(Name = "AddDouble")]
double Add(double arg1,double arg2);
}

What is the difference WCF and Web services?
-Web services can only be invoked by HTTP. While WCF Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, WCF Services are flexible.
-If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.
<client>
<endpoint
...
binding = "wsHttpBinding"
bindingConfiguration = "LongTimeout"
...
/>
</client>
<bindings>
<wsHttpBinding>
<binding name = "LongTimeout" sendTimeout = "00:04:00"/>
</wsHttpBinding>
</bindings>
If no timeout has been specified, the default is considered as 1 minute.

What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
-------------------------------------------------------------------------------------
Resource:http://www.dotnetfunda.com/interview/ShowCatQuestion.aspx?start=0&page=1&category=74