Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Thursday, 20 February 2014

Glossary for WCF

Address
The location at which a WCF service can be found. The address incorporates a protocol and URI.

Not dependent on timing. Each application or command runs in the specified order, but the specified item does not wait for any previously started processes to finish before an application or command runs.

A method call that returns to the caller immediately regardless of whether processing has completed. The results of processing are returned through another call on another thread. Asynchronous methods free the caller from having to wait until processing has finished.

In .NET Framework security, the process of discovering and verifying the identity of a principal by examining the user's credentials against some authority.

In .NET Framework security, the process of limiting access rights by granting or denying specific permissions to an authenticated identity or principal.
B
Behavior
In WCF, a way of customizing the behavior of a client or service.

In WCF, the transport-level details that define how a client interacts with a service.
C
Claim
In security, claims are pieces of information held within a credential.

The behavior and state that a class provides, which is matched with what a client of that class can expect to hold. A contract is expressed partly by the signatures for all public fields, methods, properties, and events of that class. This is augmented by a description (usually in simple descriptive text) of what each field or property represents, together with what each method does.

In security, a credential carries information about a caller, and is used for authentication.
D
Duplex
When applied to a WCF contract, indicates independent two-way communication between client and service.
E
Encoder
A class that converts a message into bytes for transmission.

A combination of address, binding and contract.
N
NAT
Network Address Translator. Hardware or software that hides local network addresses behind a single IP address, translating incoming and outgoing packets as necessary.
S
SAML
Security Access Markup Language provides a way to attach credentials to a message.

In WCF, the way in which a message is secured. Transport mode uses the security of the transport, while message mode secures the message itself.

Applications that expose services through interfaces and contracts. Service oriented applications benefit from being loosely coupled.

A simple, XML-based protocol for exchanging structured and type information on the Web. The protocol contains no application or transport semantics, which makes it highly modular and extensible.
T
Transport

The underlying communication protocol. WCF supports three transports: HTTP, TCP and Named Pipes.

Introduction to WCF Security

How to Configure Message-Based Security

In this demo, we will see how to secure a Windows Communication Foundation Service.
We will also see how to use the service trace utility provided by the Windows SDK to inspect service messages.

Now, what we have here is a very simple application for applying customer credits. This application makes a call to a WCF service for performing the transaction.

And if we look at the application, we can see in the btnApplyCredit_Click event handler, that we are creating a request object which contains account, amount, and transaction ID information.

We then invoke the service and receive a response as to whether or not the transaction was approved.
Let’s run the application. Now we will enter an account number, an amount to be credited, hit apply, and we see that the transaction was successful.

Now let’s take a quick look at the service.

Our service utilizes data contracts for the request and response objects.

As to the service itself, we see that we have an ICredit that defines a credit account method.

Now, our credit service implements the ICredit interface, credit account simply takes the request passed in and creates a response that approves the transaction.

Let’s go enable encryption for our service and also view our service messages in the service trace viewer.
We will go to the binding, we will go to the security tab, and we will specify message level security.

Now, because we are working within a windows domain, we can leave the MessageClientCredentialType set to Windows, and allow Windows to handle the encryption scheme for us.

We will save the config, and now we will go set the security on our client.

We will go to the security tab, we will set the mode to message, just as we did for the service, and now we will enable MessageLogging under Diagnostics.

Once we have enabled message logging it will automatically create a diagnostic source and listener.
If we want to change the location of the output files, we can click on the listener link and change the name.
In this case, we will change it now to c:\wcf logs\credit_service.svclog.

Also, we are going to set message logging to log the entire message so that we can see both the header and the message content.

Now we can save our configuration changes, compile, and run the application.

Now we can see that the application runs successfully without throwing an exception and that our transaction was approved.

Now let’s take a look at our log file in the service trace utility.

When we look at the messages now, we can see that the data for our request and our response is no longer being passed in clear text, but is now encrypted.

So now we have taken care of encrypting our message. However, anyone can access our service, so let’s use WCF to secure the service so only authorised users can invoke it.

So what I am going to do now is add a using statement, for System.Security.Permissions, and now what I am going to do is set permissions on my credit account method, so that only those who are members of the service users group can access it.

And I will do this by using a principal permission attribute setting the security action to demand, and the role equal to service users.

Now because we are not a member of the service users group, the call to this method should fail at runtime.
I will save my application, recompile, then I will run my application; perform my transaction for one final time.
So now you see we have received a security exception because we did not have the proper permissions to invoke this method on the service.

Customizing WCF with Behaviors

How to Configure WCF Behaviors

In this demonstration, you will see how to apply the instancing attributes to your behaviors for your Windows Communication Foundation service. For this demonstration we have an existing application that consists of a service and a client.

The service is hosted on Internet Information Server as a web service.

We have two contracts, or two interfaces in our service, one is a calculator, which has the four standard mathematical methods, add, subtract, multiply, and divide.

We also have an ICalculator instance which implements the ICalculator and this will be responsible for providing us with our ContextMode InstanceId and operationCount values.

Notice that each one of these two contracts of the interfaces in our service have the SessionMode equals SessionMode.Required.

We specify this so that when a client accesses it, we indicate the necessary type of session mode that we wish in our service, and the client will then see that behavior from our service as it is executed.

So very quickly we will take a look at our CalculatorService class which implements our ICalculator instance interface, and we see that we have a static instanceCount variable, and we will see how that plays into our client application as we execute it and we will see those values increment accordingly.

The CalculatorService in the constructor will simply implement our instanceCount and sets the InstanceId equal to the instanceCount and then we have our four methods add, subtract, multiply, and divide, and then for our ICalculator instance, we implement the GetInstanceContextMode method here, our GetInstanceId method, and our GetOperationCount method in here.

So, one of the first things that we need to do is to make sure that we have the appropriate attribute uncommented in our code.

The first one we will make use of is the PerSession attribute, where the PerSession will create an instance per channel session.

So, if we take a look at our client application, it is a console based application, we create an instance of our calculator instance client.

We then get the instance mode from the GetInstanceContextMode, write that value out to our screen, and then start calling the methods and new calculations.

Notice in the first one, that we are using a client called client, so this is our first instance, and for the second instance we will have a client called client2.

We will call the new calculations with client1 and then client2, closing outer clients here, and writing out the necessary information to terminate the client information.

And the new calculations simply call each one of our operations, add service, subtract service, multiply service, we pass in the necessary values, we call the add method, or we call the subtract method as appropriate.

In our output we will write out values that we are going to be adding, subtracting, multiplying or dividing, the result. We will grab the client.InstanceId and GetOperationCount.

So, let’s go ahead and run our client application, and we will see what our first generated output results in.
So here we have used PerSession, as you can see, InstanceContextMode indicates PerSession, we see that we have called the add method, passed in the two values, got a result back, notice our InstanceId is one, and our operationCount is one.

So we have called add, subtract, multiply, and divide, all from instance one and we can see that with the instance IDs.

For each one of these same instances that we have called, we see that our operationCount increments.
Then we went ahead and used client2 to call the same methods again, notice that our instance ID has now changed to two, and that each of our operationCounts has been incremented again within that instance.
So you can see that we have really established two sessions here, and each one of the sessions maintained its own operationCount.

Let’s go ahead and terminate that client, we will come back to our service, and we will comment out the PerSession call and we will now change our attribute to a PerCall InstanceContextMode.
Note that when we change these because we have made changes in the actual attribute that is applied to the service, we need to rebuild that service one more time, and now we can go ahead and run our client application on a PerCall basis.

Notice that our InstanceContextMode indicates that we have executed a PerCall, and you will also note as we take a look at the InstanceId for each method call, regardless of the client that called it, the InstanceId has changed.

So each time we have made a call with a client, regardless of which client it was, we have actually generated a new InstanceId for each and every call.

Also take note, that because the instance changes for every call, the operationCount never gets incremented and always remains at zero. So, once again this is the client using the PerCall method.

Let’s go ahead and terminate that client. And for the final part, comment out our PerCall attribute, uncomment the Single, rebuild our service one more time, and we will start the client application again.
So our InstanceContextMode now, has been changed to Single, again we are still calling the same operations, but you will notice that regardless of the client that is making the call, and regardless of the method that is being called, our InstanceID remains at one, so this is a single instance that is servicing all clients, and you will also notice that the operationCount increments from beginning to end regardless of the number of clients that are actually calling it.

So if we were to add client3, and have client3 call one of these methods again, our InstanceID will still remain as one, but we would also notice the values of nine, ten, eleven, and twelve in our operationsCounts incremented.


So in this demonstration, you have seen how to apply the three different attributes to a service behaviour for your Windows Communication Foundation service.

Creating and Invoking a WCF Client

How to Create a Client by Generating a Proxy


In this demonstration you will see how to create a client application to access a Windows Communication Foundation Service by generating a proxy.

In our client application, we have a label, text box, and a button. When a user enters a name into the text box, and clicks the button, a message box will be displayed showing a greeting with a name entered into the text box.

We need to add a reference to our client application, and in order to do so, we need to have our Endpoint available. This requires us to go in and edit the service behavior that we created in our previous demonstration.

Another serviceMetadata element, we notice that our HttpGetEnabled tag is set to False. We need to enable that, so we will set it to True, save our changes, and come back to Visual Studio.

We will start the service application, and once our service application is up and running, we switch back to Visual Studio. We can now add a service reference to our client application.
We simply type in the URL that was specified in our service application, and provide a service namespace reference, and call this GreetingServices. And this will cause our client application to go and search to the endpoint that we have specified, locate the necessary metadata, and generate the appropriate proxy for us.

So you can see that our client application now contains a System.ServiceModel reference, as well as our new service reference GreetingServices.app.

The proxy has been generated for us automatically, GreetingServices.cs. And as we scroll through our code we can see that it has actually generated a greeting client partial class for us, and we can utilise that in our application.

So let’s go ahead and start debugging, and we will switch back to the code for our client application.

Let’s go ahead and add a using statement here, WCFClient.GreetingServices, so we will add that namespace.

Now we want to add a new proxy client variable, so we will call this GreetingClient proxy. We need to create the proxy to the service, so proxy equals new GreetingClient.

And you will notice that we have five options available to us for the constructor for our GreetingClient. For this demonstration, we are only going to use the default constructor.

So now that we have our proxy created, we are going to call the necessary service, and store the value into the response variable, so the response equals proxy.GetGreeting, and of course the value that we are concerned with, will be displayed in the text box txtName.

And we have a little catch block in the event that we have in the issue we are trying to get the data from our service. The message box will show the response, and of course, when our form is closing, we want to go through the process of closing out our proxy service, so we will close that here.

Now in order to make both of these function, we need to go and make some changes to our solution. We will set our start-up project, so we will have our client and our demo both starting simultaneously, save our changes, and let’s go ahead and run our application and see how it works.

So we see our services running in the background. Here is our client application.
So let’s say hello to Fred Flinstone this morning. We click on Display Greeting, an error message box pops up with the greeting displayed.

So that it is it for our client application that we have generated within Visual Studio. For finer control, Visual Studio also makes available the svcutil client. The svcutil is a tool that you can execute from the command line, and it contains multiple options based on the specific type of configuration you will want to create.

Notice that we have some common options available, some code generation, metadata export options, service validation options, metadata download options, XmlSerializer type generation options, and a few examples in Help file that will show you how to make use of the svcutil command.

This allows a much finer control over the generation of the proxy. For our purposes, in this demonstration, we are simply going to generate the same files that Visual Studio did. So we will use the svcutil connecting to our local host. Note that our service is actually still running.
We will connect to that endpoint, and we will have the svcutil go ahead and download the metadata from our service, and then it will generate the two files that we have available, the app.config and our Greeting.cs.

Notice that it is called an output config.

So if we use notepad to look at our Greeting.cs file, you can see that it has created the same code that was generated in Visual Studio.

We can also use notepad to view the output.config file, and see the values that were generated in the config that we would apply to our client application. This was generated using the svcutil class.


So in this demonstration you have seen how to create a client application for accessing your Windows Communication Foundation Service by generating proxy information.

Creating a WCF Service

How to Create a Basic WCF Service

In this demonstration you will see how to create a basic Window’s Communication Foundation service.
Let’s go ahead and create new console-based application using C# language called WCF demo.

We need to add a reference to the system.ServiceModel name space, as well as a using statement at the top of our code module.

Then we can get started by first creating an interface in our program, and we will call this interface IGreeting. IGreeting will contain one method GetGreeting that will return a string value and accept a string value.

In order to make our interface a contract for communication service, we need to apply the necessary attributes. In this case, we apply the ServiceContract attribute to the actual interface itself, and any methods that we have inside of our interface need to have the OperationContract attribute applied to those as well.

So now our interface is complete, and we essentially have the workings of our contract in place. We will now create a class called Greeting that will implement the IGreeting interface.

And we will add a functionality here to simply return a simple text string concatenated with the value that gets passed in, and we are all set to go ahead and start creating our service host.

So we will create a ServiceHost instance. Note that we have two options available here: we can use a singleton instance of an object, or we can get at the type of our specific service and utilize that.

We will use the typeofGreeting, and we will create a new URI because we are actually hosting this on our local machine. The URI will consist of local host with a port number, and of course, our service name.
We can now open our host, and we can let the user know that the host is actually up and running.

And we can inform the user how they can shut down our host, and wait for Visual Studio or the user rather to press the Enter key, and at which point in time, we will close our host and the service will shut down gracefully.

Now that we have completed writing the code for this, we need to go ahead and build our project so that we can actually create the executable file, which will be required in our next step.

So now that we have created that functionality, we need to go to our project and we need to add an App.config file.

So we will add the Application Configuration file to our project, and you will currently notice that App.config is very generic and only has the opening and closing tags with nothing in between.

We are going to go ahead now, and go through the process of running the Edit WCF Configuration wizard, which will allow us to apply the necessary settings to our App.config file.

The first step is to create a new service. This is where we had to build our project first so that our WCFDemo.exe does exist, and we can get at our service that we have created inside. Also note that we now want to look at the service contract that we will be using because we only created the one interface within our application with the attributes applied to it, IGreeting is the only one that shows up.

This time we will base our communication mode on TCP rather than HTTP. Again it was local host. We are going to specify a port of 1234 this time around, and Greeting is the address for the Endpoint of our particular service.

So the wizard has created that for us. We will click on finish. Note that we have our hosting Endpoints available.

We need to next create a Service Behavior, and our Service Behavior Configuration we are going to utilise the serviceMetadata element.

We will add the serviceMetadata element to our Service Behavior. Note that it is called NewBehavior. We come back up to our WCFDemo.Greeting service, apply the new behaviour to that, save the file, and then go back to Visual Studio and very quickly open our App.config file, and you can see the changes that have taken place inside our App.config file.


So let’s go ahead and run this and see how our application behaves. Currently we have no clients that will be accessing this. The service just simply comes up and runs. It says the service host is running, press ENTER to close the host, and we are finished.

WCF Questions & Answer

Q1. What is WCF?
WCF stands for Windows Communication Foundation. It is a Software development kit for developing services on Windows. WCF is introduced in .NET 3.0. in the System.ServiceModel namespace. WCF is based on basic concepts of Service oriented architecture (SOA)

Q2. What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points: Address,Binding and Contract.

Q3. Explain Address,Binding and contract for a WCF Service?
Address:Address defines where the service resides.
Binding:Binding defines how to communicate with the service.
Contract:Contract defines what is done by the service.

Q4. What are the various address format in WCF?
a)HTTP Address Format:--> http://localhost:
b)TCP Address Format:--> net.tcp://localhost:
c)MSMQ Address Format:--> net.msmq://localhost:

Q5. What are the types of binding available in WCF?
A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP,TCP etc and encoding may be text,binary etc. The popular types of binding may be as below:
a)BasicHttpBinding
b)NetTcpBinding
c)WSHttpBinding
d)NetMsmqBinding

Q6. What are the types of contract available in WCF?

The main contracts are:
a)Service Contract:Describes what operations the client can perform.
b)Operation Contract : defines the method inside Interface of Service.
c)Data Contract:Defines what data types are passed
d)Message Contract:Defines wheather a service can interact directly with messages

Q7. What are the various ways of hosting a WCF Service?
a)IIS b)Self Hosting c)WAS (Windows Activation Service)

Q8. WWhat is the proxy for WCF Service?

A proxy is a class by which a service client can Interact with the service.
By the use of proxy in the client application we are able to call the different methods exposed by the service


Q9. How can we create Proxy for the WCF Service?

We can create proxy using the tool svcutil.exe after creating the service.
We can use the following command at command line.
svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config

Q10.What is the difference between WCF Service and Web Service?
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.

Q11.What is DataContract and ServiceContract?Explain
Data represented by creating DataContract which expose the
data which will be transefered /consumend from the serive
to its clients.

**Operations which is the functions provided by this
service.

To write an operation on WCF,you have to write it as an
interface,This interface contains the "Signature" of the
methods tagged by ServiceContract attribute,and all methods
signature will be impelemtned on this interface tagged with
OperationContract attribute.

and to implement these serivce contract you have to create
a class which implement the interface and the actual
implementation will be on that class.


Code Below show How to create a Service Contract:
Code:

[ServiceContract]
Public Interface IEmpOperations
{
[OperationContract]
Decimal Get EmpSal(int EmpId);

}

Class MyEmp: IEmpOperations
{
Decimal Get EmpSal()
{
// Implementation of this method.
}
}

Difference between SOAP and RESTful Webservices

SOAP:

1. Developer View: Object oriented
2. Standards Based: Yes .

SOAP web services are based on SOAP and WS-* specifications

For acquiring security tokens,it uses WS-Trust.

For conveying security tokens, it uses WS-Security

For defining policy, it uses WS-Policy

For suppoting distributed ACID transactions, it uses WS-AtomicTransaction and WS-Coordination

For acquiring interface definitions, it uses WS-MetadataExchange

For providing end-to-end reliability, it uses WS-ReliableMessaging

For establishing security context, it uses WS-SecureConversation

3. Security: SSL, WS-Security .

WS-Security provides end-to-end security covering message integrity and authentication

4. Transactions : WS-AtomicTransaction
5. Reliability : WS-ReliableMessaging
6. Performance: Good
7. Caching : No
8. Message Size : Heavy, has SOAP and WS-* specific markup
9. Message Communication protocol : XML
10. Message Encoding :Yes

SOAP Web Services support text and binary encoding
11. Service Description :WSDL
12. Human intelligible Payload :No
13. Developer Tooling :Yes

Complexity of SOAP Web Services dictates the need for using frameworks to facilitate rapid application development.
14. Orientation :Wraps business logic
15. Abbreviation: SOAP stands for Simple Object Access Protocol
16. Who is using SOAP? Google seams to be consistent in implementing their web services to use SOAP, with the exception of Blogger, which uses XML-RPC. You will find SOAP web services in lots of enterprise software as well.
17. Simplicity: No
18. Transport protocol support: HTTP, SMTP, JMS

Multiple transport protocol support makes SOAP Web Services flexible

REST:

1. Developer View: Resource Oriented
2. Standards Based: No
3. Security: SSL
4. Transactions : No
5. Reliability :Application specific
6. Performance: Better

Caching and lower message payload makes RESTful web services performance efficient and scalable
7. Caching : GET operations can be cached
8. Message Size : Lightweight, no extra xml markup
9. Message Communication protocol : XML, JSON, other valid MIME type .

This flexibility of REST makes its extremely useful in providing consumer need specific message payloads
10. Message Encoding : No

RESTful encoding is limited to text
11. Service Description : No formal contract definition

In REST, no formal way to describe a service interface means more dependence on written documentation
12. Human intelligible Payload : Yes
13. Developer Tooling : Minimal or none

REST on the other hand due to its simplicity can be developed without any framework
14. Orientation : Accesses resources/data
15. Abbreviation: REST stands for Representational State Transfer
16. Who is using REST? All of Yahoo's web services use REST, including Flickr, del.icio.us API uses it, pubsub, bloglines, technorati, and both eBay, and Amazon have web services for both REST and SOAP.
17. Simplicity: Yes
18. Transport protocol support: HTTP


Areas where SOAP based WebServices is a great solution:


Asynchronous processing and invocation: If application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging etc.
Formal contracts: If both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
Stateful operations: If the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.

Areas where RESTful WebServices are a great choice:


Limited bandwidth and resources: Remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
Totally stateless operations: If an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is suitable.
Caching situations: If the information can be cached because of the totally stateless operation of the REST approach, this is perfect.