Tuesday, May 29, 2012

But it is not our competitive advantage!

The financial industry (Capital Markets specifically) is a fiercely competitive arena of high risk, high return and space age technology. The competition between banks, hedge funds and exchanges leads to a very closed-source style of application development. IT secrets are closely guarded. Non-compete clauses are common place and Non Disclosure Agreements are taken very seriously. Like in other industries, time-to-market and rich feature sets increase the likely hood of an application or platform making profit.

To get the best product delivered in the fastest time, the best of breed developers and consultants are wheeled in and money is generally thrown at the problem. All the same old stuff is built from ground up hidden away from prying eyes to protect any market secret getting out. Features start getting built; Security (Authentication/Authorization/Auditing), Low latency Messaging, Blotters/Grids controls, Concurrency frameworks, Modular UIs, Blotters, Order books, Matching algorithms, Blotters, Pricing engines, Discounting curves, JSON/Fix/ProtoBuf Serializers, Risk Visualizers, Blotters, Search tools, Research tickers and of course we should build a blotter!

It is most certainly the case that all of these things are being done by the direct competitor, by a group of similar people, with similar skill sets, falling into the same problems and building the same bugs. All behind closed doors. All at consultant rates.

Managers and business owners feel the need to carefully guard their babies (the project source code) because it is the sum of the effort and more importantly the money invested in the project. To let it out in to the public would be (in their minds) the same as leaving a chest of gold open in a public park or their password to the company bank account on a post-it note. But this is not the case.

Let's enumerate the silly realities of the scenario:

  1. For the consultant to get the job they must exhibit the requisite experience delivering said technology. This means the consultant may be just reproducing their effort. Surely you are hiring the consultant to succeed on their last project right? So to get ahead of the competition you have hired the guy that has finished building their competing product.
  2. Once the consultant has built their part of the product, they either have to document it at huge cost, train the team in how it works, or just leave the project keeping all the knowledge of how it works. They move on to the next project, build another blotter, rinse and repeat.
  3. Consider the need to apply any modifications (improvements or bug fixes) to the code base.  The consultant could be applying their new features to their new version of the feature at competitor X. Your current team of developers could be applying it to your product. Either way, the same general concept is being refined either at twice the necessary cost, or features are being added to one leaving the other behind.

For a concrete example, consider the feature we are talking about is a grid control (commonly called a blotter in finance). Many will argue that the cost of a blotter is just not even enough to warrant even considering. Not true. I have been on 4 projects now where the Blotter or central grid has been the number one development cost. You can argue that we can just buy a control, but those 3rd party controls are lousy. My position is not a case of Not Invented Here mentality; I do advocate 3rd party tools like Rx, Moq, Prism, charting tools, Messaging layers etc...but only when they pay for themselves. Adopting large 3rd party libraries for a single feature or needing competing libraries installed because neither quite fits the requirements needs to be a thing of the past. I have worked with amazing developers that get pulled off otherwise critical work to help work on the blotter. With all that money that is poured into the blotter, we had better keep that blotter source code a trade secret! or should we.....?

But it is not our competitive advantage!

None of the four projects I worked on wanted to be defined by their blotter; they wanted to be defined by

  • Speed of user input
  • Quality of context sensitive research
  • Timeliness of data
  • User experience
  • Competitive prices
  • Depth of research data
  • Breadth of data across assets
  • Liquidity

So now considering that a blotter is not your competitive advantage and you as a manager were brave, and smart enough, to split your code base into code that is not sensitive and code that contains actual trade secrets. Now when that super expensive consultant builds that blotter for you, it may already be half built because it was open source in the first place. Consider when the consultant leaves and re implements that at the competitor, they may find bugs and fix them. Great! You just got that hugely expensive consultant to upgrade your product for free! Sure the competitor got the fix too, but you have tighter spreads, right? Lower latency, right? Better customer service, right? Why pour money into another blotter, another concurrent collection library, another export to Excel feature, another login system, another drag-n-drop feature? Spend your money on your competitive advantage.

Leaders in the field are coming together now to banish this kind of wasteful behaviour. The Lodestone Foundation is looking to open source much of what is burning a hole in capital market IT budgets around the world. They have a sort of rough road map of features and areas that they want to address. This is not a silver bullet but it is a huge step in the right direction. With people like Martin Thompson involved, it is likely to get traction at least with lowly developers. Martin has already proved that you can open-source key parts of the system while still keeping trade secrets and remaining competitive.

Microsoft, lead by Herb Sutter, is pushing for the same kind of collaboration in the C++ space. Projects like Casablanca are aiming to reduce the same wasteful practices in the C++ world by providing portable libraries for general consumption.

From what I understand (via rumours mainly), the thinking is; if we as an industry can spend less money and time reinventing the same wheel for each project, real effort can be put into valuable technical advancement. The beauty with this is the huge IT budgets the capital market projects have can now effectively fund R&D for the greater good. If all the code produced is Open-Source, well maintained and has a thriving community, all will benefit regardless of industry. Imagine advances in risk analysis simulations being used to help design safer cars, order matching algorithms used to help DNA research, financial time-series predication techniques used in speech recognition software.

I personally have been working on my own (much smaller scale) project that fits in with these ideals. Time will tell if they end up being complementary (I hope they do). Until then, go sew the seed with your manager that if your data-access layer, unit testing framework and logging framework are all open source, why can't your blotter* be too?

*blotter is my bugbear. Use whatever industry agnostic thing your project is building that really is just the same as the competitions as your focal point.

Technorati Tags: ,

Friday, March 23, 2012

Rx v2.0 Beta released

Some good news recently that the Rx team have released the beta of Rx 2.0.

It is a move forward and will leave .NET 3.5, .NET4.0, Silverlight 3 and Silverlight 4.0 behind. For this release the supported platforms are .NET4.5 beta (+ Metro), Silverlight 5 and Windows Phone 7.1.

There is a channel9 video (+1hr) with Bart De Smet explaining the new release. Bart also has a blog post on the release too.

As the underlying platform has moved rather drastically there are some surface/api changes. So some old code may break. The good news is that the Rx team have worked hard to squeeze even more performance out of this release. Part of this is support for async/await pattern (which was in experimental releases already).

I am looking forward to giving it crack. Win8 seems faster, Visual Studio 11 seems faster and now Rx is faster. Happy days!

Tuesday, June 21, 2011

The definitive list of Rx sites

Over at the Rx forums, Eamon_OTuathail has created what seems to be the list of Rx sites. It is a list of Blogs and open source projects.
Great stuff. This should save a lot of time for a lot of people.
http://social.msdn.microsoft.com/Forums/en-US/rx/thread/2cbd3b1c-d535-46ba-a9cf-3cd576a8e7c2
Humbled to make the grade.

EDIT: Hopefully www.IntroToRx.com will also make the grade. It is the online book that evolved from the blog series.

Saturday, June 18, 2011

Isolating custom Library dependencies versions from consumer dependency versions

This post is more about the CLR and dependency management than it is about Rx. However at this point in Rx’s lifecycle it seems relevant to comment on. The same principles could obviously be applied to open source projects et. al.

I have recently heard of an interesting situation that no-doubt has proved troublesome to people before. This problem is particularly interesting with Rx and it’s recent rate of versions. If you are trying to incorporate Rx into a library of yours and you then want to publish that library, you are effectively forcing users to use the same version of Rx that you do. Considering that a version of Rx comes out say every two months and that often there are breaking changes, this can create quite a mess. It is also made more interesting that up until recently they have not specified if a release was experimental or considered stable.

To provide an example to better understand my particular point; imagine you have a library that wraps a messaging platform. You want to avoid the use of Events and APM, and expose things via IObservable<T>. You feel happy that IObservable<T> is exposed natively in .NET 4 so you should not have to expose your implementations of Rx. You do however, want to use Rx as it has features you need and don’t want to (re-)write yourself. Your standard approaches to package/deployment are:

  • deploy the parts of the Rx libraries you use with your code. Users can just put them all into a “lib\MyFramework” folder and reference them.
  • excluded the libraries from your code and set Specific Version = False and hope your code will work with the consumer’s version of Rx
  • use a package management tool like Nuget to publish your package and specify the valid versions of Rx your library will work with.
  • rely on things being in the GAC so you can utilise the side-by-side versioning it provides
  • just try and implement the parts of Rx you want and avoid DLL Hell.

I gave this some thought and I think I have come up with a solution that could help library authors protect themselves. While there is the obvious option of using Nuget as part of your dependency management, this does not solve the problem, it just eases the pain. If the customer wants to use the latest version of Rx and you only support the 3 previous versions, your customer is still in some trouble.

The theory i had was that I can specify the specific version of Rx I want to reference in my library, the problem being that it may be named the same as the client’s referenced version. Depending on where their references were built to, they could overwrite each other. It seemed the solution was to embed the dependency into my library.

This turns out to actually be quite easy. If you have a project in visual studio that references your version of Rx, you have to follow these steps:

  1. Ensure you have a file reference (not a project or a GAC reference) to the dependency, in this case System.Reactive.dll
  2. Set the reference to be Specific Version = True
  3. Set the reference Copy Local = False
  4. Embed the dependency into your library. I created a folder in my project called EmbeddedAssemblies. I “Add Existing…” to this folder, navigate to the dependencies (just System.Reactive.dll in this case), and then choose “Add as Link…”
  5. Set the “Build Action” of  the newly added link to Embedded Resource
  6. Ensure that the resource is loaded correctly at run time…

The last part of that list proves to be not too hard. You can hook on to the AppDomain.AssemblyResolve event and load your embedded resource. You can return your embedded dependency by reading the byte stream and creating the assembly from it and then returning that in the event handler

internal static class DependencyResolver
{
  private static int _isSet = 0;

  internal static void Ensure()
  {
    if (Interlocked.CompareExchange(ref _isSet, 1, 0) == 0)
    {
      var thisAssembly = Assembly.GetExecutingAssembly();
      var assemblyName = new AssemblyName(thisAssembly.FullName).Name;
      var embededAssemblyPrefix = assemblyName + ".EmbeddedAssemblies.";

      var myEmbeddedAssemblies =
        Assembly.GetExecutingAssembly().GetManifestResourceNames()
          .Where(name => name.StartsWith(embededAssemblyPrefix))
          .Select(resourceName =>
                    {
                      using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                      {
                        var assemblyData = new Byte[stream.Length];
                        stream.Read(assemblyData, 0, assemblyData.Length);
                        return Assembly.Load(assemblyData);
                      }
                    })
          .ToDictionary(ass => ass.FullName);

      AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                                                    {
                                                      Assembly assemblyToLoad = null;
                                                      myEmbeddedAssemblies.TryGetValue(args.Name, out assemblyToLoad);
                                                      return assemblyToLoad;
                                                    };
    }
  }
}

You can return null in the event handler to say I don't know how to load this assembly. This allows others to be able to have a go at loading the assembly in the same way.

Next, to ensure that my embedded dependency resolver is called, I opted to make a call to it in the static constructor of the key types in my library. eg

public class SomeProvider
{
  static SomeProvider()
  {
    DependencyResolver.Ensure();
  }

  //other stuff goes here...
}

Have a look at the example code by downloading this zip file

Caveats : This is a thought and the code and concepts are only demo quality. I have not used this in production quality code. I also have not verified that the license allows for this style of packaging.

Further links:

Sunday, June 5, 2011

Rx v.1.0.10425–Breaking changes!

For those that follow Rx, many will have noticed a new drop was made available in late April 2011. This was interesting for numerous reasons:

  1. I believe that it was the first drop since the Rx team move off of the dev labs site and on to the Microsoft Data site
  2. They have supplied two downloads, Supported and Experimental
  3. It is available via Nuget
  4. It broke most of the sample code of this blog
  5. ...It has massive breaking changes !

The first thing I noticed was that only the more recent frameworks were in the “supported” release i.e. .NET 4, Silverlight 4 and Windows Phone. Next, when you open up the install directory (which has moved, again) the files are different to previous releases.

This is a comparison of the location and files of the old v.s. new version (.NET 4 target):

C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2856.0\Net4
System.CoreEx.dll
System.Interactive.dll
System.Linq.Async.dll
System.Reactive.ClientProfile.dll
System.Reactive.dll
System.Reactive.ExtendedProfile.dll
System.Reactive.Testing.dll

C:\Program Files\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0
Microsoft.Reactive.Testing.dll
System.Reactive.dll
System.Reactive.Providers.dll
System.Reactive.Windows.Forms.dll
System.Reactive.Windows.Threading.dll

Note the files names are named System.Reactive instead of hijacking the existing BCL namespaces such as System, System.IO, System.Linq etc. Here are a list of the old and new Namespaces found in the Rx libraries with the count of the Types in each namespace.

C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2856.0\Net4
System                         6
System.Collections.Generic     21
System.Concurrency             14
System.Diagnostics             1
System.Disposables             8
System.IO                      1
System.Joins                   34
System.Linq                    13
System.Reactive.Testing        4
System.Reactive.Testing.Mocks  10
System.Threading.Tasks         1
System.Web                     1
System.Windows.Forms           1
System.Windows.Threading       1

C:\Program Files\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0
Microsoft.Reactive.Testing     7
System                         1
System.Reactive                10
System.Reactive.Concurrency    16
System.Reactive.Disposables    9
System.Reactive.Joins          34
System.Reactive.Linq           8
System.Reactive.Subjects       8
System.Reactive.Threading.Tasks 1

Summary of impact

Here is a quick list of the changes that have affected the code from the samples off this blog

Unit has been moved to System.Reactive. I imagine to prevent any conflicts with FSharp’s Unit?

EventLoopScheduler no longer has a constructor that takes a string for the name of the thread, it instead takes a function to act as a Thread Factory so you can use that to specify a name for the thread instead.

Similar methods have been collapsed to overloads. For example; BufferWithTime, BufferWithCount & BufferTimeOrCount are all just Buffer with various overloads. Same goes for WindowWithTime, WIndowWithCount & WindowTimeOrCount. GenerateWithTime is now just an overload of Generate. CreateWithDisposable is now just an overload of Create.

Potentially confusing names have been adjusted. I must admit, I found AsyncSubject and odd name, and also found it odd that Prune was the method you would use to transform an existing observable to one that exhibited AsynchSubject behaviour. The new version of this is the far more appropriately named TakeLast(int). Obviously just pass a value of 1 to get the old semantics of Prune.

The Run method has now been renamed the more obvious (well to new comers) ForEach. It is a bit of an enumerable construct, but that is cool.

My big problem has been the disappearance of the IsEmpty extension method. So I had a long think about this and have decided that you can replace it by creating your own extension method that looks like this

public static class ObservableExtensions
{
  //Is missing now the System.Interactive has been dropped
  public static IObservable<bool> IsEmpty<T>(this IObservable<T> source)
  {
    return source.Materialize()
        .Take(1)
        .Select(n => n.Kind == NotificationKind.OnCompleted
                      || n.Kind == NotificationKind.OnError);
  }
}

For even more details, check out the forum post that has the summary release notes and allsorts of rants about what has changed and what is causing problems for other (+ some helpful tips).

http://social.msdn.microsoft.com/Forums/en-US/rx/thread/527002a3-18af-4eda-8e35-760ca0006b98

This change is not one that you can just take and expect all to be well. However assuming that you can just update some references and add the missing extensions to you own library, you could be fine.

Changes to TestScheduler

The real problems come from the big changes to the testing part of Rx. This appears to have undergone a complete change and most of my existing code does not work. This looks like a big and possibly welcome change to the TestScheduler.

Problems with the previous TestScheduler

There were some fundamental problems with the TestScheduler as it was. There were problems with running it to a specific point in time if there were not any actions scheduled for that point in time. For example, the old TestScheduler would allow you to request that it run to say 5seconds. If there were no actions scheduled, then the clock would not actually advance. You could then Schedule an action to happen at 3Seconds (effectively in the past) and then call Run and it would execute the actions. Hmmm.

TestScheduler scheduler = new TestScheduler();
scheduler.Schedule(()=>{Console.WriteLine("Running at 1seconds");}, TimeSpan.FromSeconds(1));
scheduler.RunTo( scheduler.FromTimeSpan(TimeSpan.FromSeconds(5)));
//The next line is scheduled in the past and somehow this all works!
scheduler.Schedule(()=>{Console.WriteLine("Running at 3seconds");}, TimeSpan.FromSeconds(3));
scheduler.Run();

There also seemed to be a lack of functionality for running to a relative point in time. I have used these extension methods to work around this shortcoming.

public static class TestSchedulerExtensions
{
  /// <summary>
  /// Runs the scheduler from now to the given TimeSpan. Advances relative to it's <c>Now</c> value.
  /// </summary>
  public static void RunNext(this TestScheduler scheduler, TimeSpan interval)
  {
    var tickInterval = scheduler.FromTimeSpan(interval);
    scheduler.RunTo(scheduler.Ticks + tickInterval + 1);
  }

  public static void RunTo(this TestScheduler scheduler, TimeSpan interval)
  {
    var tickInterval = scheduler.FromTimeSpan(interval);
    scheduler.RunTo(tickInterval);
  }

  public static void Step(this TestScheduler scheduler)
  {
    scheduler.RunTo(scheduler.Ticks + 1);
  }

  /// <summary>
  /// Provides a fluent interface so that you can write<c>7.Seconds()</c> instead of <c>TimeSpan.FromSeconds(7)</c>.
  /// </summary>
  /// <param name="seconds">A number of seconds</param>
  /// <returns>Returns a System.TimeSpan to represents the specified number of seconds.</returns>
  public static TimeSpan Seconds(this int seconds)
  {
    return TimeSpan.FromSeconds(seconds);
  }
}

However on initial inspection of the new TestScheduler there appears to be features that support running to an absolute or relative time. It looks like that the Post on testing Rx will need a re-write Sad smile

Technorati Tags: ,

Sunday, May 29, 2011

Rxx - Extension to the Reactive Extensions…

For those of you that use the Rx forums you will have no doubt found an answer or even had your question answered by either James Miles or Dave Sexton. These two have put their mighty brains together to produce some handy extensions to Rx. They went with the fairly obvious (but tongue-in-cheek) name Rxx.

http://social.msdn.microsoft.com/Forums/hu-HU/rx/thread/32f6ee34-5edf-4038-894c-ab47fc893a78

The key features that anyone that has been using Rx for a while will immediately be interested in are the

  • Tracing/Logging
  • PropertyChanged and PropertyDescriptor extensions
  • FileSystemWatcher
  • and the uber-funky OperationalObservable eg. var os = xs + ys – zs;

For a more complete list look at the documentation.

This could well be a community contribution that could help guide the actual Rx implementations that start coming out of Microsoft (like the Community Extensions around for P&P propjects). James and Dave seem to be taking this quite seriously. They have been checking regularly (with sensible comments!), constructed the codeplex site very well and have already got their issue trackers running.

This is one to keep an eye on.

http://rxx.codeplex.com/

Technorati Tags: ,

Wednesday, May 25, 2011

Rx code from Perth Presentation

Sorry about the delay in getting this code up. For those who could not make it, my part of the presentation did a bit of an intro and then discussed the testability of Rx and the easy way to deal with streaming data such as pricing in a financial industry.

RxSamplesGalleryScreenShot

RxSamplesTWAPChartScreenShot

The key samples from my half of the presentation that raised some interest was the testability of the Photo Gallery View model. The Gallery ViewModel was effectively this

/// <summary>
/// Tested Rx implementation of the ViewModel
/// </summary>
public sealed class RxPhotoGalleryViewModel : INotifyPropertyChanged
{
    public RxPhotoGalleryViewModel(IImageService imageService, ISchedulerProvider scheduler)
    {
        IsLoading = true;
        var files = imageService.EnumerateImages()
                                .ToObservable();

        files
            .SubscribeOn(scheduler.ThreadPool)
            .ObserveOn(scheduler.Dispatcher)
            .Subscribe(
                imagePath =>
                {
                    Images.Add(imagePath);
                },
                () =>
                {
                    IsLoading = false;
                });
    }

    private readonly ObservableCollection<string> _images = new ObservableCollection<string>();
    public ObservableCollection<string> Images
    {
        get { return _images; }
    }

    private bool _isLoading;
    public bool IsLoading
    {
        get { return _isLoading; }
        set
        {
            if (_isLoading != value)
            {
                _isLoading = value;
                InvokePropertyChanged("IsLoading");
            }
        }
    }

    #region Implementation of INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void InvokePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

Except from the constructor, there is really just two properties that expose change notification for the WPF binding engine. Now the code in the constructor is demo-quality in the sense that it is not good practice to do so much work in the constructor. Maybe this would be better

public sealed class RxPhotoGalleryViewModel
{
    private readonly IImageService _imageService;
    private readonly ISchedulerProvider _scheduler;

    public RxPhotoGalleryViewModel(IImageService imageService, ISchedulerProvider scheduler)
    {
        _imageService = imageService;
        _scheduler = scheduler;
    }

    public void Start()
    {
        IsLoading = true;
        var files = _imageService.EnumerateImages()
                                .ToObservable();

        files
            .SubscribeOn(_scheduler.ThreadPool)
            .ObserveOn(_scheduler.Dispatcher)
            .Subscribe(
                imagePath => Images.Add(imagePath),
                () =>IsLoading = false);
    }
//....
}

The test fixture is fairly simple. We pass in a mock implementation of the IImageService and the TestSchedulerProvider similar to the one shown in Rx Part 8 – Testing Rx.

[TestClass]
public class RxPhotoGalleryViewModelTests
{
    private Mock<IImageService> _imageSrvMock;
    private TestSchedulderProvider _testSchedulderProvider;
    private List<string> _expectedImages;

    [TestInitialize]
    public void SetUp()
    {
        _imageSrvMock = new Mock<IImageService>();
        _testSchedulderProvider = new TestSchedulderProvider();

        _expectedImages = new List<string> { "one.jpg", "two.jpg", "three.jpg" };
        _imageSrvMock.Setup(svc => svc.EnumerateImages())
                        .Returns(_expectedImages);

    }

    [TestMethod]
    public void Should_add_ImagesServiceResults_to_Images()
    {
        //Arrange
        // done in setup

        //Act
        var sut = new RxPhotoGalleryViewModel(_imageSrvMock.Object, _testSchedulderProvider);
        _testSchedulderProvider.ThreadPool.Run();
        _testSchedulderProvider.Dispatcher.Run();

        //Assert
        CollectionAssert.AreEqual(_expectedImages, sut.Images);
    }

    [TestMethod]
    public void Should_set_IsLoading_to_true()
    {
        //Arrange
        // done in setup

        //Act
        var sut = new RxPhotoGalleryViewModel(_imageSrvMock.Object, _testSchedulderProvider);
            
        //--NOTE-- note the missing TestScheduler.Run() calls. This will stop any observable being processed. Cool.

        //Assert
        Assert.IsTrue(sut.IsLoading);
    }

    [TestMethod]
    public void Should_set_IsLoading_to_false_when_completed_loading()
    {
        //Arrange
        // done in setup

        //Act
        var sut = new RxPhotoGalleryViewModel(_imageSrvMock.Object, _testSchedulderProvider);
        _testSchedulderProvider.ThreadPool.Run();
        _testSchedulderProvider.Dispatcher.Run();

        //Assert
        Assert.IsFalse(sut.IsLoading);
    }
}

As we now control the scheduling/concurrency we don't have to try to do anything fancy with Dispatchers,  BackgroundWorkers, ThreadPools or Tasks which are very difficult to perform unit testing on. Check out the pain that I went through to test responsive WPF apps in this post on Testing Responsive WPF complete with DispatcherFrame and Thread.Sleep(300) in my tests Sad smile

If you want the running code you can either pull the code down via SVN by following this http://code.google.com/p/rx-samples/source/checkout or you can download the zip.

The PowerPoint presentation is here

You may also be interested in the Design Guidelines produced by the Rx team at Microsoft and also where to get the latest version of Rx

Back to the contents page for Reactive Extensions for .NET Introduction