Wednesday, 7 July 2010

What is the Windows Process Activation Service (WAS)?

Here are some brief notes on the Windows Process Activation Service.

“Windows Process Activation Service (WAS) is the new process activation mechanism for the Windows Server 2008 that is also available on Windows Vista. It retains the familiar IIS 6.0 process model (application pools and message-based process activation) and hosting features (such as rapid failure protection, health monitoring, and recycling), but it removes the dependency on HTTP from the activation architecture. IIS 7.0 uses WAS to accomplish message-based activation over HTTP. Additional WCF components also plug into WAS to provide message-based activation over the other protocols that WCF supports, such as TCP, MSMQ, and named pipes. This allows applications that use communication protocols to use the IIS features such as process recycling, rapid fail protection, and the common configuration system that were only available to HTTP-based applications.” * (my bold)

“The Windows Process Activation Service (WAS) manages the activation and lifetime of the worker processes that contain applications that host Windows Communication Foundation (WCF) services. The WAS process model generalizes the IIS 6.0 process model for the HTTP server by removing the dependency on HTTP. This allows WCF services to use both HTTP and non-HTTP protocols, such as Net.TCP, in a hosting environment that supports message-based activation and offers the ability to host a large number of applications on a given machine.” ** (my bold)

WAS allows applications to be hosted in a more robust and manageable way:

  • Applications start and stop dynamically in response to incoming work items that arrive using HTTP and non-HTTP network protocols.
  • Process recycling to maintain the health of running applications.
  • Centralized application configuration and management.
  • Applications can take advantage of the IIS process model without a full IIS installation.
  • A single WAS server instance can be home to many different applications.
  • Applications are organised into groups called sites.
    • For the purposes of addressing and management.
    • Applications are also grouped together into application pools.
      • An application pool can house many different applications from many different sites.
      • Each application pool corresponds to an instance of a worker process (w3wp.exe).
  • Within a site, applications are arranged in a hierarchical manner
    • Reflects the structure of the URIs

 

* http://msdn.microsoft.com/en-us/library/ms730158.aspx
** http://msdn.microsoft.com/en-us/library/ms734677.aspx

Wednesday, 7 July 2010

Adjacent in space; stacked in time

The Dirtiest Word in UX: Complexity” from UX Magazine elucidated 2 interesting UI concepts:
  • Adjacent in space
  • Stacked in time
adjacent
Adjacent in space is taking elements of an application and positioning them all on the same screen. Depending on the information and number of features an application has, it can make the screen appear more, or less, complex. An airplane cockpit is an extreme example of this approach. It makes all of the controls readily available to pilots and keeps critical readouts and important data ready at hand to help pilots make quick decisions. The adjacent in space UI approach gives more immediate power and control. It also reduces the need for navigation between screens to reach additional functionality, speeding up interactions.
Stacked in time is splitting the functionality up into several screens or layers, like a story being spread across pages in a book rather than crammed into a single long page. This approach can reduce the chance of the users making a mistake by guiding them down clear path. It also offers a gradual engagement, showing and hiding controls so only the necessary UI/information is displayed, reducing the perceptive complexity of the UI. It can allow more screen space for feedback and guidance for the user, and can allow for a more aesthetically pleasing and/or branded experience. The stacked in time approach tends to make an application less intimidating and doesn't overwhelm the user with choices.
The adjacent in space and stacked in time approaches each has its own trade-offs. In most cases placing too many elements on screen at the same time creates unnecessary complexity. Not all controls are needed at once, so they should only be presented when needed. However, a stacked in time approach also can become overwhelming to a user if not executed correctly. If the features aren't mapped in logical paths or are split across too many layers, users might not be able to quickly find what they need. This is especially apparent on smaller screens for devices.”
These 2 simple concepts are critical for UI development and appropriate use is key to good mobile development.

Saturday, 3 July 2010

X.509 error when running simple WCF services

I was running through some tutorials and hit a problem when adding new endpoints to a WCF service. The Visual Studio service runner showed the following error:
System.InvalidOperationException: Cannot load the X.509 certificate identity specified in the configuration.
   at System.ServiceModel.Description.ConfigLoader.LoadIdentity(IdentityElement element)
   at System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress)
   at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection)
   at System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, String configurationName)
   at System.ServiceModel.ServiceHostBase.ApplyConfiguration()
   at System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses)
   at System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses)
   at System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.CreateServiceHost(Type type, ServiceKind kind)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info)
The problem lay in the App.config <identity> block of some of the newly added endpoints. Originally they looked something like this:
<identity>
    <certificatereference x509findtype="FindBySubjectDistinguishedName" storelocation="LocalMachine" storename="My" />
</identity>
Adding a <dns> element fixed the issue:
<identity>
    <dns value="localhost" />
    <certificatereference x509findtype="FindBySubjectDistinguishedName" storelocation="LocalMachine" storename="My" />
</identity>
The <dns> element is described as:
“Specifies the DNS of an X.509 certificate used to authenticate a service. This element contains an attribute value that is a string, and contains the actual identity.”
See the MSDN documentation:
Saturday, 3 July 2010

Friday, 2 July 2010

What is AppFabric?

Here are some brief introductory notes on the AppFabric platform. According to the Microsoft AppFabric site:
“Windows Server AppFabric is a set of integrated technologies that make it easier to build, scale and manage Web and composite applications that run on IIS.”
AppFabric provides 2 core services which can be used independently or together:
  • AppFabric Caching Services, which can speed up access to frequently accessed information such as session data used by an ASP.NET application.
  • AppFabric Hosting Services, making it easier to run and manage services created with Windows Communication Foundation, especially those built using Windows Workflow Foundation.
AppFabric is provided as extensions to the Application Server role of Windows Server.

AppFabric caching services

The original codename for AppFabric Caching Services was Velocity. AppFabric Caching Services speeds up access to frequently accessed data.
The main components of AppFabric Caching Services are:
  • A cache client - accesses a cache cluster containing some number of cache server machines.
    • e.g. an ASP.Net page.
  • Cache server(s) - running instances of AppFabric Caching Services and maintaining cached data.
    • All the cache servers in the cluster appear as a single logical store.
    • The client neither knows nor cares which physical server winds up holding the cached data.
  • Cache client local cache – also using services provided by AppFabric Caching Services.
When a cache client acquires data it can use the AppFabric Caching Services client library to store the data in the cache cluster under a unique name. When the client needs the same data again, it asks for it using the item’s name:
  • The query first checks the local cache (if one is being used).
  • If the data is found the client uses the cached value.
  • If the data item isn’t in the local cache the query is sent to the cache cluster.
  • If the data is found the client uses the value returned from the cluster.
  • If the data isn’t found the client needs to look elsewhere for the information (e.g. the database).
A cached data item can be any serialized .NET object.
All cached data is stored in memory. By default, cached data is only stored on one node in the cluster but AppFabric Caching Services also has a high-availability option that creates a secondary copy of each cached data item on another node in the cluster.
Cached data items can be removed from the cache by client applications or by the caching service itself (e.g. through expiration based on a configurable time-out period or by being evicted to make room for more frequently accessed information). This applies to local caches as well as the server caches. Local caches can can be set to synchronize automatically with changes to data items in the cache cluster.
Data sent between cache clients and cache servers can be digitally signed and encrypted. Administrators can limit which accounts have access to each cache.
Note that AppFabric Caching Services have built-in support for storing ASP.Net session data.

AppFabric Hosting Services

The original codename for AppFabric Hosting Services was Dublin. WCF and WF services need service hosts and AppFabric Hosting Services provide some infrastructure for hosting in IIS.
AppFabric Hosting Services build on what’s already provided by IIS and Windows Process Activation Service (WAS), adding additional capabilities for running and managing WCF services, including workflow (WF).
WCF services and WF services run in worker processes provided by IIS - AppFabric Hosting Services doesn’t provide its own host process.
AppFabric Hosting Services extends the IIS Manager and provides facilities which include:
  • Setting WCF configurations
  • Starting and stopping services
  • Examining service endpoints
  • Suspending, resuming, or terminating specific instances of workflow services
  • An IIS manager dashboard for monitoring WCF and WF services
AppFabric Hosting Services also provide PowerShell ‘commandlets’ for service management.
Visual Studio WCF and WF projects created with the built-in project templates are immediately deployable in AppFabric Hosting Services.
The WF runtime automatically persists the state of a workflow that’s waiting for input, then rehydrates it when input arrives. Using WF by itself the developer must create and configure a persistence database. However, AppFabric Hosting Services provides a pre-configured persistence store.
WF allows a workflow’s execution to be tracked giving the developer a detailed record of its execution with the tracking data being stored in a monitoring database. Conventionally the WF developer must supply a monitoring database but AppFabric Hosting Services provides a built-in monitoring database for this purpose.
AppFabric Hosting Services allows a service to be deployed to a load-balances server environment so that workflow etc. is coordinated across multiple servers in the cluster. AppFabric Hosting Services lets the same instance of a workflow service execute on different machines at different times (i.e. it makes the service more scalable).

Wednesday, 30 June 2010

Binding Modes in Silverlight

There are 3 binding modes in Silverlight (identified by the BindingMode enumeration):

  • OneTime - bindings update the target with the source data when the binding is created
  • OneWay - bindings update the target with the source data when the binding is created and anytime the data changes. This is the default mode.
  • TwoWay - bindings update both the target and the source when either changes. Alternately, you can disable automatic source updates and update the source only at times of your choosing. When the binding is created, the target property is updated from the source.

In OneWay or TwoWay bindings, the source object must implement INotifyPropertyChanged in order for the target to update when the source changes.

For TwoWay bindings, changes to the target do not automatically propagate to the source, except if the binding target is the Text property. In that case, the update happens only when the TextBox loses focus. In other words, the in-memory object to which the TextBox is bound isn’t modified until the TextBox loses focus whereas other elements perform their updates immediately (e.g. the user moves a bound slider control). If you need a TextBox to update as the user types you must implement an event handler on the TextBox TextChangedEvent. For example:

private void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    BindingExpression exp = myTextBox.GetBindingExpression(TextBox.TextProperty);
    exp.UpdateSource();
}

For OneTime and OneWay bindings, calls to SetValue automatically change the target value and delete the binding.

See:

Monday, 28 June 2010

Using Commands in Silverlight

Commands in Silverlight are a valuable way of getting away from the code-behind, event handler trap and keeping the UI decoupled from application logic. When used in combination with the MVVM pattern, what would have been event handlers are now effectively properties on the ViewModel (properties that return an object that implements ICommand), bound to the Command property of UI elements such as buttons.
Note: The command approach works well for instances where a UI element is clicked (e.g. buttons) so the resulting code (the command) is executed once. In cases where values are constantly changing (e.g. the value of a slider control) the command approach falls down; you can’t attach a command to a UI element event handler. For such event-driven scenarios you need to use a different approaches: use behaviours, bind the changing value to a property in the ViewModel that in turn updates other bound properties when changed, or create user controls and create dependency properties for the changing values which are bound via the ViewModel.
See http://thejoyofcode.com/Animating_when_Data_Changes_Part_II.aspx.
Before going further be aware that Prism (the Composite Application Library) already has some support for commanding. The Composite Application Library provides the DelegateCommand and CompositeCommand classes to simplify command implementation.
See the Commands technical overview: http://msdn.microsoft.com/en-us/library/dd458928.aspx
A DelegateCommand implementation might look something like this:
public class DelegateCommand : ICommand { private Func<object, bool> _canExecuteFunc;
    private Action<object> _executeAction;
    private bool _canExecute;
    public event EventHandler CanExecuteChanged;

    public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecuteFunc)
    {
        _executeAction = executeAction;
        _canExecuteFunc = canExecuteFunc;
    }

    public bool CanExecute(object parameter)
    {
        bool temp = _canExecuteFunc(parameter);
        if (_canExecute != temp)
        {
            _canExecute = temp;
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, new EventArgs());
            }
        }
        return _canExecute;
    }
  
    public void Execute(object parameter)
    {
        _executeAction(parameter);
    }
}
To use a DelegateCommand you then need to define a command property on the view model:
public ICommand MyCommand { get; set; }
and then instantiate a DelegateCommand passing in the appropriate methods for CanExecute and Execute:
LoadProductsCommand = new DelegateCommand(MyMethod, CanExecuteMyMethod);
The DelegateCommand can be bound to a UI control:
<Button Content="Push Me" Command="{Binding MyCommand}" />
It is possible to pass parameters to the command:
<Button Content="Push Me" Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=SomeUiEelement, Path=Text}" />
Monday, 28 June 2010

Friday, 25 June 2010

WCF RIA Services basics

This post is mainly concerned with the basics of WCF RIA Services and is intended to serve as a aide memoire for terms etc. It will be added to over time.
Some definitions:
  • Project Link
    • The server project references the domain services, shared code etc. defined on the server side.
    • Code is generated in the client project at compile time linking the client and the server.
  • Entities
    • Defined on the server and generated client-side.
    • Validation etc. also generated on the client side (i.e. you just maintain the single server-side definition).
    • Used to marshal the data across the WCF service.
    • Can be created with Entity Framework, LINQ to SQL, or POCOs.
  • Domain Service
    • Defines the operations supported on the server side (e.g. CRUD operations).
    • Can be arbitrary operations to be invoked on the server from the client exposed by WCF.
  • Domain Context
    • The client side counterpart to the Domain Service.
    • Generated code on the client side.
    • Contains a WCF proxy that makes the service calls.
    • Manages creating the queries to be executed on the server side, entity change tracking etc.
  • Domain Data Source
    • Used to execute queries and submit changes to the server side.
    • Associated with the domain context.
    • Makes calls through the domain context to query and update entities.
    • Facilitates direct data binding from XAML.
Entities or entity collections retrieved are cached through the domain context on the client side. Changes (i.e. the addition, deletion or update of entities) are effectively ‘stored’ in the Domain Context until the changes are flushed through to the database. In other words, the Domain Context must be kept around long enough to submit the changes.
The Domain Context Load and SubmitChanges execute asynchronously. They take a thread from the thread pool, make the necessary calls to the server, and when those calls complete the work is automatically marshalled back to the UI thread to modify the entity collections and subsequently update the UI (probably via INotificationChanged).
However, it would be prudent to assume at least the possibility of problems. A couple of strategies that can be employed to get around this are:
  • Subscribe to the Completed event obtained from the LoadOperation or SubmitOperation obtained from Load or SubmitChanges.
  • Call an overload of the Load or SubmitChanges that takes an Action<LoadOperation> or Action<SubmitOperation> (i.e. supply call-backs).

Attributes

When creating the Domain Service (server side) adding the EnableClientAccess attribute will cause client side code to be generated at compile time.
Operations in the Domain Service can be decorated with attributes to identify their purpose (e.g.  create, read, update or delete and entity instance).
Authentication and authorisation can be enforced using attributes (the attributes can be specified at the service or operation level):
  • RequiresAuthentication - prevents anonymous users from accessing a service to perform an operation.
  • RequiresRole - ensures that the current principal belongs to one of the specified roles.

Convention over configuration

By default WCF RIA Services uses convention over configuration to find appropriate operations defined in the Domain Service.  There are a set of named method prefixes WCF RIA Services is looking for (e.g. Update***, Insert***, Delete***).
As an alternative attributes can be used to decorate methods and indicate what they are to be used for (i.e. configuration).

Authentication and authorisation

On the client authentication functionality is accessed through a class called WebContext, a class that represents functionality provided by the web server.
Authentication services implement the IAuthentication interface. An implementation of an authentication service will use a DomainContext to work against the corresponding DomainService implementing IAuthentication on the server.
There are 2 approaches to implementing authentiaction:
1. Derive from the out-of-box AuthenticationService base class. This provides a default implementation that leverages the asp.net membership, roles and profile infrastructure.
2. Implement IAuthentication on your domain service and do whatever you like based on your unique scenarios when implementing Login, Logout and other methods of the interface. This is especially useful if you're not using the asp.net infrastructure services or want to use some custom auth mechanism.
See http://www.nikhilk.net/Entry.aspx?id=262 and http://www.nikhilk.net/RIAServices-Authorization.aspx.
Authorisation can be further controlled using attributes (see above).