Monday, May 3, 2010

Windows Phone Emulator

[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]
Windows Phone Emulator is a desktop application that emulates a Windows Phone OS 7.0 device. It provides a virtualized environment in which you can deploy, debug, and test applications. Windows Phone Emulator reduces the need to have a physical device for common application development scenarios. This can reduce the development cost of writing applications for Windows Phone. It also provides an isolated development-specific environment for early application prototypes.
Windows Phone Emulator is designed to provide comparable performance to an actual device and meet the peripheral specifications typically required for application development. However, it is expected that applications deployed to Marketplace be tested on an actual Windows Phone device.
Features

Windows Phone Emulator runs applications created for Windows Phone OS 7.0. Windows Phone Emulator enables the following features:
  • Emulation of device peripherals
  • Emulation of processor, RAM, display, and graphics processing unit (GPU).
  • Persistent store
  • Networking
  • Audio
  • Keyboard
  • Restoration to user-saved state
  • Deployment
  • Debugging
Requirements

For information about hardware and software requirements, see Setup and System Requirements for Windows Phone Emulator.
Backward Compatibility

Windows Phone Emulator is not backward compatible with Visual Studio 2005 or Visual Studio 2008. Also, it cannot load Windows Phone OS images earlier than Windows Phone OS 7.0.
Networking

Networking support is integrated with the Windows Phone Emulator. Networking is enabled by default. Therefore you do not have to install network drivers for Windows Phone Emulator or configure networking options in most environments. For information about how to use Windows Phone Emulator on a development computer that uses a proxy for Internet access, see Troubleshooting Network Connectivity on Windows Phone Emulator.
GPU Emulation

Windows Phone Emulator includes emulation for a graphics processing unit (GPU), if a GPU is present on the development computer. You need GPU emulation to support game applications that are based on XNA Framework. Some Silverlight application scenarios depend on GPU emulation for optimal performance. For more information, see Optimizing Performance of Windows Phone Emulator.
Hardware-assisted Virtualization

You can improve the performance of the emulator in some scenarios by using hardware-assisted virtualization. For more information, see Optimizing Performance of Windows Phone Emulator.
Media Support

Windows Phone Emulator supports the VC-1 format for video, and the .wma format for audio. The H.264 video format is not supported in the Windows Phone Emulator installed with Windows Phone Developer Tools CTP Refresh.
Configuration Options

The Windows Phone Emulator installed with Windows Phone Developer Tools CTP Refresh supports the following configuration options:
  • Changing from portrait to landscape mode
  • Changing the zoom setting to fit the emulator to your desktop screen
Related Topics

Setup and System Requirements for Windows Phone Emulator
Describes the hardware and software requirements for Windows Phone Emulator.
How to: Start Windows Phone Emulator
Describes how to start Windows Phone Emulator when you start an application, or independently.
How to: Stop and Restart an Application in Windows Phone Emulator
Describes how to stop and restart Windows Phone Emulator and maintain the current debugging session.
How to: Change the Orientation in Windows Phone Emulator
Describes how to change the orientation in Windows Phone Emulator to one of three orientations: portrait up, landscape left, or landscape right.
How to: Adjust the Zoom Setting in Windows Phone Emulator
Describes how to adjust the display size of Windows Phone Emulator to fit a particular screen.
Troubleshooting Windows Phone Emulator
Describes how to resolve general issues that may occur when you are using the Windows Phone Emulator.
Optimizing Performance of Windows Phone Emulator
Provides information that can be used to improve Windows Phone Emulator performance in many application scenarios.
Troubleshooting Network Connectivity on Windows Phone Emulator
Describes how to resolve network connectivity issues that can occur when you are using Windows Phone Emulator.

Thursday, December 17, 2009

How BizTalk Server Processes Large Messages What is a large message?

Unfortunately, the answer to this question isn't tied directly to a specific message size,
but rather, depends on specific bottlenecks in your Microsoft BizTalk Server 2006
system. The problems associated with large messages can be divided into the following
categories:

· Out of memory errors Certain types of message processing - such as mapping,
validation, and property promotion - load the entire message into memory. If
the size of the message in memory exceeds available resources, then an out of
memory error occurs. The size threshold for messages that fall into this category
is much lower than the size threshold for messages that are not loaded into
memory. For example, a 10 MB flat file that is parsed into XML and then mapped
may grow by a factor of 10 or more to consume over 100 MB of memory,
whereas a 100 MB XML document that is not parsed or mapped may actually
only consume 1 MB of memory as it is streamed to the MessageBox database.

· Performance problems for messages that are not loaded into memory
Messages that are not required to be loaded into memory are streamed to the
MessageBox database using the .NET XmlReader interface. While they are not
subject to the size limitations on messages that must be loaded into memory,
there are some important factors that impact how BizTalk Server processes
messages that are streamed to the MessageBox database.
Factors that affect the processing of large messages
The original message size, message format, and type of message processing all affect
how BizTalk Server processes large messages.
· Original message size The size of the message received by BizTalk Server is the
most visible indication of how large the message will be when it is processed by
BizTalk Server. The original size of a message has a much greater impact on
performance if the entire message is loaded into memory than if the message is
streamed to the MessageBox database.
· Message format Messages are received into BizTalk Server in one of two primary
formats: XML files or flat files.
o XML files In order for BizTalk Server to perform any processing on a
message other than pass through routing, the message must be in the
XML file format. If the files to be processed are received in XML format
then they will retain their original size for the most part.

1
o Flat files Flat files must be parsed into an XML format before BizTalk
Server can perform any processing other than pass through routing.
Parsing a flat file into an XML file can greatly increase the size of the file.
Flat files do not contain XML tags with descriptive information about
their data. XML files, on the other hand, wrap all of their data in
descriptive XML tags. In some scenarios parsing can increase the size of a
flat file by a factor of 10 or more, depending on how much descriptive
data is contained in the XML tags for the file.
o Flat file documents wrapped in a single CDATA section node in an XML
document This type of document is a combination of both XML and flat
file and can be problematic because BizTalk Sesrver must load the entire
wrapped flat file document into memory before processing it.

· Type of message processing In BizTalk Server, there are two types of message
processing: Routing only and Mapping. The performance variables tied to the
type of message processing that is performed are message size and whether the
message is loaded into memory.

o Routing only If BizTalk Server is only used only for routing messages
based upon promoted message properties, then the message is streamed
into the Messagebox database using the .NET XmlReader interface, and
message parts are not individually loaded into memory. In this scenario,
out of memory errors are not an issue and the primary consideration is
the amount of time that is required to write very large messages (over
100 MB) into the Messagebox database. The BizTalk Server development
team has successfully tested the processing of messages up to 1 GB in
size when performing routing only.

The primary factor that determines performance in this scenario is the
Large message fragment size used to fragment the data into the
database. The Large message fragment size is a configurable option on
the BizTalk Group Properties configuration page and has a default value
of 102400 bytes (100 KB). Increasing this value reduces the number of
round trips required to stream a message into the MessageBox database.
o Mapping Transforming a document with a map is a memory-intensive
operation. When a document is transformed by a map, BizTalk Server
passes the message stream to the .Net XslTransform class, which then
loads the document into a .NET XPathDocument object for processing.
Loading the document into the .NET XPathDocument can potentially
expand the original file size in memory by a factor of 10 or more. This
expansion may be more pronounced when mapping flat files because flat
files must be parsed into XML before they can be transformed.


2
BizTalk Server 2006 significantly improves memory management for large
documents by implementing a configurable message size threshold for
loading documents into memory during transforms. Any message with a
size below this threshold is handled in memory; any message with a size
above this threshold is buffered to the file system to reduce memory
requirements. The default message size threshold is 1 MB.
Guidelines for processing large messages
Follow these guidelines to improve performance when processing large messages in
BizTalk Server:

1. Adjust the message size threshold above which documents are buffered to the
file system during mapping. To modify the size threshold, create a DWORD value
named TransformThreshold at the following location in the BizTalk Server
registry:
HKLM\Software\Microsoft\BizTalk Server\3.0\Administration\TransformThreshold
After you have created this value, enter a decimal value with the number of
bytes to set the new threshold to. For example, enter a decimal value of
2097152 to increase the message size threshold to 2 MB (from the default of 1
MB). Increase this value on systems with a large amount of available memory to
improve throughput. Buffering documents to disk conserves memory at a cost to
overall throughput.

Note
By default, documents that are buffered to the file system during mapping are
written to the %temp% directory of the BizTalk Server computer. Change the
setting for the %temp% environment variable to a non-system disk to improve
performance when buffering large messages to the file system during mapping.

2. Minimize the use of maps in orchestrations:
o If you are using a map to extract or set properties used with business
logic in an orchestration, use distinguished fields or promoted properties
instead. When extracting or setting values with a map the document is
loaded into memory. When using distinguished fields or promoted
properties, the Orchestration engine accesses the message context and
does not load the document into memory.

3
o If you are using a map to aggregate several fields into one field, use
distinguished fields or promoted properties with an orchestration
variable to accumulate the result set.
o Do not configure an orchestration with multiple inputs to transform
shapes. An orchestration that contains multiple inputs to transform
shapes will not stream to the file system while mapping. This limitation
will cause the entire document that is being mapped to load into memory
if the document size exceeds the specified TransformThreshold registry
value. One possible workaround to this issue would be to apply
transforms at the receive port level so that the orchestration never
accepts more than a single input to transform shapes.

3. Adjust the Large message fragment size property exposed on the BizTalk Group
Properties configuration page:
If the in-memory size of a received message exceeds the number of bytes
specified for Large message fragment size then the message is split into
fragments of the specified size and the fragments are written into the
MessageBox under the context of a Microsoft Distributed Transaction
Coordinator (MSDTC) transaction as follows:.

1. If the incoming message is being published under the context of an
existing MSDTC transaction, then this transaction is used when writing
the message fragments to the MessageBox. For example if the incoming
message is being published by a transactional adapter configured to
require transactions then the existing transaction would be used when
writing the message fragments to the MessageBox.

2. If the incoming message is not being published under the context of an
existing MSDTC transaction, then a new MSDTC transaction is created to
write the message fragments.
o Increase the value for Large message fragment size to reduce the
frequency with which large messages are fragmented and reduce the
incidence of creating the associated MSDTC transactions. This should be
done because excessive use of MSDTC transactions is expensive from a
performance standpoint. Note that increasing this value may also
increase the amount of available memory that is used.

3 If it takes longer than the maximum allowable MSDTC transaction
timeout of 60 minutes to write a message to the MessageBox, then the
transaction times out, an error results, and the attempt to write the
message fails and is rolled back. The Large message fragment size value

4
should be increased enough to avoid this problem when processing very
large messages. Depending on available memory, this value should be
increased up to a maximum value of 1000000 bytes.
o Each message fragment in a message creates one or more SQL Server
database locks against the MessageBox database. When the number of
locks exceeds several hundred thousand, it is possible that SQL Server will
start generating “out of lock” errors. If this problem occurs, increase the
Large message fragment size to reduce the number of SQL Server
database locks made against the MessageBox database.

4. Consider housing your MessageBox database on a 64-bit version of SQL Server if
you are experiencing "out of lock" errors. The number of available locks is
significantly higher on the 64-bit version of SQL Server.

5. Adjust the Large message threshold property exposed on the BizTalk Group
Properties configuration page:
As a message batch is processed, if the in-memory size of a message batch
reaches the number of bytes specified for Large message threshold then the
portion of the message batch that has been processed is written to the
MessageBox before the remainder of the message batch is processed. This is
done under the context of an MSDTC transaction as follows:

1. If the message batch is being published under the context of an existing
MSDTC transaction, then this transaction is used when writing the
processed portion of the message batch to the MessageBox. For example
if the incoming message batch is being published by a transactional
adapter configured to require transactions then the existing transaction
would be used when writing the processed portion of the message batch
to the MessageBox.

2. If the message batch is not being published under the context of an
existing MSDTC transaction, then a new MSDTC transaction must be
created to write the portions of the message batch to the MessageBox.
The MSDTC transaction is used to ensure that all of the portions of a
given message batch are successfully written to the MessageBox
database.
The Large message threshold setting is directly applicable to message batches
but since a message batch can be set to a value of one, the Large message
threshold setting can also be indirectly applicable to individual messages. For
example when a message batch of one message exceeds the specified Large
5
message threshold parameter then the Large message threshold in effect
applies only to the single message in the batch.
o The Large message threshold parameter should be adjusted to mitigate
the creation of MSDTC transactions used to apportion message batches
to the MessageBox. This should be done because the excessive use of
MSDTC transactions is expensive from a performance standpoint. Use the
following calculation to determine what the minimum value for the Large
message threshold setting should be to avoid unnecessarily creating
MSDTC transactions:

Batch Size * Average size (in bytes) of each message in the batch after being processed
by the receive pipeline < Large message threshold
As long as the total size in bytes of a message batch does not exceed the
specified value for Large message threshold then there is no need for
BizTalk to initiate an MSDTC transaction to apportion the message batch
to the MessageBox database.
6

A Quick guide to handling exceptions in BizTalk Orchestrations

A Quick guide to handling exceptions in BizTalk Orchestrations
Introduction
Most of us have might have written code to handle exceptions in any programming language. In
BizTalk, exceptions are little bit different. This article explains how to handle exceptions and
notification mechanism in ports, using some simple scenarios.
Exceptions vs Delivery Notification
The Delivery Notification flag on the Send Port indicates that the orchestration must be
NOTIFIED back, in case the message has not been received by the destination. Delivery
Notification works only when the Retry Count set to 0. When a message cannot be delivered, a
DeliveryNotificationException is raised and the exception needs to be handled by the
Orchestration.
Scenario 1 : Sending a Sales Report...
Consider a scenario where a sales report needs to be uploaded to a Web service.
Assumptions
· If the Web service is not responding, it shall be online only after 24 hrs.
· The retry count and interval on the Web Service Port is set to "0".
If the Web service is not responding, an exception is raised, and is handled by sending the
message to an Offline folder.
Receive shape - Receives a Sales Report message.
Scope shape - A scope defines a context in BizTalk. A
scope is used to set a Transaction Type, in this case,
the TransactionType is set to "None". The scope's
Synchronized parameter is set to "true".
A Sales Report message is created, so as to tramit it to
the web service.
Note the properties of the Web Port which are marked
in "Red".
Delivery Notification - If a message fails to be
delivered on a Port, the "DeliveryFailureException" is
generated. Note that "Delivery Notification" is NOT
available for Binding property "Specify Now".
There are two kinds of Exceptions handled in this
orchestration.
· DeliveryFailure Exception
· General Exception
General Exception - In this case, the message which
needed to be sent to the Web Service, is written out
to an Offline Folder.
Important Note: DeliveryFailure Exception - This
exception is not thrown in this scenario, since a Web
Service Port is request-response port. This is reason
why the exception is handled in the General Exception
Event Log messages...
Observe the event log messages...
Scenario 2 : Raising the 'DeliveryFailureException' using a Dummy folder
In this scenario, we create a "Dummy" folder when messages need to be transmitted, and since
the Dummy folder does not exist, we handle an exception and send the messages to the Offline
folder.
section.
Receive shape - Receives a Sales Report message.
A Sales Report message is created, so as to transmit it
to the web service.
Scope shape - A scope defines a context in BizTalk. A
scope is used to set a Transaction Type, in this case,
the TransactionType is set to "None". The scope's
Synchronized parameter is set to "true".
Note the properties of the ReportDummyPort which
are marked in "Red".
Delivery Notification - If a message fails to be
delivered on a Port, the "DeliveryFailureException" is
generated. Note that "Delivery Notification" is NOT
available for Binding property "Specify Now".
There are two kinds of Exceptions handled in this
orchestration.
· DeliveryFailure Exception
· General Exception
A DeliveryFailure Exception is raised by the Port, since
the file path specified in the Dummy Port does not
exist. The exception handler handles the exception by
sending the message into the OfflineFolder. Notice
that in this case the DeliveryFailure Exception has
been correctly raised.
Event Log messages...
Observe the event log messages...
About the Downloadable Code
· Unzip the Web Service with the folder names into the C:\inetput\wwwroot directory
and setup the web service.
NOTE - Rename the Persist.asmxto Persist2.asmx so as to make it unavailable.
· Unzip the BizTalk project zip file with the folder names in the C:\ drive.
· The folder KeyAndBindings contains the Bindings.xml file, which can be imported after
the solution is built and deployed.
· Place the SalesMessage in the In folder and check the Offline folder.
Some Takeaways
1. Set the Synchronized property on the Scope shape to true, in the case you want to
handle exceptions.
2. Always select the "WebPortType" created when the "Web Reference" is added to the
project, while creating "Web Ports" in the Orchestration.
3. Delivery Notification is not available on Early Bound Ports.

Hosting WCF Services

Hosting WCF Services
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.
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.
" “Self-hosting is the simplest way to host your
services-and the approach that yields the least
number of hosting features.” "
Beyond operating platform and choice of protocol, other features available to the hosting environment
also influence deployment decisions and choice of host. In this article, I’ll describe the desired features of
a hosting environment; provide you with an overview of WCF hosting options and their availability; and
explain how to implement scenarios applicable to each environment.
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 messagebased
activation.
· 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.
1
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.
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, selfhosting
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.
ServiceHost
Regardless of the hosting environment, all WCF services must be associated with a ServiceHost instance to
be accessible at run time. ServiceHost is part of the System.ServiceModel namespace, and is the
centerpiece of the hosting story. A ServiceHost instance is initialized with information about the service
type, one or more service endpoints, optional base addresses, and behaviors that govern how the service
model processes requests to the service.
Initializing the ServiceHost
Listing 1 illustrates a simple example of a console host application initializing the ServiceHost
programmatically. In fact, this listing is the entire listing for the host application. The application
constructs a ServiceHost instance on startup, supplying the service type: HelloIndigo.HelloIndigoService. A
single endpoint is created exposing its HelloIndigo.IHelloIndigoService contract over NetTcpBinding. In this
example, the endpoint is initialized with a complete URI, removing the need for any base addresses.
After calling the Open() method the ServiceHost begins listening for messages. While the
Console.ReadLine() statement blocks the console application to keep the process alive, the application
processes incoming requests on their own thread taken from the thread pool. After closing the console,
the using statement disposes of the ServiceHost instance calling its Close() method. At this point new
requests are rejected while currently processing requests complete gracefully.
In this example, the console host only exposes one service. To expose multiple services, you can open
multiple ServiceHost instances within the same host process.
Table 1: A summary of hosting options and supported features.
Feature Self-Hosting IIS Hosting WAS Hosting
Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startupMessage-basedMessage-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes
2
Listing 1: Initializing the ServiceHost in a self-hosting scenario
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService)))
{
host.AddServiceEndpoint(typeof(
HelloIndigo.IHelloIndigoService), new NetTcpBinding(), "net.tcp://localhost:9000/HelloIndigo");
host.Open();
Console.WriteLine("Press to terminate the Host
application.");
Console.WriteLine();
Console.ReadLine();
}
}
Declarative Configuration
You can also initialize the ServiceHost declaratively via application configuration. In the
section you can specify one or more services in the section. Here is an
example of declarative service configuration:

"net.tcp://localhost:9000/HelloIndigoService"
binding="netTcpBinding"
contract="HelloIndigo.IHelloIndigoService" />

As with programmatic initialization, you must specify the service type and one or more endpoints. This
example illustrates how to configure a single endpoint similar to the code in Listing 1, with the addition of
a metadata exchange endpoint.
" “Processing requests on the UI thread is not
practical for services that require decent
throughput on the server. In fact, it is unlikely
that a service that processes significant requests
will even have a UI associated with it.” "
When you construct the ServiceHost instance it looks for a section matching its service type,
and initializes itself from those settings. Initializing the ServiceHost declaratively removes hard-coded
base addresses and endpoints from the code, as shown here:
using (ServiceHost host = new ServiceHost(
typeof(HelloIndigo.HelloIndigoService)))
{
host.Open();
// other code
3
}
Base Addresses
If you specify a fully qualified URI for each service endpoint, you do not need a base address to initialize
the ServiceHost. At run time, if you provide base addresses to the ServiceHost constructor you can
optionally provide a relative URI to the endpoint address as shown here:
using (ServiceHost host = new ServiceHost(
typeof(HelloIndigo.HelloIndigoService), new
Uri("net.tcp://localhost:9000")))
{
host.AddServiceEndpoint(
typeof(HelloIndigo.IHelloIndigoService),
new NetTcpBinding(),
"HelloIndigo");
host.Open();
// other code
}
Declaratively, the application provides base addresses in the section for the service configuration:




/>


contract="HelloIndigo.IHelloIndigoService" />
binding="mexHttpBinding"
contract="IMetadataExchange"/>

The ServiceHost builds endpoint addresses by appending the relative address of each endpoint to the
base address matching the endpoint’s binding protocol. For example, the NetTcpBinding endpoint shown
here uses the net.tcp base address while the MexHttpBinding metadata exchange (“mex”) endpoint uses
the http base address. If you omit the address from the configuration, the ServiceHost
assumes the base address to be the endpoint address.
Service Description
The ServiceHost instance is responsible for generating a service description for its service. This service
description incorporates information about the service type, all service endpoints, and any behaviors that
are attached to the service-exposing it through its Description property, a ServiceDescription instance.
4
ServiceDescription is part of the System.ServiceModel.Description namespace. It is a run-time abstraction
that ultimately generates the Web Service Description Language (WSDL) document for the service, and
supports interactive metadata exchange (WS-MetadataExchange) with clients. By default, the ServiceHost
uses reflection to generate the description-inspecting the service, its contracts, and relevant service
behaviors. Figure 1 illustrates how clients can use SvcUtil (svcutil.exe) or WS-MetadataExchange protocol
to initialize a channel at the client and consume a service.
Figure 1: The ServiceDescription generates the WSDL document and services WS-MetadataExchange
requests.
Under most circumstances you will not interact directly with the ServiceDescription. However, for
advanced scenarios you can control how the ServiceHost generates this ServiceDescription by subclassing
ServiceHost and overriding the CreateDescription() method.
ServiceHost Events
The ServiceHost notifies you of state changes in the channel stack through CommunicationObject events.
ServiceHost inherits ServiceHostBase, which inherits CommunicationObject. CommunicationObject is a
common base type for many objects participating in the communication channel-providing a common
state machine. The events it exposes include Opening, Opened, Closing, Closed, and Faulted.
Closing and Faulted are particularly useful for writing event logs or notifying administrators when the
communication channel for your service is closing or has encountered a problem. Just add these event
handlers to the ServiceHost instance before you open the communication channel, as shown here:
using (ServiceHost host = new ServiceHost(
typeof(HelloIndigo.HelloIndigoService)))
{
host.Closed += new EventHandler(host_Closed);
host.Closing +=new EventHandler(host_Closing);
5
host.Faulted +=new EventHandler(host_Faulted);
host.Open();
// other code
}
The ServiceHost also has a State property based on the CommunicationState enumeration. You can use
this property to detect the following states: Created, Opening, Opened, Closing, Closed, or Faulted.
Self-Hosting
Self-hosting is the simplest way to host your services-and the approach that yields the least number of
hosting features. As the label implies, self-hosting requires you to write the code necessary to initialize
the ServiceHost and manage its lifetime. At a minimum you provide a managed process, instantiate a
ServiceHost for each service, and then initialize and open them to provide a communication channel for
each endpoint to receive incoming messages.
" “Windows services are the most useful of the
self-hosting environments for WCF services. In
fact, for services deployed in a production server
system, Windows services are the only practical
self-hosting choice…” "
Typically you’ll keep ServiceHost instances alive for the lifetime of the application in which they are
hosted. Once you open the ServiceHost, the service model allocates a worker thread to process each
incoming request to its respective service endpoints. Your job is to keep the application alive as long as
you want to service those requests. Any managed application process will suffice including console,
Windows Forms, WPF, or managed Windows services as I discussed earlier.
In this section, I’ll walk you through the relevance of these self-hosting environments including scenarios
where they are most applicable.
Console Applications
Console applications are a popular hosting environment for developing and testing services. As I discussed
earlier, you need only create and open the ServiceHost instance and keep the console process alive to
receive and process requests. Listing 1 illustrates this.
A console application is ultimately impractical for deploying production services for a few reasons:
· It requires a user be logged in to the machine to start the process
· The console can be easily closed taking the communication channel along with it
Still, you can expect to see plenty of console hosts in sample code you download for WCF, and you will
likely use them to execute rudimentary tests on your services.
Windows Applications
Both Windows Forms and WPF applications can host WCF services associated with an application
interface. These scenarios might warrant this arrangement:
6
· Chat applications that participate in a peer mesh will expose services to receive broadcast
messages.
· Client applications may host services in-process to consume local services without crossing a
process boundary. For example, a smart client application may use local services when operating
offline and remote services while online (Figure 2).
· Services deployed to client or server machines may have an associated user interface if the
service presents an activity log or provides some administrative controls for service activation
and deactivation.
Figure 2: A Windows client hosting in-process WCF services for offline work, and consuming remote WCF
services over the Web while online.
Unlike console hosting, you can program a Windows application to avoid accidental shutdown with dialog
box interaction. However, these applications do require a user to be logged in to start the application-and
this limits their usefulness in server deployments. Managed Windows services solve this problem, and
may sometimes incorporate a user interface, so it is still important to understand the concurrency
implications of hosting services when UI threads are involved.
A simple way to host services in a Windows application is to process requests on the UI thread. This
means that the application processes requests through the Windows message loop, one at a time. In fact,
this is the default behavior if you construct the ServiceHost instance while running on the UI thread. For
example, the following code illustrates constructing the ServiceHost in the Form constructor for a
Windows Forms application:
public partial class Form1 : Form
{
public Form1()
{
7
InitializeComponent();
localhost.HelloIndigoServiceClient proxy = new
localhost.HelloIndigoServiceClient();
}
// other code
}
You can verify that the service is running on the UI thread by checking the Application.MessageLoop
property:
Debug.Assert(Application.MessageLoop);
While running on the message loop, service operations can freely interact with the user interface, setting
control and Form properties and so forth. The downside is that the message loop acts as a throttle for
message processing-even if the service were to allow multiple concurrent requests.
From the same Windows Form application if you were to construct the ServiceHost instance before
starting the UI thread, it will run on its own thread. That means worker threads allocated from the thread
pool process messages instead of the message loop. Thus, services can truly process multiple concurrent
requests.
One way to achieve this is to construct the ServiceHost during the Main() entry point for the Windows
application, before invoking Application.Run() as shown in Listing 2. You can see in the listing that the
application also handles the Application.Exit event to properly dispose of the ServiceHost instance. The
lifetime of the ServiceHost in this example is the duration of the application, not tied to a particular Form
instance. Closing the ServiceHost disposes the ServiceHost instance along with the thread in which it was
executed. In that case the application must recreate and open the ServiceHost in order to receive
subsequent requests.
Processing requests on the UI thread is not practical for services that require decent throughput on the
server. In fact, it is unlikely that a service that processes significant requests will even have a UI associated
with it. However, assuming you did want to attempt throughput and UI, you can configure your services
to run on a separate thread by setting the UseSynchronizationContext property to false for the
ServiceBehaviorAttribute.
[ServiceBehavior(UseSynchronizationContext=false)]
public class HelloIndigoService :
IHelloIndigoService
{
// service implementation
}
The default value for this property is true, which means that services will join the UI thread if the
ServiceHost is constructed on that thread. By setting this attribute to false your service will always process
requests on worker threads from the thread pool-regardless of where the application constructs the
ServiceHost.
Accepting requests on multiple threads introduces the potential for concurrency issues when service
operations or downstream code must interact with UI or shared resources. Since the UI will always be
running on another thread, you can’t directly interact with control or Form properties. Each control
8
(including the Form) has an InvokeRequired property that is set to true when the current thread is not the
same as the UI thread that owns the control. When true, you can use the same control’s Invoke() method
to invoke any members exposed by the control.
Listing 3 shows a service implementation that posts messages to a Windows Form when you call its
SendMessage() operation. In this case, the service is coupled to the user interface, so the static
constructor of the service type creates the Form and shares it between all running instances of the
service. If you close or dispose of the Form each service instance recreates the Form on demand. Although
not shown in this reduced listing (the code sample has a complete implementation) the service type also
provides a public ShowForm() method so that the host application can control the Form’s visibility.
When you call SendMessage(), it is running on a separate thread from the Form. The Form exposes a
public method, AddMessage(), which encapsulates the check for InvokeRequired before adding the string
to the ListBox control:
public void AddMessage(string message)
{
if (this.InvokeRequired)
{
MethodInvoker del = delegate
{
this.listBox1.Items.Add(message);
};
this.Invoke(del);
}
else
this.listBox1.Items.Add(message);
}
In a multithreaded environment, you must write code like this for all communication with control and
Form properties and methods. You can simplify this by encapsulating the functionality in the Form or in
custom thread-safe controls.
Aside from Form and control properties, you must also protect other shared resources when you allow
multiple threads into the service. For example, Listing 3 illustrates the use of the lock() statement to
protect access to the shared m_form reference. This statement applies a global lock to the Form instance
such that only one thread at a time can be interacting with any of its properties or methods. There are
other advanced synchronization techniques to increase throughput, such as Mutex, Semaphore, and other
WaitHandle types from the System.Threading.WaitHandle namespace.
Aside from throughput considerations that drive your decision to host services on the UI thread, or
provide multithreading support and manage concurrency, you should consider the following guidelines for
Windows application hosting:
· Decouple service and host implementation where possible, so that the service code is not tied to
a single host implementation.
· Where possible, the host should only provide UI related to hosting-that is, UI to control the
ServiceHost instance-not UI specific to the service functionality. Avoid having services talk
directly to host process UI.
9
· If the service is associated with UI, encapsulate the creation and display of this UI in the service
assembly, not the host. This reduces coupling between service and host. If applicable, services
can provide a mechanism for hosts to interact with service UI.
&
Listing 2: Initializing the ServiceHost on a separate thread in a Windows Forms application host
[STAThread]
static void Main()
{
Application.ApplicationExit +=new
EventHandler(Application_ApplicationExit);
Program.MyServiceHost = new
ServiceHost(typeof(HelloIndigo.HelloIndigoService));
Program.MyServiceHost.Open();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ApplicationExit(object sender, EventArgs e)
{
if (Program.MyServiceHost!=null)
{
Program.MyServiceHost.Close();
Program.MyServiceHost=null;
}
}
Listing 3: A service implementation that interacts with a Windows Form
[ServiceBehavior(UseSynchronizationContext=false)]
public class UIService : IUIService
{
private static ServiceForm m_form;
private static void CreateForm()
{
if (m_form==null || m_form.IsDisposed)
m_form= new ServiceForm();
}
static UIService()
{
m_form = new ServiceForm();
m_form.FormClosed +=new
10
System.Windows.Forms.FormClosedEventHandler(m_form_FormClosed);
}
static void m_form_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
{
lock(m_form)
{
m_form = null;
}
}
public void SendMessage(string message)
{
CreateForm();
m_form.AddMessage(message);
}
}
Managed Windows Services
Windows services are the most useful of the self-hosting environments for WCF services. In fact, for
services deployed in a production server system, the Windows service is the only practical self-hosting
choice for several reasons:
· Windows services can start when the system starts, without requiring a user to log in to the
machine.
· The Service Control Manager (SCM) provides an interface to manage service startup, restarts,
and other run behaviors-a custom user interface isn’t required.
· Services can restart after a failure, increasing overall availability.
To create a new Windows service application you can use the Windows Service application template. This
generates a Windows service class that inherits ServiceBase and overrides its OnStart() and OnStop()
methods. During OnStart() you should initialize and open your ServiceHost instances. During OnStop() you
should close all ServiceHost instances and stop processing messages. Listing 4 illustrates this
implementation.
"“One of the most important features IIS provides
your WCF services is message-based activation.”"
To install the Windows service you should also provide an installer class. Use the installer class to initialize
Service Control Manager (SCM) settings for the Windows service on installation. Listing 5 shows an
example of an installer class that provides a name and description for the Windows service, installs it to
run under the identity NETWORKSERVICE, and then sets it to start automatically when the machine starts.
To deploy the service you can run this installer using the Installer Tool (installutil.exe) as follows:
installutil.exe WindowsServiceHost.exe
In theory, the service shouldn’t stop unless something goes wrong, or an administrator explicitly stops it
through the SCM. Fortunately in the former case, you can also configure the service to restart on failure-a
necessary feature for an unattended server machine.
11
Though the hosting code is much the same as in other self-host environments I’ve discussed, there are
some special considerations for hosting WCF services in a Windows service:
· OnStart() must execute within 30 seconds or it will fail to start the service. If the startup code will
take longer to execute, you can implement a timer to delegate longer running initialization after
startup is complete. Simply initializing ServiceHost instances should fall within the 30-second
timeframe.
· OnStart() will record exceptions in the Event Log, but uncaught exceptions after startup may not
be recorded unless you explicitly catch the exception and record it.
· As with any hosting environment, the identity under which the Windows service runs will govern
the Windows resources its services have access to at run time. Your deployment scripts can
customize the account under which the service is configured if you don’t want to hard-code this
into the service installer.
On Windows Server 2003 machines the Windows service is the most reliable way to host WCF services for
access over named pipe, TCP, or MSMQ protocols. In particular, this would apply to scenarios such as
intranet applications, or distributed services behind the firewall as illustrated in Figure 3.
Figure 3: Hosting WCF services in a Windows service behind the firewall.
IIS 6.0 Hosting
12
If you expose WCF services over the Internet using HTTP protocol on a Windows Server 2003 machine, IIS
6.0 makes for a much richer hosting environment than self-hosting. Unlike self-hosting, you don’t need
code to instantiate ServiceHost instances, but you can still use declarative configuration in the
application’s web.config file. More importantly, IIS 6.0 provides other much-needed hosting features
making your service more reliable, available, and scalable.
In this section I’ll explain how IIS hosting works in general terms, discuss its distinct behaviors and added
value, and provide you with an architectural overview of the IIS 6.0 hosting environment.
IIS Service Endpoints
When you host your services with any version of IIS you must provide at a minimum the following:
· An addressable Web Site or Virtual Directory for your service endpoints.
· A file with the extension .svc that will represent the ServiceHost instance.
· A service type that is linked to the .svc file for activation.
When you create a new Web Site project in Visual Studio, a WCF Service project template is provided. This
template generates a project with a .svc endpoint, a sample service implementation, and a web.config
with the appropriate element to initialize the ServiceHost.
The .svc endpoint is the file that clients will address in their target URI to reach the service. It contains a
@ServiceHost directive that indicates the service type and if applicable the service source code in the
App_Code directory:
<% @ServiceHost Language=C# Debug="true"
Service="MyService"
CodeBehind="~/App_Code/Service.cs" %>
In reality, Visual Studio will compile your services into separate assemblies so your Web Site project must
reference those assemblies and the .svc endpoint will reference the type only through the Service
property of the @ServiceHost directive. For example, this Service.svc endpoint references the service type
HelloIndigo.HelloIndigoService:
<% @ServiceHost
Service="HelloIndigo.HelloIndigoService" %>
The service type specified in the @ServiceHost directive also tells the service model which
section to use from the web.config to initialize the ServiceHost instance. One of the distinctions between
self-hosting and IIS hosting is that the Web Site or Virtual Directory for the application provides the base
address. The section needn’t provide an address for each endpoint since the .svc file is the
endpoint:
name="HelloIndigo.HelloIndigoService" >
contract="HelloIndigo.IHelloIndigoService"
binding="wsHttpBinding"/>

Clients address the service using the .svc endpoint, for example:
13

address="http://localhost/IISHost/Service.svc"
binding="wsHttpBinding"
contract="Client.localhost.HelloIndigoContract">


In cases where you might want to expose multiple endpoints for the same .svc endpoint, you can use
relative addressing. This example illustrates a case where clients can access the same Service.svc endpoint
using BasicHttpBinding or WSHttpBinding to support different Web service protocols. The
configuration for the service uses relative addressing, appending “/Soap11” and “/Soap12” to the
endpoint address:

contract="HelloIndigo.IHelloIndigoService"
binding="basicHttpBinding"/>
contract="HelloIndigo.IHelloIndigoService"
binding="wsHttpBinding"/>

Clients address each service endpoint in this way:
http://localhost/IISHost/Service.svc/Soap11
http://localhost/IISHost/Service.svc/Soap12
Note: For file-based Web sites, Visual Studio uses the ASP.NET Development Web Server instead of IIS.
Endpoints function much the same as HTTP-based Web sites that are hosted in IIS, with the exception that
a dynamically generated port assignment will exist in the endpoint address. For example:
http://localhost:1260/FileBasedHost/Service.
svc.
&
Listing 4: ServiceHost initialization for a Windows services application
public partial class WindowsServiceHost : ServiceBase
{
ServiceHost m_serviceHost;
public WindowsServiceHost()
{
InitializeComponent();
14
// provide settings for the service
this.ServiceName = "WindowsServiceHost";
this.AutoLog=true;
this.CanPauseAndContinue=false;
this.CanShutdown=false;
this.CanStop=true;
}
protected override void OnStart(string[] args)
{
m_serviceHost = new
ServiceHost(typeof(HelloIndigo.HelloIndigoService));
m_serviceHost.Faulted +=new
EventHandler(m_serviceHost_Faulted);
m_serviceHost.Open();
this.EventLog.WriteEntry("ServiceHost is ready to receive
requests.", EventLogEntryType.Information, 0, 0);
}
void m_serviceHost_Faulted(object sender, EventArgs e)
{
this.EventLog.WriteEntry("ServiceHost has faulted.",
EventLogEntryType.Error, 0, 0);
}
protected override void OnStop()
{
try
{
if (m_serviceHost!=null)
m_serviceHost.Close();
this.EventLog.WriteEntry("ServiceHost has been closed.",
EventLogEntryType.Information, 0, 0);
}
catch
{
// Close() may fail if the ServiceHost is faulted, no
//need to throw another exception here
}
finally
{
m_serviceHost = null;
}
}
}
Listing 5: Installer class for a Windows services application
using System;
using System.ServiceProcess;
15
using System.ComponentModel;
using System.Configuration.Install;
[RunInstaller(true)]
public class WindowsServiceInstaller: Installer
{
public WindowsServiceInstaller()
{
ServiceProcessInstaller processInstaller = new
ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.NetworkService;
serviceInstaller.DisplayName ="WindowsServiceHost";
serviceInstaller.Description = "WCF service host.";
serviceInstaller.ServiceName="WindowsServiceHost";
serviceInstaller.StartType = ServiceStartMode.Automatic;
Installers.Add(processInstaller);
Installers.Add(serviceInstaller);
}
}
Message-Based Activation
One of the most important features IIS provides your WCF services is message-based activation.
ServiceHost instances need not be open prior to processing requests for a given endpoint. Instead, the
World Wide Web Publishing Service (WWW Service) is responsible for ensuring a worker process is
present to handle requests. Then, when IIS forwards requests for a particular .svc endpoint to the worker
process, the service model initializes the corresponding ServiceHost (if necessary), before dispatching the
request through the channel stack.
" “The WAS is a process activation service
installed with IIS 7.0 that decouples the
activation architecture from IIS in order to
support non-HTTP protocols such as named
pipes, TCP, and MSMQ.” "
There are many participants in this activation process:
· Microsoft introduced the HTTP Protocol Stack (http.sys) in IIS 6.0. It is a kernel-mode message
processing service that can receive messages even while worker processes are dormant. All
requests arrive and return through this service.
· WWW Service is responsible for launching worker processes on demand to handle requests. It
also determines the correct request queue (application pool) for http.sys to send messages for
processing. WWW Service is a Windows service that must be running for http.sys to successfully
forward requests.
· Ultimately, IIS forwards requests for .svc endpoints to an ASP.NET worker process, which looks to
its HTTP handler configuration ( section) to determine the correct runtime type to
process requests. In the case of .svc endpoints, the HttpHandler type from the
System.ServiceModel.Activation namespace handles requests.
16
Figure 4 illustrates how the IIS 6.0 architecture processes messages for WCF services. In fact, up to the
point when the service model’s HttpHandler takes over, the ASP.NET ISAPI extension (aspnet_isapi.dll)
handles the process much like any other HTTP request. What the service model’s HttpHandler does is
initialize ServiceHost instances as needed to process requests.
Figure 4: Services, processes, and core types involved in processing messages for WCF services.
This message-based activation process allows IIS to balance the number of worker processes required to
service request loads, releasing unused resources where appropriate. IIS also monitors the health of each
worker process and will launch a new, healthy worker process to service requests as needed. In addition,
you can configure IIS to periodically recycle worker processes to reduce the risk of resource and memory
leaks. These features improve the overall reliability and availability of your WCF services.
ASP.NET Compatibility Mode
Once you activate the ServiceHost, hosting a WCF service with IIS operates much the same as self-hosted
services. That is, the service model has a consistent way of processing requests. The ASP.NET processing
model is only involved as far as passing the request to the correct HTTP handler, the service model’s
HttpHandler type.
In fact, the service model has two modes for hosting WCF services:
· Mixed Transports Mode: This is the default hosting mode. In this mode the ASP.NET pipeline
does not process service requests. This makes it possible to expose endpoints for multiple
transports in a consistent manner.
· ASP.NET Compatibility Mode: This hosting mode restricts an application to HTTP services. When
you enable this mode, the features supplied by HTTP modules such as file and URL authorization,
session state, caching, and profile are available to the service. In addition, the hosting mode
initializes HttpContext.Current to provide access to ASP.NET-specific context.
17
In most cases, access to ASP.NET features and the HttpContext should not be necessary. The service
model provides a much richer set of authentication and authorization features that are more appropriate
for services. The service model also supplies a global OperationContext with access to contextual
information for the request including the security context, the request message and related headers, and
information about the hosting environment.
If you are porting existing ASP.NET Web services (ASMX), you may have existing code that relies on the
HttpContext or other ASP.NET features. For example, you may want to access the ASP.NET Session, Cache,
or Profile objects to provide a consistent run-time experience as you would have with ASMX. You can
enable ASP.NET compatibility by setting the aspNetCompabitilityEnabled property to true in the
section:

aspNetCompatibilityEnabled="true"/>

This makes it possible for your service code, or its downstream objects, to interact with these
aforementioned ASP.NET features. For example, you can write code that relies on the ASP.NET Profile.
Consider this section in the web.config:
automaticSaveEnabled="true">

defaultValue=""/>


Your service code could access it as follows, using the current HttpContext:
// set the culture preference
string culture =
HttpContext.Current.Profile["Culture"];
// get the culture preference
HttpContext.Current.Profile["Culture"] = culture;
Services can also require a hosting environment that supports ASP.NET compatibility by applying the
AspNetCompatibilityRequirementsAttribute from the System.ServiceModel.Activation namespace.
[AspNetCompatibilityRequirements(RequirementsMode=
AspNetCompatibilityRequirementsMode.Required)]
public class ProfileService : IProfileService
Other than porting ASMX services, you will most likely avoid using this feature in order to provide a
consistent hosting model for your services over multiple protocols.
IIS 7.0 and WAS Hosting
18
On Windows “Longhorn” Server machines, you can host your WCF services with the Windows Activation
Service (WAS). WAS is a process activation service installed with IIS 7.0 that decouples the activation
architecture from IIS in order to support non-HTTP protocols such as named pipes, TCP, and MSMQ. Like
IIS 6.0, WAS also provides features for idle-time management, health monitoring, process recycling, and
management tools for configuring application pools among other things.
In this section I’ll explain how WAS hosting works, show you how the hosting architecture compares to IIS
6.0 hosting, and provide you with some tips for getting started with WAS.
WAS Hosting Architecture
IIS 7.0 introduces some architectural changes necessary to expand support for named pipes, TCP, and
MSMQ protocols. The new architecture relies on protocol listeners, listener adapters, and protocol
handlers to process requests.
· Protocol Listeners: A protocol listener is responsible for receiving requests for a particular
protocol. There is a protocol listener provided for HTTP, named pipes, TCP, and MSMQ. For HTTP,
the HTTP listener is http.sys (same as in IIS 6.0). Listeners for other protocols are provided by
their respective listener adapter service.
· Listener Adapters: A listener adapter is responsible for bridging requests between WAS and the
worker process for a particular protocol. There is a listener adapter for HTTP, named pipes, TCP,
and MSMQ. WWW Service provides the HTTP listener adapter. IIS provides Windows services for
each of the other protocols, supplying a protocol listener and listener adapter pair (Figure 5).
· Protocol Handlers: A protocol handler channels requests through the service model for a
particular protocol. WCF provides managed protocol handlers for HTTP, named pipes, TCP, and
MSMQ.
Figure 5: How listener adapters and protocol handlers process requests with WAS hosting.
As each protocol listener receives requests, WAS checks for the existence of a worker process to service
the request (according to application pool configuration). The listener adapter’s job is then to pull
19
requests from the application pool queue and forward to the appropriate protocol handler for processing.
Figure 5 illustrates this architecture and flow.
To support this new architecture there are two services:
· Windows Activation Service (WAS): This service handles configuration, application pooling, and
process activation for all protocols.
· WWW Service: This service provides the listener adapter for the HTTP listener, http.sys.
Table 2 shows these and other services that support the architecture shown in Figure 5. Ultimately, it’s
the protocol handler provided by WCF that ensures the ServiceHost instance has been created before
requests can be processed.
Regardless of protocol, the service model handles all requests in a consistent manner, but WAS provides a
message-based activation mechanism like IIS 6.0 to increase the overall reliability and scalability for
requests over any protocol.
Enabling WAS
You’ll need to perform a few steps to configure IIS 7.0 and WAS before you can successfully host WCF
services over any protocol. As you would with IIS 6.0, you’ll first have to make sure the machine has IIS 7.0
and WAS installed. With these Windows components installed you can configure WAS for the protocols
you want to support for each Web site.
IIS provides a new command-line utility to configure Web sites-appcmd.exe. HTTP protocol is supported
by default, but with this utility you can enable support for named pipes, TCP, or MSMQ for any Web site
or application directory. The following illustrates enabling named pipes, TCP, and MSMQ support for the
default Web site:
%windir%\system32\inetsrv\appcmd.exe set site
"Default Web Site" -+bindings.[protocol=
'net.pipe',bindingInformation='*']
%windir%\system32\inetsrv\appcmd.exe set site
"Default Web Site" -+bindings.[protocol=
'net.tcp',bindingInformation='*']
%windir%\system32\inetsrv\appcmd.exe set site
"Default Web Site" -+bindings.[protocol=
'net.msmq',bindingInformation='*']
After executing these commands, IIS updates the configuration file for WAS, applicationHost.config, with
new entries for the Web site. IIS nests site configuration inside the
section as shown here:




bindingInformation="*:80:" />
20
bindingInformation="*" />
bindingInformation="*" />
bindingInformation="*" />




This section governs what protocols the Web site and WCF services can support. Put another way,
services can only expose endpoints that use service model bindings matching the supported protocols for
the application.
Choosing the Right Hosting Environment
As I mentioned at the beginning of this article, choosing a hosting environment for your services is
something that is largely driven by your operating platform and choice of protocol. Now that you’ve had a
chance to explore the different hosting environments, you can probably guess that the best possible
hosting environment would be WAS for its rich set of features and protocol support. Unfortunately, WAS
is only available on Windows Vista or Windows “Longhorn” Server machines.
Table 3 summarizes the hosting options available to you on each operating platform, including client and
server platforms. Based on this summary, you will likely make one of these choices for your production
services on each server platform:
· For Windows “Longhorn” Server machines you’ll use IIS 7.0 and WAS.
· For Windows Server 2003 machines you’ll use IIS 6.0 for HTTP and Windows services for other
protocols.
For client systems the choice is a little bit more complex. In-process services introduce the least
configuration overhead for clients, thus you’ll be using Windows Forms or WPF clients as your self-hosting
environment. If the system is a complex, distributed system where you have significant control over
setup, you may install Windows services to provide services for Windows XP machines. For Windows Vista
machines your choice of self-hosting with Windows services or enabling WAS may be governed by client
preferences.
Table 3: A summary of hosting options based on operating platform and communication protocol.
Operating Platform Protocol Hosting Options
Windows XP/SP2 HTTP IIS 5.1 or self-host
Named Pipes, TCP, MSMQ Self-host
Windows Vista HTTP, Named Pipes, TCP, MSMQWAS or self-host
Windows Server 2003 HTTP IIS 6.0
Named Pipes, TCP, MSMQ Self-host
21
Windows “Longhorn” Server HTTP, Named Pipes, TCP, MSMQIIS 7.0/WAS or self-host
http://www.code-magazine.com/Article.aspx?quickid=0701041
22

Tuesday, October 27, 2009

Building a Complete Certificate Scenario With BizTalk Server 2006




I’m working on a BizTalk project where we’re testing the use of security certificates, and
I’ve just had a bear of a time finding thorough walkthroughs of setting this up. It’s barely
mentioned in the available BizTalk books, and while the BizTalk 2004 whitepaper (which
has now been added to the BizTalk 2006 documentation) has some very nice coverage,
it wasn’t exactly what I wanted. So, after much toil (and threats of lighting myself on
fire), I present a step-by-step for building a certificate scenario using test certificates.
I’ve used the .NET Framework tool makecert to build local test certificates. The hardest
part for me was getting the correct series of command line parameters to build the cert
I wanted. I finally put together one that worked:
makecert -r -pe -n “CN=www.seroter.com” -b 02/01/2007 -e 01/01/2036 -eku
1.3.6.1.5.5.7.3.1 -ss my -sr currentuser -sky exchange -sp “Microsoft RSA SChannel
Cryptographic Provider” -sy 12
For a description of the available parameters, check out the MSDN page for makecert.
What this did, was create a (self-signed) certificate, and placed it in my “current user”
personal store.
You can see from the shot here that the certificate’s private key is included.

So first, I exported the private key certificate out. To do this, I selected the certificate,
right-clicked, and chose export. As you can see below, I chose to Yes, export the private
key and created the .pfx file.

Promoting Schemas Properties in BizTalk Server

Promoting Schemas Properties in BizTalk Server
Introduction
A common scenario in a BizTalk solution is to subscribe to a message based on its
content or context and make decisions based on the underlying values. This is known as
content-based routing. In this article, I will cover the principles and techniques to expose
this sort of metadata in BizTalk Server.
Principles of promoting properties
In order to publish metadata associated to a message in BizTalk, we need to promote
some data fields of the message using the property schema mechanism. This task can be
done using two approaches: quick promotion or regular promotion. In addition to data
fields within the message, we can also promote system properties are automatically
promoted in BizTalk. Any promoted properties (from the BizTalk system and from the
messages also known as message context) are available for subscription by BizTalk
objects such as send ports, send port groups and orchestrations.
You can use promoted properties as decision points and routing ways for the messages
inside an orchestration, although this has an overhead because the whole message must
be load to be interrogated. In order to gain in performance, we use in orchestrations
another technique known as distinguished fields which are lighter.
To access a distinguished field, we create a reference to the name of the message, the
name of the record structure and the name of the distinguished field with each named
item separated by a period using the following syntax
MessageName.RecordName.ChieldRecordName.DistinguishedFieldName. Promoted
properties are accessed by creating a reference to the name of the message, the name
of the property schema and the name of the promoted property name using the
following syntax MessageName(PropertySchemaName.PromotedPropertyName).
Getting started with an example
Now we're going to subscribe to a message based on the content of the message. We're
going to use Property Schema items to promote the data fields in the message in order
to set up filter expressions. We have to use any pipeline but PassThruReceive pipeline to
create the message context during the pipeline processing. Once added to the
message context, they can be used by send ports and other BizTalk subscribing items.
Open Visual Studio .NET and create an empty BizTalk project and add the
Customer_Schema.xsd XSD Schema item (see Figure 1).
Figure 1
Then create the schema as shown in Figure 2.
Figure 2
Now let's promote the CustomerID data field by right-clicking and selecting Promote |
Quick Promotion (see Figure 3).
Figure 3
Then you will be asked to add this data field to a property schema and in turn this new
property schema is added to the project. To view all promoted properties, select any
node of the schema and select Promote| Show Promotions option to open the Promote
Properties windows (see Figure 4).
Figure 4
Build and deploy the solution.
Now we're going to configure the solution to route the messages concerning the
underlying content. For example, if a messaging holding the value of the customer id is
greater than or equal to 1 and less than 5, then it will be routed to a directory output1,
and if the value of the customer id is greater than or equal to 5 and less than 10, it will be
routed to the directory output2. In order to configure the solution, open the BizTalk Server
2006 Administration Console and navigate to the Messaging_Schemas node in the
Applications sub-tree. Create a receive location to read the messages.
Now let's create and configure two send ports. See in Figure 5 the configuration for the
Send Port number 1 and in the Figure 6 the configuration for the Send Port number 2.
Figure 5
Figure 6
Conclusion
In this article, I covered the principles and techniques to promote properties in BizTalk
Server 2006 with an illustrative example that you can use as a baseline to apply it for your
own situation.

BIZTALK Interview Questions

General

  1. Does BizTalk 2004/2006 support Synchronous communication?

BizTalk is essentially Asynchronous. It can exhibit some synchronous behavior, if an Orchestration is converted into a web service.

  1. Enumerate the new functoids added BizTalk 2006?

Please refer to this article New functoids in BizTalk 2006

Schemas

  1. What is the difference between a Document Schema and a Property Schema?

A document schema is like any regular schema, whereas a Property schema consists of only child elements under a root node.

  1. Can an Envelope schema consist of more than one schema type?

Yes. Technically it is possible.

Messaging

  1. Can a flat file message be processing without a pipeline?

A Pipeline's job is to convert any external format into XML, be it a flat file or EDI or anything else.

  1. Can multiple messages be processed or batched without an envelope schema?

It is possible to process multiple messages, without an envelope.

  1. What is property promotion, why is it required?

When a property is promoted, it is exposed to the orchestration/send port filters etc.

  1. In which scenarios would use a "promoted property" vs. "distinguished fields"?

The rule here is, if you don’t want the schema element to appear in send port filters/debugging information then make it a distinguished field.

  1. In Biztalk, what does a message type consist of?

A message type consists of the TargetNamespace#RootElement name.

  1. What are un-typed messages, how does one create them?

A message created in BizTalk Orchestration is bound to a schema, this is a typed message. In un-typed messages, the message is bound to System.Xml.XmlDocument instead of a schema.

  1. What is the difference between static, dynamic and direct binding?

Refer to Binding models in BizTalk

  1. How does one enable subscriptions in BizTalk?

A filter on the Send Port is the first step to enable subscriptions in BizTalk.

Orchestrations

  1. How do you prevent occurring of zombies in a Parallel Convoy?

Refer to the article known as "Convoy Deep Drive" on MSDN

  1. What is the difference between a delay shape vs. a listen shape?

A 'Delay' is very much similar to a sleep on the current thread. A 'Listen' shape is used to wait for an incoming resource, with a timeout period.

  1. When you use Call Orchestration shape vs. Start Orchestration shape?

A Call Orchestration returns the control back to the caller. A Start Orchestration shape starts the orchestration in a non-deterministic way.

  1. What is the difference between a "Message Assignment" shape and an "Expression" shape?

A "Message Assignment" shape is used to create a new message and assign values to it. A Expression shape is used to assign values to variables and also write 'if' conditions.

  1. Does BizTalk Orchestrations support recursion?

An Orchestration does NOT support recursion.

  1. What is the purpose of the property "Activate" in a Receive shape?

It is used to invoke a new instance of an Orchestration.

  1. Can an orchestration Start without an Activatable receive?

A Nested Orchestration can be started without an Activatable receive

  1. Is it necessary for all .NET components being called from an Orchestration be Serializable?

Yes it is necessary. There are cases where a .NET component need not be Serializable.

  1. When do we need set the property "Synchronized" = true for a scope?

This needs to be set, when a variable is shared across the branches of a parallel shape.

  1. What is the difference between an Exception block and a Compensation block? is it the equivalent of try-catch-finally?

Refer to HOW To Compensate a Transaction in a BizTalk Orchestration

  1. Is it possible to have a exception block for an Atomic scope? if not why?

Refer to Parallel Branching and Scoping in BizTalk Orchestrations - Advanced Concepts

  1. How does one enable Correlations in BizTalk?

First create a Correlation type and then create an instance of it.

  1. Is it possible to share variables across two branches in a Parallel shape?

Refer to Parallel Branching and Scoping in BizTalk Orchestrations - Advanced Concepts

  1. Does BizTalk automatically compensate a unsuccessful transaction?

Refer to HOW To Compensate a Transaction in a BizTalk Orchestration

  1. What is the main difference between a Long-Running transaction and an Atomic Transaction in BizTalk context?

Refer to HOW To Compensate a Transaction in a BizTalk Orchestration

Architecture and Design

  1. In an Orchestration design, Orchestration "A" calls another Orchestration "B", and vice versa. Is it possible to implement this design?

It is NOT possible, since it forms a cyclic dependency.

  1. List out the three important things to consider while designing a BizTalk orchestration!

The Incoming data format, The Business process and The Outgoing data format.

  1. Enumerate the steps required to deploy an BizTalk solution from one machine to another machine.

Refer to Using the MSI installer wizard for deploying applications created in BizTalk Server 2006

  1. What is BizTalk?

Biztalk is a messaging based integration tool.
Bonus: It consists of several different pieces including Business Processes (Orchestrations), BAM, Rules Engines, and HAT.

  1. What is a Message Type (i.e. BTS.MessageType) and how is it used in BizTalk?

Message Type is a BizTalk System property that is promoted inside a Pipeline. It is made up of Document Name Space # Root Node Name.

  1. What is the default mapping for Auto Mapping?

The default is by structure. This can be change to by node name on the map properties.

  1. How do you call a Non-Serializable .Net helper class inside an Expression Shape?
    • Add a reference to that class.
    • Make sure your Orchestration is Long Running transactional.
    • Add an Atomic scope.
    • Create an Orchestration variable of that class inside the scope.
    • Create an instance on that object inside the scope.
    • Call the method.
    • Bonus: Mention the class must be strongly signed and in the GAC.
  2. What if the class is Serializable?

No transactional Orchestration or Atomic scope is needed.

  1. What does the Value Mapping Functoid do?

Returns the second parameter if the first parameter is true

  1. What is the difference between a distinguished field and a Promoted Property?
    • Distinguished fields are light weight and can only be used inside an Orchestration.
    • Promoted Properties are defined inside a property schema, are tracking in SQL, can be tracked in HAT, and can be used for content based routing.
  2. How do you achieve First-In-First-Out message processing of messages received from multiple sources using an Orchestration?
    • Use a Sequential Convoy to process the messages in the order they are received into the Message Box.
    • Make sure Ordered Delivery is set to true inside the Orchestration Receive Port.
  3. At high level, what do Receive Ports and Orchestration Send Port really do in terms of messaging? What about Send Ports and Orchestration Receive Ports?
    • Receive Ports and Orchestration Send Ports are both publishers.
    • Ports and Orchestration Receive Ports are both subscribers.
  4. When working with Schemas, Maps, Pipelines, and Orchestrations how the projects should be structured?
    • Schemas and Maps in its own project.
    • Or Schemas and Maps together in its own project.
    • Orchestrations in its own project.
    • Pipelines in it own project.
  5. What is direct binding?
    • Direct binding has three types: direct to message box, self correlating, and partner ports.
    • Used to route message between the message box and Orchestrations without using bindings or from one Orchestration to another Orchestration.
  6. What is BAM used for?

BAM is used to monitor business milestones and key metrics in near real-time throughout a process in BizTalk.

  1. What is the Rules Engine?

Rules are used to provide highly efficient, easily changeable business rules evaluation to Business Processes. This allows rules to be changed without rebuilding and redeploying .net assemblies. The Business Rules Engine (BRE) can also be called from any .net component through the API’s

  1. What are Persistence Points and what causes them?
    • Persistence is when the state of a running Orchestration is stored into SQL.
    • It is good enough to know various shape and actions cause persistence. More specifically, it occurs: end of a transactional scope, at a send shape, at a start Orchestration shape, during dehydration, if the system shuts down expectedly or unexpectedly, or the business process suspends or ends.
  2. What group does a user need to belong to in order to submit messages to the message box?

The user needs to be a member of the hot group or isolated host group (assuming a default installation).

  1. What user rights to you need to perform most actions in HAT?
    • BizTalk Server Administrator

When installing Biztalk in a multi-server configuration with a remote SQL and Analysis Services