Friday, November 28, 2008

Top WF/WCF Sessions in PDC2008

There are still 21 days to go until the PDC. Are you excited to attend those fascinating technical sessions? You might have noticed that we have the following interesting sessions for WF/WCF as part of .NET Framework 4.0:

· WF 4.0: A First Look (Kenny Wolf)

· WCF 4.0: Building WCF Services with WF in Microsoft .NET 4.0 (Ed Pinto)

· WF 4.0: Extending with Custom Activities (Matt Winkler)

· WCF 4.0: Developing RESTful Services (Steve Maine)

· WPF/WF 4.0: Declarative Programming Using XAML (Rob Relyea/Daniel Roth)

· WCF: Zen of Performance and Scale (Nicholas Allen)

Through these talks, you will see how Microsoft is refreshing these technologies in the next release in .NET 4.0 by investing heavily on usability, modeling, performance, and scalability. There are also a bunch of other PDC talks which are related to WF/WCF. Enjoy it!

Orcas SP1 Improvement: Asynchronous WCF HTTP Module/Handler for IIS7 for Better Server Scalability

Introduction

As mentioned in my last blog entry, for IIS-hosted WCF services, WCF holds the worker thread coming from ASP.NET until the whole request is completed to avoid a Denial of Service (DOS) attack. I also mentioned that on Windows 2008 Server, IIS7 has introduced the following registry setting to provide request throttling for all incoming requests:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\2.0.50727.0]

“MaxConcurrentRequestsPerCpu”=dword:0000000c

Based on this, in Orcas SP1 (.NET 3.5 SP1), WCF has implemented the asynchronous HTTP Module/Handler to allow better server scalability for high latency requests.

Asynchronous WCF HTTP Module/Handler

Besides the existing synchronous WCF HTTP Module/Handler types, WCF introduced the asynchronous versions. Together, WCF has the following four types implemented:

· Synchronous Module:

System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

· Asynchronous Module (new):

System.ServiceModel.Activation.ServiceHttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

· Synchronous Handler:

System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

· Asynchronous Handler (new):

System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Asynchronous HTTP Module

The new type ServiceHttpModule implements the System.Web.IHttpModule and it registers the async event HttpApplication.AddOnPostAuthenticateRequestAsync with a pair of async handlers:

static public IAsyncResult BeginProcessRequest(object sender, EventArgs e, AsyncCallback cb, object extraData)

static public void EndProcessRequest(IAsyncResult ar)

When a request comes in, WCF does some validation and returns from BeginProcessRequest immediately after passing the request up to internal processing logic. In this way, the worker process is immediately released.

If the service operation is asynchronous and it is waiting for slow I/O operations, the whole stack does not hold any thread. The only performance concern would be the memory usage to hold objects used to process the request. This allows many concurrent requests to be served by WCF without using a lot of threads and thus greatly improves the scalability of the service. This is very helpful when completing each request takes significant amount of time and many clients are served. In some private testing, WCF can easily support more than 10K concurrent slow requests, which is not possible with the synchronous HttpModule.

Asynchronous HTTP Handler Factory

You might have already noticed that WCF implements the Handler Factory instead of the asynchronous Handler directly. This allows more flexibility in the future to support different types of HTTP Handlers. The ServiceHttpHandlerFactory creates a stateless asynchronous HTTP handler of the following type which implements System.Web.IHttpAsyncHandler:

System.ServiceModel.Activation.ServiceHttpHandler

It implements the pair of asynchronous request handlers:

public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)

public void EndProcessRequest(IAsyncResult result)

Default Installation – Synchronous Version

Though the asynchronous version of HTTP Module/Handler is added in this release, the default installation is still the synchronous version. Why is this?

First of all, you should not use asynchronous version of HTTP Module/Handler on Windows 2003 Server (with IIS6) without knowing the risk. If you have many clients, the service would be easily DOS attacked by too much memory usage due to huge amount of pending requests queued up in WCF transport layer without the throttling inside IIS/ASP.NET.

Because of the limitation on IIS6, WCF did not change the setup to switch to purely asynchronous due to the ramifications between IIS6 and IIS7 for this quick release. This means that in order to use the asynchronous version, you have to perform some manual registration.

Don’t worry, I have provided a private tool to do this registration for you.

WCF Module/Handler Registration Tool

You can find the simple tool called WcfAsyncWebUtil.exe attached in this blog. Here is the usage:

Usage: WcfAsyncWebUtil

Options:

/is

Install WCF Synchronous HTTP module and handler into IIS7 configuration

in Integrated Mode.

/ia

Install WCF Asynchronous HTTP module and handler into IIS7 configuration

in Integrated Mode.

/l

List WCF HTTP module and handler registered into IIS7 configuration in

Integrated Mode.

/t [ ]

Configure the throttling registry MaxConcurrentRequestsPerCpu for the ASP.NET

integrated pipeline to the value . Default is 100. This argument is

used together with /ia only

For example, if you want to register asynchronous HTTP Module/Handler with the ASP.NET throttling to be 1000, you can run the following command:

WcfAsyncWebUtil.exe /ia /t 1000

To list the installed WCF HTTP Module/Handler, you can run:

WcfAsyncWebUtil.exe /l

.NET 4.0, WF/WCF, and Oslo

Lately I have been quite busy working on .NET 4.0 which will be the next major side-by-side release of .NET Framework since .NET 2.0. It will be unveiled at PDC on October 27th. .NET 4.0 will be shipped together with the next version of Visual Studio.

As you know, Windows Workflow Foundation (WF) and Windows Communication Foundation (WCF) were first released in .NET 3.0. WF enables data-driven programming, or “code as data” inDon’s words. WCF provides a service-oriented programming model which enables easy, secure, and reliable communications for distributed applications. In .NET 3.5, WF and WCF were first integrated together through WorkflowServiceHost and message activities. .NET 4.0 will contain major improvements in both WF and WCF. The two will be integrated seamlessly together from the programming model to the runtime. Workflows and services are tightly coupled and both can be declaratively modeled by XAML. With the significant performance improvements in the runtime, the new workflow framework will enable a broad spectrum of model-driven programming scenarios.

By mentioning “model-driven” programming, you will see a general modeling platform to be unveiled at PDC: Oslo. As Doug said, Oslo contains three “simple” things: a visual tool helps building models, a new textual DSL language helps defining models, and a relational repository that stores models. XAML represented workflows and services are special models in this domain. Check for more details in the postings from Doug and Don.

WPF Bind to a Method

In this part we will bind to a method. As we type a number into a textbox the results will be displayed in label below it. For this example we use a class which figures out the area of a circle.


Let's start off with a class which calculates the area of a circle. This class has one function named CalculateArea.

Public Class Area

Public Function CalculateArea(ByVal Radius As Double) As Double
Return Math.PI * Radius ^ 2
End Function
End Class


Now that we have a class set up to calculate the area we need 2 additonal classes. The first needs to inherit from ValidationRule to alert the user if they enter an incorrect value (textbox's border turns red for invalid values). The other need to inherit from IValueConveter to convert the user input from string to double and back again.


Imports System.Windows.Controls
Imports System.Windows.Data

Public Class ValidDouble
Inherits ValidationRule


Public Overrides Function Validate(ByVal value As Object, ByVal cultureInfo As System.Globalization.CultureInfo) As System.Windows.Controls.ValidationResult
Dim num As Double

If Double.TryParse(value.ToString, num) Then
Return New ValidationResult(True, Nothing)
Else
Return New ValidationResult(False, "Invalid Number")
End If
End Function
End Class


Public Class DoubleToString
Implements IValueConverter

Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value IsNot Nothing Then
Return value.ToString
Else
Return Nothing
End If
End Function

Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Dim num As Double
If (value IsNot Nothing) AndAlso Double.TryParse(value.ToString, num) Then
Return num
Else
Return Nothing
End If
End Function
End Class

Now that we have the classes we need its time to register the namespaces with the form.


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFBindToMethod"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="WPFBindToMethod" Height="300" Width="300"
>
Finally we will use an ObjectDataProvider to bind to the method and register the ValidationRule with the form.



MethodName="CalculateArea" x:Key="CircleArea">

0







The Form's complete XAML



xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFBindToMethod"
xmlns:system="clr-namespace:System;assembly=mscorlib"
Title="WPFBindToMethod" Height="300" Width="300"
>

MethodName="CalculateArea" x:Key="CircleArea">

0


















BindsDirectlyToSource="true" UpdateSourceTrigger="PropertyChanged"
Converter="{StaticResource doubleToString}">









WPF OneWay Binding Part 3

In this part we will bind to a class. We will start off by creating a grid to display the properties of the class. Finally we will show how to get the form to update itself when a value changes in the class.


Lets start off creating a class that shows some info about the computer. Here is the class.

Public Class ComputerInfo

Public ReadOnly Property UserName() As String
Get
Return Environment.UserName
End Get
End Property
Public ReadOnly Property ComputerName() As String
Get
Return Environment.MachineName
End Get
End Property
Public ReadOnly Property UpTime() As Integer
Get
Return Environment.TickCount
End Get
End Property


End Class



Ok lets register the class with the form.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFOneWayBindToVariable"
Title="WPFOneWayBindToVariable" Height="300" Width="300"
>




Now lets create a grid with 2 columns and 3 rows to show the class in.












Lets put the data in the grid we just created.

WPF OneWay Binding Part 2

In the last part we bound a label to the value of the scrollbar. In this part we will format the scrollbar's value before we display it.


To be able to format the output of a bound value you need a class which inherits from IValueConverter. For this example I am using the NumbersToWords function found here to convert the number to a word for display.



Public Class NumberToWord
Implements IValueConverter


Private Function NumbersToWords(ByVal num As Decimal) As String
Dim power_value(5) As Decimal
Dim power_name(5) As String
Dim digits As Integer
Dim result As String
Dim i As Integer

' Initialize the power names and values.
power_name(1) = "trillion" : power_value(1) = 1000000000000.0#
power_name(2) = "billion" : power_value(2) = 1000000000
power_name(3) = "million" : power_value(3) = 1000000
power_name(4) = "thousand" : power_value(4) = 1000
power_name(5) = "" : power_value(5) = 1
For i = 1 To 5
' See if we have digits in this range.
If num >= power_value(i) Then
' Get the digits.
digits = Int(num / power_value(i))
' Add the digits to the result.
If Len(result) > 0 Then result = result & ", "
result = result & Words_1_999(digits) & " " & power_name(i)
' Get the number without these digits.
num = num - digits * power_value(i)
End If
Next i
NumbersToWords = Trim$(result)
End Function

' Return words for this value between 1 and 999.
Private Function Words_1_999(ByVal num As Integer) As String
Dim hundreds As Integer
Dim remainder As Integer
Dim result As String
hundreds = num \ 100
remainder = num - hundreds * 100
If hundreds > 0 Then
result = Words_1_19(hundreds) & " hundred "
End If
If remainder > 0 Then
result = result & Words_1_99(remainder)
End If
Words_1_999 = Trim$(result)
End Function

' Return a word for this value between 1 and 19.
Private Function Words_1_19(ByVal num As Integer) As String
Select Case num
Case 1
Words_1_19 = "one"
Case 2
Words_1_19 = "two"
Case 3
Words_1_19 = "three"
Case 4
Words_1_19 = "four"
Case 5
Words_1_19 = "five"
Case 6
Words_1_19 = "six"
Case 7
Words_1_19 = "seven"
Case 8
Words_1_19 = "eight"
Case 9
Words_1_19 = "nine"
Case 10
Words_1_19 = "ten"
Case 11
Words_1_19 = "eleven"
Case 12
Words_1_19 = "twelve"
Case 13
Words_1_19 = "thirteen"
Case 14
Words_1_19 = "fourteen"
Case 15
Words_1_19 = "fifteen"
Case 16
Words_1_19 = "sixteen"
Case 17
Words_1_19 = "seventeen"
Case 18
Words_1_19 = "eightteen"
Case 19
Words_1_19 = "nineteen"
Case Else
Words_1_19 = ""
End Select
End Function

' Return a word for this value between 1 and 99.
Private Function Words_1_99(ByVal num As Integer) As String
Dim result As String
Dim tens As Integer
tens = num \ 10
If tens <= 1 Then ' 1 <= num <= 19
result = result & " " & Words_1_19(num)
Else
' 20 <= num
' Get the tens digit word.
Select Case tens
Case 2
result = "twenty"
Case 3
result = "thirty"
Case 4
result = "forty"
Case 5
result = "fifty"
Case 6
result = "sixty"
Case 7
result = "seventy"
Case 8
result = "eighty"
Case 9
result = "ninety"
End Select
' Add the ones digit number.
result = result & " " & Words_1_19(num - tens * 10)
End If
Words_1_99 = Trim$(result)
End Function

Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
Dim d As Double
If Double.TryParse(value.ToString, d) Then
Return NumbersToWords(CDec(d))
Else
Return value
End If
End Function

Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Return Nothing
End Function
End Class

Now that we created the class we need to register the xml namespace with the window. The namespace you need to use for this is clr-namespace:NamespaceName. In this case it is the applications name. I am adding the local prefix so we can reference it later.


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFOneWayBind"
Title="WPFOneWayBind" Height="300" Width="300"
>

Now we need to make the converter a resource for the window.







Right after we set the path for the binding we can specify the converter. The converter is a StaticResource of the window.


WPF OneWay Binding Part 1

Windows Presentation Foundation (WPF) foundation is for building applications and experiences in Windows Vista that blend the application UI, documents, and media content. In this series of blog entries we willl start to explore some of the improvements to data binding in WPF. You will need to have the .Net Framework 3.0, Windows Vista SDK, and Visual Studio 2005 extensions for WPF and WCF installed for this sample.


For this example we will start off with a Windows Application (WPF). In the forms XMAL we will add a stack panel to hold a label and scrollbar. The label's content will be bound to the scrollbar's value so as we move the scrollbar the value will be displayed in the label.


In the Lets set up a DataContext which is bound to the scrollbar .