Sunday, December 14, 2008

Composite WPF Guidance - Part 10 Modules (Dynamic Loading)

Dynamic Module Loading: In dynamic module loading, modules are discovered at run time, which the shell does not directly reference. The advantage of dynamic module loading is that modules can be added to the application without having to add any new references or modify the executable. The other advantage is that it gives you flexibility as to how modules are discovered; for example, the Composite Application Library ships with support for loading modules by scanning a directory, specifying in configuration, or on demand.
Configuration Driven Module: LoadingIn this style of loading, modules are located by the ConfigurationModuleEnumerator, which scans the App.config file for modules and module dependencies.
protected override IModuleEnumerator GetModuleEnumerator()
{
ConfigurationStore store = new ConfigurationStore();
return new ConfigurationModuleEnumerator(store);
}
App.Config file entries
Directory Driven Module Loading: In this style of loading, modules are located by the DirectoryLookupModuleEnumerator, which scans the assemblies in a directory and locates all the types that implement IModule. It will also look for the ModuleDependency attribute to determine the dependent modules that need to be loaded before loading the current module. protected override IModuleEnumerator GetModuleEnumerator()
{ return new DirectoryLookupModuleEnumerator(@".\"); }

Composite WPF Guidance - Part 9 Modules (Static loading)

A module in the Composite Application Library is a logical unit in your application. These modules are defined in such a way that they can be discovered and loaded by the application at run time. Because modules are self-contained, they promote separation of concerns in your application. Modules can communicate with other modules and access services through various means. They reduce the friction of maintaining, adding, and removing system functionality. Modules also aid in testing and deployment.

A module in CAL is a class that implements the IModule interface. This interface contains a single Initialize method that is called during the module's initialization process. Module loading in the Composite Application Library is a two-step process:

Static Loading and Dynamic Loading

The module enumerator discovers modules and creates a collection of metadata about those modules. The module loader instantiates the module and calls its Initialize method.

Static Module Loading: In static module loading, the shell has a direct reference to the modules, but the modules themselves do not directly reference the shell. They can be in the same assembly or a different assembly. The benefit of this style of loading over dynamic module loading is that modules are easier to use and debug because they are directly referenced. The disadvantage of static module loading is that you have to add new references to the shell and a line of code to the bootstrapper for each module.

protected override IModuleEnumerator GetModuleEnumerator()
{
return new StaticModuleEnumerator()
.AddModule(typeof(User.UserModule))
.AddModule(typeof(Accounts.AccountModule));}

}

Thursday, December 11, 2008

Composite WPF Guidance – Part 8 (Creating a Shell)

The shell is the main window of the application where the primary user interface (UI) content is contained. The shell provides the outermost container of your Composite WPF application. You can think Shell as a single main window that contains multiple views. The shell may contain named regions where modules can add views. It may also define certain top-level UI elements, such as the main menu and toolbar. The shell also defines the overall appearance and behavior (look and feel) for the application. It may define styles and borders that are present and visible in the shell layout itself, and it may also define styles, templates, and themes that get applied to the views that are plugged into the shell.
Implementing a Shell consists of creating a WPF window which includes defining several ItemsControls that are identified as regions for modules to add their views to.

The Shell contains a Presenter and is an implementation of the IShellView interface.
The IShellView contains a method signature to launch the Shell form.
void LaunchShell();
The LaunchShell method is called by a BootStrapper to launch the shell form.

Tuesday, December 9, 2008

Composite WPF Guidance – Part 7 (Events)

In a composite application, components, such as presenters, services, and controllers, residing in different modules often need to communicate with one another based on state changes. This is a challenge due to the highly decoupled nature of a composite application because the publisher has no connection to the subscriber. Additionally, there may be threading issues because the publisher is on a different thread than the subscriber. CAL uses the EventAggregator service registered in the container for events that allow decoupling of publishers and subscribers so they can evolve independently. EventAggregator allows subscribers or publishers to locate a specific EventBase. The event aggregator also allows for multiple publishers and multiple subscribers.

As shown in the figure above the real work of connecting publishers and subscribers is done by the CompositeWpfEvent class. This is the only implementation of the EventBase class that comes out of the box in the Composite Application Library. This class maintains the list of subscribers and handles event dispatching to the subscribers.

Composite WPF Guidance – Part 6 (Commands)

In a composite WPF application actions within the view are routed to the appropriate handlers outside of the view by using delegation and composition. WPF-routed commands deliver command messages through UI elements in the tree, but the elements outside the tree will not receive these messages because they only bubble up or down from the focused element or an explicitly stated target element. Additionally, the WPF-routed commands require a command handler in the code behind.
Use of Delegation and Composition overcomes this issue.
In delegation a command is used that delegates off its handling logic, either through events or delegates where it can be handled externally by a class such as a presenter, service, controller, and so on. This provides the benefit of not having to put any code in the code behind. The command requires two handlers: one for the Execute method and one for the CanExecute method. Whenever the Execute or CanExecute methods are called on the command, the handlers are called either through the event being raised or the delegate being invoked.
The DelegateCommand in CAL allows delegating the commanding logic instead of requiring a handler in the code behind. It uses a delegate as the method of invoking a target handling method.


The DelegateCommand uses its delegate to invoke a CanExecute method or Execute method on the target object when the command is invoked.

A composite command delegates off its handling logic to a set of child commands. The composite command needs to provide a way for the child commands to be registered. Executing the composite command executes the children. The composite commands CanExecute returns false, unless all the children return true. The CompositeCommand class contains a RegisterCommand method to register the child commands.

The figure below shows the relationship between a CompositeCommand and DelegateCommand.

Composite WPF Guidance – Part 5 (View Layout)

In CAL views from different modules are laid out using two approaches:
  • View Injection
  • View Discovery
In View Injection the application contains a registry of reserved locations called Regions. A module can access regions in this registry using a Region Manger service and use it to inject views. The view being injected does not have any specific knowledge of how it will be displayed in that location. The place it is being injected is referred by a unique name. Each of the objects in the registry implements a specific interface that is used to inject the view. Below given figure illustrates the View Injection approach to dynamic layout.


In View Discovery the modules register their views (or presenters) in a central location, such as in the container, using a well-known interface. In CAL each module constructor accepts an instance of IUnityContainer which can be used to register presenters using the IUnityContainer RegisterType() where TTo : TFrom method. A shell service or a composite view then queries the container to discover the views that were registered.


Monday, December 8, 2008

Composite WPF Guidance - Part 4 (Patterns)

The seperated presentation pattern separates the responsibilities for the visual display and the event handling behavior into different class. In Composite WPF Guidance this pattern is implemented in multiple ways

Supervising Controller. This pattern, a variant of the Model-View-Presenter pattern, separates the responsibilities for the visual display and the event handling behavior into different classes named, respectively, the view and the presenter, and permits using data binding to enable direct communication between the view and the model.

Presentation Model. This pattern, a variant of the Model-View-Presenter pattern, supplements a façade on the model with UI-specific state and behavior that is easy to consume from the view.

Wednesday, December 3, 2008

Composite WPF Guidance - Part 3 (Patterns)



The Inversion of Control (IoC) pattern is used to enable extensibility in a class or framework. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
In Composite Application Library the container is provided by implementing the IContainerFacade interface. The above mentioned diagram explains the IoC implementation in CAL.

The Service Locator pattern is a form of the Inversion of Control pattern. It allows classes to locate specific services they are interested in without needing to know who implements the service. Frequently, this is used as an alternative to dependency injection, but there are times when a class will need to use service location instead of dependency injection, such as when it needs to resolve multiple implementers of a service. In the Composite Application Library, this can be seen when ModuleLoader service resolves individual IModules.

Tuesday, December 2, 2008

Composite WPF Guidance - Part 2 (Patterns)

The Composite Application Guidance for WPF involves applying varios design patterns when building composite user interface (UI) applications. Some of the patterns used in a Composite WPF applcation development are:
  • Seperated Interface and Plug In pattern
  • Inversion Of Control
  • Service Locator
  • Command
  • Adapter
  • Seperated Presentation
  • Event Aggregator
  • Facade etc

I will explain the use of these patterns in the Composite WPF development using CAL and their significance in the forthcoming articles.
Seperated Interface and Plug In pattern: The ability to locate and load modules at run time encouraging a more loosely coupled application development using CAL is enabled by the Seperated Interface and plug in pattern.
In CAL the quality of its design is improved by reducing the coupling between the system's parts. This is acheived by grouping the classes into packages and controlling the dependencies between them. However, you can invoke methods in other packages by defining an interface in one package but implement it in another. This way a client that needs the dependency to the interface can be completely unaware of the implementation. In CAL each module implements the IModule interface which provides a good plug point for Gateway. The below figure shows the seperated interface implementation in CAL.


Plug In pattern allows the concrete implementation of a class to be determined at run time to avoid requiring recompilation due to which concrete implementation is used or due to changes in the concrete implementation. In the Composite Application Library, this is handled through the DirectoryLookupModuleEnumerator, ConfigurationModuleEnumerator, and the ModuleLoader. The figure below describes the plugin implementation in CAL.

We will look into the other patterns in the following series in CAL.

Monday, December 1, 2008

Composite WPF Guidance - Part 1

Microsoft released the new Composite Application Guidance for WPF that helps architects and developers create composite Windows Presentation Foundation (WPF) applications. The main part of interest is the Application Library (CAL) which accelerates the development of composite applications using proven design patterns to help you build Composite WPF applications.
The composite WPF application created using CAL will use the Unity Extensions for Composite Application Library and the Unity Application Block. These are built on the .NET Framework 3.5.

>

The architecture the Composite Application Library as mentioned below consists of a shell application that defines regions for hosting content with views and services offered by multiple modules—possibly dynamically loaded. Underlying the application, and the Composite Application Library, is a service layer to provide access to the application services based on the Composite Application Library


>
Most of the components in the diagram have the same functionality or definition as in CAB.
Shell is the top level container window to host user interface components.
Any logic for the shell is handled by the shell presenter. This follows the separated presentation pattern* and helps separate the display of content from the user interface logic.
Regions are placeholders for content and host visual elements in the shell. These can be located by other components through the RegionManager to add content to those regions. Regions can also be used in module views to create discoverable content placeholders. Regions replace the Workspaces in CAB.
Modules represent a Use Case and have sets of views and services, frequently logically related, that can be independently developed, tested, and optionally deployed. Modules are discovered and loaded, in the Composite Application Library by a process known as module enumeration and module loading.
Views are responsible for displaying content on the screen. The views logic are handled by implementing appropriate design patterns for separations of concerns. Typically, this involves some type of binding-oriented design pattern, such as Supervising Controller* or Presentation Model*. Views are created to take full advantage of the data binding features of WPF.
Communication within the modules should not require hard dependencies on one another. The Composite Application Library provides mechanisms to do this with the CompositeCommand and EventAggregator. The composite command is a strategy to combine the execution of commands. This allows the command invoker to interact with a single command that affects multiple commands. EventAggregator is used in views that need to send an event to other views or components and do not require a response. Multiple components can publish an event, and multiple subscribers can receive the event.
The application and modules expose services for their own and shared use. These are exposed through a service container that locates and, often, constructs the services. By default, the Composite Application Library uses the Unity container for this service location.

I will explain in detail about the components used in CAL and their functionality in detail in the upcoming series.

Tuesday, November 25, 2008

Preventing DoS (Denial of Service) attacks on WCF services

WCF services are the most attractive target for hackers because even an unsophisticated hacker can bring down a server by repeatedly calling the WCF service. WCF uses mechanisms like Throttling and Quotas to prevent DoS attacks. Throttling allows you to "smooth" out the load on the server. WCF handles throttling through the ServiceThrottlingBehavior class. This represents a behavior that can be applied to a service.
The ServiceThrottlingBehaviour class contains three properties
  • MaxConcurrentCalls bounds the total number of simultaneous calls that we will process (default == 16). Each call corresponds to a Message received from the top of the server-side channel stack. If you set this high then you are saying that you have the resources to handle that many calls simultaneously. Increase this value if you want your service to be able to process a larger message load.
  • MaxConcurrentSessions bounds the total number of sessionful channels that we will accept (default == 10). When we hit this throttle then new channels will not be accepted/opened. Note that this throttle is effectively disabled for non-sessionful channels (such as default BasicHttpBinding).
  • MaxConcurrentInstances bounds the total number of instances created. This throttle provides added protection in the case that you have an instance lifetime that is not tied to a call or a session (in which case it would already be bounded by the other two throttles).
These properties can be applied either programmatically or by configuring the behavior in your web.config or app.config file.

<system.serviceModel>

<services>

<service behaviorConfiguration="TradeService.ExchangeService.ServiceBehavior" name="TradeService.ExchangeService.TradeService">

<endpoint binding="wsHttpBinding" contract="TradeService.ExchangeService.ITradeService"/>

service>

<service behaviorConfiguration="TradeServiceBehavior" name="TradeService">

<endpoint address="" binding="wsHttpBinding" contract="ITradeService">

<identity>

<dns value="localhost"/>

identity>

endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

service>

services>

<behaviors>

<serviceBehaviors>

<behavior name="TradeService.ExchangeService.ServiceBehavior">

<serviceMetadata httpGetEnabled="true"/>

<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="false" />

<serviceThrottling maxConcurrentCalls="16" maxConcurrentInstances="1000" maxConcurrentSessions="10"/>

behavior>

<behavior name="TradeServiceBehavior">

<serviceMetadata httpGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

behavior>

serviceBehaviors>

behaviors>

system.serviceModel>


In the example given above I have set the maxConcurrentCalls to 16, maxConcurrentInstances to 1000 and maxConcurrenctSessions to 10.

Quotas can be used in situations where the client may force the server to allocate a significant amount of memory over what should be used. When a quota is exceeded a QuotaExceededException is thrown. Without Quotas a malicious message could attempt to access all available memory can create an OutOfMemoryException, or access all available stacks to cause a StackOverflowException.
By setting the maxRecievedMessageSize on the binding you can mitigate DoS attacks. This setting restricts the maximum messages size so that a client can’t send messages that are too large and flood the system.

<bindings>

<wsHttpBinding>

<binding name="WSHttpBinding_TradeService" closeTimeout="00:01:00"

openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"

bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"

maxBufferPoolSize="524288" maxReceivedMessageSize="65536"

messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"

allowCookies="false">

<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"

maxBytesPerRead="4096" maxNameTableCharCount="16384" />

<reliableSession ordered="true" inactivityTimeout="00:10:00"

enabled="false" />

<security mode="Message">

<transport clientCredentialType="Windows" proxyCredentialType="None"

realm="" />

<message clientCredentialType="Windows" negotiateServiceCredential="true"

algorithmSuite="Default" establishSecurityContext="true" />

security>

binding>

wsHttpBinding>

bindings>