WCF Copyright © SUPINFO. All rights reserved WCF.

Post on 25-Dec-2015

260 views 8 download

Tags:

Transcript of WCF Copyright © SUPINFO. All rights reserved WCF.

WCF

www.supinfo.com

Copyright © SUPINFO. All rights reserved

WCF

Course Objectives

Understand how do Services work. Presentation, protocol and format.

Create and consume a Service in .NET. Creating, deploying and consuming them.

Optimize Services. By using cache, sessions…

After this course, you will be able to:

Services

Course Topics

Introduction. Protocol and formats used in Services.

Services in .NET. Creating, deploying and consuming Services in .NET.

Optimizing Services. By using cache, sessions…

This course is divided into the following sections:

Services

Service Basics

Introduction, protocol and format of services…

Services

Section Topics

Introduction to Services

SOAP Protocol

WSDL Format

UDDI Directory

We are going to walk through the following chapters:

Service Basics

Introduction to Services

A Service is a group of protocols and computer standards, used for exchanging data between applications.

— Wikipedia,

Service Basics

OOP complement

Used in processing and communicating with Services.

Objectives

Productive

Reactive

Capable of managing responsibility

SOA : Services Oriented Architecture

Service Basics

Introduction to Services

Based on 4 principals:

The borders are explicit.

The services are independent of one another.

Contracts are shared, but not objects.

Semantics are dictated by rules.

SOA : Services Oriented Architecture

Service Basics

Introduction to Services

Service Basics

Introduction to Services

Amazon

Internet

A service and clients communicates by messages.

A client sends a request, the server sends back a response.

Advantages:

Interoperability

Simplified access

Accessible data exchange format

Centralized arrangement

Disadvantages:

Poor performance

Ever-changing standards

Advantages and disadvantages of Services

Service Basics

Introduction to Services

Allows the transmission of structured and formatted data in messages between 2 distant objects.

Standard defined by W3C

Based on XML

Current version: 1.2

Service Basics

SOAP Protocol

SOAP ProtocolService Basics

Envelope:

is the root element of SOAP message.

contains no or several attributes.

contains

Header (optional)

Body (mandatory)

Composition of a message

SOAP ProtocolService Basics

Header :

Optional

Used for adding complementary information to the message

Contains arguments: actor, mustUnderstand…

Body :

Contains data of the message

Corresponds to the XML Schemas specified in the service contract.

Composition of a message

SOAP ProtocolService Basics

Example of a SOAP message

<soap:Envelope xmlns:"http://schemas.xmlsoap.org/soap/envelope"/><soap:Header>

</soap:Header><soap:Body>

</soap:Body></soap:Envelope>

WSDL Format

WSDL defines, in an abstract and independent way, a group of operations and messages which can be transmitted to and from a given Service.

— JDNet Developers,

Service Basics

WSDL FormatService Basics

Description language of Services in XML format

Used to draft a Service: describing functionalities

“how”

“where”

Current version: 2.0

Service Description Language

WSDL :A contract

Location

Operation’s description

Type Description

WSDL FormatServices Basics

WSDL FormatService Basics

WSDL skeleton

<definition><type />

<message><operation>

<message /></operation><portType>

<operation/></portType><binding>

<operation/></binding><service>

<port><binding/>

</port></service>

</definition>

UDDI DirectoryWhat is it?

Service Basics

Universal Description, Discovery and Integration

It is a directory of Services.

which is a Service itself.

It contains

information on service providers (contracts, activities…)

description on services(as part of the WSDL contract)

UDDI DirectoryService Basics

1. I am looking for a Service…

2. Tell you how to connect to it.

3. What is the format for messages?

4. Here is my WSDL contract.

5. I send my SOAP requests.

6. Result for the SOAP request.

How does it work?

Stop-and-Think

Do you have any questions?

Service Basics

Services in .NET

Creating, deploying and consuming Services in .NET.

Services

In .NET you can use:Introduction

WCF

WCF RIA Services

WCF Data Services

WCF and SOAIntroduction

Most developers do not have to learn WSDL

Lots of functionality is handled by the runtime

Tools to enable easy creation and consumption of services

WCF supports SOA:

Just because you have exposed an interface over a Web service protocol stack does not mean that you have created part of an SOA

WCF plays the role of distribution mechanism, while SOA comes in at a higher level

However:

PreviewWCF Basics

Section plan:

Service-Oriented Development with WCF

Sending a WCF Message

The ABC of Endpoints

Structure of a Service

A Unified Programming Model

Communicating with Non-WCF Services

A unified development model

WindowsCommunication

Foundation

Many confusing and complicated options

Remoting COMDCOM

COM+MSMQ

WSEASMX

A Unified Programming ModelWCF Basics

Service-Oriented Development with WCFWCF Basics

Over a network protocol

Create a service:

Contact the service to access one part of that functionality Use a service:

Clients and services communicate by passing messages

Not limited to one particular set of protocols

Aimed at clients and services that do not share the same address space

Service-oriented architecture is a bigger concept related to the style of the application and granularity of the services

Service

Where to find the service

Example: http://localhost:8001/MathService

Where to find the service

Example: http://localhost:8001/MathService

AddressAddress

How to communicate with the service

Example: BasicHttpBinding

How to communicate with the service

Example: BasicHttpBinding

BindingBinding

What the service can do for you

Example: [OperationContract]int Add(int num1, int num2);

What the service can do for you

Example: [OperationContract]int Add(int num1, int num2);

ContractContract

The ABC of endpointsWCF Basics

Client ServiceWCF

dispatcherProxy

Message EncodingEncoding

Transportchannel

Transportchannel

ChannelChannelChannelChannel

ChannelChannel

Transportchannel

Transportchannel

EncodingEncodingBindingBinding

ChannelChannelChannelChannel

ChannelChannel EndpointsEndpoints

Sending a WCF messageWCF Basics

Service

.NET Classesand Interface

ServiceHostService Contracts for

Domain Functionalityor Metadata Exchange

Structure of a serviceWCF Basics

Stop-and-think

Do you have any questions ?

WCF Basics

Using a Language-Level Interface as a Service Contract

Defining a service contract

Windows Communication Foundation

Example of a Simple Contract

The ServiceContract Attribute

The OperationContract Attribute

Data and Messages

Defining a data contract

PreviewDefining a service contract

Section plan:

using System;using System.ServiceModel;

namespace ServiceContracts{ [ServiceContract(Namespace="http://myuri.org/Hello") ] public interface IService { [OperationContract] HelloMessage GetHelloMessage(string name); }}

Principal namespace for WCF

Defining a service contract

Attributes control exposure of types and methods

Example of a Simple Contract

Defining a service contract

The ServiceContract attribute:

The ServiceContract attribute

Can be used on interfaces or classes

Is identified by tools and environments that understand WCF

Support services

Are analogous to interfaces on a polymorphic object – caller may not know or care about other contracts

Are only visible to clients if exported on an endpoint

Contains one or more operations

Service contracts:

Defining a service contract

Namespace serves to disambiguate types and operations in service metadata

The ServiceContract attribute

Defaults to http://tempuri.org

Not to be confused with language-level namespace

Defining a service contract

The OperationContract Attribute:

The OperationContract Attribute

Attribute can be used on methods but not other class elements, such as properties or indexers

Identified by tools and environments that understand WCF

Methods are only visible in service contract if marked with OperationContract

Defining a service contract

Data and messages

Parameters and return values must be marshaled between client and server

CLR types are mapped to XML Infoset by serialization

WCF enables you to define custom serialization

Serialized data is packed into the message

Contents and structure of message must be understood by client or service at the other end

Data and message contracts provide control overthese areas

Defining a service contract

Defining a data contract

using System;using System.Runtime.Serialization;

namespace DataContracts{ [DataContract] public class HelloMessage { private string _content;

[DataMember] public string Content { get { return _content; } set { this._content = value;} }}

Defining a service contract

Implementing a service contract

Define a class implementing the service contract

using System;using ServiceContracts;using DataContracts;

namespace ServiceImplementation{ public class HelloService : IService { public HelloMessage GetMessage(string name) { // Write implementation code here } }}

Stop-and-think

Do you have any questions ?

Defining a service contract

DemonstrationDefining a service contract

Service

contracts and

implementation

Hosting and Consuming a WCF Service

Windows Communication Foundation

Separation of Concerns in a WCF Service

Life Cycle of a Self-Hosted WCF Service

Consuming a WCF Service

Configuring a WCF Service Host and a client

Generating artifacts from service metadata

Hosting and Consuming a WCF Service

Preview

WCF Service HostWCF Service Library

Contract

Implementation

Configuration

WCF solution

Host code

Hosting and Consuming a WCF Service

Separation of Concerns in a WCF Service

Life Cycle of a Self-Hosted WCF Service

Hosting and Consuming a WCF Service

Using the namespace System.ServiceModel

Instantiate a Service Host object

System.ServiceModel.ServiceHost

Add a service endpoint with :

Contract

Binding

Address

Open the ServiceHost to start listening

11

22

33

Life Cycle of a Self-Hosted WCF Service

Hosting and Consuming a WCF Service

Prevent the ServiceHost from closing (i.e Console.ReadLine()

Close and dispose of the ServiceHost object

44

55

ServiceHost

Service type Address

Calling a WCF Service

Hosting and Consuming a WCF Service

A channel over which to pass messages

Transport channel at the bottom

The makeup of the channel derives from the binding

A client-side representation of the contract

Referencing the service contracts assembly

Generating artifacts from metadata

A way of creating WCF messages to pass across the channel and a way of retrieving message contents

An address for the WCF service

To call a WCF service, the client needs the following:

ServiceClass

ServiceInterface

ServiceMetadata

Implements

RunningService

ServiceProxy

Implements

ServiceAssembly

ProxyArtifacts

GenerateGenerateGenerateGenerate

GenerateGenerate

ServiceModel Metadata Utility Tool (Svcutil.exe) generates metadataand artifacts

ServiceModel Metadata Utility Tool (Svcutil.exe) generates metadataand artifacts

Hosting and Consuming a WCF Service

Contracts, metadata and artifacts

Consuming a service (1)

Hosting and Consuming a WCF Service

Using the ChannelFactory class

Reference the Service Contracts assembly

Instantiate a typed Channel Factory with the binding and the address of the service

System.ServiceModel.ChannelFactory<T>

T represents the type of the contract

Call the CreateChannel() method to contact the service and create a proxy

Start calling the methods…

11

22

33

44

DemonstrationHosting and Consuming a WCF Service

« First WCF

Demo »

File-based configuration

Hosting and Consuming a WCF Service

File-based configuration

You can use app.config, web.config, and machine.config files

You can change the WCF configuration without recompiling the assembly

Programmatic configuration

Provides greater control of your WCF configuration

Takes precedence over file-based configuration

Identifying WCF Entries in Configuration Files

Hosting and Consuming a WCF Service

Host configuration file

<system.serviceModel> <services> <service name=”ServiceImplementation.HelloService"> <endpoint address="http://localhost:1664/HelloService" binding="basicHttpBinding" contract="ServiceContract.IService"/> </service> </services></system.serviceModel>

<system.serviceModel> <client> <endpoint name="tcpEndpoint" address="http://localhost:1664/HelloService" binding="basicHttpBinding" contract="ServiceContract.IService"/> </client></system.serviceModel>

Client configuration file

DemonstrationHosting and Consuming a WCF Service

« Configuration 

»

WCF Service

MEX endpoint

WCF types

Artifacts

Hosting and Consuming a WCF Service

Obtaining Service Information

Obtain information from service metadata and generate artifacts

Obtain information and artifacts manually from service provider

Consuming a service (2)

Hosting and Consuming a WCF Service

Using generated artifacts – Mex (Metadata Exchange)

Add a reference to the service (“Add Service Reference”)

The tool Svcutil.exe generates code from the metadata of the service:

Proxy classes and interface

Instantiate a proxy service class object

Start calling the methods…

11

22

33

DemonstrationHosting and Consuming a WCF Service

« Mex »

Solutions to host a WCF Service

Windows Communication Foundation

Hosting a service in a self-managed Application

Hosting a service in a Windows Service

Hosting a service in IIS

Hosting a service in WAS

Solutions to host a WCF Service

Preview

Hosting a service

Solutions to host a WCF Service

Host environment

Typical functionality:

• Reads and understands WCF configuration settings

• Creates endpoints and listens for requests from remote clients

• Routes requests to an appropriate service instance

• Creates and destroys service instances

Additional functionality:

• Isolate different service instances from each other

• Serialize and re-activate unused service instances

• Manage pre-created pools of service instances

Service Hosting Options

Solutions to host a WCF Service

Self-hosted managed application

IIS

WAS

IIS and WAS offer the following improved hosting features:

Message-based activation

Process recycling

Idle shutdown

Process health monitoring

Windows Forms application

Windows Console application

Windows service

WPF application

Solutions to host a WCF Service

Hosting a WCF Service in a Self-Hosted Managed Application

Implementing a Self-Hosted Service

Solutions to host a WCF Service

Manually activated by starting process

Need to write your own hosting code

WCF configuration in the app.config file

Expose your WCF service over any protocol

Self-hosted service application

WCF configurationService host code

Hosting in a Windows Service

Solutions to host a WCF Service

Easily auto-started on startup

Manage process life cycle in the managementconsole snap-in

Subclass ServiceBase and override OnStart and OnStop

protected override void OnStart(string[] args){ //Instantiate the ServiceHost...}

protected override void OnStop(){ // Close the ServiceHost...}

DemonstrationSolutions to host a WCF Service

« Windows

Service

Deployment »

Implementing an IIS-Hosted Service

Solutions to host a WCF Service

Instances activated when messages arrive

No hosting code required from service developer

WCF configuration in web.config file

Limited to HTTP protocol

Need service file (.svc) containing ServiceHost directive to link IIS to service class

In its simplest form, you can store the service classes in the

App_Code sub directory

<%@ServiceHost Service="ServiceImplementation.HelloService"%>

DemonstrationSolutions to host a WCF Service

« IIS

Deployment »

Implementing a WAS-Hosted Service

Solutions to host a WCF Service

No hosting code required from service developer

WCF configuration in web.config file

Not limited to the HTTP protocol

Need service file (.svc) containing ServiceHost directive to link IIS to service class

<%@ServiceHost Service="ServiceImplementation.HelloService"%>

Configuring WAS

Solutions to host a WCF Service

Enable “WCF Non-Http Activation Components” Windows components

Bind desired Web site (usually default) to a non-HTTP port to support non-HTTP-based activation

appcmd set site "Default Web Site"-+bindings.[protocol='net.tcp',bindingInformation='9000:*']

appcmd set app "Default Web Site/BankService“ /enabledProtocols:http,net.tcp,net.pipe

Ultimately the service must leave the development environment

Deployment mechanism and process depends on type of service host

Preparing Services for Deployment

Solutions to host a WCF Service

Compile code

Install correct runtime

Check endpoint addresses Disable debugging

Deploying IIS-Hosted Services

Solutions to host a WCF Service

Deploying WAS-Hosted Services

Solutions to host a WCF Service

+Perform WAS setup:

1. Install components

2. Configure non-HTTP activation

Compile code

Install correct runtime

Check endpoint addresses

Disable debugging

Create a Windows Installer (MSI) for the classes

Register your Windows Service at installation time by using ServiceProcessInstaller and ServiceInstaller

Deploying Self-Hosted Services

Solutions to host a WCF Service

[RunInstaller(true)]public class ProjectInstaller : Installer{ private ServiceProcessInstaller process; private ServiceInstaller service;

public ProjectInstaller() { process = new ServiceProcessInstaller(); process.Account = ServiceAccount.LocalSystem; service = new ServiceInstaller(); service.ServiceName =  "HelloService"; Installers.Add(process); Installers.Add(service); }}

Stop-and-Think

Do you have any questions?

Services

For more…

CoursesBooks

Websites

http://www.dotnetguru.org

ASP.NET 2.0 Basics

Security and Customization of Web Applications

If you want to go into the topic more deeply,

http://www.asp.net

www.fnac.com

Services

http://stephaneey.developpez.com/tutoriel/dotnet/webservice/

Congratulations

You have successfully completed

Module 4

Services

End

Adopt Services for your distributed applications!

You have finished the modules ASP.NET 2.0 and Services!

Services