Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Tuesday, March 15, 2011

A strongly typed implementation of INotifyPropertyChanged

INotifyPropertyChanged is an interface used to notify clients that a property has changed. It's used heavily in Silverlight and WPF in combination with databinding and when used it makes updating the ui and then retrieving data from the ui very simple.

I have a major gripe with the way it's generally done though. There are usually two places where the parameter name is specified as text. In the xaml code:
<TextBlock Text="{Binding Name}" />

and in the viewmodel
public class Person : INotifyPropertyChanged
{
  public string Name
  {
    get { return _name; }
    set { _name = value; NotifyPropertyChanged("Name"); }
  }
}

The main problem here is that if you refactor or rename a property you might miss these two locations and will not be alerted. Your app will not work and unless you're testing all your ui field databindings you'll never notice.

Unfortunately we can't fix this problem in the xaml, but in the viewmodel here is a neat typesafe implmentation of NotifyPropertyChanged.

protected void NotifyPropertyChanged<T>(Expression<Func<T>> expression)
 {
   if (PropertyChanged != null)
   {
     PropertyChanged(this, new PropertyChangedEventArgs(expression.MemberName()));
   }
}

public event PropertyChangedEventHandler PropertyChanged;

Usage:
public class Person : INotifyPropertyChanged
{
  public string Name
  {
      get { return _name; }
      set { _name = value; NotifyPropertyChanged(() => Name); }
  }
}

Wednesday, April 07, 2010

Windows Phone 7 Series

I've been experimenting and researching development on Windows Phone 7 Series. I've installed the CTP and written my first program! If you want to get started, look at this free book by Charles Petzold.

Here are some of my observations.

Dev Framework
You can only write apps using silverlight or XNA (Xbox development framework). This has some pretty big implications, such as the fact that all applications written for previous versions of windows mobile will not run on Phone 7.

All of them. Throw them away. All of those organisations who have built product and ip based on Windows Mobile will not be coming to the Phone 7 party with any advantage. In fact, most of the current applications will not even have a parallel in Phone 7.

It will be nice for people who are already familiar with Silverlight. So there might be some nice apps written targetting Silverlight. The downsides is that it will require a connection and the performance will be related to the speed of your network connection.

XNA might also bring some XBox devs across. But there's a fairly steep learning curve and isn't that accessable for noobs.

One really big advantage is that MS has taken a much stronger grip on the hardware. Their specs are much more stringent. For example there will only be two screen sizes allowed. Large and small. No more having to cater for 15 different screen sizes!

DataStorage
There is no database on the phone. Silverlight apps can access a sandbox storage location. The word I've seen on various forums is that you're supposed to use cloud for data storage and you can store simple data as xml in Isolated Storage. However, this guy (http://sviluppomobile.blogspot.com/2010/03/sqlite-for-wp-7-series-proof-of-concept.html) has a POC with SQLLite running on Phone 7.

Target audience
The phone seems to be squarely targetted at the consumer. Most of the enterprise apps will mostly likely stay at version 6.5 and earlier. In a lot of ways, it looks like they've copied the iPhone but with bigger icons on the home screen.

Does the world need an iPhone clone with no applications currently written? Who knows.

ASP.NET MVC

I've been working with ASP.NET MVC for a while now. I really enjoy working with the framework and had a very successful project delivered using it. Some of my highlights are listed below.

Separation of concern
The framework is a wonderfully elegant implementation of the MVC pattern. Once you get your head around the responsibilities of the controller, model and view you can very rapidly produce robust, testable code.

Productivity
There are huge productivity gains available when using ASP.NET MVC. It takes so much complexity away from ASP.NET devlopment, without reducing flexibility and power. When doing ASP.NET development, you need to be aware of the page lifecycle at all times and trying to work out which actions should be performed at which step of the page lifecycle can be extremely complex.

Testability
The framework really lends itself to testability. You have to be a little careful to keep it clean, but if you do, the whole system is very testable. The key point to ensure testability is to only pass ViewModels into your controller actions. I cannot stress how important this is. As soon as you try to access the Request.Form in your controller method it becomes incredibly hard to test. You have to mock out the HttpContext and it just gets messy. Even with some very complex forms, I always found a way to represent it all using ViewModels. If you get stuck, use a custom model binder.

Reliability
This is the area that surprised me the most. We had a very low rate of regression errors. I attribute this to two factors:
1. Separation of responsibility - Each controller method operates quite independently, so changing code should not affect other functionality
2. Testability - Having a good suite of unit tests helps to catch any errors that might creep into the code.

I put together a presentation explaining some of these points in more detail. It's available here.

A strongly typed RadioButtonList for ASP.NET MVC

There are many strongly typed controls in ASP.NET MVC. For example TextBoxFor. I really like using the strongly typed HTML helpers because you get much better information at compile time. Especially if you've turned on compile time view checking.

The one control that was missing, however is RadioButtonList. There is no "RadioButtonListFor" to be found. So I wrote my own.

This is what the code looks like in the aspx
<%= Html.RadioButtonListFor(m => m.GenderRadioButtonList)%>

Here's the code in the controller to check what the user has selected

public ActionResult Submit(HomePageViewModel viewModel)
{
  if (viewModel.GenderRadioButtonList.SelectedValue == HomePageViewModel.GenderType.Female)
  {
    // Do something
  }
  return View("Index", viewModel);
}
The code, plus a sample website using it, is in this zip file.

Additionally, at the risk of creating an infinite loop, here's a StackOverflow question that this post is an answer to. It's got some useful comments and more code.

Tuesday, November 08, 2005

Shrink wrapped software and Feature Prioritisation

Just read an interesting article written by Joel Spolsky. You can read it here.

It covers two important concepts in Software Development.

1. Developing shrink-wrapped sofware vs customised software. I've developed both kinds of software at various times.

I find that writing customised software really isn't a good business model. The process tends to go like this:
- Sales guy talks to the client
- Asks for a quote with some very vague, hand-wavy "requirements"
- BA/Architect comes up with an estimate based on gut feel
- Estimate is turned into a dollar figure, discounts are applied to ensure the deal is won
- Contract is signed

Later on, down the track, the consulting company decides what functionality can be crammed into the budget, negotiates with the customer and they come to some agreement.

The end result is that the customer doesn't really get what they want and the consulting company make a very small profit (or sometimes, large losses!) and that's it. No more chance to benefit from that work at all.

At least if you develop some software that can be resold (even with customisation) you've got an opportunity to leverage that work into future earnings.

2. Priorities
The other interesting concept discussed is prioritisation. I think this is so important, but lots of people just don't get it. If you set priorities and then develop components based on their importance, everybody wins!

Thursday, October 27, 2005

Modern Programming Languages/Systems

I just read an interesting and thought provoking article by Charles Petzold. Read it here.

While I don't claim to have the experience that Petzold has, I started my programming experience back on Windows 3.1, writing C++. I feel a similar disquiet towards .NET programming that he describes.

Back in the day, when I wrote a program, I wrote every line of code. I controlled everything about the program. When a window resized, the controls moved because I put in code that told it how to move. I had complete power over the behaviour of the program. The downside of having that power is that it takes a long time to write all that code.

Nowdays I can get a program up and running a lot faster. However the cost of this improved productivity is that a lot of code is hidden away from me and that makes me feel vaguely nervous. When I write a foreach loop to iterate an arraylist these days I have no idea what's actually happening under the covers. So I just have to shrug and hope it performs okay. Because the alternative is too onerous and most of the time it's just not necessary.

The biggest extreme in this direction I have experienced is working with Borland Builder. It took me a week to get two windows to communicate with each other because it was a 'non-standard' communication and builder hid so much of the implementation from me that I had to work around it in incredibly complicated ways.

Could I go back? It'd be very hard to have to worry about ensuring that I deallocate all my pointers again. But at the same time I really miss the mental stimulation and discipline that that imposes. I feel 'careless' as a programmer now. At the same time I'm sure I'm romanticising C++ programming. I haven't mentioned the endless frustration of spending 3 days tracking down that annoying memory allocation bug. But then I also haven't mentioned the incredible surge you get when you find it and fix it!

So for 90% of programs, the extra productivity that modern programming languages provide are well and truly worth it. But I'll always look back and miss the real challenges and satisfaction that C++ programming provided.

Tuesday, May 24, 2005

Macro to attach to asp.net process

You know how much of a pain it is to debug web apps in Visual Studio .Net? You either run the website (which takes forever) or have to attach to the aspnet_wp.exe by clicking [Alt]dp[Enter][Enter][Enter].

Finally! A macro to attach to the process automatically! Thanks to Dan.


Sub AttachToAspDotNet()
  Dim attached As Boolean = False
  Dim proc As EnvDTE.Process
  For Each proc In DTE.Debugger.LocalProcesses
    If (Right(proc.Name, 13) = "aspnet_wp.exe") Then
      proc.Attach()
      attached = True
      Exit For
    End If
  Next

  If attached = False Then
    MsgBox("aspnet_wp.exe is not running")
  End If
End Sub

Wednesday, May 18, 2005

VB.NET vs C#.NET

There's an interesting discussion happening at work at the moment about VB vs C# code. My thoughts:

VB as a language was designed to abstract a lot of complex functionality so that the programmer didn't have to "bother" with it. This is great for small and simple applications. It provided a great platform for developing small applications quickly and efficiently.

C++ however doesn't try to hide detail (although later libraries such as the STL started to edge in this direction). So you have more power and control, but also an increased level of complexity. So it took longer to produce a simple application but is more capable for a complex application.

So from my point of view, the comparison is between ignoring complexity and knowing, at a deeper level, what was actually happening when you call a function with a reference parameter. Knowing how memory is managed and how pointers work. Coz this stuff is still important, no matter how much .NET tries to hide from you.

I don't think there is any difference in VB or C# code. The only differences nowdays (.NET) is the syntax.

However, there is a big difference in code written by someone how 'gets' how the low level operations work and someone who doesn't. This is, to me, the essence of the (unfair IMO) categorisation of VB programmers and C++/# programmers. The categorisation is based on where you came from. If you started working with C++ you probably understand this stuff, or you wouldn't have cut it as a C++ developer. If you started working with VB, you didn't have to do that. Mind you, that doesn't necessarily mean that you don't get it... there's no reason that a programmer starting with VB is any less capable of understanding what's going on under the hood.

Joel on Software has an interesting article about Leaky Abstractions that also illustrates this issue. It's pretty long, but it's almost certainly written better than this (admittedly long-winded) post :)