h1

Coding Styles and Standards

July 5, 2009

At my current engagement, recently, we have decided to start making our coding standards more uniform and so some of the guys got together and decided that from now on, we shall no longer prefix private member fields with an underscore “_” and will just use lower case.

So for example the following property:

private string _foo = null;

public string Foo

{

get

{

Return _foo;

}

}

would be written like this instead:

private string foo = null;

public string Foo

{

get

{

return foo;

}

}

I thought it was a much nicer coding style in terms of pure cleanliness of the code. It seemed more pleasurable to look at. Today on a separate project I am working on, I spent 1.5 hours debugging the following mistake because of this practice. Let’s see how quickly you can find the error

Now, I’m sure you found the error quite quickly especially because I have specifically given you the context of the problem but as you can Imagine, this is not terribly hard mistake to make. I know I have learnt my lesson on the importance of clear code > pretty code. I would be interested in hearing what others have to say about this.

h1

Chrome browser is bad for Silverlight Development

April 26, 2009

Today I switched over from IE to Chrome for my Silverlight development. As I did so I realised I lost the ability to debug both my Silverlight project and web server project at the same time. The reason is because the debugging process needs to attach to your browser process. One of chromes great features is that each tab is its own process. This is a problem because it means you can no longer debug your Silverlight applications and web server projects at the same time.

 

Just a quick gotchya that I thought I’d mention..

h1

Silverlight 2.0 and WCF Duplex Service

January 20, 2009

Today I was doing a POC on Silverlight 2.0 and WCF Duplex Services. It seems to be a great alternative to using sockets because of the cleaner and easier programming model. It also has almost the same advantage as socket programming because under the head it uses a sort of ‘smart polling’ where the client sends a request to the server checking for any new events/messages that need to be passed back to the Silverlight client, the connection and hangs around until there is something to send back to the client and does so when the server queues any messages. The max time this connection can stay open before timing out is 90 seconds, at which point another ‘half pole’ if you will happens. Pretty good trade off I must say. There is only one problem with this current solution and that is there is no visual studio support to add service references via the GUI so basically you not only have to generate the proxy client code yourself but you even need to do all the serialization and de-serialization manually! Very tedious, I will be researching for any alternatives in the next few days.

h1

Silverlight 2.0 MVP Architecture

November 6, 2008

I have recently kicked off a new project at work and decided to use Silverlight 2.0 as the technology of choice. Why? Because web 2.0 is dead and RIA is the way of the future. I got the structure of Tim Ross’s blog, he wrote an excellent in depth article with source code. I thought I would also write an article about it but by introducing some of the extra projects that I found necessary and some of the design decisions involved. The rest of this article will give you an idea of how to structure a Silverlight 2.0 application in visual studio 2008 that uses Silverlight WCF enabled services over BasicHttpBinding (the only one currently supported) to communicate with the web server. The separation of concerns pattern that I will be using will be the MVP pattern. I chose this pattern over the MVVM pattern because of two reasons. 1) It has been officially documented on the MSDN site and MVVM at this time of writing hasn’t

2) It has been around for longer than MVVM which was invented by a team of Microsoft guys during the writing of blend and therefore the chances of people knowing it will be higher. Because I’m using an emerging technology, my concerns are that people will already have a big learning curve to conquer and I don’t want to introduce a new(ish) pattern on top of it.

Here is a snip of the solution structure

Client and Server

To start off, we create two solution folders, one named Client and one named Server.

Client

This folder contains 3 projects

SilverlightMvp.View <- The actual SilverlightApplication

SilverlightMvp.Core <- Silverlight Class Library

SilverlightMvp.Core.UnitTests <- Unit tests for the presenters.

The unit test project won’t actually reside on the client machine but it makes more sense to group it in the client folder as it is purely testing the presenters.

Server

This folder contains 5 projects.

Database <- The database

DataAccess <- the CRUD library

Common <- Entities folder (The Model) and ExtensionMethods

SilverlightApplication.Web <- Web Application that hosts the Silverlight application. This has a folder in it called WCFServices which contains the Silverlight enabled WCF services. To add a Silverlight enabled WCF service, select the WebApplication that is hosting your Silverlight project. Right click -> Add -> New File.

This is where you will find the WCF template:

Business <- Business logic that the WCF Services will expose to the Silverlight application (SilverlightMvp.Core)

Tests <- The reason why this project is called Tests is because it will be hosting both my Unit tests and Integration tests. I have created two folders in there named Unit Tests and Integration Tests. Using the dependency injection pattern we ensure mocking the DataAcess Layer will be easy. For my requirements I will not be testing the WCF Services inside the SilverlightApplicaiton.Web projects because they will just expose Business Library methods and have no logic in them at all.

Notes

  • The Client and Server folder structure help enforce the developer to be constantly aware of the fact that the Silverlight application is actually a tiny subset of the .net CLR and therefor is missing a lot of functionality.
  • Because you are using a separate CLR that’s on the clients machine, you cannot point WCF to your existing Model. They must be dynamically generated.
  • Make sure you do all your data retrieval on the web server and pass it down in one hit rather than putting loops in your client service proxy’s retrieving data multiple times and therefore opening pooled database connections. As a general rule of thumb, loops in the presenter or client service making single calls to the database can usually be avoided and can speed things up

Conclusion

Overall I’m happy with the final design of the solution and I’m convinced that it’s the simplest solution that has the right balance of complexity to provide functionality, separation of concerns and maintainability but at the same time, not overly architected to cause Shunting friction

If I wasn’t so busy, I would look into creating a Guidence Automation package for this structure.

I would be very interested to hear comments on the Tests and Unit Test structure and would also love to hear about any alternatives you may have come up with.

h1

Don’t use funny ASCII chars in Application names…

September 12, 2008

Today I found a reason not to be too clever when using application names. Personally, I use the search in vista’s start bar quite a lot. Today I thought it was strange when I attempted to open uTorrent and it wouldn’t come up in the results. The reason is because I typed “uTorrent” which is not that funny looking ASCII u (I don’t even know what alt # that is).

h1

CopyPaste+

August 31, 2008

I have always been bitten with the limitation of the windows clipboard. I have a bad habit (completely my fault as a user) to copy (usually important) things into my clipboard and then close down the screen with the intention to paste the clipboard contents into another application which is usually a browser, word, notepad or maybe even excel. Sometimes tho, I get distracted before I paste in the content and accidently press control c again over some other content, thereby losing what was in my clipboard.. Arghh! Normally, I would have to relaunch the application and fetch the original contents of what I wanted copied into my clipboard. Well this week end I finally got around to creating CopyPaste+ which is pronounced CopyPastePlus, sort of like C#. Yes, so I’m not the most creative guy around, but hey – I don’t care! Anyway, here is what I would LIKE my application to look like:

CopyPaste+

CopyPaste+

This is just a quick mock-up that I made… Okay maybe not me but, my so much more creative friend William did.

And here is what the app currently looks like:

puke

puke

Okay, so it looks like puke… BUT, I promise, it’s super useful!

Download the application here

Note: Requires .net framework 3.5 to run which can be found here

How to Use

The application monitors the windows clipboard and adds it to a list of 5 clipboard contents (The default is 5 but this is configurable). At this point you may want to retrieve clipboard content #3 so you would press control + shift + v instead of the normal control v to paste. This activates the applications sexy UI which appears in front of you, fixed and glued to the centre of the screen. From here, you should click on the box you would like to paste. Once clicking on the rectangle, the application hides itself and has overwritten your current clipboard with the selected item. You then simply paste in (tip: control v ;p) your content into whatever application you want. Simply repeat this step to retrieve any clipboard content you would like.

Configuring Number of Clipboard Content Items:

To increase or decrease the number of items you would like to have, all you need to do is have this config file sitting side by side to the exe and change the “NumberOfBoxes” value from 5 to whatever you like

Future Releases

  • Configurable number of Items will be done via User Interfaces options
  • UI will look like Williams
  • Selecting Icon in task bar will activate the UI
  • Will be able to handle content other than just text i.e. images, files etc.

License Agreement

On Request, I will supply the source code to anyone that wants it for non commercial use, for free.

Contact me here to request the source code.

h1

Using T-SQL and the Registry to Retrieve a List of Countries

August 20, 2008

I was catching up on some blog reading tonight when I saw this post. For retrieval purposes, I have made a copy of the post and will keep it for when in use. Thanks Omar!

Using T-SQL and the Registry to Retrieve a List of Countries

So every time I create a SQL script to populate a countries table I end up losing it. So here is proc I decided to keep forever on my blog that retrieves the list of countries from the registry of the machine it’s sitting on. Remember to run it under elevated permissions.

1:
PRINT
‘Building dbo.ListCountryFromRegistry’

2:
IF
EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N‘dbo.ListCountryFromRegistry’) AND OBJECTPROPERTY(id, N‘IsProcedure’) = 1)

3:
BEGIN

4:
DROP
PROC dbo.ListCountryFromRegistry

5:
END

6:
GO

7:
CREATE
PROC dbo.ListCountryFromRegistry

8:
AS

9: –Root Key

10:
DECLARE @RootKey nvarchar(255)

11:
SET @RootKey = ‘HKEY_LOCAL_MACHINE’

12: 

13: –Registry Key
for country list

14:
DECLARE @CountryListKey nvarchar(255)

15:
SET @CountryListKey = ‘SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Country List\’

16: 

17:Table
to store registry extracts

18:
CREATE
TABLE #RegistryOutput ( countryKey int)

19: 

20:Table
to store registry outputs with rownumbers.

21:
CREATE
TABLE #NumberedRegistryOutput ( rowNumber int, countryKey int)

22: 

23:Get the the list of country nodes under the cuntry list tree

24: INSERT INTO #RegistryOutput EXEC master..xp_regenumkeys @RootKey, @CountryListKey

25: 

26:Add RowNumbers to
use
as indexers later

27: INSERT INTO #NumberedRegistryOutput ( rowNumber, countryKey )

28: (SELECT ROW_NUMBER() OVER(ORDER
BY countryKey), countryKey

29:
FROM #RegistryOutput)

30: 

31: –Grab a counter to
use
in looping through country nodes

32:
DECLARE @Counter int;

33:
SET @Counter = (SELECT
MAX(rowNumber) FROM #NumberedRegistryOutput);

34: 

35:Current
index
to be used to
iterate the countr nodes.

36:
DECLARE @CurrentCountryKey int;

37: 

38:Current Country Registry Key

39:
DECLARE @CountryRegistryKey nvarchar(150)

40: 

41: –Country name returned form registry and
to be added to
output

42:
DECLARE @CountryName nvarchar(255)

43: 

44:Output
table
with Country Names

45:
Create
table #CountryNames ( CountryName nvarchar(255))

46: 

47: –Loop through country nodes

48:
WHILE (@Counter > 0)

49:
BEGIN

50:
SET @Counter = @Counter – 1

51:
SET @CurrentCountryKey = (SELECT countryKey FROM #NumberedRegistryOutput WHERE rowNumber = @Counter)

52:
SET @CountryRegistryKey = @CountryListKey + RTRIM(LTRIM(CAST( @CurrentCountryKey as nvarchar(20))))

53: 

54:
EXEC master..xp_regread

55: @RootKey,

56: @CountryRegistryKey,

57:
‘Name’,

58: @CountryName OUTPUT

59: 

60: Insert #CountryNames VALUES (@CountryName)

61:
END

62: 

63:Output

64:
Select * from #CountryNames ORDER
BY CountryName

65: 

66: –Cleanup

67:
drop
table #RegistryOutput

68:
drop
table #NumberedRegistryOutput

69:
drop
table #CountryNames

70: 

71:
GO

h1

VB Extension Methods > C# Extension Methods =(

July 31, 2008

As my title childishly explains VB extension methods seem to have one over c# extension methods. Yesterday I found the following limitation in c#: You cannot modify the object you are calling the extension method on by ref. you must create a copy of the object and pass it as a return value. An example will make this clearer. You CAN do this:

public static IEnumerable<T> AddRange<T>(this IEnumerable<T> list, IEnumerable range)
{
List<T> totalList = new List<T>();

foreach (T t in list)
{
totalList.Add(t);
}

foreach (T t in range)
{
totalList.Add(t);
}

return totalList;
}

You can NOT do this

public static void AddRange<T>(this IEnumerable<T> list, IEnumerable range)
{
List<T> totalList = new List<T>();

foreach (T t in list)
{
totalList.Add(t);
}

foreach (T t in range)
{
totalList.Add(t);
}

list = totalList;
}

It’s a sad day today my c# friends ;p

h1

WPF Findings

July 28, 2008

Here at work I am currently on my first commercial WPF project. Some of the things that I have learnt about wpf (the hard way)

* There is no Paging or Sorting support in the gridview (unbelievable isn’t it?)

* There are no validators!

* The WPF Binding Engine uses reflection when binding against Dependency Properties and as such your properties need to be public. If not, you will get a silent exception in the output screen

* When binding to a dropdown list ComboBox you cannot bind against a nullable int. Why? I have no idea, but you will find that the selected index changed event will not fire

* There is no Gif Animation Support in the Image control. (expected to be supported in next release of wpf)

I have quite a few more points but they were the top few that I could think of that were easy to list out.

Overall I am loving what WPF has to offer and it is quite a different thinking approach as to web development. Although I must admit I feel a bit home sick (asp.net)

h1

Unit Testing Internal methods.

July 10, 2008

Today I did some pair programming with Richard Banks from Readify.

When I explained to him that I use the IDE to generate these property accessors that use reflection to test internal and private methods he showed me a nicer way around it:

  http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx

Basically all I had to do was [assembly: InternalsVisibleTo(“Assembly Name”)] to the assembly.cs file and make sure that the “Assembly Name” was pointing to the unit tests assembly name.

This worked perfectly! Thanks Richard!

P.S I should state the obvious note that this approach doesn’t work for private methods