Thursday, December 23, 2010

Difference between Arraylist and Generic List


Difference between Arraylist and Generic List

private void button1_Click
(object sender, EventArgs e)
{
//Arraylist - Arraylist accept values as object
//So i can give any type of data in to that.
//Here in this eg: an arraylist object accepting
//values like String,int,decimal, char and a custom object

Employee emp = new Employee("2", "Litson");
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
//This process is known as boxing

//To get inserted vales from arraylist we have to specify the index.
//So it will return that values as object.
//we have to cast that value from object to its original type.

String name = (String)arr[0];
int num = (int)arr[1];
decimal dec = (decimal)arr[2];
Employee em = (Employee)arr[3];
char c = (char)arr[4];
//This process that is converting from object to its original type is known as unboxing
//------------------------------------------------------------------------------------
//Generic List
//List<>

//Main advantage of Generic List is we can specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing
//Eg:
List strLst = new List();
strLst.Add("Sabu");//Here List accepting values as String only
strLst.Add("Litson");
strLst.Add("Sabu");
strLst.Add("Sabu");

List intLst = new List();
intLst.Add(12);//Here List accepting values as int only
intLst.Add(14);
intLst.Add(89);
intLst.Add(34);

List decLst = new List();
decLst.Add(2.5M);//Here List accepting values as deciaml only
decLst.Add(14.4587m);
decLst.Add(89.258m);
decLst.Add(34.159m);

List empLst = new List();
empLst.Add(new Employee("1", "Sabu"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Mahesh"));
empLst.Add(new Employee("3", "Sajith"));
empLst.Add(new Employee("4", "Binu"));


//To get values from Generic List
String nme = strLst[0]; //No need of casting
int nm = intLst[0];
Decimal decVal = decLst[0];
Employee empVal = empLst[0];
}

Understanding .NET Application Domains

Understanding .NET Application Domains

Assuming you understand the role of Windows processes and how to interact with them from managed code, you must investigate the concept of a .NET application domain. To run your managed .NET code in a process, you create assemblies. These assemblies are not hosted directly within a Windows process. Instead, the common language runtime (CLR) isolates this managed code by creating separate logical partitions within a process called an application domain. A single process may contain multiple application domains, each of which is hosting distinct pieces of code encapsulated in assemblies. This subdivision of a traditional Windows process offers several benefits provided by the .NET Framework.

The main benefits are as follows:

• Application domains provide the operating system–neutral nature of the .NET platform by abstracting away the concept of an executable or library.
• Application domains can be controlled and (un)loaded, as you want.
• Application domains provide isolation for an application or within a process where multiple application domains live. Application domains within a process are independent of each other and as such remain functional when one fails the other.

Wednesday, December 22, 2010

Introduction :Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is a dedicated communication framework provided by 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 a lot of distributed communication technologies that exist. Some of them are:

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

ExistingTechnologies.gif


Creating and Consuming a Sample WCF Service:

Three major steps are involved in the creation and consumtion of 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. A contract is a neutral way of describing what the service does. Mainly we have four types of contracts:
  1. Service Contract

    This contract describes all the available operations that a 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 are passed into and out of the service.

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

  3. Fault Contract

    This contract describes about the error raised by the services.

    [FaultContract(<>)] 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 for those members of the type we want to make into SOAP headers
    [MessageBodyMember] attribute is used for 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)


Endpoints.GIF
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: localhost
    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 bindingTransportEncodingInter operableComments
Basic BindingBasicHttpBindingHttp / HttpsText / MTOMYesUsed to expose a WCF service as a legacy ASMX web service.
TCP bindingNetTcpBindingTCPBinaryNOTCP is used for cross-machine communication on the intranet.
Peer network bindingNetPeerTcpBindingP2PBinaryNOIn this peer network transport schema is used to communicate.
IPC bindingNetNamedPipeBindingIPCBinaryNOThis 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.
WSbindingWSHttpBindingHttp / HttpsText / MTOMYesThis uses Http / Https as a communication schema.
Federated WS bindingWSFederationHttpBindingHttp / HttpsText / MTOMYesThis is a specialization of the WS binding. This offers the support for federated security
Duplex WS bindingWSDualHttpBindingHttpText / MTOMYesThis is a WS binding with bidirectional communication support from the service to the client.
MSMQ bindingNetMsmqBindingMSMQBinaryNOThis supports for disconnected queued calls
MSMQ integration bindingMsmqIntegrationBindingMSMQBinaryYesThis 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 TypeAdvantagesLimitations
IIS HostingIIS 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 the 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".

ProjectType.GIF

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

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

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

IISHosting.GIF

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");

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 are that end point contains three 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 added 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.

ServiceBoundaries.GIF

Consuming WCF Service Hosted by IIS/WAS

Consuming WCF service is a 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.

AddServiceRef.GIF



AddServiceRef_2.GIF

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")).CreateChannel();
Here IFirstWCFService is the service contract interface, that is exposed.

Gridview add empty row with tab

Gridview add empty row with tab

The last column of the grid is a textbox called "txtbox"

In the code behind:

ItemDataBound event write

TextBox txtDescription = (TextBox)e.Row.FindControl("txtDescription");

txtDescription.Attributes.Add("onkeydown", "javascript:KeyPress(event, " + e.Row.Parent.ClientID + ((int)(e.Row.RowIndex + 1)).ToString() + ");");


then in the html write the following javascrit:


function KeyPress(event, btn)

{

if(event.keyCode==9 && !event.shiftKey)

{

btn.style.visibility = 'visible';

}

}


POC : Check a radiobutton just by clicking the Gridview Row


Check a radiobutton just by clicking the Gridview Row


POC :

ASPX Page :

1. <html>

2. <head runat="server">

3. <title>title>

4.

5. <script type="text/javascript">

6. function toggleSelection(targetID) {

7. var radioButton = document.getElementById(targetID);

8. radioButton.checked = !radioButton.checked;

9. }

10. script>

11.

12. head>

13. <body>

14. <form id="form1" runat="server">

15. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"

16. OnRowDataBound="GridView1_RowDataBound">

17. <Columns>

18. <asp:TemplateField>

19. <ItemTemplate>

20. <input id="rdMoveType" type="radio" runat="server" name="rdMoveType" value="Something" />

21. ItemTemplate>

22. asp:TemplateField>

23. Columns>

24. asp:GridView>

25. form>

26. body>

27. html>



Code Behind :

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  2. {
  3. if (e.Row.RowType == DataControlRowType.DataRow)
  4. e.Row.Attributes.Add("onclick", "toggleSelection('" + ((HtmlInputControl)e.Row.FindControl("rdMoveType")).ClientID + "');");
  5. }

Script Language :

You can write code to loop through Gridview rows and uncheck radiobuttons other than selected one