Skip to content
    • About
    • About

Steve Cooper's Personal Blog

  • Quick phone topup hack

    October 14th, 2010

    I have discovered a neat little hack for topping up you mobile on pay and go. Most companies use a fixed menu system. If your phone allows you to store phone numbers including hashes and pauses, you can create a contact that navigates the menu system like a robot rat. Here is the phone number you use on 02 to top up by £15;

    44 44 ,#,1,#,1,#,#,9876#,543#,15#

    You’ll need to swap ‘9876’ with the last digits of your debit card, and ‘543’ with the security code on the back. 

    If that’s a useful trick and you use another mobile provider or phone, feel free to post your own patterns in the comments. 

  • Databinding a System.Drawing.Image into a WPF System.Windows.Image

    August 6th, 2010

    I’m learning WPF, very slowly, as a background thing.

    I’m working very slowly through some WPF at the moment, and discovered something I thought was really odd. The classic .Net Image class — System.Drawing.Image — can’t be easily databound into the WPF Image control.

    That seemed crazy to me — it’s like having a `PictureBox` control without an `Image` property. I resolved to fix it in the most ‘WPFy’ way I could.

    What I’d tried was binding a ListView to a list of objects, like so;

    Id bound to an object which declares two properties;

    string DisplayName { get; }
    System.Drawing.Image Image { get; set; }

    I wanted to populate a `DataTemplate` but if I did this in my template;

    The text appears but the image does not. It turns out that WPF can’t find a suitable converter.

    So, thanks to [Reed Copsey](http://reedcopsey.com/) and his very helpful [pointer on Stack Overflow](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/833ca60f-6a11-4836-bb2b-ef779dfe3ff0/), and [this tutorial](http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-converters), I’ve found a way I’m happy with; one that doesn’t involve c# code-behind.

    I’ve created an `IValueConverter` which does the conversion from `System.Drawing.Image` to `System.Windows.Media.ImageSource`. A big thank-you to [Matt Galbraith of Microsoft](http://social.msdn.microsoft.com/profile/matt%20galbraith%20-%20msft) for providing the core code;

    using System;
    using System.Drawing.Imaging;
    using System.Globalization;
    using System.IO;
    using System.Windows.Data;

    namespace System.Windows.Media
    {
    ///

    /// One-way converter from System.Drawing.Image to System.Windows.Media.ImageSource
    ///

    [ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]
    public class ImageConverter : IValueConverter
    {
    public object Convert(object value, Type targetType,
    object parameter, CultureInfo culture)
    {
    // empty images are empty…
    if (value == null) { return null; }

    var image = (System.Drawing.Image)value;
    // Winforms Image we want to get the WPF Image from…
    var bitmap = new System.Windows.Media.Imaging.BitmapImage();
    bitmap.BeginInit();
    MemoryStream memoryStream = new MemoryStream();
    // Save to a memory stream…
    image.Save(memoryStream, image.RawFormat);
    // Rewind the stream…
    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
    bitmap.StreamSource = memoryStream;
    bitmap.EndInit();
    return bitmap;
    }

    public object ConvertBack(object value, Type targetType,
    object parameter, CultureInfo culture)
    {
    return null;
    }
    }
    }

    Then you need to bring the image converter into XAML as a resource. Add the namespace declaration to the window;

    xmlns:med=”clr-namespace:System.Windows.Media”

    Stick an instance of the `ImageConverter` into a static resource;

    Then you can use it in XAML to bind directly to the Image, using the new converter;

    So. A re-usable converter which allows databinding directly to GDI image objects.

    Originally discussed [on stack overflow](http://stackoverflow.com/questions/3427034/using-xaml-to-bind-to-a-system-drawing-image-into-a-system-windows-image-control)

  • Popular Ajax Libraries — jQuery far in the lead in July 2010

    July 19th, 2010

    [http://2tbsp.com/node/100](http://2tbsp.com/node/100) suggests using google trends to judge popularity of ajax libraries; looking at the current data, it looks like jQuery is the clear winner so far in the AJAX library stakes. The current trends can be found [here](http://trends.google.com/websites?q=dojotoolkit.org%2C+jquery.com%2C+prototypejs.org%2C+mootools.net%2C+http%3A%2F%2Fdeveloper.yahoo.com%2Fyui%2F&geo=all&date=all&sort=2)

  • Learning Languages Followup; Test Languages

    July 6th, 2010

    I managed to write a new language, and 135 unit tests in that language, in a single day. When I talked about big wins coming from writing in the correct language, this is what I meant.

    So, the language is a test language for a function library. We have arithmentic, date, string, and other functions that we need to test. Each function is identified internally by a GUID, and may be configured. So the language looks like;

    01 #
    02 # Check Array Sum function
    03 #
    04 declare Sum = {11669A5A-45BA-46c0-A6F6-97CDE4F5CAA5}
    05 Sum(null) = null
    06 Sum([]) = 0
    07 Sum([1.0, 2.0]) = 3.0

    In this short script, I add comments, give a function a name (binding the name `Sum` to the function identified with the id `{11669A5A-45BA-46c0-A6F6-97CDE4F5CAA5}`. Then, I define three tests; `Sum(null) = null` means what you would expect; call the sum function, passing in a single null parameter; the result should be null.

    Having defined this language (which, I think, took me about an hour) I was then able to write about 135 tests with relative ease. The equivalent C# unit tests would be full of repetition and would not express their meaning anywhere near as fully. You’ve have something like;

    [TestMethod]
    public void TestSumNullIsNull()
    {
    var expected = (double)null;
    var thefunction = FieldModifierHost.Instance()[“{11669A5A-45BA-46c0-A6F6-97CDE4F5CAA5}”];
    var maker = thefunction.MakeMethod();
    var instance = maker(new object[]{});
    var result = instance(null);
    Assert.AreEqual(expected, result);
    }

    Which is frankly impenetrable.

    PS: I’ve just had a colleague add a number of tests, without any instruction, and he’s managed to put confidence tests around a function he wants to change in minutes. Unit test languages FTW!

  • How long have you been at work? A Windows Hack.

    June 28th, 2010

    I get into work anywhere between 8:00am and 9:30am. As the end of the day draws on, I’m sometimes not sure whether I’ve served my time. To make sure I don’t go home too early, I use this little trick.

    Windows tracks your logons in the event log. So to find out when you came in;

    1. Open the event viewer; *windows+r, ‘eventvwr’, enter*
    2. Select ‘Custom Views’
    3. Right-click and choose ‘Create custom view…’
    4. Open the ‘XML’ tab
    5. Check ‘Edit query manually’
    6. Enter this XML;

      <QueryList>
      <Query Id="0" Path="Security">
      <Select Path="Security">*[System[(EventID=4672)] and EventData[Data[@Name='SubjectUserName'] = 'your-name-here']]</Select>
      </Query>
      </QueryList>
    7. Replace ‘your-name-here’ with your domain username
    8. Choose ‘OK’.
    9. Set the name to ‘Logins’
    10. Hit ‘OK’.

    And there you go. There in Custom Views will be a list of your login events. Find the earliest one in the day and that’s when you first logged in.

  • On Learning to Write Languages

    June 27th, 2010

    I’ve been learning to write languages recently.

    I read Steve Yegge’s thought-provoking post, in which he talks about how, if you know how to deal with language problems like lexing, parsing, translating, and compiling, then you know how to solve a large number of common programming problems.

    I’ve been using very simple custom languages at work to write integration tests. Just little bits of work, but they’ve really helped quality by allowing us to write loads and loads of tests quickly and confidently. I think we have about 500 integration tests written which rely on small setup languages.

    I think this has become possible because the system we’re writing against is pretty stable. The underlying classes and database tables we’re writing against don’t change too often.

    This seems to be the key time for writing your own languages; the underlying libraries have reaches a point of stability, and you are being asked to do complex things to the underlying data.

    So if you deal with classes or database tables called ‘Document’, ‘Alert’, and ‘Error’, then you can start making statements using those objects; things like

    ‘When the document is saved, if the document is not Signed Off, alert the document owner and log an error’

    Now, it should be possible to write a translator that turns this into c-sharp; something like;

    public void OnSaved(Document document)
    {
    if (document.State != DocumentState.SignedOff)
    {
    SendAlert(document.Owner);
    LogError(document);
    }
    }

    The first version is significantly easier to understand and write. You can show this to your customer and ask if he agrees with the statement. The language helps communication. The c-sharp is no help at all in communicating.

    So, custom languages can help put together systems that are easier to understand, because the language is tuned to the problem, and easier to modify, because the code is invariably shorter than it would be in the general-purpose programming language.

    To my mind, if I can learn to write interpreters, compilers, and translators, it allows me to write software in a way that is significantly more easy to maintain.

    There are, however, two big problems;

    First, learning to write languages is not trivial. It’s a significant investment of time. Your manager is not going to be happy about a proposal that starts “Can I spend the next month learning about languages and not writing production code…” so I think you have to learn about these things in your own time.

    Second, once you know how to write interpreters, they are themselves fairly hefty beasts. If it takes you 300 lines and a day of work to write a lexer and parser, you’d better be certain you save more than 300 lines and a day of work in the course in writing scripts in the new language — otherwise what was the point? So you have to pick your battles, picking only those areas that are ripe for better automation.

    If you meet these two criteria — you’ve learned languages on your own time and you’re picking an area that’ll benefit from it — I think writing your own languages is a very valuable ability.

    So, I’m now reading heavily in the area, writing my own lexers and parser by hand, and starting to look at automated tools like ANTLR and Irony. Irony .Net Language Implementation Kit

  • iOS4 bluetooth keyboard first impressions

    June 25th, 2010

    I installed iOS4 yesterday; here are the first impressions of the bluetooth keyboard support. Being able to use a keyboard with the phone, without jailbreaking, is absolutely great. The phone starts to become a really viable writing platform; for blog posts, mail, and fiction. I’ve got one of the old foldable keyboards originally designed for a Palm, and it folds down to the size of a paperback book. This makes it really easy to write while on the move. Some of the Best Gaming Keyboard have blue tooth support, so they can be used for this too.

    Of course, this makes it even more important to have a decent editor. I’m still going for Simplenote, which uses syncing with the cloud, but I’ve got a terrible urge to write some kind of subversion integration so that I have all my writing in the same source-controlled location.

    As yet there are still some issues; for instance, the bluetooth keyboard means that the on-screen keyboard doesn’t need to be on-screen, but the wordpress app still reserves space for it.

    53.942168 -1.072569
  • ‘This’ in Javascript and C#

    January 16th, 2010

    I noticed something today while learning jQuery, and that’s the way the keyword `this` differs between C# and JavaScript. It suprised me when I saw some javascript that looked like;

    01 $(document).ready(function() {
    02 $(‘div’).each(function() {
    03 this.style.color = ‘blue’;
    04 });
    05 ));

    and I realised that this wouldn’t work in C# — at least, not the same way it works in JavaScript. In the JavaScript above, the `this` on like 03 refers to each `div` element that’s being iterated over.

    Now consider similar C# code;

    class Document
    {
    List divList = …;

    void Ready()
    {
    divs.foreach(delegate () {
    this.style.color = “blue”;
    });
    }
    }

    In C#, `this` doesn’t refer to the div, but to the Document class.

    In both pieces of code, we’re creating a function with a reference to `this`, but they mean different things;

    – In C#, `this` means `the object that declares the function`
    – In JS, `this` means `the object the function is being invoked on.`

    To see the difference, realize that you can attach the same function to two different javascript objects, and you’ll see `this` referring to each one in turn. Here’s a piece of javascript to illustrate;

    var func = function() {
    alert(this.name);
    }

    var obj1 = { ‘name’: ‘first object’, ‘func’: func };
    var obj2 = { ‘name’: ‘second object’, ‘func’: func };

    obj1.func();
    obj2.func();

    When you run this; you get two alerts: `first object` and `second object`. But when you run this in C#

    Action func = delegate() {
    MessageBox.Show(this.GetHashCode());
    };

    var obj1 = new { func = func };
    var obj2 = new { func = func };

    obj1.func();
    obj2.func();

    You see the same hashcode in both message boxes. It’s the hashcode of the object that contains this method.

    So. Don’t confuse the meaning of `this` in C# and JavaScript. They are very different beasts.

    Now, if you want C#’s semantics in Javascript, you have to take account of this behaviour. With my C# head on, I was tempted to understand ‘`this`’ as a _variable name_, but it isn’t. It’s a keyword, and not a variable name. To make it work like C#, you need to create a _real_ variable, and use the variable in the function. Like so;

    var outerThis = this; // declare a real variable
    func = function() { alert(outerThis.name); }

    And this will give you C# semantics in Javascript.

  • Bonfires and Bon Jovi

    November 5th, 2009

    Huge firework display, candy floss, and an eighties medley. Perfect.

  • IPhone app review: RedLaser

    October 12th, 2009

    This is a capsule review of the iPhone app, [RedLaser](http://www.redlaser.com/). It’s a barcode-scanning application which looks up scanned products on amazon and google. In short; start the app, point your phone at the barcode, get online price comparisons.

    The app is extremely simple to use, and cheap, too. It can save you money in a purchase or two. I used it at Borders the other day, scanned a book, and found a copy six quid cheaper somewhere else online. Since the app costs less than two quid, it’s a great little moneysaver. It also acts as a nice ‘outboard memory,’ storing a list which can form a wishlist. Scan in books you want to remember, and it’ll keep the list and let you email it off.

    Because it uses amazon amd google product search, it doesn’t work well with things that are very cheap, or own-brand products. I wondered if I could use it as a shopping list (scan stuff as it runs out) but, well, no-one sells paxo stuffing on the Internet, so no dice.

    What it seems to excel at is products that make good presents; books, DVDs, xbox games, and board games all worked well. I think I will be using it for my own christmas wishlist, and for keeping track of presents for friends and family.

    PS: a little tip. I had a couple of books fail to scan properly, until I noticed that the books had _two_ adjascent barcodes. Cover up the smaller one with your thumb and it’ll work perfectly.

←Previous Page
1 2 3 4 … 18
Next Page→

Create a free website or blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
Loading Comments...
  • Subscribe Subscribed
    Steve Cooper's Personal Blog

    Have a WordPress.com account? Log in now.

  • Steve Cooper's Personal Blog
    View site in Reader
    Manage subscriptionsSign upLog in
    Report this content
    Collapse this bar