windows server 2008 – windows communication foundation dave allen isv application architect...

Post on 20-Dec-2015

221 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Windows Server 2008 – Windows Communication Foundation

Dave AllenISV Application ArchitectDeveloper and Platform GroupMicrosoft UK

Agenda

WCF ArchitectureContractsBindingsAddressBehavioursWindows Process Activation ServiceHosting WF from WCF in IIS 7.0

Client Service

Clients and Services

Message

EndpointEndpoint

Endpoint

Endpoint

CBA

CBA

ABC

CBA

AddressWhere?

ContractWhat?

BindingHow?

Endpoint

EndpointsAddress, Binding, Contract

Bv Bv Bv Bv

Behaviours

ServiceHost

ClientChannel

Runtime

Metadata

Contracts

Service ContractDescribes the service endpoints and the operations that can be performed on those endpoints.

Data ContractDescribes the message serialization. Maps CLR types to schema definition.

Message ContractDescribes structure of message on the wire. Provides control over the structure of the message.

[ServiceContract]public interface IHello{ [OperationContract] string Hello(string name);}

Service Contract

public class HelloService : IHello{ public string Hello(string name) { return “Hello ” + name; }}

[ServiceContract]public interface IIncomingMessage{ [OperationContract(IsOneWay=true)] void SendMessage(string name);}

Service Contract: OneWay

[ServiceContract(CallbackContract=typeof(IOutgoingMessage))]public interface IIncomingMessage{ [OperationContract(IsOneWay=true)] void SendMessage(string name);}

public interface IOutgoingMessage{ [OperationContract(IsOneWay=true)] void ReceiveMessage(string s);}

Service Contract: Duplex

[ServiceContract]public interface IHello{ [OperationContract] [FaultContract(typeof(InvalidNameException))] string Hello(string name);}

Service Contract: Faults

public string Hello(string name){ if(name != “Dave”) { throw new FaultException<InvalidNameException>( new InvalidNameException(“Wrong name")); }}

[ServiceContract]public interface IHello{ [OperationContract] string Hello(HelloMessage msg);}

Data Contract

[DataContract]public class HelloMessage{ [DataMember(Name=“From”)] public string from; [DataMember(Name=“From”, IsRequired=true)] public string to; [DataMember] public string message;}

Message Contract

[DataContract][MessageContract]public class HelloMessage{ [DataMember] [MessageBody] public string from; [DataMember] [MessageHeader] public string to; [DataMember] [MessageBody] public string message;}

Bindings

Transport

PipesMSMQ

Custom

TCP HTTP

Encoders

Binary

Text

Custom

BindingHTTP Text TXSecurity RM

MTOM

Protocol

WS-*

Custom

Standard Bindings

Interop Security

Session

Transactions

Duplex

Streaming

BasicHttpBinding BP 1.1 T

WsHttpBinding WS T | S X X

WsDualHttpBinding WS T | S X X X

NetTcpBinding .NET T | S X X X O

NetNamedPipesBinding .NET T | S X X X O

NetMsmqBinding .NET T | S X X

NetPeerTcpBinding .NET T | S X

T = Transport Security | S = WS-Security | O = One-Way Only

ASMX/WSE3 WCF

WCF ASMX/WSE3

Interop Bindings

MSMQ WCF

WCF MSMQ

WS-* Protocols

WS-* Protocols

MSMQ Protocol

MSMQ Protocol

MSMQBinding

MSMQBinding

Http/WSBinding

Http/WSBinding

WCF WCFWS-* Protocols *Binding

*Binding

Bindings have semanticsSession, Duplex, Transaction Flow, Transacted Read, Queued Delivery, Ordered, Assurances

Asserting Semantic Requirements in Code[ServiceContract][DeliveryRequirements]

Customization‘Tweak’ existing standard bindingsCreate completely new bindings

Choosing Bindings

Addresses

http://microsoft.com:80/OrderService/WShttps://microsoft.com:443/OrderService/BPnet.tcp://microsoft.com:808/OrderService/TCPnet.pipe://microsoft.com/OrderService/NP

Scheme http, https, net.tcp, net.pipe

Host Name microsoft.comPort (Optional) *

80, 443, 808

Base Path /OrderService/Endpoint Address

WS, BP, TCP, NP* - Port Does Not Apply to Named Pipes

Service Hosting Options

ServiceHost allows for hosting anywhereConsole applicationsWindows applicationsWindows services

IIS provides a scalable host environmentEdit a .svc file and point at your serviceOnly HTTP transports in IIS 6.0All transports in IIS 7.0 (Windows Process Activation Service)

class HelloHost{ static void Main (string[] args) { ServiceHost host = new ServiceHost(typeof(HelloService)); host.Open(); // Wait until done accepting connections Console.ReadLine(); host.Close(); }}

Service Hosting

<%@ServiceHost language=c# Service=“HelloService" %>

http://localhost/HelloService/HelloService.svc

Self-host

IIS-host

Service Configuration

<?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <services> <service name=“HelloService”> <endpoint address=“”

binding=“basicHttpBinding" contract="IHello" /> </service> </services> </system.serviceModel></configuration>

demo

Windows Communication Foundation

Behaviours

Behaviours cover the system semanticsService features

ConcurrencyInstancingTransactionsImpersonation

Deployment featuresThrottlingMetadata exposure

Instancing

Per Call

Single

Private Session

Shared Session

Concurrency

Multiple

Reentrant

Single

demo

Windows Communication Foundation

WAS Activation

Activation and health of worker process is managed by Windows Process Activation Service

Provides “external” monitoring and recycling Activate over TCP, Named Pipe, MSMQ, or HTTP

Provides high availability, managed process for web service based applications

WAS

In IIS 7.0, Windows Process Activation Service (WAS) manages application pool configuration and worker processes instead of WWW Service in IIS 6.0. This enables the same configuration and process model for HTTP and non-HTTP sites.Additionally, you can run WAS without WWW Service if you do not need HTTP functionality. For example, you can manage an WCF service through a listener, such as NET.TCP, without running the WWW Service if you do not need to listen for HTTP requests in HTTP.sys.

Enabling WAS

Adding net.tcp binding to IIS 7.0Add net.tcp binding to “Default Web Site”

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

Add a new applicationappcmd add app /site.name:"Default Web Site" /path:/WasDemo /physicalpath: c:\Inetpub\wwwRoot\WasApplication

Enable protocols for the applicationappcmd.exe set app "Default Web Site/WasApplication" /enabledProtocols: http,net.pipe,net.tcp,net.msmq

demo

Windows Communication Foundation

Hosting WF from WCF in IIS 7.0

Implement a ServiceHost extensionOverride Attach and Detach to start and stop the WorkflowRuntime

Derive a new ServiceHost that loads the loads the ServiceHost extensionDerive a new ServiceHostFactory to load the new ServiceHostAdd the Factory attribute to .svc file

demo

Windows Communication Foundation

.NET Framework 3.5 “Orcas”

WF & WCF IntegrationWCF partial trust supportWCF JSON Serialization

webHttpBinding to enableIntegrate with ASP.NET AJAX Framework

WCF POX/REST supportProgramming against resource-centric applicationswebHttpBinding to enable

WCF RSS/Atom supportAdd SyndicationBehavior to endpoint

Code Name “Orcas”

WCF Features Summary

Address Binding BehaviorContractHTTP

Transport

TCPTransport

NamedPipeTransport

MSMQTransport

CustomTransport

WS-SecurityProtocol

WS-RMProtocol

WS-CoordProtocol

DuplexChannel

CustomProtocol

http://...

net.tcp://...

net.pipe://...

net.msmq://...

xxx://...

ThrottlingBehavior

MetadataBehavior

Error Behavior

CustomBehavior

InstancingBehavior

ConcurrencyBehavior

TransactionBehavior

SecurityBehavior

Request/Response

One-Way

Duplex

net.p2p://...Peer

Transport

Externally visible,

per-endpoint

Opaque, per-service,endpoint, or operation

Resources

MSDN WCF home page http://msdn2.microsoft.com/en-us/netframework/aa663324.aspx WCF community site http://wcf.netfx3.com/ Great WAS article for developers http://msdn.microsoft.com/msdnmag/issues/07/09/WAS/

Windows Server 2008 – Windows Workflow Foundation

Windows Server 2008 – Windows Workflow Foundation

Dave AllenISV Application ArchitectDeveloper and Platform GroupMicrosoft UK

AgendaAgenda

What is Windows Workflow Foundation?Architecture & Core conceptsBuilding WorkflowsBuilding ActivitiesRuntime Services

Windows Workflow FoundationWindows Workflow Foundation

Single workflow technology for WindowsAvailable to all customers of WindowsAvailable for use across a broad range of scenarios

Redefining workflowExtensible framework & API to build workflow centric productsOne technology for human and system workflow

Take workflow mainstreamBring declarative workflow to any .NET developerFundamental part of the Office 2007Strong workflow partner & solution ecosystem

Windows Workflow Foundation is the programming model, engine and tools for quickly building workflow

enabled applications on Windows.

What is a workflow?What is a workflow?

A set of activities that coordinate people

and / or software...EscalateToManagerExample activities…. CheckInventory

Like a flowchart….

…organized into some form of workflow.

Or a state diagram…. or based on rules.

Windows Workflow FoundationWindows Workflow Foundation

Key Concepts

Host Process

WindowsWorkflow Foundation

Runtime Engine

A Workflow

An Activity

Runtime Services

Base Activity Library

Custom Activity Library

Visual Designer

Visual Designer: Graphical and code-based construction

Workflows are a set of ActivitiesWorkflows run within a Host Process: any application or serverDevelopers can build their own Custom Activity Libraries

Components

Base Activity Library: Out-of-box activities and base for custom activities

Runtime Engine: Workflow execution and state management

Runtime Services: Hosting flexibility and communication

Building a WorkflowBuilding a Workflow

Workflow Authoring ModesWorkflow Authoring Modes

.NET assembly• ctor defines

workflow

Markup Only“Declarative”

XOML

Markup andCode

C#/VB

Code Only ApplicationGenerated

XOML C#/VB

• XML definesworkflow structurelogic and data flow

• XML definesworkflow• Code-beside defines extra logic

• Code createsworkflowin constructor XOML C#/

VB

App creates activitytree and serializes

Workflow Compilerwfc.exe

C#/VB Compiler

Flexible Control FlowFlexible Control Flow

Rules-driven Activities

Step2

Step1Rule1

Rule2

DataRules + data statedrive processing order

• Data-driven• Simple Conditions, complex

Policies • Constrained Activity Group

State Machine Workflow

State2

State1Event

Event

External events drive processingorder

• Reactive, event-driven• Skip/re-work, exception

handling• Graph metaphor

Sequential WorkflowStep1

Step2

Sequentialstructure prescribesprocessing order

• Prescriptive, formal• Automation scenarios• Flowchart metaphor

Order Processing ExampleOrder Processing Example

On Order CreatedOn Order Processed

OrderCreated Order

Processed

OrderShipped

On Order Shipped

On Order Completed

On Order Completed

Waiting toCreate Order

On Order Completed

On Order Shipped

OrderCompleted

A State Machine WorkflowA State Machine Workflow

What are Activities?What are Activities?

An activity is a step in a workflowHas properties and events that are programmable within your workflow codeHas methods (e.g. Execute) that are only invoked by the workflow runtime

Think of Forms & ControlsActivity == ControlsWorkflows == Forms

Activities fall under two broad categoriesBasic – steps that “do work”Composite – manage a set of child activities

Base Activity LibraryBase Activity Library

Base Activities get you started…Designed for modeling control flow & communications

IfElse, Delay, While, State, etc.InvokeWebService, InvokeMethod, etc.

Custom activities can derive from the Base ActivitiesBase Activities have been built using the same framework that’s available to you as developers

Activities: An Extensible ApproachActivities: An Extensible Approach

OOB activities,workflow types,base typesGeneral-purposeActivity libraries define workflow constructs

Create/Extend/Compose activitiesApp-specificbuilding blocksFirst-class citizens

Base ActivityLibrary

Custom ActivityLibraries

Author new activity

Out-of-Box Activities

Extend activity

Compose activities

Vertical-specificactivities & workflowsBest-practice IP &Knowledge

Domain-SpecificWorkflow Packages

Compliance

RosettaNet

CRM

IT Mgmt

Why build custom activities?Why build custom activities?

Activity is unit of:ExecutionReuseComposition

Enable workflow modelingCustom activity examples

SendEmail, FileSystemEvent, etc.

Write custom activities forReusing workflow logicIntegrating with technologiesModeling advanced control flowsModeling various workflow styles

Simplicity

Flexibility

Code Activity

InvokeMethod &EventSinkCustom Activities

InvokeWebService Activity

Workflow Execution Logic

Example: A SendMail ActivityExample: A SendMail Activityusing System.Workflow.ComponentModel;public partial class SendMail : System.Workflow.ComponentModel.Activity{ public SendMail() { InitializeComponent(); } protected override Status Execute(ActivityExecutionContext context) { // logic here to send the email

return Status.Closed; }}public partial class SendMail{ public string subject; public string Subject { get { return subject; }

set { this.subject = value; } } private void InitializeComponent() // designer generated { this.ID = "SendMail"; }}

Activity Component ModelActivity Component Model

Each activity has an associated set of componentsComponents are associated through attributes on the Activity Definition

Required

Optional (defaults provided)

// Companion classes

[Designer(typeof(MyDesigner))]

[CodeGenerator(typeof(MyCodeGen))]

[Validator(typeof(MyValidator))]

// Behaviors

[SupportsTransaction]

public class MyActivity: Activity {...}

Activity

Code Generator

Designer

Validator

Serializer

Behaviors

Activity Definition ClassActivity Definition ClassClass that defines the activity’s properties, events and conditionsDefines how the activity manages stateTwo types of state:

Instance state: data is instance-specificMetadata state: data remains the same across all instances

State can be managed using fields, variable-backed properties, or Dependency PropertiesDependency Properties:

Used to support data bindingRequired for property promotionState is stored in a dictionaryUsed by the runtime to:

Serialize and manage stateIntercept the state changes made during execution

Building ActivitiesBuilding Activities

Activity Execution StatusActivity Execution Status

Returned by Execute() methodCan be determined by a parent activity or workflow

Activity.ExecutionStatus

Tracked by a Tracking Runtime ServiceActivityExecutionStatus Enumeration

InitializedExecutingCompensatingCancellingClosedFaulting

Activity ExecutionActivity Execution

Activity Execution MethodsInitialize()Execute()Cancel()Compensate()HandleFault()

Transition Types

ActivityRuntime

Initialized

Executing

Closed

Canceled Compensating

Faulted

Building Long-Running ActivitiesBuilding Long-Running Activities

Activity SummaryActivity Summary

An Activity is a key concept of Windows Workflow FoundationWF allows you to write custom activities to model your application control flow explicitlyActivities are the fundamental unit of:

Execution, Reuse, & Composition

Two broad types of activities:Basic & Composite

Activity Designer simplifies the development of custom activities – especially compositesSystem.Workflow.ComponentModel provides the framework to build custom activitiesCall to action: Write Activities!

Runtime ServicesRuntime Services

The workflow runtime is lightweightDepends on a set of services

Often you also want Transactions and Persistence

Add services programmatically or using a config file What ships in System.Workflow.Runtime.Hosting?

Concrete service implementationsDefaultWorkflowSchedulerService (asynchronous)ManualWorkflowSchedulerService (synchronous; for ASP.NET scenarios)DefaultWorkflowTransactionServiceSqlWorkflowPersistenceService

Runtime ServicesRuntime ServicesHost Application

App Domain

SQL

Out of Box Services are provided that support SQL Server 2000 & 2005

Common resource services for managing threading, timers and creating transactions

PersistenceService stores and retrieves instance state.TrackingService manages profiles and stores tracked information.

WF Runtime

Services

PersistenceService

TrackingService

SchedulerService

TransactionService

Out-of-Box ServicesOut-of-Box ServicesManualWorkflowSchedulerService

Synchronous threading service used for in-line execution; used by ASP module for web services

DefaultWorkflowSchedulerService

Used for asynchronous execution of workflows; uses default .Net thread pool

DefaultWorkflowTransactionService

Creates .NET transactions

SharedConnectionWorkflowTrans-actionService

Sql* services share connection to SqlServer

SqlStatePersistenceService

Stores workflow instance state information in SqlServer/MSDE

SqlTrackingService Stores tracking information in SqlServer/MSDE

Workflow State ManagementWorkflow State Management

Many workflows are long runningA workflow instance is idle when it has no runnable workPersistence services determine whether to unload the WF when idleLoading/unloading is not a concern of the workflow developer or the application developer

Persistence points are checkpointsTransactionsEnable crash recoveryPersistence occurs at:

Closure of a transactionClosure of any activity marked [PersistOnClose]Closure of the workflow

Enabling Workflow PersistenceEnabling Workflow PersistencePersistence Support for Workflow Instances

Create the SQL database with the SqlWorkflowStatePersistence schemaCreate a Workflow RuntimeDefine Connection StringRegister StatePersistenceService with RuntimeStart the WorkflowLoading and Unloading uses StatePersistenceService

private void RunWorkflow(){ WorkflowRuntime wr = new WorkflowRuntime(); string connectionstring = "Initial Catalog=Persistence;Data Source=localhost;Integrated Security=SSPI;";

wr.AddService(new SqlWorkflowStatePersistenceService(connectionstring));

wr.CreateWorkflow(typeof(SimpleWorkflow)).Start();}

Building Custom ServicesBuilding Custom Services

Hosting the Workflow DesignerHosting the Workflow Designer

SummarySummaryA single workflow technology for Windows

Platform level workflow framework for use within Microsoft products & ISV applicationsWill be used by BizTalk Server, Office 2007, MBS & other Microsoft client/server productsAvailable to all Windows customers

Microsoft is redefining workflowUnified technology for System & Human workflowMultiple styles: sequential, rules-based, state machineSupports dynamic interaction

Microsoft is taking workflow mainstreamConsistent and familiar programming model for reaching mainstream application developerAvailable to millions of end-users through Office 2007Extensible platform for ISVs

Community SiteSubscribe to the RSS feed for news & updatesFind, download, & register ActivitiesFind blogs, screencasts, whitepapers, and other resourcesDownload samples, tools, and runtime service componentshttp://wf.netfx3.com

MSDN® Workflow PageDownload 12 Hands-on Labshttp://msdn.microsoft.com/workflow

ForumsAsk questions in the forumsGo to the community site

Windows Workflow Foundation ResourcesWindows Workflow Foundation Resources

top related