Archive for the ‘Software Development’ Category

Handling events from within a ControlTemplate in WPF

Here’s an interesting one that had me stumped for a few hours.

Following on from my previous post, where I explained how to create a ControlTemplate to style a TextBox in WPF, I’ve got an object, TextEntryBox, which dervies from a TextBox (it provides some custom event handlers when text is entered, but to all intents and purposes, it’s a regular TextBox).

I wanted to style my TextEntryBox, this time including a button within my ControlTemplate (this will eventually toggle an on-screen keyboard pop-up, but that’s another blog post!). I came up with this:
Read the rest of this entry »

Tags: , , , , , , , , , , ,

1 Comment


How to create a ControlTemplate for a WPF TextBox

This is a short post, but has one specific piece of information I want to keep.

Q: If you want to create a ControlTemplate to provide a custom style for a TextBox, how do you specify where the text goes when it’s used in WPF?

A: The answer was hidden in the depths of the MSDN Documentation. You have to include a <ScrollViewer> within your ControlTemplate with an x:Name value of “PART_ContentHost”.

Here’s a noddy example:


Tags: , , , , , , , , , ,

No Comments


Personal Route Logging with MobileMe’s Find My iPhone

Although I’m struggling to achieve a happy co-existence between Google’s Calendars and Contacts and my MobileMe subscription (still fighting dupes and funny syncs with the wrong numbers being associated with the wrong contacts etc… but that’s for another blog post!), one part of MobileMe I was keen to do something with was their “Locate My iPhone” feature. Regular apps aren’t allowed to run in the background on the iPhone, making any form of auto-updating tracking application all a bit “manual”  (e.g. Google Latitude on the iPhone), Apple have provided the ability to get the location of your iPhone automatically, but as it’s officially being touted as a feature to use when you’ve lost your iPhone it’s tucked away within the “Account Settings” section of the MobileMe web page.

This was screaming out to be screen-scraped and Read the rest of this entry »

Tags: , , , , , ,

4 Comments


All quiet on the blogging front…

I know I’ve been pretty quiet as far as technical blog posts are concerned but I’ve not abandoned this blog, I’ve been working over the last few months entirely on Windows network driver development (NDIS 5.1), something which I profess to having absolutely no prior experience with so there really wasn’t anything relevant to blog about.

I’ve been making notes throughout the whole experience and so plan to post them shortly with the aim of helping anyone else who finds themselves in a similar situation and needs to get up to speed with Windows network driver development (NDIS 5.1). I am by no means an expert but want to share what I’ve learnt so far.

Tags: , , , ,

No Comments


C#’s Null-Coalescing (??) Operator

Although I’ve always been a big fan of the ternary operator, kudos goes to the Refactoriser (you know who you are!) for pointing me in the direction of an even more effective way of obfsuca^H^H^H tidying up my code; the ?? operator.

The null-coalescing operator (to call it by its more catchy name) allows you to provide an alternative value in the event that the reference type object (or nullable value type) you are trying to access evaluates to null. So instead of having to do something like this:

            int? myNullableInt = null;
            int myInt;

            if (myNullableInt == null)
            {
                myInt = -1;
            }
            else
            {
                myInt = (int)myNullableInt;
            }

You can do this in-line:

myInt = myNullableInt ?? -1;

Apologies for the heavily contrived and quite pointless example, but at least it gets the syntax down and should make it apparent how useful this operator can be when dealing with a mixture of nullable and non-nullable types.

Tags: , , , , , , ,

No Comments


Making a function call on another thread using the C# Dispatcher class

There may be a situation when you need to execute a function on a different thread, such as ensuring that calls across the interface between a multi-threaded dll and its single-threaded user are made on the same, single thread. To achive this, you can use the target thread’s Dispatcher object as follows:

  1. Create a delegate of the function you wish to be able to call:
    public delegate void MyDelegate(int i, string str);
    public class TargetThreadClass
    {
        public TargetThreadClass()
        {
            MyDelegate del = new MyDelegate(this.FuncToExec);
        }
        public void FuncToExec(int i, string str)
        {
           // Do something
       }
    }
  2. Within the target thread, create an instance of a Dispatcher object and set it to the thread’s current dispatcher:
    Dispatcher UserDispatcher = Dispatcher.CurrentDispatcher;

    Then pass this dispatcher, along with the delegate into the source thread.

  3. Then to call FuncToExec on the target thread, use:
    UserDispatcher.Invoke(del, new object[] { 123, "arg string"});

    Where the first parameter of Invoke is the delegate itself and the second an array of the delegate’s parameters (if any), in this example the delegate takes an int and a string.

Tags: , , , ,

2 Comments


DoshTracker Update #2 – Ext JS and Google Maps API Integration

Shea Frederick on the extjs blog has produced a component which extends Panel and integrates with the Google Maps API here allowing you to display google maps anywhere you can use a Panel, that includes windows, viewports and layouts. This is great for the DoshTracker development as I can use this code to form the basis of the mapping displays, saving me a lot of code hacking and fiddling.

The issues I am having at the moment revolve around Google’s geocoding of UK postcode data. For those who don’t know, geocoding is the process of turning an address into longitude and latitude location information which can then be displayed on a map. It can be a bit hit or miss, especially in the UK where the physical area covered by a single postcode can vary widely but prior to Google providing this feature in its API, the only way of achieving this was to buy a horrendously expensive license from the Royal Mail (who own our postcodes, apparently?!?!?) making this an unfeasible option for DoshTracker.

It appears that the results you get back through the API functions are sometimes different to those you’d get typing in the same postcode into maps.google.com, a fact that they confirm in their original press release when they state that “(the) geocoder is not using the same resources as maps.google.com and may not return the same results”,  but hats off to them anyway for providing the feature in the first place. For privacy reasons, I don’t intend on displaying either the full postcode or a map at a sufficient zoom level to work out the precise location of notes entered into the system, so it may be that the accuracy provided by Google will suffice, but I’m designing the system to allow me to use other geocoding services in future.

In order to do this, I’ve separated the geocoding from the actual map display. A lot of code I’ve seen so far calls the geocoding functions when drawing the map in order to set the map center dynamically. This is unnecessary for me as DoshTracker will be using maps to display previously entered locations and so I plan to only geocode the hit’s location when the new note or hit is added to the system and then to store that information in the database. This not only reduces the number of calls to the Google Maps API (reducing the chances of me exceeding their acceptable policies) but also means that I can substitute the geocoding component in the future with only minimal code changes.

I’m just ironing our a few bugs in the display but I’ll be adding a new tab to the DoshTracker homepage over the weekend to allow you guys to test the geocoder. I’ll be logging the geocoded results to a database for use in the eventual system so please feel free to geocode all of your common locations and let me know what you think. I’m particularly interested in feedback on the map zoom level and the accuracy of the results you get.

Update (13/03/2009): The most up to date version of this component is now being hosted here at Google Code.

Tags: , , ,

No Comments


Creating Excel .xls spreadsheets with PHP

A web-based statistics system I’m developing for a client needs the facility to dynamically generate Excel spreadsheets. The system runs on a Linux platform with a typical Apache, MySQL and PHP install and is hosted on a virtual server at a commercial hosting company so access to anything Microsoft or COM-like wasn’t an option and I only had a basic PHP install available. Most web searches come up with solutions that rely on PEAR (such as the Spreadsheet_Excel_Writer module) but my hosts’ PHP didn’t support PEAR and they wouldn’t let me install it.

Finally I came across Johann Hanne’s port of the Perl Spreadsheet::WriteExcel module on his website and it’s working brilliantly without any additional dependencies! Although his documentation is a little thin on the ground, he does provide some example scripts to get you going and as it’s a direct port, you can still refer to the original Perl documentation. In particular the reference pages on cell number format strings here and here were most useful when tweaking the output.

Creating a simple spreadsheet in PHP is as simple as importing the writeexcel classes and setting up a new workbook and worksheet:

require_once "class.writeexcel_workbook.inc.php";
require_once "class.writeexcel_worksheet.inc.php";

$fname = tempnam("/tmp", "simple.xls");
$workbook = &new writeexcel_workbook($fname);
$worksheet = &$workbook->addworksheet();

…then use the write($row, $column, $token) function to put values into cells:

# Write some text
$worksheet->write(0, 0,  "Hi Excel!");
# Write some numbers
$worksheet->write(1, 0,  3);

…and tidy up and return it, in this example through the browser, but you could always copy the file from the /tmp folder to somewhere more permanent and do what you want with it:

$workbook->close();
header("Content-Type: application/x-msexcel; name=\"example.xls\"");
header("Content-Disposition: inline; filename=\"example.xls\"");
$fh=fopen($fname, "rb");
fpassthru($fh);
unlink($fname);

…and there you go, automatically generated Excel spreadsheets through PHP.

Tags: , , , , ,

No Comments


Non-blocking keyboard input in C#

I know this one is pretty noddy, but these posts are as much a way of me storing code snippets I might need quickly in the future as any form of ‘public service’ so I’ll post it anyway.

I quite frequently want to capture key presses in my apps, and to do this I use Console.ReadKey which returns a nice ConsoleKeyInfo object to tell me what’s just been pressed. The problem is this call blocks until a key has been pressed and sometimes I don’t want to block out the main execution thread or have to create a separate thread *just* to handle the keyboard input.

This is where Console’s KeyAvailable property comes in.  It returns true if there is a key press available in the input stream without blocking allowing you to do something like:

while (true)
{
    if (Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
        {
            case ConsoleKey.F1:
                Console.WriteLine("You pressed F1!");
                break;
            default:
                break;
        }
    }
    // Do something more useful
}

Tags: , , , , , ,

No Comments


Trust issues working on a network share in Visual Studio 2008

An unfortunate combination of my rear-wheeled drive car and the mini-ice age which hit us here in Northamptonshire left me stranded and working from home earlier this week. Not a problem I thought, as I had previously taken the liberty of backing up my current source onto the USB stick I carry with me and already had a VMWare Fusion image with XP and MS Visual Studio 2008 on my MacBook.

So in went the USB key, project folder copied to my “Documents” folder and the XP virtual machine opened. But after browsing to the network drive which VMWare maps onto my OS X “Documents” folder and opening the solution file, I was greeted with something that looks like this:

Visual Studio 2008 - Network Share Project Not Trusted Dialog

A quick google search for this error message brought me to this MSDN article which looked promising, but despite having a full VS 2008 SP1 install on my machine I couldn’t find Mscorcfg.msc anywhere, and the suggested Caspol.exe command just didn’t work!

According to this article, I needed to install the .NET Framework 2.0 Software Development Kit (SDK) (x86) from here to then get the “Microsoft .NET Framework 2.0 Configuration” tool which should help. Once all 300+mb of it was downloaded and installed it then appeared in my Control Panel -> Administrative Tools, progress at last!

In the tool, expand “My Computer” and select “Runtime Security Policy” to get the following:

Microsoft .NET Framework 2.0 Configuration Tool

From here I was then able to select “Adjust Zone Security” to be taken to the “Security Adjustment Wizard”. After selecting whether I want to make changes to the computer or current user only (I chose computer) and clicking “Next”, I was taken to the important part, the zone security level settings. The problem with trusted network shares appears to be caused by the “Local Intranet” zone defaulting to one “notch” below “Full Trust”, causing all sorts of havoc to my VS2008 security. By moving the slider up to “Full Trust” for the “Local Intranet” zone and clicking “Next” and then “Finish” to close the wizard I was then able to successfully load, compile and debug VS2008 projects located on a network share.

I must admit that I’m still not 100% convinced that this is either the correct or even a safe solution so please exercise caution when changing zone security settings, especially on networks with internet access, and feel free to set me straight in the comments if this is far off the mark, but in the meantime it has at least enabled me to perform the tasks I have been able to carry out with every other IDE I’ve ever used and develop code on a network share!

Tags: , ,

No Comments



SetPageWidth