Book review: Essential LINQ

A few months ago I wanted to look into LINQ to SQL and grabbed a copy of Essential LINQ. The book is targeted at people who are coming from .NET 2.0 or people who are new to LINQ. It’s is very well written, almost like you’re following a class with clear examples showing you how you can leverage the platform to suit your needs.

Essential LINQ

The new language features of .NET 3.0 are covered which enable LINQ in the first place so if that’s new for you no need to buy another book. All LINQ operators are explained using LINQ to Objects followed by a very thorough discussion of LINQ to SQL. Mapping, stored procedures, modifying objects and how you can plug into the system with extension methods. After diving deep into LINQ to SQL there’s only a very small description of the Entity Framework or LINQ to Entities. Which is probably, in hindsight, the biggest issue you can have with this book since it’s now the de facto standard of data access promoted by Microsoft. The book finishes with another in depth discussion of LINQ to XML which was new to me and just like LINQ to SQL you’ll be an expert by the end of the chapters.

So to wrap it up, the book reads like you’re being thaught by a very good teacher. If you want to make sure you know your basic LINQ this is the one you need.

Book review: Silverlight 4 in Action

In order to prepare for a Silverlight course I was going to give I looked around for some new books and material to help my students and to refresh my knowledge. If you want to get started from zero on Silverlight I can highly recommend Silverlight 4 in Action. It’s an updated version from Silverlight 2 in Action and available since August 2010 via Manning.

Silverlight 4 in Action

The book is divided in three parts with the first two giving you all the necessary information to get you started and a third part which digs deeper into some more special topics.

In part one you’re introduced to Silverlight, how it relates to WPF and why you could choose it to build your next application. You get an overview of XAML and browser and desktop integration options. While it’s just the first part of the book, don’t think it’s just for newbies. You get an in depth explanation on how the rendering system works, what the different types of controls are and how text can be used.

Part two gives you all the information you need to build real applications. You’re introduced to the binding features, what your options are for data validation and how you can communicate with other applications. Either Silverlight plugins on the same page or other systems via web services. The last two chapters also give a nice explanation of the MVVM pattern, although it goes way further and shows you ways to improve the maintainability of your code. Very nice to see SOLID and DRY come into play hopefully we’ll see more developers using those principles. The last chapter covers WCF RIA services, these were new to me and I was a bit blown away by the functionality that’s available out of the box, though I’m still a bit sceptic. It might be a bit too much forms over data even though there are some layers in between where you can plug into to do your thing.

The last part adds chapters on working with graphics, creating animations, improving the install experience, using styles and resources and creating custom controls. Some of those you’ll use often, printing for instance, others maybe once in a lifetime, like creating a custom panel.

Overall a very nice read to introduce you to the platform and create real world applications. It’s definitely developer oriented though, don’t expect to see much Expression Blend which you’ll use to create themes and animations which I don’t think you’ll be doing in code as illustrated in the book.

October 2009 bookshelf

Sams Teach Yourself WPF in 24 Hours

I’m in the process of creating an application for a friend of mine who is starting his own company. He needs a little CMS system to support his business in the advertising world. He gave me a nice layout to use in the application so WPF seemed to be the best option. I jumped right in only to find that it was more complex than I first expected. After looking around what was available I decided to go for this book since it’s co-authored by Rob Eisenberg who is in charge of the Caliburn framework.

I’m just passed the first part of the book which introduces the layout containers (grid, stackpanel, wrappanel,…) and the basic containers. It already helped me getting the layout right for the application I’m writing. Also the code snippets in the book are in colour which certainly improves the readability of especially the XAML.

The Art of Unit Testing: with Examples in .NET

Though I’m convinced of TDD and unit testing in general I find it hard to apply when doing projects at work. I’m hoping this book will help me to structure my programming work around TDD and how to write good maintainable tests. The text is written in an easy to read manner and currently feels like a step by step guide on how to become a better test writer. You don’t need any prior knowledge to get started with this book. I’ve only read the first 100 pages but in my eyes it’s already a classic, go get it.

Dependecy Injection in .NET

Earlier this week you could get this one for a mere $10 via a twitter promo code. Though I’m fairly confident I know what DI is, when to use it and what the advantages are you always need to keep an eye out for any new insights or information. Have only read the first couple of pages where the problem of coupling between your components is sketched. The book is still a work in progress, but you can already get it via the Early Access Program.

Cocoa Programming for Mac OS X (Ch 19-21)

After a little Cocoa break I’m back, while continuing through the book I seemed to have forgotten some stuff already, not good.

So, next up, Keyboard Events.

This chapter explains how the events are used for handling keystrokes as well as the first responder concept. The first responder being the active view element (button, text area,…) and there’s a whole mechanism working in the background when the first responder changes. Not a lot of ground breaking material here, probably the most important piece of code here is an example of how to code the fuzzy blue box around an active custom view.

Chapter 20, Drawing text with attributes.

Here we are taught how to show strings in various formats, not that interesting. One nice feature however is that all the drawing commands you write can be converted into PDF by the AppKit framework.

Chapter 21, Pasteboards and Nil-Targeted actions.

The clipboard in Windows, pasteboard in OS X. Different name, same concept, although I’ve never read about it in any .Net book I’ve seen but you know what it does :). What you need to remember from this chapter is that you can do a lazy paste. Meaning that you don’t have to put it in the clip errr pasteboard when the user presses the copy command. You can wait until he presses paste, very valuable if you’re working with large quantities of data.

Nil targeted actions are best explained with an example. You can set the selector (method signature for .net people) of a menu item to anything you want, say removeEmployee:, when the menu item’s target is nil and the menu item is invoked, it will traverse the responder tree until someone acts upon it.

Nothing fancy was covered in these past chapters, but you need to know about these things. I did spend quite some time on the applications, probably because there was a two week pause. For those interested I’ve attached all the source code.

As always, you can get the book here .

TypingTutor – Chapter (46.44 kb)

TypingTutor – Chapter (53.47 kb)

TypingTutor – Chapter 20 Challenge (53.73 kb)

TypingTutor – Chapter 20 Challenge (57.89 kb)

TypingTutor – Chapter (53.58 kb)

TypingTutor – Chapter 21 Challenge (53.75 kb)

RaiseMan – Chapter 21 Challenge (111.20 kb)

Cocoa Programming for Mac OS X (Ch 17-18)

Euro 2008 and the challenge application on the end of chapter 18 have slowed me down, so only some notes about these two chapters this time.

Chapter 17, Custom Views.

This chapter deals about manipulating views (forms) manually. You can compare it with the .net System.Drawing namespace and subclassing the Control class to create your own controls. It also explains the alignment and docking of controls. Pretty basic stuff.

Chapter 18, Images and Mouse Events.

With the new knowledge on how to draw on views we now will allow the user to interact with the form and allow him to draw figures. This is done by handling mouse events. Also the file open dialog is introduced, but it’s called a NSOpenPanel here, to add images on the view.

The challenge application invites the reader to further customize the application, which draws rectangles when you complete the chapter, to draw ovals, adding undo redo capabilities and implementing archiving.

Most of the time I spend finding out how to hook up the document window to the custom view which handled the drawing of the ovals, as always key-value coding saved the day. You should also watch out that when a document is unarchived this is done before UI controls, I mean views :), are created. So don’t start assigning your saved ovals to a view that does not exist yet, like I did. It’ll save you time.

As always, you can get the book here .

ImageFun – Chapter (44.46 kb)

ImageFun – Chapter (46.78 kb)

TheOvalApp – Chapter 18 (65.73 kb)

Cocoa Programming for Mac OS X (Ch 13-16)

I’ve been busy at work so haven’t made as much progress in the book as I wanted, the chapters I did cover however were great!

Chapter 13, User Defaults.

In chapter 12 a preference screen(panel) was introduced, a preference menu item is standard in a default application. In OS X preferences are automatically stored under ~Library/Preferences. To access them you can use the NSUserDefaults class which has a standardUserDefaults method and returns an NSMutableDictionary. When the application starts you need to enter your defaults in that dictionary and call the registerDefaults method. Any changes the user makes are persisted to the location stated above, just make sure whatever you put into it can serialize itself. In the rest of your application you can just read or set values in that dictionary it’s automatically saved.

In .Net you’d use user specific application settings which are stored in the app.config.

Chapter 14, Using Notifications.

Something which is definitely missing in the .Net framework is a Pub/Sub mechanism. There is one available in the EnterpriseLibrary and in Spring.Net but it’s great to see this in Cocoa. Every running application has an instance of NSNotificationCenter, an observer can ask to be notified of certain events, certain events of a certain object or all events of a certain object. A publisher will tell the NotificationCenter about the notification it wants to send. The NotificationCenter will look up the observers and call the method that was supplied when they subscribed. I just recently needed this in a very large application, having it at hand would certainly have saved time.

Chapter 15, Alert Panes.

In the .Net world the MessageBox.The only big difference here is that here they can be run modally, meaning no other windows will receive events until it is closed, or as a sheet, meaning it’s specific to a certain form.

Chapter 16, Localization.

Again this can be compared to the work you need to do in Visual Studio and .Net, the main difference here is that you can pretty easy extract the strings that need to be localized. This is probably possible in the .Net world too with some sort of plugin, but it’s always nice to see it build in, like the notifications.

I’m now half way through the book and can say that it’s a very pleasant one to read, you can get it here . I’ve also adjusted my view on Objective-C and Cocoa, while at first it seemed a bit rough and basic I’m beginning to see that it’s full featured language and framework with very advanced capabilities which don’t require a lot of code. Though the real challenge will be to build a real application after I’ve completed the book. I’m still staring at the screen sometimes wondering why I got three errors when there’s only a missing ) .

Oh yeah, thanks Lemmy for giving me a tilde over IM, I haven’t found that key on the keyboard yet :p.

RaiseMan – Chapter (86.38 kb)

RaiseMan – Chapter (87.29 kb)

RaiseMan – Chapter (87.67 kb)

RaiseMan – Chapter (111.13 kb)

Cocoa Programming for Mac OS X (Ch 9-12)

Read part one here, part two here and get the book here .

The plot thickens!

Chapter 9, NSUndoManager.

For those wondering what that NS is doing everywhere, it comes from NeXTSTEP more information about it here.

This chapter is all about adding undo / redo capabilities to your application and maybe it’s because the current sample application is, well, a sample, but it’s rather easy to add this capabilities to your program. Also you get it integrated with the menu bar at no extra cost, the window shows that there are changes, and the undo and redo buttons come to live. The underlying mechanism relies heavy upon Key-Value coding which was discussed in chapter 7 , again demonstrating it power.

- (void)insertObject:(Person *)p inEmployeesAtIndex:(int)index
    NSLog(@"adding %@ to %@", p, employees);
    NSUndoManager *undo = [self undoManager];
    [[undo prepareWithInvocationTarget:self] removeObjectFromEmployeesAtIndex:index];
    if(![undo isUndoing])
        [undo setActionName:@"Insert Person"];
    [self startObservingPerson:p];
    [employees insertObject:p atIndex:index];    

Chapter 10, Archiving.

The sample application now tracks changes and when you try to close an edited window it asks if it should save its changes. So the logical next chapter is about adding this capability.

In this chapter we learn that the notion of an interface in .Net actually also exists in Objective-C, but it’s called a protocol and unlike .Net and Java you can have optional methods in a protocol so any method marked optional does not need to be implemented.

Archiving is coupled with the NSCoding protocol and the abstract NSCoder class, most of the time you’ll be dealing with the abstracted class which hides the underlying mechanism. Implementing this can be compared to the implementation in .Net. Though it requires less code to write since your object graph is stored automatically in a file. You can configure the extension and the icon from within XCode, it was also nice to see that OS X had automatically associated the extension with my application.

#import <Foundation/Foundation.h>
@interface Person : NSObject <NSCoding>{
    NSString *personName;
    float expectedRaise;
@property (readwrite,copy) NSString *personName;
@property (readwrite) float expectedRaise;
#import "Person.h"
@implementation Person
    [super init];
    expectedRaise = 5.0;
    personName = @"New Person";
    return self;
    [personName release];
    [super dealloc];
@synthesize personName;
@synthesize expectedRaise;
- (void)setNilValueForKey:(NSString *)key
    if([key isEqual:@"expectedRaise"])
        [self setExpectedRaise:0.0];
        [super setNilValueForKey:key];
- (void)encodeWithCoder:(NSCoder *)coder
    [coder encodeObject:personName forKey:@"personName"];
    [coder encodeFloat:expectedRaise forKey:@"expectedRaise"];
- (id)initWithCoder:(NSCoder *)coder
    [super init];
    personName = [[coder decodeObjectForKey:@"personName"] retain];
    expectedRaise = [coder decodeFloatForKey:@"expectedRaise"];
    return self;

Chapter 11, Basic Core Data.

You thought it was good, well it just gets better. All the code we still had to write to add undo/redo, change tracking and archiving to our application can be done without writing any line as illustrated with this chapter. Again we see the power of Key-Value coding.

Chapter 12, Nib Files and NSWindowController.

Nib files contain the state of the window designed with interface builder, this chapter tells you how you can postpone loading a window/panel to save memory and resources. It also how you can load classes (this includes Windows, custom classes, etc.) by their name. Much like the Activator in .Net.

- (IBAction)showAboutPanel:(id)sender
    BOOL successful = [NSBundle loadNibNamed:@"About" owner:self];
        NSLog(@"Loaded nib from NSBundle");
        NSLog(@"Unable to load nib");

RaiseMan – Chapter (72.21 kb)

RaiseMan – Chapter (74.18 kb)

CarLot – Chapter (43.54 kb)

RaiseMan – Chapter (85.23 kb)

Cocoa Programming for Mac OS X (Ch 6-8)

View Chapters (1-5) here, get the book here .

The title of chapter 6 “Helper Objects” did not sound good. Whenever I find classes with the words Helper or Util in their name, this usually indicates a “code smell” and most of time the underlying problem is a leaky domain model. Turns out something completely different is the subject of this chapter, delegates!

They can be compared with delegates in .Net though they are being used in a different way. I’ll illustrate with a sample.

The TableView UI component deals with displaying data like a table, compare this with the .Net grid. What it displays however is not part of his responsibility, this behaviour can be added though by using delegates. The tableView has a delegate member which you can set, if that object implements methods which map to delegate methods of the tableView they will be called, otherwise they won’t. This means that you don’t need to implement everything, just what you need.

I think in .Net this behaviour would be implemented by using interfaces. So if you had your own grid component, it’s datasource could be set to something of type IDatasource which would provide the necessary functionality that would be called by the grid component.

Overall this is off course a powerful feature, though implementing it requires attention, misspelling the method name means that your method won’t be called and you won’t get any errors. The author states that the best way is to look at the documentation and copy paste the method signatures in your code.

Chapter 7 “Key-Value Coding; Key-Value Observing”.

A short chapter, only 12 pages, but it seems to be a core concept. If you have an instance variable foo in class Bar, you can have other objects be notified of changes to it. This can be compared to the .Net INotifyPropertyChanged interface and its interweaving with databinding. Since the observers call the methods valueForKey: and setValue:forKey: you need to make sure your code follows the strict naming convention to get this functionality.

If you are changing the observed instance variable in methods you need to call the methods willChangeValueForKey: before changing it and didChangeValueForKey after you’ve changed it to alert the observers of the change. If you find that too much work just call the setter of the instance instead of changing it directly.

- (int)foo
    return foo; 
- (void)setFoo(int) x
    foo =  x;

A handy shortcut to write a property is to use the @property and @synthesize which do all the work for you, the above code can thus be replaced by a simple

@property(readwrite) int foo;

in the header file and

@synthesize foo;

in the implementation.

Overall familiar material, I’ve seen this in .Net and it’s available to me in Objective-C excellent! There even is a valueForKeyPath: method that traverses the object tree i.e: spouse.scooter.modelName.

Chapter 8, NSArrayController.

In this chapter all you’ve seen so far comes back, but in a different way. In the previous chapter you had to write a lot of plumbing to get your list of objects to display and be editable. The NSArrayController however can help you on this, it allows user interface components be bound using chapter 7’s techniques. You can automatically add and delete objects, display them and edit them without writing code, just hook everything up.

To solve challenge 1 for this chapter edit the sortKey to be personName.length and selector to compare:. I’ve attached the code for those interested.

RaiseMan – Chapter (69.85 kb)

KVCFun – Chapter (53.38 kb)

SpeakLine – Chapter (59.93 kb)

DelegateResize – Chapter 6 Challenge (47.51 kb)

ToDoApplication – Chapter 6 Challenge (57.66 kb)

Cocoa Programming for Mac OS X (Ch 1-5)

Earlier this week I purchased this book: Cocoa Programming for Mac OS X since I wanted to get an introduction on how to develop native applications for OS X. It’s the most recently published one on the issue and got mentioned on MacRumors.

In a series of small posts I’ll put down some notes for myself here and anyone who is interested can read along.

Chapter one gives you some background on the language, what tools will be used throughout the book and explains the different kinds of frameworks available in Cocoa. Nothing special here, I want to write code!?

And there’s chapter two, the author guides you through your first Objective-C program. The interface of XCode and Interface builder (IB) are explained. I was surprised to read that any method you write is public and every instance variable is protected. Also instance fields which are connected through the IB are called outlets and you designate them accordingly in your header file. Methods that can be used by user interface objects are called actions.

#import <Cocoa/Cocoa.h>
@interface Foo : NSObject 
    IBOutlet NSTextField *textField; 	
- (IBAction)seed:(id)sender; 
- (IBAction)generate:(id)sender;

The – before the two method declarations indicate that it’s an instance method, class methods are designated with a +. The IBAction and IBOutlet are hints for the IB. NSObject is the base class for every other object. The id ‘type’ (don’t know if I am allowed to call it that way) is a pointer to basically anything.

Chapter three digs a little deeper on objects and classes. Calling methods on objects looks a bit different if you come from a Java or C# background.

MyClass* myInstance = [[MyClass alloc] init]; 
[myInstance doStuff]; 
[myInstance doStuffWith:bar];  
[myInstance doStuffWith:bar using:foo];

The first line first calls the constructor and init method. Both are inherited from NSObject and on the second line I call the doStuff method on myInstance. It takes some getting used to, also note the naming convention if you’re a .Net programmer methods start with a capital. Method names are also called selectors. On the third line I assume I’ve an other object called bar and it illustrates how you pass parameters with method calls. Finally the last line illustrated how multiple arguments are passed along.

I raised an eyebrow when I read that if you call a method of on objects which points to nil (null), no exception will be raised. Sure, it allows you to omit those tedious if(!= null) checks but I’ll probably pull out my hair when I’m writing more real life application and it’s not responding the way it should.

One final note for this chapter, calling methods of your base type is done in the Objective-C world by using the super keyword.

Chapter four talks about memory management. This was fairly new for me, I knew about it but I’ve only written programs in .Net (C#, Vb.Net, managed C++) or J2EE (Java) and both environments come with the garbage collector (GC) which manages memory for you. Mac OSX 10.5 introduced the GC as well, but it’s an option. If you turn it on your application will only run on 10.5 and later, so if you want to target previous versions you’ll have to release and retain yourself.

It was an interesting read, I never had seen an example of how memory can be managed in code you write. I’ll probably just turn the GC on for stuff I write. The chapter ends with stating that you should now have a basic understanding of Objective-C and Cocoa and that the next chapters will focus on the different frameworks you can use to build your applications.

Chapter five introduces some user interface components available in the IB (buttons, textboxes,…), nothing big here although I encourage you to write the challenge application. Challenges in the book are exercises which you should be able to write.

Attached you find the challenge exercise from chapter five (countline), the guided application (speakline) also from chapter five and the lottery application from chapter three and four. (55.52 kb) (16.43 kb) (52.62 kb)

Also I apologize for the layout of the code in this post I’ll fix that as soon as I can, Objective-C isn’t supported by default 🙂 .