Dmitry Shechtman's Blog

December 13, 2014

AsyncActivator: Targeting Silverlight

This is an (unplanned) article in a series concerning AsyncActivator, a generalization of the .NET Asynchronous Factory pattern:

  1. Basics
  2. Cancellation
  3. Portability
  4. Silverlight

Dependency injection is quite a complex issue that garners a series of its own.

If you’ve been following this blog, you might have noticed that I’m a bit of a perfectionist. Although my latest article concluded:

Our portable AsyncActivator is now compatible with all platforms we’re aware of, save for legacy (i.e., non-Windows-Phone) Silverlight, which supports neither async/await (out of the box) nor reflection (to our requirements).

that little Silverlight box left unchecked kept bothering me. So with a little extra effort I made Ditto.AsyncInit and (some of) its upcoming child libraries compatible with Silverlight 5.

Now, don’t get me wrong. I’m fully aware of Silverlight’s current status — if it’s of any indication, Microsoft’s Immutable Collections library, released in mid-2013, targets every possible platform (including Xamarin), but not Silverlight.

However, that old dog can be taught the async/await trick, meaning many developers maintaining existing applications could benefit from asynchronous initialization having taken care of. If you happen to be a Silverlight developer with asynchrony in mind, you may find this article useful. Regardless of your plans of using any of the Ditto.AsyncInit components, you might still be interested in some of the challenges I encountered while making them compatible with Silverlight.

(more…)

November 30, 2014

AsyncActivator: Targeting Multiple Platforms

This is the third article in a series concerning AsyncActivator, a generalization of the .NET Asynchronous Factory pattern:

  1. Basics
  2. Cancellation
  3. Portability
  4. Silverlight
  5. Dependency injection

The Problem

Two previous installments discussed an implementation of AsyncActivator, later extended to support cancellation. Today we’re going to make it Portable Class Library (PCL) compliant.

AsyncActivator works great on the full-blown .NET Framework 4.5, but what if we wanted to use it, say, on WinRT?

We’ll start by creating a new Class Library (Portable) project and adding our existing files to it:

  • AsyncActivator.cs
  • AsyncInitBase.cs
  • CancelableAsyncInitBase.cs
  • IAsyncInit.cs
  • ICancelableAsyncInit.cs

Make sure the Silverlight box is unchecked, and it builds without a hitch. However, trying to run our UniversalAnswerService example results in:

Unhandled Exception: System.MissingMethodException: Constructor on type ‘UniversalAnswerService’ not found.

How’s that possible? We didn’t even touch UniversalAnswerService!

(more…)

November 27, 2014

AsyncActivator: Handling Cancellation

This is the second article in a series concerning AsyncActivator, a generalization of the .NET Asynchronous Factory pattern:

  1. Basics
  2. Cancellation
  3. Portability
  4. Silverlight
  5. Dependency injection

The Problem

Recall UniversalAnswerService from the previous article:

class UniversalAnswerService : AsyncInitBase<UniversalAnswerService>
{
    private UniversalAnswerService()
    {
    }

    protected override async Task InitAsync()
    {
        await Task.Delay(TimeSpan.FromDays(7500000 * 365.25));
        Answer = 42;
    }

    public int Answer { get; private set; }
}

Unlike Stephen Cleary’s original example, our implementation conveys a more realistic delay. Let’s assume that we’re able to come up with a server that’s actually capable of running this code. We’re now bound to deal with particularly impatient end users refusing to wait for the computation to complete. What we need is a way for our service to respond to cancellation requests.

Although this is a somewhat contrived example, cancellation is a very serious issue that needs to be addressed in most real-life scenarios.

(more…)

November 24, 2014

AsyncActivator: Yet Another Take on the .NET Async Constructor Problem

Filed under: AsyncActivator — Tags: , , , , , , , , — Dmitry Shechtman @ 21:18

This is the first article in a series concerning AsyncActivator, a generalization of the .NET Asynchronous Factory pattern:

  1. Basics
  2. Cancellation
  3. Portability
  4. Silverlight
  5. Dependency injection

If you’re in a hurry, feel free to

Update 2014-11-30: The second and the third article in the series provide important updates. Please consider reading them before using code from this article.

The Problem

The Task-based Asynchronous Pattern introduced in .NET Framework 4.5 provides developers with a streamlined syntax for consuming asynchronous tasks and operations. WinRT takes it to the extreme by effectively forcing the developers to incorporate TAP in their code.

This leaves us with the problem of asynchronous constructors, or, more precisely, lack thereof. Stephen Cleary had a great write-up a while ago (more recently republished as part of his MSDN Magazine series) with a couple of solutions to this problem.

(more…)

March 21, 2010

Developer Academy

Filed under: Blog — Tags: — Dmitry Shechtman @ 21:02

Wow, it’s been a long time. Crazy deadlines and long commutes are to blame. Nothing to do with my laziness :P

I’ll be attending Microsoft Developer Academy 4.0 (Hebrew-only site, sorry). I’ll take a stab at blogging live from the event (wireless coverage permitting). See you around!

Update: Got myself a Twitter account @dudnet.

January 14, 2010

Looking for Something?

Filed under: Blog — Tags: , — Dmitry Shechtman @ 01:18

It looks like this blog just hit the front page of Google’s search results for IDataErrorInfo. I certainly hope this wasn’t caused by the Chinese attack on Google.

P.S. I didn’t abandon the PropertyChange series; the third article is to be published soon. In the meantime, check out some derivaciónes :D

December 19, 2009

IDataErrorInfo with Validation Application Block and Unity Interception AOP

Filed under: PropertyChange — Tags: , , , , , , , , , , , , — Dmitry Shechtman @ 12:40

This is the second article in a planned series of articles concerning AOP with Unity Interception and Policy Injection:

  1. INotifyPropertyChanged AOP
  2. IDataErrorInfo AOP
  3. Policy Injection
  4. Performance and optimizations
  5. The final solution

I hope you will find this useful in your work; all feedback will be greatly appreciated.

The previous article discussed an implementation of the INotifyPropertyChanged aspect using Unity Interception AOP. Today we will see how a similar approach can be applied to another interface commonly used by WPF (as well as by ASP.NET MVC).

The IDataErrorInfo interface consists of two methods:

  1. an indexer accepting a property name (columnName) parameter and
  2. an Error property.

We will solely focus on the indexer, which returns error messages on a per-property basis.

The Validation Application Block allows developers to easily incorporate input validation via property attributes and/or application configuration, supporting a variety of provided validators, as well as custom ones.

IDataErrorInfo and VAB seem to be a perfect match, and have indeed been integrated. Adding Unity Interception will further simplify input validation, so that (presentation) models could be specified in the following manner:

[NotifyPropertyChanged, DataErrorInfo]
public class Contact : MarshalByRefObject, INotifyPropertyChanged, IDataErrorInfo
{
    [StringLengthValidator(1, 20, MessageTemplate = "First name length must be between {3} and {5}.")]
    [ContainsCharactersValidator("0123456789", Negated = true, MessageTemplate = "First name cannot contain digits")]
    public string FirstName { get; set; }

    [StringLengthValidator(1, 20, MessageTemplate = "Last name length must be between {3} and {5}.")]
    [ContainsCharactersValidator("0123456789", Negated = true, MessageTemplate = "Last name cannot contain digits.")]
    public string LastName { get; set; }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public string Error
    {
        get { return null; }
    }

    public string this[string columnName]
    {
        get { return null; }
    }
}

Note: The implementation presented below is limited to classes derived (possibly indirectly) from MarshalByRefObject.

(more…)

December 15, 2009

Turn your project into WPF User Control Library in 10 seconds

Filed under: Tips — Tags: , , , , — Dmitry Shechtman @ 08:29

I recently had to add a WPF resource dictionary to a project that was previously created as a plain Control Library. I learned that:

  1. all the WPF stuff (barring WPF User Control) is hidden in Add New Item menus/dialogs,
  2. no fine-tuning of project types is provided and
  3. TFS doesn’t make recreating a project an easy task,

so I created a new WPF User Control Library project and compared between the two.

Now, if you need to add WPF capabilities to your Control Library, just follow these simple instructions:

  1. Open the .csproj file in your favorite text editor (no, VS won’t do :twisted:)
  2. Under the first element add:
        <ProjectTypeGuid>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  3. If (VS.version >= 2010) add:
        <TargetFrameworkProfile>Client&amp</TargetFrameworkProfile>
  4. Save changes.
  5. Reload in VS.

Hey VS team, great obfuscation job! :?

December 12, 2009

INotifyPropertyChanged with Unity Interception AOP

Background

If you have ever developed a non-trivial application in WPF, you’ll probably find this familiar:

    public class ProductFamilyViewModel : INotifyPropertyChanged
    {
        private bool isSelected;
        public bool IsSelected
        {
            get { return isSelected; }
            set
            {
                if (isSelected != value)
                {
                    isSelected = value;
                    SendPropertyChanged("IsSelected");
                }
            }
        }

        private bool isExpanded;
        public bool IsExpanded
        {
            get { return isExpanded; }
            set
            {
                if (isExpanded != value)
                {
                    isExpanded = value;
                    SendPropertyChanged("IsExpanded");
                }
            }
        }

        private bool isActive;
        public bool IsActive
        {
            get { return isActive; }
            set
            {
                if (isActive != value)
                {
                    isActive = value;
                    SendPropertyChanged("IsActive");
                }
            }
        }

        private void SendPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

(This is an excerpt from a real class I’ve been working on; the actual code is bigger and uglier.)

Isn’t it sad that you have auto-implemented properties, but not the ability to use them? Wouldn’t you love to be able to do something like that?

[NotifyPropertyChanged]
public class ProductFamilyViewModel : MarshalByRefObject, INotifyPropertyChanged
{
    public bool IsSelected { get; set; }
    public bool IsExpanded { get; set; }
    public bool IsActive { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}

This has been achieved (with varying levels of success) with DynamicProxy2 and repeatedly with PostSharp (reportedly refined in PostSharp 2.0), but what about Microsoft Enterprise Library?

At first, the Policy Injection Application Block might look like the perfect tool for the task, but looks are often deceiving; quoting Richard Banks:

Windsor and PIAB both have a shortfall that we can’t overcome.  Neither of them can alter the type of a class they are providing aspects for – they simply provide proxies that add hooks to intercept method calls.  We would still need to implement INotifyPropertyChanged in our class for binding to work.

Not to fret! Luckily, Enterprise Library 4.1 ships with the Unity Application Block (also available as a separate download). Unity, in turn, contains the mighty Interception Extension, which seems to be getting undeservedly little attention from developers. I guess this has to do with its poor documentation and lack of UI configuration support (expected to be added in 5.0).

None of these, however, have prevented Derek Greer from trying. His post contains a great introduction to Unity Interception (Prolegomena is definitely recommended) and quite a few insights, but sadly falls short of achieving the ultimate goal.

This article details a complete user-friendly implementation of the INotifyPropertyChanged aspect using Unity Interception AOP. It is the first in a planned series of articles concerning AOP with Unity Interception and Policy Injection:

  1. INotifyPropertyChanged AOP
  2. IDataErrorInfo AOP
  3. Policy Injection
  4. Performance and optimizations
  5. The final solution

I hope you will find this useful in your work; all feedback will be greatly appreciated.

Note: The implementation presented below is limited to classes derived (possibly indirectly) from MarshalByRefObject.

Update 2009-12-14: Dima Gershman, a truly knowledgeable colleague of mine, says go with the looks. Policy Injection wraps user objects with Interception’s transparent proxies, relieving us of the burden of manual configuration (and even improving performance!), although that comes at the price of some extra library dependencies. To be continued…

(more…)

Hello, World!

Filed under: Blog — Tags: — Dmitry Shechtman @ 12:00

Welcome to my blog. I hope you find it useful. Let me know anyway.

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 309 other followers