Steven Nagy .NET

Friday, 29 June 2007

Vista Gadgets - Tips and Tricks

Today I completed a Vista Gadget called SurfWatch. You can download it here. I learnt a lot while creating this Gadget. My Javascript skills are are a

lot better now, and of course I learnt some of the Gadget API. Here's some tips that might be useful to you if you are writing gadgets also.

1. Use Visual Studio Codename 'Orcas'. The intellisense on javascript makes it extremely useful.

2. When using flyouts, set the style of the page body tags to remove the padding and margin, otherwise your flyout doesn't line up with your gadget.

3. You can also use the g:background tag for your flyout window to ensure transparency.

4. You can set data and call functions in the flyout from your main gadget window by calling against it's DOM. For example, if you had a textbox in your flyout, you would access it like this:

var flyoutDOM = System.Gadget.Flyout.document;
var myText = flyoutDOM.getElementById('myText');

Likewise, if you have registered functions in your DOM in your flyout, they can be called the same way. This allows for a form of communication between your two gadget windows.

5. Docked and undocked versions of your gadget actually run under the same html file. If you want them to look different and have different contents, keep this in mind when designing your gadget.

6. Emailing gadgets is tricky! Since they are essentially a zip file, most email servers will detect that the attachment contains items with Javascript, and may zap it. Not sure how to get around this yet!

7. There is a mime-type for gadgets:
application/x-windows-gadget

Technorati Tags: , , ,

Thursday, 14 June 2007

Generic Collections in .Net 2.0

One of the things I have discovered about ASP.NET developers is that they don't have a firm understanding of the difference between VALUE types and REFERENCE types. While I'm not interested in dispensing that information here (because other people have done it before way better than I ever could) I do want to demonstrate something that came up at work today relating to reference types.

For confidentiality reasons I can't provide the same code, so I will come up with an example that is similar (demonstrates the same concepts).

Consider this: I want to write a method that connects to a database and returns a generic list of "Customer" objects, and also for each customer, I want to store a generic list of "Order" objects. The Customer object contains a CustomerID and a generic list of Order objects. There would be other information but its not important at this stage.

My SQL or Stored procedure will return 2 result sets from 1 call for performance reasons. The first contains all the customers, the second contains all the orders with a customer ID for each order.

I need to read from my data reader all the customers first (since this is the first result set) and then I need to read all the orders, and assign them to the correct customer object. I already have a method that takes a reader object and returns the next customer object. I also have a method that takes the reader and returns an Order object. What we are interested in is how to assign an order to a customer long after all the customers have been loaded?

Here's the first pass at the code:

List<Customer> AllCustomers =
        new List<Customer>();
SqlDataReader reader =
        DatabaseHelper.GetReaderForCustomers();

while (reader.Read()) {
    Customer customer = GetNextCustomer(reader);
    AllCustomers.Add(customer);
}
reader.NextResult();
while (reader.Read()) {
    Order order = GetNextOrder(reader);
    foreach (Customer c in AllCustomers) {
        if (c.CustomerID == order.CustomerID) {
            c.Orders.Add(order);
        }
    }
}
reader.dispose();
return AllCustomers;

Looking at the above code, we are creating a list of customers, and then as we load each order object, we are finding the right customer to add the order to. The 'foreach' loop is an expensive operation in the above example, yet is probably something we find ourselves doing quite a lot in our code. Is there a better way? Well we could add a "break" statement in when we find the right customer so that the loop doesn't finish. But there still must be more we can do?

Enter: the Dictionary! This is another generic collection, that allows you to choose what "type" the value AND the key will be. Dictionaries are fast to lookup data based on their key, so are ideal for our situation. We need to keep our generic List for the return type of the method, but we can also utilise a dictionary for storage. Consider the new code:

List<Customer> AllCustomers = new List<Customer>();
Dictionary<int, Customer> customersByID =
        new Dictionary<int, Customer>();
SqlDataReader reader =
        DatabaseHelper.GetReaderForCustomers();

while (reader.Read()) {
    Customer customer = GetNextCustomer(reader);
    AllCustomers.Add(customer);
    customersByID.Add(customer.CustomerID, customer);
}
reader.NextResult();
while (reader.Read()) {
    Order order = GetNextOrder(reader);
    customersByID[order.CustomerID].Orders.Add(order);
}
reader.dispose();
return AllCustomers;

Great! And if you understand the basics of reference types, you'll understand that this code works. If not, you might be asking: "How does adding the order to the Dictionary item also add to the List item?"

Well, as I said above, you need to understand reference types. The "Customer" object is the same object, whether it is a variable in my method, an item in the dictionary, an item in the list, a parameter to a method, etc. Its the SAME customer object regardless.

Well that's all I want to say about that really. Check out the System.Collections.Generic namespace for other generic collections.

Technorati Tags: , , ,

Friday, 8 June 2007

Why Patterns

Technorati Tags: , , ,

We all know about design patterns for everyday coding use like Singletons, MVP, Factories, Builders, etc. And to someone who's knew to this aspect of development it might seem quite daunting, given how many patterns there seem to be. For example, the gang of 4 wrote about 23 straight off the bat. You can find a lot more if you look around online. It might seem like a hard task to "learn" as well as truly understand when (and when not) to use them.

I have no intention of relieving those tensions in this blog post!

The gang of 4 break down their patterns into 3 groups: Creational, Structural, and Behavioral patterns. These relate particularly well to object design; in other words, good practices for creating objects, for designing objects, and how they should behave.

So what about patterns for how systems communicate/integration? Or specifically for system design?

Jimmy Nilsson and Eric Evans provide some patterns around Domain Driven Design in their books.
If you look at Martin Fowler's "Refactoring" book you see on the inside cover a list of patterns for refactoring code as long as your arm. Likewise Joshua Kerievsky provides a list of patterns to help you refactor to patterns.

Patterns that help you implement patterns! Scared yet?

Let's take a step back. Think about what the word pattern actually means. Normally a good writer would reference a dictionary meaning here, but hey, Wikipedia has pretty much every piece of information on earth so lets quote that instead:

The pattern is a form, template, or model (or, more abstractly, a set of rules) which can be used to make or to generate things or parts of a thing, especially if the things that are created have enough in common for the underlying pattern to be inferred.

So that doesn't just apply to objects. That applies to processes as well as more tangible entities. "Walking" is a pattern because some human worked out the best way to do it thousands of years ago, so now we all do it.

So my question to you is that, if a some guy who is a way better coder/designer/architect than I am, and has learnt all the hard lessons, AND he (along with the entire community of similar experts) has named a pattern, why wouldn't I take that on board and use it where relevant to my everyday work? Of course knowing when and when not to apply these patterns is important, but hey, that's why these guys write books!

Scenario: So you are well rehearsed on the common design patterns, and you walk into a new job. You sit down to commence work on a complicated system that is the company's core product, and you open a class file that you think you need to change. Right a the top is the class name: "WidgetFactory". Wow, you already know what this class does without reading any more code! How powerful is that!

Its not unusual to write a comment at some code to say "This uses Singleton" or "This internal class is used as a 'momento' pattern". So if someone else speaks the "pattern language" they can translate those few words into a wealth of wisdom instantaneously.

Well that's all I have to say about patterns for now. If you want to find out more, check out some of the authors mentioned in this post, or search online. I think a nice project would be a repository (another pattern!) of patterns along with code examples in multiple languages. Perhaps it could be community promoted and tagged? Martin Fowler has a site with patterns, and I've seen other sites that blatantly rip off the gang of four book, but there's nothing that really incorporates ALL sorts of design patterns from all angles of development (that I know of).

Friday, 1 June 2007

Windows Live Writer - A Test

This is just a quick entry to test the new beta release of Windows Live Writer. Its a free tool for writing blogs.

If you can see this then it works. If you can't...