Welcome to WindowsClient.net | Sign in | Join

Zuker On Foundations

The realm of .NET (WPF, WCF and all around)
WPF – ComboView – ComboBox with a TreeView

Update 26/09/2011 - There is an issue with the control where the entire tree is loaded, which may affect performance and memory allocation when working with many items. Unfortunately, I don’t think I would be able to fix that any time soon.

A few years back, I built a WPF control that I decided to share here now.
The control is called ComboView – A ComboBox showing a TreeView inside to display hierarchical data (you can use it for flat data if you need its features though).

The control provides some really nice built-in features that you can use.
The control uses another control that I had to write, called ‘ExtendedTreeView’. This control inherits from TreeView and adds some features on top of that.
Another thing, I used the ‘Reveal’ control provided by Bag’o’Tricks, it has some very cool stuff, worth a look.

Following is a common mode that you can use it for -

image

In order to see all the options and features, feel free to download the code with the showcases here – Zuker.WpfSamples.zip

Known Limitations:

  1. If you wish to bind to the SelectedViewItems or SelectedViewValues (Supports Two-Way), the source property must be of type ‘ObservableCollection<object>’
    1. If you wish to use SelectedViewValue / SelectedViewValues, you should set SyncSelectedViewValues to true.
  2. If you set selection in code – items or values, the SelectedViewItems property of the ComboView will not necessarily include these items right away.
    1. This is because of the true nature of WPF’s TreeView, I may have to expand the items internally
    2. If you’re dependent on that in the next line, put this logic in Dispatcher.BeginInvoke, it should be ready there.
  3. Since there were some patches along the way, and features that were added at a later stage, the code can be organized better
Posted: Oct 10 2010, 06:09 PM by Amir Zuker | with 7 comment(s)
Filed under:
WCF Contrib – Your own base Client Channel Classes

One of the core components in WCF Contrib is the ‘ClientChannel’ which handles the client side proxy creation and management, allowing you to easily call services, with the addition of environment support, using using, and comprehensive behaviors extensions model.

Currently, the built-in Client Channels can be instantiated with a configuration name which it loads the ChannelFactory with.
A common question is, how can you use the Client Channel if you like to instantiate the ChannelFactory in code.

The way to do that is to inherit from ClientChannel and override ‘CreateChannelFactoryCore’ and just return the ChannelFactory of your wish.
A more general solution, one that I recommend in every company that wants to use WCF Contrib, is to write your own base Client Channel classes to be used everywhere in your code.
This approach gives you a singular point where you can control how every Client Channel behaves and plug-in default behavior extensions.

Following is an example of such base classes. This example allows the developer to pass in a ChannelFactory to be used, that way, we enable the scenario of using a Channel Factory through code.

Code Snippet
public class MyClientChannel<T> : MyClientChannel<MyClientChannel<T>, T>
    where T : class
{
    public MyClientChannel() { }

    public MyClientChannel(ChannelManageOptions manageOptions)
        : base(manageOptions) { }

    public MyClientChannel(ChannelFactory channelFactory)
        : base(channelFactory) { }

    public MyClientChannel(ChannelFactory channelFactory, ChannelManageOptions manageOptions)
        : base(channelFactory, manageOptions) { }
}

public class MyClientChannel<TInstance, T> : ClientChannel<TInstance, T>
    where T : class
    where TInstance : ClientChannel<T>, new()
{
    private ChannelFactory _factory;

    public MyClientChannel()
    {
        OnInitialize(null);
    }

    public MyClientChannel(ChannelManageOptions manageOptions)
        : base(manageOptions)
    {
        OnInitialize(null);
    }

    public MyClientChannel(ChannelFactory channelFactory)
    {
        OnInitialize(channelFactory);
    }

    public MyClientChannel(ChannelFactory channelFactory, ChannelManageOptions manageOptions)
        : base(manageOptions)
    {
        OnInitialize(channelFactory);
    }

    void OnInitialize(ChannelFactory channelFactory)
    {
        //You can decide to disable factory caching if you provide it with a factory which is cached already
        //CacheChannelFactory = (channelFactory != null);

        _factory = channelFactory;
    }

    protected override ChannelFactory CreateChannelFactoryCore(string endpointName)
    {
        if (_factory == null)
        {
            //If the factory wasn't provided from outside, just call the base which tries to load it from the configuration
            _factory = base.CreateChannelFactoryCore(endpointName);
        }

        return _factory;
    }
}

Then, you can use it as follows -

Code Snippet
ChannelFactory<IService> myFactory = new ChannelFactory<IService>(
    new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:11000/MyService"));
using (MyClientChannel<IService> myClientChannel = new MyClientChannel<IService>(myFactory))
{
    myClientChannel.Channel.Do(null);
}
Posted: Oct 10 2010, 04:41 PM by Amir Zuker
Filed under:
StreamInsight In a Nutshell

I’ve been reading about StreamInsight lately, there’s a lot of buzz around it nowadays.

StreamInsight is mainly a data processing engine which has great performance and latency achievements, as well as massive throughput handling capabilities.
It generally targets systems which need to handle events in massive concurrency or in cases where short latency is needed for resolving the information results.

Let’s look at High Level Architecture -

http://media.techtarget.com/rms/misc/4streaminsight.jpg

The architecture resembles BizTalk to say the truth, and is common for such processing engines.
The main terms that you need to be familiar with -

  1. Event – An event can be any .NET class which represents an occurrence that should be processed by the processing engine. An event can have different shapes to describe the specific scenario.
  2. Event Sources – Any given source for inputting events into the processing engine. You build the input adapters yourself so you can implement whatever you wish to do with any given source.
    For example, you may have a source which publishes events via WCF Service, Push / Polling style, Feeds, Database, etc.
  3. Input Adapters – You implement input adapters as you need. The role of the input adapter is to get events from sources and push it over to the processing engine.
  4. Streams – The input adapters create an event stream that you can query against to extract any desired information.
  5. Complex Event Processing (CEP) Engine – The processing engine gets events from the input adapters, and handles the events altogether.
  6. Query – You create and define queries over input streams to retrieve any information you like.
  7. Output Adapters – Once you define the input streams and the desired query, you need to do something with the results. The processing engine distributes the proper results to your predefined output adapters where you can do anything you like.
  8. Event Targets – The target components to which you want to send the results to. For example, database, SharePoint, applications, logging, etc.

To get a notion of the order of things, let’s look at the following scenario -

You have a system which monitors a very busy high-way road and publishes events when every car passes by a certain point.
Let’s assume a new requirement is being presented - write an analytic processing system on top of that.
For example, let’s assume we need to extract the daily average amount of black cars that drive through the road.

This is a classic example for using StreamInsight.
Our first step would be to create the input adapter to get the events when a car passes by and push it over to the processing engine.
Then, we will define the query that interests us. You do that using LINQ. In this example I would query all the black cars that passed on a daily basis and get the average amount.
Afterwards, I will connect everything to my output adapter which persists the processed results into my database.
Finally, I can view the results on any given application since I have it already persisted.

General Pros -

  1. Great Performance and Scale-Up – This product is written in native C++ and does great work regarding performance and resource allocations. Furthermore, it knows how to scale-up. It uses more resources if available and take advantage of multi-core environments.
  2. Good architecture – Such architecture which consists of Input/Output and query models enables good and clean separation of things.
  3. Great product for dealing with massive concurrent events or short latency requirements

General Cons -

  1. Customization and External Code Support – The query model generates XML configuration which the processing engine can execute in its unmanaged code environment. This means that the code is executed in their environment. Such thing does enable very good performance on the one hand, but once you need to customize it or call external infrastructures, it becomes a more difficult task, especially if you don’t wish to affect the performance to the worse.
  2. Scale-Out – Currently, the processing engine is designed to work in-memory in one process. This means it doesn’t scale-out by design. You could perhaps write your own solution for that, but doesn’t come out-of-the-box.

There’s much more that you can learn deeper, such as event shapes, windowing, liveliness, CTI, configuration, deployment, testing, debugging, etc.

Starting on a New Path

After six months as a senior consultant and architect at Sela, I have decided to take on a new venture.

Myself and some other great guys are starting a new company, named CodeValue.

The company’s main focus is developing products for developers and ALM. We already have a product at heart, which we are really excited about, and some other very cool ideas.
Furthermore, I don’t intend to stop providing consultations and training, it’s a part of me.
As a company, the purpose is to make things simpler and better for you, the developers, and we will continue to implement projects in the software industry and help bring things to life.

I had a great time during my stay at Sela. I participated as part of the experts group which consists of highly skilled architects and consultants.
Throughout my stay, a relative short one, I had done some really nice things, such as co-authored the WCF 4.0 MOC, passed lectures, consultations, and had the chance of working in highly advanced technology development groups.

I really enjoyed working at Sela, and I’d like to thank the people for giving me the chance to be a part of it – Caro Segal, Dudu Bassa, Ishai Ram.
This doesn’t mean goodbye. The goal is to join hands and work together in the future.

Posted: Aug 22 2010, 03:34 PM by Amir Zuker | with 7 comment(s)
Filed under:
WPF – Editing Mode with Save and Cancel Capability – Serialization

In continuation of the previous posts -
WPF – Editing Mode with Save and Cancel Capability

WPF – Editing Mode with Save and Cancel Capability – Dynamic ViewModelProxy

In this post I will demonstrate an elegant and simple solution that you can use regarding the second option presented in the first post series (cloning via serialization).

The Use-Case

Often, in more advanced scenarios, you need to duplicate your object for a different view. (read the first post for more detail)

A commonly used technique is using serialization to clone the object. Unfortunately, in many times, our view models aren’t cloneable easily in their nature by using serialization, especially when we use PRISM within our view models. When using PRISM, your view models may contain references to all sorts of CAL services for example, which are usually non-serializable.

The common approach for dealing with this is using serialization events. You can set the fields not be serialized (or simply set them to null before serializing) and set their values after deserialization is complete.
You need to design your object to fit such cloning technique. For example, where would you register/instantiate your commands? constructor alone is no good due to the fact the we need to support duplication via serialization.

What I have to offer is..

  1. ViewModelBase – My ViewModelBase provides a method that you can override - InitializeCore(bool deserializing)
    1. This method occurs only once!
      1. If the object is being instantiated normally – part of the constructor
      2. If the object is being serialized – after deserialization completes
    2. This method provides easy access for implementing things needed either in cases of instantiation or serialization

One more thing..

I mentioned this above – in PRISM (and other cases), your view models are usually not easy to duplicate, look at the following example -

Note: The code here and in my samples are using the BinaryFormatter.

Code Snippet
public class MyViewModel : ViewModelBase
{
    IEventAggregator _eventAggregator;
    IUnityContainer _container;

    public MyViewModel(IUnityContainer container)
    {
        _container = container;
        _eventAggregator = _container.Resolve<IEventAggregator>();

        //Use the event aggregator to subscribe to events..
    }
}

Currently, MyViewModel is not serialiable.
In order to make it serializable, I need to decorate my class with the Serializable attribute, but that is not enough.
The serialization will fail because the fields _eventAggregator and _container are not serializable too.

In order to make the serialization work, here is what I need to do -

Code Snippet
[Serializable]
public class MyViewModel : ViewModelBase
{
    [NonSerialized]
    IEventAggregator _eventAggregator;

    [NonSerialized]
    IUnityContainer _container;

    public MyViewModel(IUnityContainer container)
    {
        _container = container;
        _eventAggregator = _container.Resolve<IEventAggregator>();

        //Use the event aggregator to subscribe to events..
    }
}

2 things have been made – 1) I set my class to be serializable 2) Marked the fields to not participate in the serialization process.

Is that all? Well, no.
The serialization and deserialization back will work fine and I will have a duplicate object. However, the state of the duplicate object would be incomplete – the _eventAggregator and _container would be nulls and no processing had been done.

Now what? well, in order to make all things work properly, I would have to encapsulate the duplication in one method (be that in my view model or somewhere else) to do the following -
Serialize the view model, call an exposed method to complete operation, return the duplicate.

For example -

Code Snippet
[Serializable]
public class MyViewModel : ViewModelBase
{
    [NonSerialized]
    IEventAggregator _eventAggregator;

    [NonSerialized]
    IUnityContainer _container;

    public MyViewModel(IUnityContainer container)
    {
        LoadState(container);
    }

    public void LoadState(IUnityContainer container)
    {
        _container = container;
        _eventAggregator = _container.Resolve<IEventAggregator>();

        //Use the event aggregator to subscribe to events..
    }

    public MyViewModel Duplicate()
    {
        MyViewModel other = Helpers.CloneBySerializing(this);

        other.LoadState(_container);

        return other;
    }
}

This is quite fine and gives us a neat solution.
My goal was to make such cases simpler though, since it is quite common in PRISM-based business applications.

Here is the solution

I built a nice wrapping on top of the binary serialization that you can use for such cases. (you can switch the actual serialization provider as you may need)
You can instruct it to serialize fields by ref.

Furthermore, it supports the entire object graph. If your view model contains other view models which have such decorated fields, it will process them as well.

This means, that upon serialization, it will set null to these fields and set their value back both in the duplicate and the original object.
So, using that, my view model looks as follows - (note the use of the InitializeCore I mentioned in the beginning of the post)

Code Snippet
[Serializable]
public class MyViewModel : ViewModelBase
{
    [NonSerialized, SerializeByRef]
    IEventAggregator _eventAggregator;

    [NonSerialized, SerializeByRef]
    IUnityContainer _container;

    public MyViewModel(IUnityContainer container)
    {
        _container = container;
        _eventAggregator = _container.Resolve<IEventAggregator>();

        //need to call it once more because in the base ctor the fields are null
        InitializeCore(false);
    }

    protected override void InitializeCore(bool deserializing)
    {
        if (_eventAggregator != null)
        {
            //Use the event aggregator to subscribe to events..
        }
    }
}

As you can see, I no longer need to worry about state preserving. I simply tag the fields I need to be set as references and do what I need in the InitializeCore implementation which occurs at the constructor or after deserialization when the fields already have their by-ref values.

While in such a simple case it is hard to see the benefit, when it comes to more complicated classes with deeper object graphs, it becomes much easier using this approach.

So.. how do you get the actual duplicate?
You need to call my wrapper in order to generate the duplicate. the internal implementation uses the BinaryFormatter but you can change that to NetDataContractSerializer/DataContractSerializer/XmlSerializer if you need.

Code Snippet
MyViewModel other = ObjectProducer.CloneByBinarySerialize(myViewModel);

Important Note – this serialization technique goes through the entire object graph, so it is advisable to use that in scenarios where you need to serialize a single object at a certain given time. (in this example, when the user edits an employee, the performance hit isn’t an issue for the benefit of using that)

You can download the source here - Zuker.WpfSamples.zip. (Edit State Preserve – EditWithCloneSerialize)
The sample shows a case of a really simple view model, but you can go ahead and try it with the example shown here, with the use of ‘SerializeByRef’.

Posted: Aug 09 2010, 11:42 PM by Amir Zuker | with 107 comment(s)
Filed under:
WPF – Editing Mode with Save and Cancel Capability – Dynamic ViewModelProxy

Update 29/07: The project was updated, there was a minor bug in the object changed notifier.

In continuation of a previous post -
WPF – Editing Mode with Save and Cancel Capability

In this post I will demonstrate an elegant and simple solution that you can utilize regarding the first option presented in the previous post.

The Use-Case

If you want to open an editable view over an existing read-only view with cancel capability, you usually wish you could use the same ViewModel instance as the DataContext.
However, this means that changes are reflected in the read-only view, plus, how would you implement the cancel operation?

The following solution demonstrates a dynamic proxy that I had written that you can use to provide elegant solution in cases where your ViewModel is simple.
By ‘simple’ I mean the ViewModel contains a set of self-contained properties (their setters don’t affect anything else) and that there are no commands needed for the editable view.

The common approach for such simple cases is defining the bindings with UpdateSourceTrigger set to ‘Explicit’.
My solution is simpler, it doesn’t require you to do that, thus you need not update the bindings upon save and such.
Moreover, my solution still provides a way to support IDataErrorInfo on the ViewModel!

The right pane contains the read-only view:
image
When clicking Edit, a dialog is shown:

image

Let’s see the code

When the user clicks ‘Edit’, the code opens the dialog with the DataContext set as follows -

Code Snippet
var proxy = new ViewModelProxy<EmployeeViewModel>(emp);
editView.DataContext = proxy;

When the user chooses Save or Cancel in the dialog, the following code merges the changes into the actual EmployeeViewModel -

Code Snippet
bool? result = editView.ShowDialog();

if (result.GetValueOrDefault())
{
    proxy.AcceptChanges();
}

That is all that is needed! Nothing else!
The proxy has another method - ‘RejectChanges’ if you need to reject the changes and go back to the state of the original EmployeeViewModel.

How is the magic done?

I implemented the ViewModelProxy using the DynamicObject that comes with .NET 4.0, sweet.
This can be done in previous .NET framework versions too. It would require more code though, you could implement a dynamic property bag with a type descriptor.

The ViewModelProxy performs mainly the following parts -

  1. When a property is set on it – it stores it into a local dictionary and notifies upon property changed
  2. When a property is requested from it – returns the value from the local dictionary if present, or from the source ViewModel otherwise.
  3. AcceptChanges applies the local dictionary values to the source ViewModel
  4. RejectChanges clears the local dictionary and notifies upon property changes.
  5. I mentioned it above, my solution supports IDataErrorInfo, make sure to check out the sample

You can download the source here - Zuker.WpfSamples.zip.

In the next post I will demonstrate another infrastructure I had implemented that you can use for more advanced scenarios.

Posted: Jul 23 2010, 09:11 PM by Amir Zuker | with 1 comment(s)
Filed under:
WPF – Editing Mode with Save and Cancel Capability

A common scenario that is required by applications is the ability to show an entity in a view mode, and when the user wishes to edit that entity, another view is loaded in edit mode.
In most cases, you would allow the user to save or cancel his changes.

To illustrate the concept, consider the following interface -

image When a user clicks ‘Edit’:

image

Usually, in a MVVM application, you would have a view model for each list item on the left screenshot.
When the user clicks ‘Edit’ and the editable view is shown as modal dialog, you may want to use the same view model.

However, if it is the same instance, how would you support cancelling the save operation. Additionally, how would you prevent that changes in the edit mode won’t be reflected in the view mode until the user chooses to save the changes. (If you use bindings, the change would reflect in the view mode as well, as long as the binding is active and the source is updated).

Well, there are numerous ways to go about it.

  1. Use the same instance: To use the same actual instance, a common approach is to define all the bindings in the editable view with update source trigger set to ‘Explicit’.
    This gives you the ability to save state explicitly when the user chooses to save his changes.
    This method isn’t suitable for all the cases. If you have more than a plain simple view model where properties may set other properties or commands can be invoked from the edit view – you’re in a dead end. Plus, you can’t use the IDataErrorInfo validation model since the bindings don’t update the source nor calls its validation methods.
  2. Use a separate instance using some sort of cloning and merging methods: To support more advanced scenarios, or simply provide a complete solution, you would generally prefer binding the editable view to a new instance.
    Obviously, you would need to construct the new instance, either imperative instantiation/cloning or use serialization which is quite a common technique in this scenario.
    Finally, if the user chooses to save his changes, you would need to merge back the changes to the instance in the view mode or simply replace it with the new instance.

I plan to address both the approaches mentioned above in the next post to show some nice extensions that you can use, so stay tuned.

Posted: Jul 17 2010, 11:02 PM by Amir Zuker | with 196 comment(s)
Filed under:
WPF – A Cool Feedback Control – 3D Book View Switching

Update 29/07: The project was updated, there was a minor bug in the object changed notifier.

A few years back I was looking for a good place to start with for building a nice feedback control.
The purpose was to allow end-users to provide feedback on the application on any given subject.

After browsing the internet, I found the following -
Creating a 3D book-shaped application with speech and in using WPF 3.5 by Roberto Sonnino.

It’s a very cool and a beautiful project, nice work Roberto!

To make the application fit into my solution, I made the following changes -

  1. I removed the speech and rotate functionality. There was no need for these features (although they’re very cool), you can edit the code to enable it back if you like.
  2. I wrapped it into a reusable control. There was quite some work to do in order to do that, but I managed :)
    1. Currently, there’s a small hack that needs to be done in order to use it with more than one instance. I didn’t invest the time to solve this since in most cases, you should have one instance in the application and that’s it.
  3. In the control, I edited the template and functionality to provide the ability of saving the feedback input
  4. I added some API methods to get the ink as image and the text in order to allow doing something useful with it

You can then choose to save the input and persist it somewhere, send notifications and whatnot.
Then, developers and project managers can take a look at the images and feedback users had sent them.

So.. how does it look like?

All you need to do in order to add this control is place the following XAML in your application’s main area -

Code Snippet
xmlns:controls="http://schemas.zuker.com/wpf/xaml/presentation"
        
<controls:FeedbackView x:Name="feedbackView" />

When running, there is a new addition in the bottom right corner (that’s the default) -

image

The above image is a bit small, I recommend you get the sample in the link below to see it in action.

When clicking it, you get the book working for you -

image

You can download the source and showcases here - Zuker.WpfSamples.
NOTE: The project contains more things I plan to address in future posts, so stay tuned :) (I will post when I update the project too)
In the application, just click the ‘FeedbackViewShowcase’ in the list.

Thanks for Roberto who was kind enough to allow me to share this.

WCF Contrib v2.1.1

Make sure you visit WCF Contrib home.

This release adds core optimizations and internal fixes to the infrastructure.
There are no breaking changes from the last version, only internal improvements.

In previous versions you may have encountered synchronization related errors such as recursive write/read locking.
These issues were resolved and you should no longer experience that.

This release is highly recommended over previous versions, make sure you use this one.

Posted: Jul 03 2010, 09:52 PM by Amir Zuker
Filed under:
WPF PRISM (CAL) / MVVM – DelegateCommand Extensions – Part 2

I recommend you read Part Two, some cool stuff :)

Posted: Jul 03 2010, 09:14 PM by Amir Zuker
Filed under:
WPF PRISM (CAL) / MVVM – DelegateCommand Extensions – Part 1

Well, it has certainly been a while since I got to a good posting rhythm, I hope it changes soon because I have a series of posts in mind.

This isn’t a post about general help and description for PRISM, MVVM, or DelegateCommand. There are many resources about these already.
This post is to demonstrate how I managed to extend the DelegateCommand with some really cool features.

The DelegateCommand that ships with CAL expects an “execute method” and a “can execute method” arguments in its constructor.
This is nice, but I wanted something more.

I am involved in a big WPF development project where we have many commands that their state depends on several state-related parameters. I could just “push” it all in the “can execute” method, however, I don’t quite like it due to the following:

  1. The code is written very imperatively
  2. You need to reserve fields for every command to trigger its “CanExecuteChanged” when the appropriate state changes
  3. No encapsulation, the code is scattered around, code gets repeated
  4. Difficulty to maintain – you need to search for all related places when the requirement changes and synchronize everything appropriately.
  5. Plain and simple - not pretty

The goal is to make the Delegate Command to be attachable with numerous state bound objects that can alert it when it needs to be refreshed.

Starting Point – Attachable Components

I needed to make a common interface for the attachable components that could be attached to the DelegateCommand, as follows -

Code Snippet
  1. public interface INotifyCanExecuteChanged
  2. {
  3.     event EventHandler CanExecuteChanged;
  4.  
  5.     bool CanExecute();
  6. }

To make things a bit more easy for future classes, I created also a base class -

Code Snippet
  1. public abstract class NotifyCanExecuteChangedBase : INotifyCanExecuteChanged
  2. {
  3.     public event EventHandler CanExecuteChanged;
  4.     protected virtual void OnCanExecuteChanged()
  5.     {
  6.         var evt = CanExecuteChanged;
  7.         if (evt != null)
  8.         {
  9.             evt(this, EventArgs.Empty);
  10.         }
  11.     }
  12.  
  13.     public abstract bool CanExecute();
  14. }

Step 2 – Enable INotifyCanExecuteChanged attachments to the DelegateCommand

Code Snippet
  1. public abstract class BaseDelegateCommandEx<T> : ICommandEx
  2. {
  3.     public BaseDelegateCommandEx(Action<T> executeMethod, params INotifyCanExecuteChanged[] notifiers)
  4.         : this(executeMethod, (IEnumerable<INotifyCanExecuteChanged>)notifiers)
  5.     { ... }
  6. }

At this point I got a delegate command that can get attachable notifiers. My command binds to the event of each notifier and raises its own CanExecuteChanged.
Additionally, there’s logic in the CanExecute to call the notifiers as well.

In Conclusion for this Part

This seals the first part of the Delegate Command Extensions.
The delegate command can get attachable notifiers which it bounds to and mange calls to them. This is the basic implementation that allows the developers to define a command and bind it to numerous state-bound notifiers.

Next Time..

I will show the continuation of the solution which turned our real nice, I recommend you stay tuned :)

Posted: Jul 01 2010, 08:16 AM by Amir Zuker
Filed under:
WCF Contrib v2.1 and .NET 4.0

We all know Visual Studio 2010 and .NET Framework had been released during the last week..

I’ve compiled WCF Contrib v2.1 in .NET 4.0 to be available for download if you need -

wcfcontrib.mar07.binaries.4.0.zip

Posted: Apr 16 2010, 11:17 AM by Amir Zuker
Filed under:
WCF Contrib v2.1 Mar07

A new release had been published - WCF Contrib v2.1 Mar07.

This release is the final version of v2.1 Beta that was published on February 10th, you can check the entire updates made from v2.0 further in this post.

You can distinguish between this release and the v2.1 Beta Feb10 by checking the assembly file version, in this release it was incremented to v2.1.0.1.

Changes from v2.1 Feb10 Beta:
There is a one small change which is a breaking change for those who used the asynchronous invocation pattern using the "InvokeChannelAsync" or "InvokeAsync". (protected methods of ClientChannel)
This is a seldom used pattern so the chances of that affecting you are pretty minimal.
The change is very simple, instead of working with AsyncServiceInvokeCallback in these methods, it gets the general AsyncCallback which it then calls by passing it a ChannelInvokeAsyncResult which contains all the information needed.

WCF Contrib Questions

I decided to blog about common questions I receive regarding WCF Contrib.

You can find all questions in the WCF Contrib FAQ.

Communication Patterns

  1. What's the best practice for web applications that call services?

    Research has shown that in concurrent environments such as web it is more scalable and has better performance to use a dedicated communication object per a sequence of invocations (sequential - one call after another in the same execution chain flow).

    It's important to note that for few users, you may notice that using a single communication object to address them all may work faster, however, as soon as more requests come in you should see a noticeable decrease in your application performance, which is bad.

    In essence, you should use the singleton instance for single calls or instantiate a new client channel with Sequential/SequentialAsyncOwnChannel to perform a sequence of calls at a given time and dispose it when you're done with it.

Client Channel

  1. When should I set the GlobalEndpointName?
    ClientChannel<T>.GlobalEndpointName = "myEndpointName";

    This needs to be set only once since it's the global name that will be used for all client channels created for the specific 'T' contract.
    It is usually placed in the process main entry point.

    Note that in WCF Contrib v2.1, if you have a single endpoint in the configuration for the given contract, you don't have to specify the endpoint name at all, it will pick it up automatically.
  2. When should I call LoadRuntime?
    ClientChannel<T>.LoadRuntime();

    This also needs to be called once, it too will usually be placed in the process main entry point.
    It is a good practice that you call it whenever you can spare time to load the runtime behavior information, this isn't a necessity though. If you don't call it the infrastructure will automatically load the runtime information upon first access.
  3. Is disposing the singleton instance mandatory?
    using (ClientChannel<T>. Instance) { }

    The implementation of IDisposable in the client channel disposes the channel factory and communication object associated with the client channel.

    The necessity of calling the dispose depends on the channel management mode.
    The singleton instance is set with SingleCall, this means that behind the scenes upon every call a communication object is created and terminated right after.

    That indicates it is not a necessity to call the dispose for such management mode. (The dispose of the factory isn't critical in this point since it just disposes the communication objects associated with it which were already disposed by the client channel infrastructure)

    As a general approach, I'd say "If it's IDisposable and you're done with it, dispose it".
    If you have control at your application/process exit point and you know which client channels you were using, I don't see a reason not disposing it.
Posted: Feb 10 2010, 12:22 PM by Amir Zuker
Filed under: ,
WCF Contrib v2.1 – Customize Output Caching Provider

Via http://wcfcontrib.codeplex.com/wikipage?title=ClientChannelOutputCache

Output Cache Provider Factory
This is the factory class that is responsible for creating the actual output cache provider.
This is where you extensibility point kicks in, you can replace the built-in factory with your own, read about it here.

The factory needs to have a public parameter-less constructor and implement 'IOutputCacheProviderFactory'

public interface IOutputCacheProviderFactory
{
    IOutputCacheProvider CreateProvider();
}

As you can see, this is a simple factory interface for providing the actual provider implementation.

Output Cache Provider

Output cache provider is where the magic really happens.
This is where you should implement your custom output caching solution if you like.
public interface IOutputCacheProvider
{
    void AddItem(OutputCacheItemKey key, OutputCacheInterval interval, object value);
    bool TryGetItem(OutputCacheItemKey key, out object value);
}
  • AddItem - this method is supposed to add a new item to the output cache solution.
  • TryGetItem - this method should look up the output cache solution for the item that was stored.
  • OutputCacheInterval - you're getting the desired interval as a parameter.
    • Consider setting the fields "LastVisitedAt" and "AddedAt" to the proper values at a given time so you can reference it later.
    • You can use "IsActive()" method if you like to check whether the interval is active for the current time according to its policy and time properties.
Note: If the provider implements IDisposable, it will be disposed once the OutputCacheController is disposed.
The built-in provider is called "IntervalBasedCacheProvider", it is important to know this since this too is written in a reusable way where you can plug-in your custom store.
The provider gets two parameters in its constructor:
  1. purgeTimerIntervalInMilliseconds - The interval in milliseconds for the timer that is in charge of iterating the items and purging those which are inactive.
  2. store - An implementation for IOutputCacheStore
    1. AddItem - The provider basically saves the key and interval in its local state, sets the time properties of the interval to the current time and adds the item to the store.
    2. TryGetItem - When an item is requested from the cache, the provider checks if there's an active key in its local state, if so, sets the last visited time to the current time and gets the item from the store.
    3. Removing Items - In the timer callback, it iterates the keys in its local state and removes the inactive ones from the store

Output Cache Store
The store is responsible for storing the items.
public interface IOutputCacheStore
{
    void SetItem(OutputCacheItemKey key, object value);
    void RemoveItem(OutputCacheItemKey key);
    bool TryGetItem(OutputCacheItemKey key, out object value);
}

The store that is provided with the built-in solution is using the SynchronizedDictionary that is a part of WCF Contrib as well.

Implementing your own custom output caching solution
You can go about it in two ways:

  1. Plug-in your own factory and provider and implement a different scenario - you can use this approach to write a provider that uses an interval-based caching solution such as HttpRuntime Caching, Enterprise Library, etc
  2. Plug-in your own factory and still use the built-in IntervalBasedCacheProvider only with your own custom store, such as a AppFabric caching, file-system, database, etc
Output Cache Item Key
It's important to recognize the description of the item keys if you like to implement you own solution since you will need a way a way to correlate between the item and key.
  • The key contains the operation action and parameters and custom equality comparers if any were provided.
  • It can be used as a dictionary key since it overrides Equals and GetHashCode by calculating it over the action and parameters using the appropriate comparer.
  • ToString() is also overriden to return the aggregation of the action and parameters.
Posted: Feb 08 2010, 09:15 PM by Amir Zuker
Filed under: ,
Next page »
Page view counter