DCSIMG
September 2009 - Posts - Manu Cohen-Yashar's Blog

Manu Cohen-Yashar's Blog

September 2009 - Posts

WF toolbox is broken after resetting toolbox in VS 2010

I am playing with WF 4.0.

I accidently pressed "Reset Toolbox" in a WF 4.0 project. This broke the toolbox.

All the Flow chart and messaging activities were gone and I could not add them back manually. Only the procedural tab activities remained.When I tried to add the missing activities manually (choose Items) I could not find them under the activities tab.

To solve this issue simply delete the .tbd files under:

XP:   %USERPROFILE%\Local Settings\Application Data\Microsoft\VisualStudio\10.0
Vista: %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\10.0

Enjoy

Confirmation in WF 4.0

WF 4.0 is a revolution in relation to WF 3.5. I want to speak about a new mechanism called conformation.

In WF 4.0 every CompensableActivity has three handlers:

  1. Cancellation handler
  2. Compensation handler
  3. Confirmation handler

The idea of Cancellation and Compensation is the same as it was in WF 3.5.
If the activity is still active (executing state) and an exception occurred or an activity on an upper level completes (the activity that contains the CompensableActivity) than the activity would cancel and the cancelation handler would run.
If the activity completed and an exception occurred than the activity would compensate and the Compensation handler would run.

But what is confirmation ?

Well,  when the workflow successfully completes, all CompensableActivity instances that have not been confirmed or compensated are automatically confirmed using the default order.

It is also possible to activate compensation and and confirmation explicitly.

When an CompensableActivity completes in returns a compensation token. This token can be used in a Compensate or Confirm activity to force compensation or confirmation.

Confirmation allows CompensableActivity to have two business zones
1. The main business can be compensated or canceled
2. If the the business succeeded a confirmation zone is executed (like a final stamp) and this activity cannot be compensated.

The result is stronger workflows and better business accuracy.

Microsoft has released few confirmation demos to demonstrate this.

Using MEF

MEF – Managed extensibility framework is one of the most exciting new technologies brought by the new .Net framework 4.0.

Using MEF it is simple to create extensible applications.

There are so many extensibility design patterns but non is as simple as MEF.

One of the most popular extensibility pattern is the “provider” pattern. You define an interface that a provider should implement and in config you specify the location of the actual provider. On startup someone has to read the config, load the assembly, create an instance of the provider and start to work.

There are two main problems.

1. The configuration file gets complicated. It is filled with classes and assemblies names (Not a short definition considering the strong name and the version). The following snippet is not a rare example:

<providers>

   <add name="AspNetSqlRoleProvider"
        type="System.Web.Security.SqlRoleProvider, System.Web,
              Version=2.0.0.0, Culture=neutral,
              PublicKeyToken=b03f5f7f11d50a3a
" />       

</providers>

2. Someone has to do the job of creating the instance. There are issues to consider like: When should the provider be created? How shell the provider instance creator be available? How to insure the correct number of creations etc…

MEF provide a simple mechanism to implement the provider pattern without the manual creation of the providers. No more complex configuration. No more manual creation. MEF enables developers to create extensions dynamically, without the either the extending application or the extension requiring any specific knowledge of the other.

How to use MEF:

Step one: Define an interface the provider should implement (like good old days). Let us refer to this interface as a contract

Step two: Create one or more implementation of the interface one or many assemblies.
                 In each implementation add reference to: System.ComponentModel.Composition.

Step three: Decorate each implementation with the export attribute

[Export(typeof(IProviderContract))]
public partial class MyProvider : IProviderContract

Step four: Create the consumer. (add reference to: System.ComponentModel.Composition)

There are several ways to define the consumption. The simplest one is to create in the consumer a property of type IProviderContract that will hold the provider and decorate it with an Import attribute:

[Import]
public IProviderContract Provider { get; set; }

If you want more control on the identity of the dynamic provider you can use a CompositionContainer. This container will manage all the sources form which a provider can be created and coordinate the matching. The container needs a catalog to find all the providers.

Here is a simple example how to create a container:

var catalog = new AggregateCatalog();
var thisAssembly = new AssemblyCatalog(
                    System.Reflection.Assembly.GetExecutingAssembly());
catalog.Catalogs.Add(thisAssembly);

catalog.Catalogs.Add(new DirectoryCatalog”path”));

var container = new CompositionContainer(catalog);
          

Now when you have a container you can create a collection of all possible providers by calling: container.GetExportedObjects<IProviderContract>()

or by creating a simple property

[Import(typeof(IProviderContract))]
public ExportCollection<IProviderContract> Providers { get; set; }

This list can be queried to choose the right provider to use.

To trigger the matching between exports and imports you should call:

container.ComposeParts(all the attributed objects to be matched)

For example:
container.ComposeParts(this)

Now you are done. The consumer gets assigned a dynamically created provider ready to be used.

There is more you can do to better control the execution of MEF but this is for later posts.

Pub sub using .Net Services

In one of my last posts I spoke about pub-sub using WS discovery. Now I want to speak about the implementation of pub-sub using .Net Services.

.Net services is a future infrastructure running on the cloud that will provide ISB (Internet service bus) capabilities. The .Net services includes an access control infra, an orchestration infra, an addressing infra and finally a messaging infrastructure. I will go deeper on each of those on future posts.

The messaging infra comes in the form of WCF bindings so for anyone who uses WCF it is very easy to learn and use. Using this infrastructure solves critical communication problems for services deployed on different networks on the web. For example communicating through a firewall or bypassing NAT.

The main idea is the use of the mediator pattern (Microsoft Data Centers). If all parties can communicate to the mediator, communication can be established between them.

The messaging infrastructure introduces several messaging patterns. One of them is Pub-Sub. This is done using a binding called "netEventRelayBinding" There is a great example on the .Net Services SDK.

So if you want to enjoy pub-sub between networks on the web do not spend time and money on development of the infrastructure. Someone had done it for you. Consider using the .Net Services. We are now in the CTP phase but it is important to know where we are heading…

AJAX is not secure

AJAX is the new Hot technology concerning web application. It allows the client to do much more than it used to and to achieve a much better user experience.

AJAX is based on XmlHttpRequests that the browser creates while the page is presented on the browser. The client does not know that under the cover so many requests are being sent. Ajax is a java script technology running mostly on the client side and on the server the following question arises: will the average AJAX-enabled web-application be able to tell the difference between a real and a faked XmlHttpRequest?

The answer is NO. AJAX is a client side technology and we all know that the client should not be trusted.

This makes AJAX a much more difficult technology to protect. We all know how difficult is to bring application security to traditional server application. For AJAX it is double the effort.

AJAX is advancing rapidly and new frameworks are introduced frequently but none can secure the AJAX application in a reasonable manner.

From a business and an architectural point of view unfortunately today we have to make a tradeoff. Security versus User Experience.

Proper design can use AJAX in a sandbox. This means less sensitive areas of the application can enjoy AJAX but around the sensitive business and information an "AJAX Firewall" is built. For example there will be no AJAX enabled Web Service that exposes sensitive information.

If you do need to implement some AJAX remember that AJAX enables new XSS capabilities and so server validation must be much more strict. Not only the body of the http packet must be validated but all of its headers. Never trust a third party. AJAX applications fetch information from various untrusted sources such as feeds, blogs, search results. If this content is never validated prior to being served to the end browser, it can lead to dangerous cross-site exploitation.

With AJAX, a lot of the logic is shifting to the client-side.

This may expose the entire application to some serious threats.

The urge for data integration from multiple parties and untrusted sources can increase the overall risk factor as well: XSS, XSRF, cross-domain issues and serialization on the client-side and insecure Web services, XML-RPC and REST access on the server-side.

Conversely, Ajax can be used to build graceful applications with seamless data integration.

However, one insecure call or information stream can backfire and end up opening up an exploitable security hole.

These new technology vectors are promising and exciting to many, but even more interesting to attack, virus and worm writers.

To stay secure, first answer the question is AJAX really needed? Then make sure it lives in a sandbox and third make sure your developers are paying attention to implementation details and taking security into consideration.

Pub sub and WCF discovery in framework 4.0

I have implemented many pub sub infrastructures for many customers. I found out that one of the major rezones they used the pub sub infra was to be able to tell that a service just went up.

Now with WCF 4.0 all this pub sub infrastructure we built is not needed any more. A service can use WS Discovery messages and publish the fact that it is up. Simple and clean!

The question is what about other events?

Well you can always keep using the pub-sub infra but I am looking for a cheaper solution.

I personally think that an infrastructure should be built only when there is a really good reason.

There are two major alternatives

1.       Soon the .Net services will be released. They offer a pub-sub functionality using the .NetEventRelay binding. In future posts I will speak more about the .Net services.

2.       Another alternative is to use dummy services and WS discovery messages.
The idea is simple: For each event you want to publish just create a dummy service that do nothing. When the event occurs bring it up and use WS discovery to spread the message. The consumers will know to interpret that this dummy service notification actually means that a business event had happened.  After some time bring the dummy service down.
Loading a service and killing it has a performance price but for rare events this can be a nice solution that saves the need to build a whole infrastructure.

 

So what do you need to do to notify the world that you are up using WS Discovery?

 

1.  Add the following behavior and make sure your service uses it. You can of course always add this behavior to an existing one:

<behavior name="WSDiscoveryBehavior">

  <serviceDiscovery>

    <announcementEndpoints>

      <endpoint name="udpEndpointName"

                kind="udpAnnouncementEndpoint"/>

    </announcementEndpoints>

  </serviceDiscovery>

</behavior>


2.  All those who wants to listen to the notifications should use an announcement service.

So create an instance of such and register to its events

this.myAnnouncementService = new AnnouncementService();

 // Register to the events

this.myAnnouncementService.OnlineAnnouncementReceived +=

        new EventHandler<AnnouncementEventArgs>(this.OnlineHandler);

3. Host the announcement service to create listening endpoint for the Online (Hello) and Offline (Bye) announcement messages.

    this.myAnnouncementServiceHost = new ServiceHost(this.announcementService); 

    // Add the announcement endpoint

    this.myAnnouncementServiceHost.AddServiceEndpoint(new UdpAnnouncementEndpoint()); 

    this.myAnnouncementServiceHost.BeginOpen(

        (asynResult) =>

        {

            myAnnouncementServiceHost.EndOpen(asynResult);

        },

        null);

}

 

In the handler you have to make sure you get the right notification from the right service

private void OnOnlineAnnouncement(object sender, AnnouncementEventArgs e)

{

    EndpointDiscoveryMetadata discoveryMetadata =

        e.AnnouncementMessage.EndpointDiscoveryMetadata;   

    FindCriteria criteria =

        new FindCriteria(typeof(IDummyService));  

    if (criteria.IsMatch(discoveryMetadata))

    {       

 ...

    }

}

That is it.

Enjoy

 

Manu