Search This Blog

25 February, 2010

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

WCF Videos

Windows Communication Foundation:" Hello World"

The Windows Communication Foundation is a new framework for building distributed applications. In this session we'll take a look at the basics of getting an application up and running

Click here to watch the video online or here to download a zip file to watch offline

Windows Communication Foundation: Type Serialization

The WCF offers a number of different serialization technologies for turning .NET object types into XML for transmission across service boundaries. This session explores what's available.

Click here to watch the video online

Windows Communication Foundation: DataContract Serialization

The DataContract is the standard mechanism in the WCF for serializing .NET object types into XML. This session looks at the various options that DataContract makes available.

Click here to watch the video online

Windows Communication Foundation: Typed and Untyped Messages

The WCF has a lot of flexibility in the way in which it goes from .NET objects to SOAP messages. It can handle parameters and typed/untyped messages. Let's take a look.

Click here to watch the video online

Windows Communication Foundation: Bindings

A great deal of power and flexibility comes from the use of bindings in the WCF to specify communication details. Here we explore a little of the standard bindings and how we can configure them.

Click here to watch the video online

Windows Communication Foundation: Message Encoding

The WCF offers a flexible choice of mechanisms for turning a SOAP message into something that we can transmit between services. In this session we'll look at the options.

Click here to watch the video online

Windows Communication Foundation: Message Patterns

And you thought service communication was just request and response? This session looks at how we can use the WCF for one way and two way message exchanges.

Click here to watch the video online

Windows Communication Foundation: Sessions

The WCF has facilities for maintaining a session of messages between a client and a service. In this session we'll take a look at how we can make use of those facilities.

Click here to watch the video online

Windows Communication Foundation: Instancing

WCF services can be singletons, they can be single-call objects or they can have a lifetime that is tied to the session. Let's dive into how we make this work.

Click here to watch the video online

Windows Communication Foundation: Concurrency

In an server side development, concurrency always crops up and the WCF is no exception. Here we explore the options for single and multi-threaded services.

Click here to watch the video online

Windows Communication Foundation: Exceptions

Every piece of code needs to think about how to deal with exceptions - the WCF has particular mechanisms for translating .NET exceptions into SOAP faults which we explore here.

Click here to watch the video online

Windows Communication Foundation: Transactions

The WCF has facilities for coordinating work done by multiple pieces of software under a single atomic transaction. In this session we'll look at getting that set up and working.

Click here to watch the video online

Windows Communication Foundation: HTTPS Transport Security

The WCF provides transfer security for messages either by relying on the transport or by using message level mechanisms. In this session we'll look at using HTTPS at the transport layer to provide integrity, privacy and authentication for messages in transit.

Click here to watch the video online

Windows Communication Foundation: Message Security

The WCF provides transfer security for messages either by relying on the transport or by using message level mechanisms. In this session we'll look at using message security in order to perform authentication and provide privacy and integrity for messages.

Click here to watch the video online

Windows Communication Foundation: Authorisation

In this session we'll look at some basic mechanisms for authorising access to service operations that the WCF offers.

Click here to watch the video online

Windows Communication Foundation: Auditing

The WCF has facilities for auditing message authentication operations and service authorisation operations. In this session we'll look at how we can configure those facilities.

Click here to watch the video online

24 February, 2010

The Motivation behind WCF

Each of the previously examined distributed APIs can still be used directly within the .NET platform.
However, WCF provides a single unified model to access these previously diverse technologies. WCF
integrates the services of previous distributed technologies (COM+, .NET remoting, XML web services,
MSMQ, P2P, and so on) into a streamlined API. Without WCF, the wide array of distributed technologies
made it difficult to pick the right tool for the job.

The core problem was each API was an island unto itself (different programming models, different
fundamental data types, different ways to define contracts, among other issues). This was further
complicated by the fact that several of these technologies overlapped in the services they provide (i.e.,
providing numerous ways to do the same thing). Even when a .NET developer selected what appear to be the
‘correct’ technologies for the task at hand, maintaining and configuring such an application was complex at
best.

Although new, the WCF API builds on top of the success of previous concepts. As WCF is a SOA-based
system, WCF services look very similar to a traditional XML web service. WCF applications also borrow
several aspects found when building software making use of .NET remoting (*.config files, choice of
transportation layers and data persistence, and so on).

Beyond integration of diverse APIs, WCF provides a rich software fabric that complements the distributed
technologies it exposes, including the following examples:
• Support for strongly typed, as well as untyped, messages. This approach allows .NET
applications to share custom types simply and efficiently, while software created using other
platforms such as Java can consume streams of loosely typed XML.
• Support for several endpoints (raw HTTP, HTTP + SOAP, TCP, MSMQ, and named pipes) to
allow you to choose the most appropriate plumbing to transport data.
• Tracing, messaging, and performance counter APIs.
• Security APIs, including a new security feature named CardSpace (.NET 3.0 and higher).
• Transactional and peer-to-peer (P2P) APIs.

WCF Architecture




Contracts

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

- 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).


WCF Hosting

Windows Communication Foundation (WCF) Services can be hosted with Internet Information Services (IIS); with the new Windows Activation Service (WAS) installed with IIS 7.0; or with any managed application process including console, Windows Forms, Windows Presentation Foundation (WPF), or managed Windows service applications. Selecting the right hosting environment for your services is a choice driven largely by deployment requirements related to transport protocol and operating platform.

Beyond operating platform and choice of protocol, other features available to the hosting environment also influence deployment decisions and choice of host. This article describes the desired features of a hosting environment; provides you with an overview of WCF hosting options and their availability; and explains how to implement scenarios applicable to each environment.

WCF is part of the .NET Framework 3.0 stack and thus is supported on the following operating platforms: Windows XP/SP2, Windows Vista, Windows Server 2003, and Windows "Longhorn" Server. Regardless of platform, you can access WCF services over many protocols including HTTP, TCP, IPC and MSMQ. Unfortunately, not all hosting environments are available to each platform, nor does every host support the entire suite of protocols—limiting your options at times.

Features of a Great Host
Hosting environments make it possible to expose your services to client applications. They facilitate request processing to service operations, but they can also play a critical role in the availability and scalability of your services. A great hosting environment should provide these important features:

* Executable Process/Application Domain: You can use any managed process to host WCF services, which implies the existence of an application domain ("app domain").
* Configuration: A mechanism for external configuration should be available to support deployment and manageability. For managed hosts this is supplied by the application configuration file (app.config or web.config).
* Activation: Ultimately the service model instantiates the appropriate service type to handle incoming requests, but the host process must initialize the channel stack that receives incoming messages. You can do this activation at host startup but it is preferably done through message-based activation.
"Self-hosting is the simplest way to host your services-and the approach that yields the least number of hosting features."
* Idle-Time Management: To conserve server resources during idle time, hosts can release unused resources. Hosts that support this feature usually provide a configurable timeout. Idle-time management relies on the activation capabilities of the host to instantiate resources as needed.
* Health Monitoring: To ensure availability a host process must always be running to service requests. Some hosting environments can proactively monitor their processes to ensure a new host process is started when existing processes are unable to service requests.
* Process Recycling: To avoid problems associated with memory leaks or faulty code, some hosting environments support configurable process recycling to "freshen up" running host processes.
* Management Tools: Sophisticated hosting environments also provide tools for configuring hosting features for greater control and manageability. This toolset sometimes contains tools for monitoring the health and status of running host processes.

There are three types of hosting environments for WCF services: IIS, WAS, and self-hosting. The term "self-hosting" refers to any application that provides its own code to initialize the hosting environment. This includes console, Windows Forms, WPF, and managed Windows services. Table 1 provides a summary of these three hosting environments and the features they support.

Table 1: A summary of hosting options and supported features.



At a minimum, all WCF hosts provide an executable process and application domain in which services are loaded. They also provide support for external configuration. The remaining hosting features discussed here are built into IIS and WAS, but not provided by self-hosting environments. Despite this fact, self-hosting does have its value under the right circumstances.

In the sections to follow, I'll discuss how the service model exposes WCF services, and then I'll describe scenarios for self-hosting, IIS, and WAS.

18 February, 2010

Regarding WCF Question and Answers

What is three major points in WCF?
1) Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
2) Contract --- Specifies the interface between client and the server. It’s a simple interface with some attribute.
3) Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols

What is WCF?
The Windows Presentation Foundation (WPF) is a next generation graphics platform that is part of .NET 3.0 and .NET 3.5. It allows you to build advanced user interfaces that incorporate documents, media, 2D and 3D graphics, animations, and web-like characteristics. In just 24 sessions of one hour or less, you will be able to begin effectively using WPF to solve real-world problems, developing rich user interfaces in less time than you thought possible. Using a straightforward, step-by-step approach, each lesson builds on a real-world foundation forged in both technology and business matters, allowing you to learn the essentials of WPF from the ground up

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.


Difference between WCF and Web services?
Web Services
1.It Can be accessed only over HTTP
2.It works in stateless environment
WCF
WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service
What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server.

What is three major points in WCF?
We Should remember ABC.
Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols
Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute.

What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) 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.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
For more details, read http://msdn.microsoft.com/en-us/library/aa738737.aspx

What are various ways of hosting WCF Services?
There are three major ways of hosting a WCF services
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.

• Host in application domain or process provided by IIS Server.
• Host in Application domain and process provided by WAS (Windows Activation Service) Server.
What was the code name for WCF?
The code name of WCF was Indigo .
WCF is a unification of .NET framework communication technologies which unites the following technologies:-
NET remoting
MSMQ
Web services
COM+


What are the main components of WCF?
The main components of WCF are
1. Service class
2. Hosting environment
3. End point


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.

binding = "wsHttpBinding"
bindingConfiguration = "LongTimeout"
/>






If no timeout has been specified, the default is considered as 1 minute.

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);
}
Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name AddInt and AddDouble.



How to configure Reliability while communicating with WCF Services?

Reliability can be configured in the client config file by adding reliableSession under binding tag.



address = "net.tcp://localhost:8888/MyService"
binding = "netTcpBinding"
bindingConfiguration = "ReliableCommunication"
contract = "IMyContract"
/>










Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding

What is Transport and Message Reliability?
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.


What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like


address = "http://localhost:8000/MyService/"
binding = "wsHttpBinding"
contract = "IMyContract"
/>





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


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.

Service contracts

Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
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";
}
}
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.
DataContract - attribute used to define the class
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.
Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
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.


What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow
[transport]://[machine or domain][:optional port] format.
for example:
HTTP Address Format
http://localhost:8888
the way to read the above url is

"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.

TCP Address Format
net.tcp://localhost:8888/MyService

When a port number is not specified, the default port is 808:
net.tcp://localhost/MyService

NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format
net.pipe://localhost/MyPipe

We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.

MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService


How to define a service as REST based service in WCF?
WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.
The below code shows how to expose a RESTful service
[ServiceContract]
interface IStock
{
[OperationContract]
[WebGet]
int GetStock(string StockId);
}
By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.


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 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.
For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx


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)
For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx


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:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

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.

1. A user has a service with a one-way operation that includes a fault contract, and he
gets an exception when he tries to host the service. Why?
This happens because, to return faults, the service needs some form of a two-way communication channel in place, which is not the case with one-way operations.

2. A user has a service he wants to expose on the Internet, and it needs to send notifications
out to its consumers. Would the WCF Duplex MEP be a good choice for
implementing this?
No. The WCF Duplex MEP can be problematic to enable, even inside an enterprise.
Its implementation depends upon the service establishing a connection back to the consumer, which can’t happen in certain scenarios, such as when the client’s machine uses NAT behind a firewall. On the Internet, where you are never certain
where your consumers are coming from, this type of callback channel would rarely, if ever, work. When you factor in the security risks it could pose and the scalability concerns with the fact that callback channels require the presence of sessions
between client and service, it isn’t a feasible solution.


3. You have a Data contract specifying a Person class from which you derive a Customer class. Does a Customer object automatically have a Data contract as well?
No. The Data contract is not inherited, so any derived class, such as the Customer class, would have to be explicitly declared as having a Data contract as well.


4. Your company has its own proprietary authentication mechanism, and you are required to authenticate every message coming into the service. What is the best way to handle using this mechanism with WCF?
Likely the best way to handle this would be to design a Message contract that accepts these proprietary authentication tokens in the header.

5. Can you support the Rpc SOAP style by using the DataContractSerializer?
Yes. You need only adorn your service with the DataContractFormatAttribute and explicitly set the attribute’s Style property to OperationFormatStyle.Rpc.

6. What does the “ABCs of endpoints” refer to?
The ABCs of endpoints refers to the three required elements that comprise a service endpoint: address, binding, and contract.

7. Which standard binding could be used for a service that was designed to replace an existing ASMX Web service?
The basicHttpBinding standard binding was designed to expose a service as if it were an ASMX Web service. This enables you to support existing clients as applications are upgraded to WCF.

8. What is the main disadvantage of using IIS to host a service?
Using IIS to host your services means that you will not be able to support non-HTTP protocols such as TCP, named pipes, and MSMQ. You will have access to the many built-in features available with IIS such as process recycling and messagebased
activation.

9. Which file specifies the types that your service will expose in IIS?
Service types are exposed through IIS by using the service file. This file must have an .svc file extension and should reside in the application directory for your IIS hosting application. This file will include an @ServiceHost directive, which specifies
the service name and language for the service code files. These files should be located in an App_Code subdirectory.

1.) How does Windows Communication Foundation address Service Oriented Architecture (SOA)?
WCF is the first programming model built from the ground up to provide implicit service-oriented application development, enabling developers to work autonomously and build applications that are more version independent, thereby increasing application resilience to change.

2.) How to deal with operation overloading while exposing the WCF services?
By default overload operations are not supported in WSDL based
operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.

[ServiceContract]
interface Isum
{
[OperationContract(Name = "MultiplyInt")]
int Multiply(int arg1,int arg2);

[OperationContract(Name = "MultiplyDouble")]
double Multiply(double arg1,double arg2);
}


Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name MultiplyInt and MultiplyDouble.

3.) Is Windows Communication Foundation going to interoperate with my existing applications?
The current plan is for Windows Communication Foundation to provide wire-level interoperability with WSE3, System.Messaging, .NET Enterprise Services, and ASMX applications. With minimal or no changes to code, applications built with these technologies will be able to call Windows Communication Foundation services and be callable by Windows Communication Foundation services.


4.) How to configure Reliability while communicating with WCF Services?
Reliability can be configured in the client config file by adding reliableSession under binding tag.
Reliability is supported by following bindings only:
NetTcpBinding
WSHttpBindingWSFederationHttpBinding
WSDualHttpBinding

5.) Will Windows Communication Foundation applications interoperate with Web services built with other technologi
es?
Yes. By default,services built with WCF will communicate with other services based on the interoperable Web services specifications. This means that WCF services will communicate with any application built on an infrastructure that also conforms to these standards. Microsoft is deeply committed to p
latform interoperability and is an active member of key standards organizations defining the latest Web services standards.

6.) 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. If no timeout has been specified, the default is considered as 1 minute.

7.) What are the core components of an Windows Communication Foundation service?
A host environment—an application domain and process—in which the service runs;
A service class, implemented in C# or VB.NET or another CLR-based language that implements one or more methods;
One or more endpoints that allow clients to access the service.

8.) What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract.

15 February, 2010

List all network computers

Make the following code as a NetworkBrowser.cs
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections;
using System.Windows.Forms;

namespace ListNetworkComputers
{
#region NetworkBrowser CLASS
public sealed class NetworkBrowser
{
#region Dll Imports

[DllImport("Netapi32", CharSet = CharSet.Auto, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]

public static extern int NetServerEnum(
string ServerNane, // must be null
int dwLevel,
ref IntPtr pBuf,
int dwPrefMaxLen,
out int dwEntriesRead,
out int dwTotalEntries,
int dwServerType,
string domain, // null for login domain
out int dwResumeHandle
);

[DllImport("Netapi32", SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]

public static extern int NetApiBufferFree(
IntPtr pBuf);

[StructLayout(LayoutKind.Sequential)]
public struct _SERVER_INFO_100
{
internal int sv100_platform_id;
[MarshalAs(UnmanagedType.LPWStr)]
internal string sv100_name;
}
#endregion
#region Public Constructor

public NetworkBrowser()
{

}
#endregion
#region Public Methods

public ArrayList getNetworkComputers()
{
//local fields
ArrayList networkComputers = new ArrayList();
const int MAX_PREFERRED_LENGTH = -1;
int SV_TYPE_WORKSTATION = 1;
int SV_TYPE_SERVER = 2;
IntPtr buffer = IntPtr.Zero;
IntPtr tmpBuffer = IntPtr.Zero;
int entriesRead = 0;
int totalEntries = 0;
int resHandle = 0;
int sizeofINFO = Marshal.SizeOf(typeof(_SERVER_INFO_100));


try
{
int ret = NetServerEnum(null, 100, ref buffer, MAX_PREFERRED_LENGTH,
out entriesRead,
out totalEntries, SV_TYPE_WORKSTATION | SV_TYPE_SERVER, null, out
resHandle);
if (ret == 0)
{
for (int i = 0; i < totalEntries; i++)
{
tmpBuffer = new IntPtr((int)buffer + (i * sizeofINFO));
_SERVER_INFO_100 svrInfo = (_SERVER_INFO_100)
Marshal.PtrToStructure(tmpBuffer, typeof(_SERVER_INFO_100));
networkComputers.Add(svrInfo.sv100_name);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with acessing network computers in NetworkBrowser " +
"\r\n\r\n\r\n" + ex.Message,
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return null;
}
finally
{
NetApiBufferFree(buffer);
}
return networkComputers;

}
#endregion
}
#endregion
}


In the form add the combo box and put the name cmbNetworkComputers
In the form load add the following code

try
{
NetworkBrowser nb = new NetworkBrowser();
foreach (string pc in nb.getNetworkComputers())
{
cmbNetworkComputers.Items.Add(pc);

}
}
catch (Exception ex) {
MessageBox.Show("An error occurred trying to access the network computers", "error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}

OUTPUT:

Enable and Disable Ctrl+Alt+Delete

public void KillCtrlAltDelete()
{
RegistryKey regkey;
string keyValueInt = "1";
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";

try
{
regkey = Registry.CurrentUser.CreateSubKey(subKey);
regkey.SetValue("DisableTaskMgr", keyValueInt);
regkey.Close();
}
catch (Exception ex)
{

}
}

public void EnableCtrlAltDelete()
{
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
try
{
Registry.CurrentUser.DeleteSubKey(subKey);
}
catch( Exception ex)
{

}
}

Hide and Show TaskBar

Make this file as separate HandleTaskBar.cs and call the public method

using System;
using System.Runtime.InteropServices;

namespace FullScreenMode
{
internal class HandleTaskBar
{
private const int SWP_HIDEWINDOW = 0x0080;
private const int SWP_SHOWWINDOW = 0x0040;

public HandleTaskBar()
{
}

[DllImport("User32.dll", EntryPoint="FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);

[DllImport("User32.dll")]
private static extern int SetWindowPos(int hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);

public static void showTaskBar()
{
int hWnd = FindWindow("Shell_TrayWnd", "");
SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_SHOWWINDOW);
}

public static void hideTaskBar()
{
int hWnd = FindWindow("Shell_TrayWnd", "");
SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW);
}
}
}

Windows form fullscreen

Make this is as separate FullScreen.cs file

using System;
using System.Drawing;
using System.Windows.Forms;

namespace FullScreenMode
{
public class FullScreen
{
private Form _Form;
private FormWindowState _cWindowState;
private FormBorderStyle _cBorderStyle;
private Rectangle _cBounds;
private bool _FullScreen;

public FullScreen(Form form)
{
_Form = form;
_FullScreen = false;
}

private void ScreenMode()
{

// set full screen
if (!_FullScreen)
{
// Get the WinForm properties
_cBorderStyle = _Form.FormBorderStyle;
_cBounds = _Form.Bounds;
_cWindowState = _Form.WindowState;

// set to false to avoid site effect
_Form.Visible = false;

HandleTaskBar.hideTaskBar();

// set new properties
_Form.FormBorderStyle = FormBorderStyle.None;
_Form.WindowState = FormWindowState.Maximized;

_Form.Visible = true;
_FullScreen = true;
}
else // reset full screen
{
// reset the normal WinForm properties
// always set WinForm.Visible to false to avoid site effect
_Form.Visible = false;
_Form.WindowState = _cWindowState;
_Form.FormBorderStyle = _cBorderStyle;
_Form.Bounds = _cBounds;

HandleTaskBar.showTaskBar();

_Form.Visible = true;

// Not in full screen mode
_FullScreen = false;
}
}

public void ShowFullScreen()
{
ScreenMode();
}

public void ResetTaskBar()
{
HandleTaskBar.showTaskBar();
}
}
}

Use like Follow

from the form load or button click event call like

FullScreen fullScreen = new FullScreen(this);
fullScreen.ShowFullScreen();

MS Agent in .net

public const int FAILURE = -1;
public const int SUCCESS = 100;
private string strPath= AppDomain.CurrentDomain.BaseDirectory ;
private string strFileName = string.Empty;
IAgentCharacterEx CharacterEx=null;

private void ShowAgent()
{
strFileName = "\\"+ CBSelectStyle.SelectedItem.ToString() + ".acs";
AgentServer Srv = new AgentServer();
if (Srv == null)
MessageBox.Show("ERROR: Agent Server couldn't be started!");
IAgentEx SrvEx;
SrvEx = (IAgentEx) Srv;
int dwCharID=0, dwReqID=0;
try
{
String strAgentCharacterFile = null;
if (!strFileName.Equals(string.Empty))
strAgentCharacterFile = strPath + strFileName;
else
{
MessageBox.Show("Select Style");
return;
}

if (TxtSpeakInput.Text.Equals(string.Empty))
TxtSpeakInput.Text = "Please enter text in textbox";

//load the acs file
SrvEx.Load(strAgentCharacterFile, out dwCharID, out dwReqID);

}
catch (Exception)
{
MessageBox.Show("Failed to load Agent character! Exception details:");
}

SrvEx.GetCharacterEx(dwCharID, out CharacterEx);
//show the agent
CharacterEx.Show(0, out dwReqID);
}

private void HideAgent()
{
int dwReqID=0;

switch(strFileName.ToUpper() )
{
case "\\GENIE.ACS":
CharacterEx.Hide(0, out dwReqID);
break;
case "\\MERLIN.ACS":
CharacterEx.Hide(0, out dwReqID);
break;
case "\\PEEDY.ACS":
CharacterEx.Hide(0, out dwReqID);
break;
case "\\ROBBY.ACS":
CharacterEx.Hide(0, out dwReqID);
break;
case "\\Vrgirl.acs":
CharacterEx.Hide(0, out dwReqID);
break;
default :
break;
}
}


private void speakAgent()
{
AgentServer Srv = new AgentServer();
if (Srv == null)
MessageBox.Show("ERROR: Agent Server couldn't be started!");
IAgentEx SrvEx;
SrvEx = (IAgentEx) Srv;
int dwCharID=0, dwReqID=0;
try
{
String strAgentCharacterFile = null;
if (!strFileName.Equals(string.Empty))
strAgentCharacterFile = strPath + strFileName;
else
{
MessageBox.Show("Select Style");
return;
}

if (TxtSpeakInput.Text.Equals(string.Empty))
{
TxtSpeakInput.Text = "Please enter text in textbox";
}
SrvEx.Load(strAgentCharacterFile, out dwCharID, out dwReqID);
}
catch (Exception)
{
MessageBox.Show("Failed to load Agent character! Exception details:");
}

SrvEx.GetCharacterEx(dwCharID, out CharacterEx);
CharacterEx.Speak(TxtSpeakInput.Text, null, out dwReqID);
}

OUTPUT:


14 February, 2010

Encryption and Decryption

namespace RSACryptoPad
{
public class EncryptionThread
{
public static string EncryptData(string data, string password)
{
if (data == null)
throw new ArgumentNullException(Constants.dataMessage);
if (password == null)
throw new ArgumentNullException(Constants.passwordMessage);
byte[] encBytes = EncryptData(Encoding.UTF8.GetBytes(data), password, PaddingMode.ISO10126);
return Convert.ToBase64String(encBytes);
}

public static byte[] EncryptData(byte[] data, string password, PaddingMode paddingMode)
{
if (data == null || data.Length == 0)
throw new ArgumentNullException(Constants.dataMessage);
if (password == null)
throw new ArgumentNullException(Constants.passwordMessage);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes(Constants.UTF8GetBytes));
RijndaelManaged rm = new RijndaelManaged();
rm.Padding = paddingMode;
ICryptoTransform encryptor = rm.CreateEncryptor(pdb.GetBytes(16), pdb.GetBytes(16));
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream encStream = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
encStream.Write(data, 0, data.Length);
encStream.FlushFinalBlock();
return msEncrypt.ToArray();
}
}

public static string DecryptData(string data, string password)
{
if (data == null)
throw new ArgumentNullException(Constants.dataMessage);
if (password == null)
throw new ArgumentNullException(Constants.passwordMessage);
byte[] encBytes = Convert.FromBase64String(data);
byte[] decBytes = DecryptData(encBytes, password, PaddingMode.ISO10126);
return Encoding.UTF8.GetString(decBytes);
}

public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode)
{
if (data == null || data.Length == 0)
throw new ArgumentNullException(Constants.dataMessage);
if (password == null)
throw new ArgumentNullException(Constants.passwordMessage);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes(Constants.UTF8GetBytes));
RijndaelManaged rm = new RijndaelManaged();
rm.Padding = paddingMode;
ICryptoTransform decryptor = rm.CreateDecryptor(pdb.GetBytes(16), pdb.GetBytes(16));
using (MemoryStream msDecrypt = new MemoryStream(data))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
// Decrypted bytes will always be less then encrypted bytes, so len of encrypted data will be big enouph for buffer.
byte[] fromEncrypt = new byte[data.Length];
// Read as many bytes as possible.
int read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
if (read < fromEncrypt.Length)
{
// Return a byte array of proper size.
byte[] clearBytes = new byte[read];
Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read);
return clearBytes;
}
return fromEncrypt;
}
}
}
}

Get Hard Drive Volume Serial

public string GetVolumeSerial()
{
uint serNum = 0;
uint maxCompLen = 0;
StringBuilder VolLabel = new StringBuilder(256); // Label
UInt32 VolFlags = new UInt32();
StringBuilder FSName = new StringBuilder(256); // File System Name
string strDriveLetter = "C:\\"; // fix up the passed-in drive letter for the API call
long Ret = GetVolumeInformation(strDriveLetter, VolLabel, (UInt32)VolLabel.Capacity, ref serNum, ref maxCompLen, ref VolFlags, FSName, (UInt32)FSName.Capacity);
return Convert.ToString(serNum);
}

Get MAC Address

Before use this one include the
System.Management Reference

public string getMACAddr()
{
string MacAddress = "";
try
{
ManagementClass mc = new ManagementClass(managementclasspath);
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo[ipCheckingKey] == true)
{
// MessageBox.Show(mo["MacAddress"].ToString());
MacAddress = mo["MacAddress"].ToString();
break;
}
mo.Dispose();
}

//MacAddress = MacAddress.Replace(":", "-");
}
catch (System.Management.ManagementException Me)
{
MessageBox.Show(Me.Message);
}

return (MacAddress);
}

Get System IP Address

public string getIP()
{
//Get IP Address
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
return ipAddress.ToString();
}