Code

Leopard upgrade
28 October 2007 in Apple & Code | Comments (2)

Once again, Apple did well with their logistics and our pre-ordered copies of Leopard arrived at the Mindscape office at about 11am Friday. I did my install in the evening and much like Rod’s comments, it took a wee while but was about the most painless OS upgrade I’ve ever done.

I was certainly looking for “wow” features and so far I have not really found any – it is very much just additional polish to the OS. Spaces seem cool, the dock update is nice, having a “current time” line in iCal is finally there. There is apparently 1500+ of these types of changes and I’m sure I’ll keep coming across more of them as time goes on.

So what are some of the more major features for the developer crowd?

XCode 3.0 is included and Leopard also adds support for Objective-C 2.0 which is a nice step up from previous versions which did not have automatic garbage collection. I’ll certainly be having a bit more of a look into what else is lurking in the XCode box (so far I haven’t had the time).

Instruments is an interesting new tool for profiling your applications. I haven’t had a chance to poke around with this tool yet and it looks from screen shots that it’s mostly somewhat “fuzzy” in profiling (e.g. showing cpu load or network load in a graph rather than giving extremely detailed dumps of what is going on). I’m looking forward to seeing how Instruments performs.

Dashcode is a tool for helping build dashboard widgets. I’m not quite sure why it’s not included in XCode which seems to have templates for just about every other sort of project under the sun. I’ve never been a big user of widgets so I doubt I’ll use this tool very much.

One of the pain points with doing any development on the Mac is that the books currently in circulation all seem rather out of date. This could be because the documentation explorer, so far, seems quite impressive. Can anybody suggest a good book on Mac development?

– JD

WPF: Keep an eye on binding errors
8 September 2007 in .Net & Code & Windows | Comments (2)

I’m posting this because it escaped my attention initially and I’ve been meaning to post it for any other WPF developers out there who have issues with their bindings.

Whenever doing WPF development make sure that you pay attention to the “output” pane in Visual Studio (or better yet, drag the pane to a second monitor while running the application). Here you will see any errors that are occurring with your WPF bindings. You may even spot some you didn’t know were having problems.

Anybody working with WPF will be using the rich binding capabilities and I’m sure, like me, you get annoyed when things just seem to fail silently behind the scenes. Now you can see what’s really going on.

Hope that helps,

John-Daniel Trask

Howto: Write a PowerShell Drive Provider
21 June 2007 in Code & Tools | Comments (2)

Earlier this year I was tooling around with PowerShell and generally having a fun time with it and, based on a comment from Andrew, decided to see how difficult it would be to write a PowerShell Drive Provider. A drive provider is a mechanism of allowing you to navigate any store with the same commands as navigating the file system. PowerShell ships with several providers already, a registry and certificate store. This means you are able to “cd” into your registry and write commands like “dir” or “ls” on a node and get a list of all the children for example.

The attached download includes working commented code and a detailed tutorial PDF on how to write a drive provider that will enable you to mount a zip file as a drive and then navigate through it. This is powerful for removing the need to extract and then navigate files quickly and easily. I’ve implemented it in a simplistic manner and there is plenty of room for additional features but I wanted to keep it simple for educational purposes. Note that you will need PowerShell installed to even compile as it relies on several assemblies that ship with PowerShell.

So if you find yourself lying awake at night wishing you could mount zip files as drives within PowerShell (don’t we all?) or just want to learn more about writing drive providers or managed plug-ins for PowerShell then check this out.

Download the PowerShell Zip Drive Provider and Tutorial

Hope this helps people have more of a poke at PowerShell,

– JD

Basic querying with LightSpeed
12 June 2007 in .Net & Code & Mindscape & Tools | Comments (2)

In my previous post about LightSpeed I discussed setting up a very basic LightSpeed instance but didn’t go into any detail about working with the data once we had configured it. In this post we’ll have a look at some basic ways of performing CRUD actions on our database through LightSpeed.

Creating Objects

To create an object we simply need to create an instance of our model class and assign the properties that we want set. This isn’t complicated and not LightSpeed specific so this isn’t a difficult mechanism to understand.

ConfigurationItem item = new ConfigurationItem();
item.ReferenceName = referenceName;
item.ValueType = type;
item.DisplayName = displayName;
item.Description = description;
item.Value = value;
 
Repository.Add(item);
Repository.CompleteUnitOfWork();

The important part here is at the end where we add the item to the repository and then tell the repository to complete the associated unit of work.

Retrieving Objects

There are many ways to retrieve objects in LightSpeed but I will detail two basic queries here. Retrieving my primary key and retrieving by a single field.

// Find the configuration item that has a primary key of 2
ConfigurationItem configItem = Repository.Find<ConfigurationItem>(2);

Here is a query by the DisplayName property which is just a normal property, not a primary key.

// Create a query to get an entity where the property "DisplayName" is equal to "Example"
QueryExpression query = Entity.Attribute("DisplayName") == "Example";      
 
// Get a collection of items that match that query from the database
IList<ConfigurationItem> items = Repository.Find<ConfigurationItem>(query);

Queries certainly are a breeze when working with LightSpeed. In later posts we will look at more advanced queries that have multiple criteria.

Updating Objects

Updating an object with LightSpeed is an easy operation of just updating one or many properties on your entity and telling the repository to save those changes.

// Retrieve an object
ConfigurationItem configItem= Repository.Find<ConfigurationItem>(2);
 
// Update the display name
configItem.DisplayName = "My Updated Display Name"
 
// Save the changes to the database
Repository.CompleteUnitOfWork();

Deleting Objects

Last but not least we occasionally need to delete data from our database.

// Get a configuration item of primary key 2
ConfigurationItem configItem = Repository.Find<ConfigurationItem>(2);
 
// Mark the entity as deleted
Repository.Remove(configItem);
 
// Save the change, actually commiting the delete to the database
Repository.CompleteUnitOfWork();

Now we have walked through CRUD interactions through LightSpeed.

Hope that helps,

– JD

Getting started with Mindscape LightSpeed
11 June 2007 in .Net & Code & Mindscape & Tools | Comments (2)

Mindscape LightSpeed Logo

In the weekend I was reworking a prototype of something I’m working on and I wanted to use LightSpeed to manage the data access and thought it would be appropriate as a code example of how to quickly and easily get started with LightSpeed. To clarify, I only needed LightSpeed for the persistence mechanism as opposed to the full domain modeling capability at this stage of my project.

The Problem
My application needed a mechanism for persisting configuration. The configuration this application stores is extensible and ideally will be extended by 3rd party plug-ins which means I needed to expose a service that can be used by these 3rd parties to store their custom configuration in a manner that will give access both to their plug-in as well as our application.

I’m also a staunch hater of >300KB XML configuration files and it’s early days in the prototype :)

Step 1: Create your model classes
I have a simple configuration entity that I wanted to be able to persist to a SQLite database (LightSpeed supports many different database engines by the way). At this stage of my prototype I’m effectively only storing a key/value pair, a human readable name and description and a type (e.g. string, color, int). In this code example you will need to reference LightSpeed in your project to gain access to the Entity<> class that we are inheriting off.

Note that LightSpeed takes care of the enum as well and will happily convert it to an int at the database level :) Too easy.

using System;
using Mindscape.LightSpeed;
 
namespace Mindscape.Carbon.Core.Configuration
{
  public class ConfigurationItem: Entity<guid>
  {
    public enum ConfigValueType
    {
      STRING,
      INT,
      COLOR
    }
 
    private string _referenceName;
    private string _value;
    private ConfigValueType _valueType;
    private string _displayName;
    private string _description;
 
    public string ReferenceName
    {
      get { return _referenceName; }
      set { Set(ref _referenceName, value, "ReferenceName"); }
    }
 
    public string Value
    {
      get { return _value; }
      set { Set(ref _value, value, "Value"); }
    }
 
    public ConfigValueType ValueType
    {
      get { return _valueType; }
      set { Set(ref _valueType, value, "ValueType"); }
    }
 
    public string DisplayName
    {
      get { return _displayName; }
      set { Set(ref _displayName, value, "DisplayName"); }
    }
 
    public string Description
    {
      get { return _description; }
      set { Set(ref _description, value, "Description"); }
    }
  }
}

Step 2: Create your database
Currently you create your database manually however we are working on tools to do this for you. Note that I’m using a GUID as the primary key on this table and we didn’t need to add it to the model object in the previous step, LightSpeed does this for you. You only need to supply the primary key type in Entity. Now you can jump into whatever database you’re working with and create the table.

In my case I was using SQLite and just used a simple create table command:

CREATE TABLE ConfigurationItem(
  Id                GUID            NOT NULL PRIMARY KEY,
  ReferenceName     NVARCHAR(50)    NOT NULL UNIQUE,
  Value             NVARCHAR(100)   NOT NULL,
  ValueType         INT             NOT NULL,
  DisplayName       NVARCHAR(100)   NOT NULL,
  Description       NVARCHAR(1024)  NOT NULL);

Step 3: Add LightSpeed to your configuration
We need to tell our application about the database that LightSpeed should be working with and we can do this in code or in the .config file for our project. In this example I’ve elected to put it into the app.config of my project.

  <configSections>
    <section name="LightSpeed" 
        type="Mindscape.LightSpeed.Configuration.LightSpeedConfigurationSection, Mindscape.LightSpeed" />
  </configSections>
 
  <connectionStrings>
    <add name="ConfigDB" connectionString="Data Source=MyDatabase.db3"/>
  </connectionStrings>
 
  <LightSpeed dataProvider="SQLite3"
           connectionStringName="ConfigDB"
           identityMethod="Guid"/>

Step 4: Work with your data
That’s it! All the configuration work has been completed and there is no heavy XML mapping file or complex setup to tell LightSpeed about the database. The whole philosophy behind LightSpeed is to help developers get work done quickly and I hope this example and your own work with LightSpeed proves that. In following posts I will provide detail about working with your data however here is a taster of how easy it is to now put new objects into the database:

    ConfigurationItem item = new ConfigurationItem();
    item.ReferenceName = "MyRefName";
    item.ValueType = ConfigurationItem.ConfigValueType.STRING;
    item.DisplayName = "Example Config";
    item.Description = "This is an example configuration key";
    item.Value = "example";
 
    Repository.Add(item);
    Repository.CompleteUnitOfWork();

In this example I had an extremely simple model however you can appreciate that there is significantly less leg work required to get a LightSpeed solution up and running. I will post more advanced real world examples to help you gain more from working with LightSpeed in the near future. Also please leave any comments or questions you have on my blog regarding LightSpeed.

How can you use LightSpeed?
We currently are in late beta with an RTM of LightSpeed just around the corner. You can grab the download of LightSpeed from the Mindscape EAP site. You can also post in the forums to discuss any challenges that you have or to ask questions. We welcome any feedback.

Update: LightSpeed was released and is now available to play with here: http://www.mindscape.co.nz/products/LightSpeed/

Hope that helps,

– JD

Flow testing with WatiN
7 June 2007 in .Net & Code | Comments (31)

Last night I had the opportunity to speak to the Christchurch .NET User Group about web standards and took the opportunity to add some discussion about testing using a tool called WatiN (pronounced “what-in”, horrible I know). From the feedback I’ve received so far the WatiN demo captured everyone’s imagination. I had a great time as well, very friendly folks in Christchurch :)

WatiN effectively allows you to script interactions with Internet Explorer and do things like fill out forms, click through and test the results that come back. This makes testing things such as a process flow really easy to do in a repeatable manner and included in your unit tests which ideally are being executed as part of your continuous integration processes.

Examples:

The example I demonstrated last night was just doing a simple test of the BackgroundMotion search engine. You can probably understand what is going on just from the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
    [Test]
    public void TestSearchWithNoResult()
    {
      IE ie = new IE();
      ie.GoTo("http://backgroundmotion/");
      ie.TextField(Find.ById("ctl00_SearchBox")).Click();
      ie.TextField(Find.ById("ctl00_SearchBox")).TypeText("beach");
      ie.Button("ctl00_Search").Click();
 
      Assert.IsTrue(ie.ContainsText("No results found"));
 
      ie.Close();
    }

Automated Validation is a hot topic for me as I really hate working on a project and then remembering to validate well after I wrote the HTML only to find I have a lot of work ahead of me. I wrote the following test code to allow automated posting of web content to the W3C validation service for checking:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    private static bool IsValidPage(string url)
    {
      string rawHtml = GetFile(url);
      IE ie = new IE("http://validator.w3.org/fragment-upload.html");
      ie.GoTo("http://validator.w3.org/fragment-upload.html");
      ie.TextField(Find.ByName("fragment")).Click();
      ie.TextField(Find.ByName("fragment")).Value = rawHtml;
      ie.Button(Find.ByValue("Validate this document")).Click();
 
      return ie.ContainsText("Is Valid");
    }
 
    public static string GetFile(string url)
    {
      WebRequest myWebRequest = WebRequest.Create(url);
      WebResponse myWebResponse = myWebRequest.GetResponse();
      Stream ReceiveStream = myWebResponse.GetResponseStream();
      Encoding encode = Encoding.GetEncoding("utf-8");
      StreamReader readStream = new StreamReader(ReceiveStream, encode);
 
      string response = readStream.ReadToEnd();
 
      readStream.Close();
      myWebResponse.Close();
 
      return response;
    }

With these two methods you can do write a test per page to validate the content:

1
2
3
4
5
    [Test]
    public void TestValidHTML()
    {
      Assert.IsTrue(IsValidPage("http://www.mysite.com/mypage.aspx"));
    }

Note that this code doesn’t take into account subtle changes with the use of AJAX, it simply gets the raw content from the request. WatiN does however support handling AJAX changes quite nicely so upgrading to support a richer website would not present much of an issue. The interesting thing with the raw request is we could change the agent-type on the request to ensure that we’re getting valid HTML for various browsers despite being called from one central location. This can be great if you’re working with ASP.NET where the server controls will be rendered differently based on the agent type by default.

The code also doesn’t take account of potential network connectivity issues and was more for showing the sort of things that you might want to do with WatiN. WatiN is certainly a useful tool to have in your toolbox. If you want to learn more about WatiN just pull it down and also grab one of the few WatiN recorders as the one listed below and get a kick start in scripting your site interactions.

The Tools

WatiN: http://sourceforge.net/projects/watin/

WatiN Recorder: http://watintestrecord.sourceforge.net/

Hope that helps,

- JD

Online and Offline convergence
31 May 2007 in Apple & Code & Google & Microsoft | Comments (2)

Rather than echoing the “oooh -Google gears” and “oooh – Microsoft surface” stories I thought I’d put a bit more thought into these recent announcements and why I see them as important. Earlier this week Andrew and I were discussing the web and how we both agreed that the humble browser is not the ideal application platform. There are many advantages of web applications (instant updates, great metrics on use, much more) but we’re yet to see the richness and flexibility of what can be done in the offline world. Of course the positives of one platform are effectively the negatives of the other and vice versa. People still make a conscious decision about the type of application they’re building and this got me thinking.

Offline Applications

As I commented on Rod’s blog, I agree with DHH on his views about offline applications. Retrofitting existing applications doesn’t strike me as being a huge win, I’m virtually always connected with a pretty fat pipe. I don’t believe the advantages of offline applications are really obvious yet because we are all still thinking how it affects the current web model. We need to pull our view back another 20,000 feet and start thinking outside the box. I’m not claiming I have the answers on this one but I’m sure we can do better than an RSS reader that has an offline mode!

Breaking out of the browser

With Microsoft Silverlight we have the opportunity to break applications outside of the browser (To see an example check out our Silverlight Video player on the Mindscape blog, just click the video when it is playing). I firmly believe this is a significant step forward again that didn’t really get noticed all that much. Suddenly the browser isn’t all that important other than to host these applications. I joked with Andrew that I look forward to the day when the web browser is a non-visual host and the applications are the only visual part (no jokes about visibility inheritance please ;)

Microsoft Surface

First off, this is pretty damn cool. Personally I think it knocks the socks off the iPhone in terms of cool – Microsoft are helping to usher in a new paradigm here but that’s not why I’m bringing it up. Taking into account what we are discussing here you can quickly start to see the benefits of dropping the web browser. I really don’t want to see Internet Explorer or FireFox as a Window on a device like Microsoft Surface – it would just break the model of how the device is meant to be used. If web applications are no longer looking like web applications and are becoming super rich with cloud and offline storage we’re actually seeing a a convergence of the desktop and web worlds.

Challenges

Having said all this there is a HEAP of work still left to do. We don’t really want every application to look different, uniqueness isn’t actually a benefit in terms of usability, there needs to be standards. We need to consider accessibility for less able users or how this content can be moved between the various devices (PC, tablet, phone…coffee table). I really look forward to some of these problems getting solved though, the future looks bright.

I suspect that in the next 10 years we’re going to stop being able to define an application as being a web application or a desktop application. Rather than consciously trying to build Smart Clients, it will just be the way applications are built and we’ll all laugh at why we ever struggled to build them well in the past :)

What do you think? Agree? Disagree? Want to hire me for tarot card reading?

- JD

Reduce your .NET assembly size
12 April 2007 in .Net & Code | Comments (1)

I’ve always been interested in writing very small and efficient code. There isn’t much need for coding in C or Assembler these days (which I used to like playing with a few years back) so I really enjoy finding new ways of making .NET code smaller and faster. I thought I would share one inexpensive trick for making your assemblies just that bit smaller on disk.

  • Bring up the properties to your C# project file.
  • Click on the build tab.
  • Click on Advanced.
  • Set the File Alignment value to 512 (it will default to 4096 for C# projects)

File Alignment Property on C# Projects Dialog

For some reason Visual Basic solutions will default to 512 and C# projects seem to default to 4096. This affects how the MSIL code is written in the assembly and appropriately pads the file with zeros if required to fit code neatly into the file alignment size. Reducing this value has negligible or no affect on application start-up but can reduce your assembly size by a noticeable amount. Likely in the 10 – 20% range in terms of savings.

Always nice to get a free saving on assembly size!

- JD