Tuesday, 27 May 2014

Camera Remote


Well it's been a long time since I've posted anything here, but releasing an App to the Windows / Windows Phone Store has made me crawl out of my blogging hole!

I bought myself an Olympus camera, and I was quite intrigued by the fact you could control the camera using Wi-Fi.  Unfortunately the Olympus application is only available for Android and iOS, so I decided to write an App for Windows.

I went the new 8.1 Unified App route, so there's a version for both the Windows and Windows Phone Stores.  At some point it might be interesting to cover some of my development experiences, either here or on the app website.  In the meantime you can find the store links and some more details at http://camera-remote.kime-limited.co.uk/

It's free so if you have an Olympus camera with Wi-Fi head over and download it now!

Thursday, 25 February 2010

MySql .NET Connector Connection Problems

Summary

It’s been a while since I’ve posted anything and I’ve got a few subject ideas lined up, if and when I get going again.  In the meantime I thought I’d share some problems I’ve had with the MySql .NET Connector (MySql.Data.dll).

When using the C API you can specify a reconnect option for a connection.  Specifying this means that if the connection to the server fails then the client library will automatically reconnect and retry the connection.  Unfortunately, this option doesn’t seem to be available in the .NET Connector and we were seeing issues with connections timing out or otherwise closing.

To get round this issue I wrote a couple of small helper routines that will retry failed queries and automatically re-open a connection if it fails.

The Implementation

So the plan I came up with was to create a generic wrapper function that will run a provided delegate, catch database related errors and retry the query a couple of times.  I also provided a function that checks the state of a database connection, and re-opens it if necessary.

Retry Wrapper
public static TRetVal RetryWrapper<TRetVal>(RetryRoutine<TRetVal> queryRoutine)
{
Exception lastException = null;
for ( int queryRetries = 0; queryRetries < 2; ++queryRetries )
{
try
{
return queryRoutine();
}
catch ( DbException err )
{
lastException = err;
}
catch ( System.IO.IOException err )
{
lastException = err;
}
}

throw new DatabaseRetryFailedException(
String.Format("Too many retries. Last error: {0}", lastException.Message),
lastException);
}

I’ve implemented it by catching DbException so it could be used for other providers (I did this primarily for use with DbLinq).  I’ve also thrown a custom exception at the end, but you could change this to re-throw the final exception.

Connection Checking

You would think this bit would be straight forward, check if the connection is open and if it’s not then re-open it.  Unfortunately, when I tried this with the MySql Connector the first open after killing a connection would always fail.  So I put this in a retry loop as shown below.


public static DbConnection CheckConnection(DbConnection connection)
{
if ( connection.State != System.Data.ConnectionState.Open )
{
// For some crappy reason, the first re-open seems to fail in MySql
bool isRetry = false;
while ( true )
{
try
{
connection.Open();
return connection;
}
catch ( Exception )
{
connection.Close();
if ( isRetry )
throw;
isRetry = true;
}
}
}
return connection;
}
Using The Retry Functions

For ease of use, I created a MySql specific function that automatically checks the connection and tries a query:

public static MySqlDataReader ExecuteReader(MySqlCommand cmd, System.Data.CommandBehavior behaviour)
{
DatabaseRetryHelper.RetryRoutine<MySqlDataReader> queryRoutine = delegate()
{
DatabaseRetryHelper.CheckConnection(cmd.Connection);
return cmd.ExecuteReader(behaviour);
};
return DatabaseRetryHelper.RetryWrapper<MySqlDataReader>(queryRoutine);
}

and then in your code:

MySqlCommand selectCmd = new MySqlCommand("SELECT * FROM atable", myDbConnection);
using ( MySqlDataReader dataReader = MySqlRetryHelper.ExecuteReader(selectCmd) )
{
if ( dataReader.Read() )
return dataReader.GetString(0); // "First field"
}
Using With Linq

Using the retry helpers with Linq isn’t quite as neat, primarily as you have to run all the Linq expressions again.  (The retry routine was actually already written by the time we started using DbLinq with MySql).


private static string LookupSomeOtherFieldValue(string someWhereValue)
{
DatabaseRetryHelper.RetryRoutine<string> routine = () =>
{
IDbConnection db conn = CheckConnection(myDbConnection);
MyLinqDb db = new MyLinqDb(conn);
string result = (from record in db.MyTable
where record.SomeField == someWhereValue
select record.SomeOtherField).FirstOrDefault();
return userRecresultrd;
};
return DatabaseRetryHelper.RetryWrapper<string>(routine);
}

Other Notes

This is a work around for what I see as missing functionality in the .NET Connector (did you used to be able to set the MySql Options with a raw value in an old version of connector?).  This isn’t necessarily the best solution, especially using Linq, which could do with a Proxy class of some kind (so only the actual query gets retried), but it’s relatively simple and flexible.

Another method that may help solve this is to use pooled connections.  The documentation seems to suggest this is the preferred way to use the connector, but the software that uses this will end up doing lots of queries per second so I’d want to check performance etc, but I may well look in to this in the future.

Ultimately, I hope the Connector will implement automatic reconnection- I might even look in the source code a bit deeper myself…

Wednesday, 2 December 2009

Code Contracts in .NET 4

Overview

One of the new features that’s included in .NET 4 is something called Code Contracts. (In fact Code Contracts are available already, but they're being made a standard part of the Framework in .NET 4.)

I'll say up front that I haven't really used Code Contracts yet, but I like the basic idea so thought it'd be worth writing down a quick summary of what they do.

Code contracts allow you to specify various conditions, or contracts, that must be met by your code and / or any code that calls it.  These contracts can be enforced with a combination of static (reported by the tools) and run time checking (reported by asserts or exceptions).

There are three types of contracts:

  • Preconditions – these specify conditions that function arguments must satisfy when a function is called.
  • Postconditions – these specify conditions about the return value, or the state of the object when a function returns.
  • Object Invariants – these specify conditions that the public state of the object always meets.

The main aim of Code Contracts is to formalise coding assumptions you make, and to help find and locate bugs in your code.  The Code Contracts are written in code so that they are human readable, and so that they can be analysed and enforced by the tool chain.

An Example

Examples always help, so here we go:

Preconditions:
// Calling this function with null, or with an object with TestValue less than zero 
// would fail the contract
public static void MyTestContractFunction(MyTestContractClass testItem)
{
  // Preconditions:
// Ensures testItem is null. 
// Throw NullReferenceException if not satisfied at run-time
Contract.Requires<NullReferenceException>(testItem != null); // Always compiled in
Contract.Requires(testItem.TestValue >= 0); // Compiled in depending on tool options

}
Or an alternative, more familiar way:
public static void MyTestContractFunction(MyTestContractClass testItem)
{
  // You can also write code contracts in the 'old-style' argnull exception way
  if ( testItem == null )
    throw new NullReferenceException("test item must not be null");

  // But you need to specify the end of the contracts
// i.e. if statements up to here classed as contracts
  Contract.EndContractBlock();

  // Do stuff...
}
Postconditions:
public static void MyOtherFunction(MyTestContractClass testItem)
{
  // Do stuff...

  // This line would cause the post-condition to fail
// (if it compiled- there appears to be a bug in the tools?!?)
  //testItem.TestValue = 0;

  // Postconditions:
  Contract.Ensures(testItem.TestValue >= 0); 
} 

Getting Started

To get started you need to download the tools as although the libraries are included in .NET 4, the tools aren’t.

The tool chain uses binary re-writing to enable runtime checking, as well as generating xml documentation to include contracts and performing static checking of code to catch potential violations at compile time (Visual Studio Team System version only).

Check out the following links to get more detail about Code Contracts and how they work:

CLR Inside Out: Code Contracts

Code Contracts FAQ

Getting Started With Code Contracts Video (VS2008)

Thursday, 29 October 2009

Google Maps Navigation

Well, it was bound to happen.  Google have released a new version of Google Maps that’s designed to provide in car navigation. 

Cunningly entitled Google Maps Navigation it basically does what you expect from in-car Sat Nav plus what you expect from Google Maps.  I imagine this is going to cause a dent in the sales of Tom Tom, Co-Pilot etc!

Currently it’s only available in the US on Android 2 handsets, but I’m sure it’ll be available elsewhere before long.  A more interesting question is whether Google will release it for Windows Mobile?  I’ve noticed that Google Sky Map only seems to be available for Android, so it looks like they might use all these applications to add value to the Android platform.  Not a bad strategy.  It means I probably won’t be able to get it for my Touch HD though.  :-(

Friday, 16 October 2009

Application Lifecycle Management Tools

Revision Control with Work Item Tracking

At the company I work for we’ve been thinking of moving revision control systems.  We currently use CVS and are looking at moving to subversion. 

Before we moved over I thought it would be a good time to have a quick look at team based Development / Application Lifecycle Management suites. 

The idea would be that the system would be designed for teams and combine some basic project management, requirements capture, task and bug tracking with revision control software, and a way of encouraging / enforcing certain development practices (e.g. Test Driven Development). 

Because we’re only a small team, it would have to be integrate well or at least be lightweight in terms of day to day use; ideally having a web interface and integrating in to both Eclipse and Visual Studio (the two IDEs we use).  It would also have to be (very) cheap! :-)

The Different Offerings

I started off my search with a bit of Google and Wikipedia.  Unsurprisingly, most of them are aimed at Enterprises rather than small teams like us.  This meant you had to either call for a price, or the price was just too high.

Code Beamer

Code Beamer looked like it would fit the bill.  They do a free version, but the licensing for it is a bit unclear.  In the end I decided as a commercial company doing proprietary software, we wouldn’t be able to use the free version.  You have to contact the sales team for pricing of the commercial version.

JavaForge runs on Code Beamer, which gives you an idea of how it looks and feels. Apparently there’s integration in to Eclipse, but unfortunately not in to Visual Studio.  Also the code analysis tools support Java and C/C++ but not C#, and it’s likely the C# apps that we’ll using any system with to start with.

I wasn’t blown away by JavaForge, not having any pricing details at all put me off somewhat (whatever it is, it’s probably too expensive for us!), and I finally gave in at the download page.  Perhaps worth another look later, but in this quick tour I didn’t have the enthusiasm.

Borland Star Team

The Star Team website didn’t particularly inspire me either.  Again, no hint of pricing so probably too expensive.  Not really any screenshots and stuff either.  But it does support Eclipse and Visual Studio.  You can download a trial, which might be worth a go at some point.

Rational Team Concert

The first one I actually wanted to try out was IBM’s Rational Team Concert.  Part of the Jazz software set.  Why?  Because it has a version that’s free for 10 users or less, has clients for both Eclipse and Visual Studio and had a decent website to back it up.

So I downloaded the Team Concert Express-C version.  The installation instructions looked a little convoluted, but actually it was really easy to set up and I was impressed at how easy it was to get something up and running on my desktop.

The feature set also looked to cover what we wanted, and after a brief play I decided to try and import an existing C# project in to it.  So I installed the Visual Studio client and started looking at the Revision Control it includes.  It took me a little while to work out how it worked, but I got the basic idea and liked the idea of workspace streams and change sets.  So I decided to import the Visual Studio Solution I was currently working on.

This particular solution had three projects in it.  The main project, a test project and a library project that it uses.  I obviously wanted to install the library project in a separate component within the revision control project, so that it could be shared in other projects when required.

This is where I started to bang my head against the metaphorical brick wall.  It appears that when using the Visual Studio client, you have to import a solution as a Revision Control Component and you can’t easily exclude any of the projects it contains.  So I imported the solution, and then looked at a way of splitting out the sub-folder containing the library in to a separate component.  But I couldn’t seem to do this (although the docs suggested you could).

After much frustration, and a few errors about updating, and even at one point accidentally removing all the code from the Revision Control Project I managed to get the separate components by importing separate Solutions.  I then tried to create another solution that contained the projects I wanted to work with, but then got a load more errors.

Given the struggle I had, the various errors and the fact I managed to do some stuff I couldn’t quite understand how I did, I eventually gave up.  What ever system we have, it has to be simple and easy- CVS has caused people here issues at times!

To be fair, I think some of the problem here maybe be the difference between the way the Visual Studio and Eclipse plug-ins work.  But I didn’t really want to have to download and install Eclipse for editing of C# projects.

Team Foundation Server

Team Foundation Server is Microsoft’s offering in this area, but unfortunately we don’t get it as part of the Microsoft Action Pack we subscribe to, and it’s too expensive and probably over the top for a small company like ours.  But after my struggle with Team Concert, I thought I’d download the demo Virtual Machine and give it a go out of interest.

As it was a Virtual Machine it was easy to get running (although they could really do with having a getting started tutorial linked from the desktop of the VM or something), and creating a new Project was easy.

Then to importing the project.  This was easy, I imported the projects and could say which bits went where.

Then on to trying out some of the Work Item tracking.  Again, all relatively easy from within the Visual Studio client, and does the kind of thing I was looking for.

The website end of TFS is basically a Sharepoint site, but doesn’t seem as comprehensive when it comes to the management of various parts as the Team Concert site.

So I liked the kind of thing TFS had to offer but well, it’s too expensive!  I was bemoaning the lack of a version that didn’t include an MSDN subscription that I didn’t want, and also wondering how much you were being charged for Sharepoint, which we already have.  Then the day after I’d finished playing I read that MS are releasing TFS Basic- a cut down version that doesn’t include Sharepoint, and presumably excludes MSDN as well. designed to replace Visual Source Safe and still provide the work item tracking functionality, so I’ll be interested to see that when it comes out.

In Conclusion

I didn’t spend much time looking in to all these solutions, and so probably haven’t done them justice. 

Rational Team Concert has potential, but it had a few too many niggles and I’m not sure that the Revision Control system is straight-forward and logical enough.

I’m interested to see what Team Foundation Server Basic is like (it’s going to be part of VS2010 Beta 2, which I’ll be trying), and ultimately how much it costs.

Finally, I think there might be an opening in the market for a simpler solution aimed at small businesses / teams.  Especially an Open Source one that bases itself on existing packages such as Subversion, Bugzilla etc (which incidentally, you can already do some linking between).  Eclipse are already doing some work in this area-  they’ve started a Framework designed to provide a standard way for different development packages to work with each other, but there still seems to be a lack of clearly defined product suites out there.

If anyone else has any recommendations, I’d be happy to check them out! :-)

Tuesday, 22 September 2009

Coding Dojo

Mark mentions on his blog that he attended a Coding Dojo the other day.  I won’t go in to details here as Mark covers it all in his post, but it’s an interesting idea.

It made me think, maybe we should do some exercises like this at work?

Monday, 7 September 2009

Windows 7 and .NET Framework 4 Beta 1

As mentioned in an earlier post, I recently upgraded from Vista to Windows 7.  Be warned, if like me, you have Visual Studio 2010 and the .NET Framework 4 Beta 1 installed the Windows 7 upgrade breaks .NET 4 quite drastically!  If only I’d seen Scott Hanselman's post first!

Luckily the following steps seemed to have done the job on my PC:

1. Uninstall VS2010 Beta

2. Uninstall .NET 4 by doing the following:

For x86 OS:
cmd /c "msiexec /x {19BD09BF-3BBD-3663-A5ED-50B6B2B07E42} /qb"
cmd /c "msiexec /x {1DF6A8F6-5048-323F-8758-DA533CE0F07E} /qb"
For amd64 OS:
cmd /c "msiexec /x {175D5555-EE49-3033-99AF-BC1E206223FD} /qb"
cmd /c "msiexec /x {13B27C82-19BA-3494-9420-F932B40673CA} /qb"

3. Reboot, just in case!

I found this in a forum post linked from Scott’s page.