Composite Presentation Events and Silverlight

Saturday, January 09 2010         No Comments

Recently, I have been working on my first Silverlight application. It has given me the opportunity to learn a lot about a technology that I have never used before. One of the many tools that I have learned to use over the past few weeks is Microsoft’s Composite Presentation Events. The application that I am working on relies heavily on these events. In this application, just about everything that occurs is asynchronous. Thus, the application is filled with subscriptions and publications of predefined events. It’s fairly simple to utilize. One simply has to use an EventAggregator to acquire the desired event, then either subscribe to that event or publish that event.

IEventAggregator aggregator = new EventAggregator();
var fryEvent = aggregator.GetEvent<BeginEatFrenchFryEvent>();
 
// ...
 
fryEvent.Subscribe(OnBeginEatFrenchFry, ThreadOption.UIThread);
 
// ...
 
fryEvent.Publish("lunch is served");

BeginEatFrenchFryEvent is defined as:

public class BeginEatFrenchFryEvent : CompositePresentationEvent<string> { }

The action to take when an event is published is the first parameter. In this case, it’s OnBeginEatFrenchFry:

public void OnBeginEatFrenchFry(string payload)
{
    // Will see the 'Publish' call and execute.
}

OnBeginEatFrenchFry will receive the string “lunch is served” and then execute. Simple, eh? Well, if one wants all of the event subscriptions to stay alive forever, then that’s all there is to it. However, what if one does not want the subscription to last more than, say, once? There is an Unsubscribe method, but is there a way to tell the application up-front to only subscribe to a published event once? The short answer is no. The long answer is no, due to bugs that exist in Composite Presentation Events and limitations of Silverlight.

We recently had a problem in this application where event subscriptions were getting stacked. Subscriptions were compounding on every subsequent load of a view. First four events would fire. On the next load, 8. The next, 16. We had found one event that was firing no less than 150 times before the view would finish loading. Needless to say, this slowed down the application a fair bit.

So back to our problem: How can we prevent events from remaining subscribed? Well, subscribe has more than two parameters. There’s a third parameter, bool keepSubscriberReferenceAlive. At first, we thought that this was the simple solution: Just past false to this parameter and it will automatically unsubscribe. Unfortunately, not only is this not the case, but it also gets eaten by the implementation unless you pass the fourth parameter to subscribe (a Predicate<bool> which serves as a filter; more on this later). Using .NET Reflector, we saw that the implementation of Subscribe is very interesting. If you pass no third or fourth parameters in, the values false and null are used for the third and fourth parameters, respectively. In the implementation of Subscribe that takes four parameters, if the fourth parameter (the filter) is null, then a hard-coded value of true is passed instead of whatever keepSubscriberReferenceAlive was set to. The only real workaround at this point is to pass a dummy filter as a fourth parameter so that the bool one passes in actually gets used.

fryEvent.Subscribe(OnBeginEatFrenchFry, ThreadOption.UIThread, 
    false, dummyVariable => true);

Problem solved? Not quite. This is where the aforementioned Silverlight limitation comes into play. Silverlight does not support weak references to delegates or anonymous methods. Unfortunately, the above filter is such a method. Where did we go from there? Create a strong referenced dummy filter, of course.

public static class StaticFilter
{
    public static bool AllowAllValues<T>(T dummy)
    {
        return true;
    }
}

So at the end of the day, we have the following:

fryEvent.Subscribe(OnBeginEatFrenchFry, ThreadOption.UIThread, 
    false, StaticFilter.AllowAllValues);

Finally we reach the end of our endeavors in trying to get an event to automatically unsubscribe. Does this work? Unfortunately, no. The event remains subscribed even if the above subscription is used. As far as we can tell, keepSubscriberReferenceAlive is useless to us.

Anyway, we eventually found that the only way to guarantee that a given event is unsubscribed from is to explicitly unsubscribe from it. The Unsubscribe method works either two ways: Either by passing in the SubscriptionToken returned by the Subscribe method, or by giving it the Action (in the above example, OnBeginEatFrenchFry) that was used in the Subscribe method. The former can get really hairy. If you have several events, that’s several SubscriptionTokens you have to manage. The latter is much cleaner, however, as all you need is the Action method one used to subscribe to the event.

fryEvent.Unsubscribe(OnBeginEatFrenchFry);

One could easily put this within the method itself to automatically unsubscribe after one usage. What we eventually did was create a static class, called OnceEvent, that had its own Subscribe method that internally took care of the unsubscribing so that the client would only have to worry about one line of code instead of many.

Phew, this certainly ended up being longer than I intended. I think I’ll stop here. There was a lot of other stuff that I skipped regarding this topic, but I hope that what I have written will provide others who are using these technologies in tandem with solid advice on how to get around some of the insidious limitations and bugs lying within them.

Depends On What Your Definition of “Is” Is

Tuesday, December 22 2009         No Comments

Yesterday I discovered the “is” keyword in C#. Is it a common keyword? Perhaps, but it’s the first time that I have seen it, so I wanted to share my newfound keyword with the world. At first, I thought I could replace conditionals such as:

if(variable.GetType() == typeof(DomainObject))

with the is keyword instead:

if(variable is DomainObject)

However, the is keyword functions like the term “is a” works in the world of hierarchies: It will not only return true if the same types are given, but also if the the given type to check is a derived member of a parent class. Take a look at this example:

public class FooBase { }
public class Foo : FooBase { }
 
class Program
{
    static void Main()
    {
        object foo = new Foo();
 
        Console.WriteLine(string.Format("{0, 40}: {1, -5}", "foo is Foo", 
            foo is Foo));
        Console.WriteLine(string.Format("{0, 40}: {1, -5}", 
            "foo.GetType() == typeof(Foo)",
            foo.GetType() == typeof(Foo)));
        Console.WriteLine(string.Format("{0, 40}: {1, -5}", "foo is FooBase", 
            foo is FooBase));
        Console.WriteLine(string.Format("{0, 40}: {1, -5}", 
            "foo.GetType() == typeof(FooBase)",
            foo.GetType() == typeof(FooBase)));
        Console.WriteLine();
    }
}

 

And here’s the output:

image

As you can see, the object foo, which is of type Foo, obviously returns true for the cases where the exact type is checked. The is keyword also returns true, however, when foo is checked against FooBase. Note how the GetType()/typeof conditional returns false in this instance, however. Thus, if you want to check against a precise type, you have to stick with using GetType() and typeof to get the job done. Otherwise, however, the is keyword provides a much cleaner syntax to use (and is quite easy to read to boot).

Note that I deliberately used the general object type for foo in the above example. I did that because if you use the is keyword on exact types, ReSharper will catch that that particular conditional will always be true (or false, if comparing two different compile-time defined types):

image 

Note that such convenience is not offered through the runtime method of type comparison.

Using TransactionScope to Keep Repository Concerns Separate

Sunday, November 08 2009         No Comments

Alright, so you’re using the Repository Pattern for your persistence needs. Within the repositories you’re using the Adapter Pattern provided with LLBLGen in order to access your persistence layer. Everything is going great. But then you encounter an issue: Multiple queries need to be executed, and all must be executed within a single transaction. How could you accomplish this? Well, the adapter pattern provides a simple implementation.

using (var myAdapter = new DataAccessAdapter())
{
    myAdapter.StartTransaction(IsolationLevel.ReadCommitted, "Transaction Name");
    try
    {
        // Execute queries using myAdapter here.
        myAdapter.Commit();
    }
    catch (Exception)
    {
        myAdapter.Rollback();
    }
}

All you have to do is call StartTransaction on the adapter, giving it an isolation level and a name, then call either Commit or Rollback on the adapter when you’re done. This works, but begins interfering with the Single Responsibility Principle. Say you have to insert a new Pizza into your database, but also have to insert any new Toppings that were not in your database before. On top of that, you need to have a Price record for this Pizza. Now you're making multiple updates to the database in a single repository method. Which repository would you put this under? You would probably concede putting it in your PizzaRepository, as that’s the focal point of this operation. However, you already have a nice Add method in your IngredientRepository, and you wouldn’t want to repeat yourself in PizzaRepository’s Add method, now would you?

An quick solution to this problem would be to just pass around your active adapter from repository to repository. This would, however, expose infrastructure details to your interface details, which reside in the Core of your application (if you’re using the ONION architecture, that is). It is usually unwise to be passing around active database connections in the first place as well.

The solution to preserve our Separation of Concerns and our Single Responsibility Principle is to utilize the TransactionScope class, which is located in System.Transactions. LLBLGen’s adapters work directly with this class, and will change their end-result behavior depending on whether or not the TransactionScope is committed. Notice that this is built right into the .NET Framework, so you could use this in your Core project if necessary. Hooray! Now, instead of depending on keeping a single adapter alive to execute a transaction, you can merely wrap your repository calls in a single TransactionScope.

Pizza pizza = new Pizza();
pizza.Ingredients = new List<Ingredient>();
// Populate pizza and pizza.Ingredients here.
 
// Newing up repositories here only for the sake of brevity.
IPizzaRepository pizzaRepository = new PizzaRepository();
IIngredientRepository ingredientRepository = new IngredientRepository();
 
using (var transactionScope = new TransactionScope())
{
    bool isPizzaSaved = pizzaRepository.Save(pizza);
    bool areIngredientsSaved = ingredientRepository.Save(pizza.Ingredients);
    if (isPizzaSaved && areIngredientsSaved)
    {
        transactionScope.Complete();
    }
}

 

In order to commit a TransactionScope’s transaction, you simply call Complete on the TransactionScope object. If Complete is not called, the transaction will automatically roll back. In fact, there is no rollback method, so you have to rely on this behavior. You could also wrap your repository calls in a try/catch block if they throw exceptions when something goes wrong as well.

With TransactionScope, you could create a Controller class or something similar which can house all of the repositories you depend on to complete the transaction. Furthermore, all of your repositories can be transaction-ignorant: They may be part of a transaction, or they may not. The point is that they don’t have to care. They just execute their single responsibility and are done!

To get TransactionScopes to work is slightly less than intuitive, however. In my next post I will detail how to setup both the client machine and the database-serving machine so that you can use TransactionScopes.

Asynchronous Method Calls to Code-Behind

Monday, September 28 2009         No Comments

One of the many things we’ve been trying to do at work lately is keep as much logic out of the UI as possible. We’ve been making extensive use of jTemplate to help us out on this: Specify an HTML file that you can pass a set of JSON data to, and it loads it up for you in the format you specify. Another technique we have been utilizing lately is the use of Web Service files: We are calling these the “controllers” of our project. Even though they aren’t controllers in the fullest sense of the definition, they are a step in the right direction. In any case, one particular flaw that we noticed in this system was that in some cases we were creating controllers for one usage only: The methods were only being called by a single ASPX page. We figured such methods should actually go in the code-behind instead of a separate class in this case.

It turns out that creating a code-behind method suitable for asynchronous calls is not very difficult. One merely has to declare the method to be both public and static. In addition, it must carry the WebMethod attribute.

namespace Project.UI
{
    public partial class FooStuff : Page
    {
 
        // Hopefully not too much code here!
 
        [WebMethod]
        public static List<Foo> GetFoos()
        {
            // Asynchronous stuff here.
        }
    }
}

As you can see, you don’t even need to decorate the class FooStuff with the ScriptService attribute or even the WebService attribute. The only requirements are on the method itself. To invoke this method, we use a jQuery Ajax call.

$.ajax
({
    type: 'POST',
    url: './FooStuff.aspx/GetFoos',
    data: '{}',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
});
The primary line to note here is the URL. All one has to do to invoke the code-behind method is use the current page as the URL (“./FooStuff.aspx/”) followed by the method name as any other Web Service call would require (“GetFoos”). I suppose it’s even possible to call such methods from other code-behind methods, but if you’re doing that I would suggest separating that method out into its own Web Service class instead.

A Quick JavaScript Gotcha: parseInt

Friday, September 04 2009         No Comments

A co-worker recently shed the light on an interesting “feature” of JavaScript’s parseInt function. parseInt actually takes in a second parameter in addition to the string you are trying to parse: The base number system you are attempting to convert to. If you do not specify a second parameter, JavaScript will try to derive the base system from the input string. This can lead to some very unexpected results when, for example, one has parseInt(“010”). In this example, the number 8 is returned since it was interpreted to be an octal number.

To prevent this from happening, always be sure to specify base 10 when using parseInt() in JavaScript.

Using Interfaces for Repositories in PHP

Saturday, August 08 2009         No Comments

I’m working on a restructuring/re-design of the web site VGMusic. This is my first attempt at applying such delightful techniques such as the Repository Pattern and Dependency Injection in PHP, and that language does not make this easy. Support for object-oriented techniques is not the best, and the biggest obstacle is the fact that PHP is weakly typed. This makes it really difficult to do things like program against an interface. If I wrote the line:

<?php
$fooRepository = new FooRepository();
?>

Then I’m actually instantiating an instance of the concrete implementation FooRepository(). What I would like to do, however, Is use the interface IFooRepository instead. What I decided to do is to take a page out of the MVC Pattern and use controllers. A controller can have a private instance of a repository.

<?php
class FooController
{
    private $_fooRepository;
    
    function __construct(IFooRepository $fooRepository)
    {
        $this->_fooRepository = $fooRepository;
    }
 
    public function GetFoo($id)
    {
        return $this->_fooRepository->GetFoo($id);
    }
}
?>

Now I can pass in any class, including fakes, that implements IFooRepository (thankfully Type Hinting allows me to restrict what type of variable is passed into the constructor). It’s still not technically programming against an interface, but it’s the solution I’ve chosen to go with. In addition to doing this, I would also like to have a default constructor for the controller that just uses the default implementation for the repository. Since PHP does not allow for overloaded constructors, I will fake a parameterless constructor by giving $fooRepository a default value of null:
 
<?php
class FooController
{
    private $_fooRepository;
    
    function __construct(IFooRepository $fooRepository = null)
    {
        if ($fooRepository = null)
        {
            $fooRepository = new FooRepository();
        }
        $this->_fooRepository = $fooRepository;
    }
}
?>

If I create a new instance of a FooController without passing parameters, the default repository will be used. I also wanted to use controllers to begin with, lest my PHP code start looking like classic ASP where both the business logic and UI-related logic end up in a gigantic if-then-else block in a single PHP file. When it comes to using these techniques that I’ve learned a great deal about over the past few months, PHP leaves a lot to be desired. Hopefully I can make it through this project without running into many more obstacles.

// TODO: Write Tests

Friday, July 24 2009         2 Comments

We’ve all done this at one point or another. It always sounds like a good idea at the time. You’re working on a particular feature for a client and that deadline is fast approaching. The tests aren’t contributing to that feature, so you figure they can be put off until after the feature is complete. Then, when the deadline has passed, the feature is delivered, and the client is satisfied, you can go back and write the tests that prove your code does what you expect it to. Simple, right? Not quite. In fact, not writing these tests simply leads to a frustrated client reporting yet another bug in the great feature you’ve just delivered. You end up spending a lot more time on the feature, going through a debugger and an angry client than you would have if you had just written the tests first.

In the project I’ve been working on for the past month and a half or so, this exact scenario happened (the client is slightly more forgiving than the one portrayed above, thankfully). We were coming up against a deadline and had to get a feature out the door. We had a couple of choices: Make sure our tests were written so that we could assure ourselves that the code worked, or just write the feature and ship it off. We chose the latter, which led to a few of the comments in the fashion of the title of this blog post. There were perhaps a half-dozen or so of these comments littered throughout the feature’s source. Naturally, a few days after the feature goes live, we received calls from the client pointing out that some bugs have turned up. We then spent the better part of that day hunting down the source of these bugs and writing tests for them anyway. In the end, we spent a lot more time than we budgeted for on this particular feature, all because we thought that we could temporarily forgo the tests in order to save a little bit of time. In actuality, if we had written well-defined tests first and had let the tests drive our code, we would not have had to spend so much extra time on the feature.

On the subject of taking time to write tests, there will never be “time” to do so. If you make a solemn vow to write tests just after this feature is published, you’ll find yourself making more excuses later on. “I have other features to get out the door.” “I’ve already finished that code, so why waste time writing tests for it?” “There isn’t enough time in the day to spend time writing tests.” The list goes on and on. The thing is that you’ll never get around to writing tests for code you’ve already declared to be finished, no matter how much you promise yourself to do so. The best time to write the tests is before you write the code for the feature: Let the tests drive your development, and you’ll find yourself completing the feature on time with fewer bugs (or none at all) and another satisfied client.

Delegates For LLBLGen Entities

Wednesday, July 15 2009         2 Comments

This isn’t meant to be an LLBLGen-centric blog; I just work with it a lot and happen to come across a lot of these little nuances.

When writing unit tests, I make every effort to mock or fake all dependencies on the code that I’m testing. When it comes to testing repositories, it usually requires mocking of LLBLGen’s classes so that I do not end up talking to the database during the unit tests. In this case, I want to mock the LLBLGen method FetchEntity(IEntity2 entityToFetch), which populates entityToFetch via reference and returns whether or not the fetch was successful in terms of a boolean. In order to thoroughly test a method using FetchEntity, I need to return fake data. To do that, I create a delegate method:

   1: private IEntity2 _entityToFetch;
   2: private delegate bool FetchEntityDelegate(IEntity2 entity);
   3: private bool FetchEntity(IEntity2 entity)
   4: {
   5:     if (_entityToFetch != null)
   6:     {
   7:         entity = _entityToFetch;
   8:     }
   9:     return true;
  10: }

 

When I want to use this delegate, I set _entityToFetch to the entity that I want returned and call the delegate, right? It’s not that easy, unfortunately. On line 7 above, entity is merely being set to a reference to _entityToFetch, which is not passed along once this delegate is finished executing. The calling method still gets an empty entity.

What do we do here? Well, in actuality I am really only interested in the fields of this entity. If I can get the fields to be copied over to the entity, we’re golden. This is accomplished using Clone():

   1: entity.Fields = _entityToFetch.Fields.Clone();

This will copy over the fields from _entityToFetch to entity and successfully returns them to the calling function. Now I can easily get fake data from FetchEntity and test methods using it to my heart’s content.

LLBLGen and Pagination

Friday, July 10 2009         No Comments

LLBLGen's methods provide for an easy way to fetch a subset of rows from persistence. One can limit the returned results using a filter bucket (i.e. a where clause) or by using pagination. All one has to do is give the current page and the number of records per page to LLBLGen and it handles the rest. This is the code that I wrote in order to get numberOfRecordsPerPage records for page pageNumber:

   1: int maxItemsToReturn = 0; // No limit.
   2: using (var myAdapter = PersistenceLayer.GetDataAccessAdapter())
   3: {
   4:     myAdapter.FetchTypedView(typedViewCollection.GetFieldsInfo(),
   5:         typedViewCollection, filterBucket, maxItemsToReturn, null, false, 
   6:         null, pageNumber, numberOfRecordsPerPage);
   7: }

Unfortunately, this was not limiting the returned records by any means – all of the records that fit the filter bucket were being returned and no pagination filtering was occurring. The query that LLBLGen generates shows that no limiting is being done.

I found out this morning that the maxItemsToReturn argument was overriding the pagination arguments given to the function. Since 0 was given to it, LLBLGen will not limit the returned rows by any means, despite the fact that I gave it pagination limitations. This is the only overload of FetchTypedView() available to utilize the pagination capabilities, so we’re stuck with providing some value for maxItemsToReturn. While I do not want unlimited rows returned (i.e. setting it to 0), I also do not want to return a smaller amount than expected. The fix I settled on was to set the maximum number of items to return to whatever numberOfRecordsPerPage is so that that argument does not unintentionally limit the resulting set of data:

   1: using (var myAdapter = PersistenceLayer.GetDataAccessAdapter())
   2: {
   3:     myAdapter.FetchTypedView(typedViewCollection.GetFieldsInfo(),
   4:         typedViewCollection, filterBucket, numberOfRecordsPerPage, null, false, 
   5:         null, pageNumber, numberOfRecordsPerPage);
   6: }

This generates the proper query and returns the correct result.

It's a Brand New Blog

Thursday, July 09 2009         1 Comment

Hooray, I have an official blog now! The fancy new domain name is set up and everything as well. I am really excited about filling this site with rich, fulfilling content. Now I have a place to share musings about the various curiosities I come across in the software development world. I do hope that I will be able to maintain a steady stream of updates, as I believe that blogging about these new chunks of information will not only help me recall the new material more easily, but will also provide a good reference for myself and others in the future.