Home Contact

X

Coder, not artist.

News

Current archive is at: http://cskardon.wordpress.com/ - I aim to move it all soon! All code on here is free, but as a consequence it's up to you to check it, ha! If you have any questions, feel free to email: cskardon -- @ -- xclave dot co dot uk I'm sure you can decrypt the address there!

Twitter












Archives

Post Categories

Image Galleries

Syndication:

Quick note RE: Euler problem 13

In the post about the solving of the Euler problem 13, I was using an older version of F#, to fix the code, replace the 'N' with an 'I'. So for example, the bigNums collection looks like this:

let bigNums =  [37107287533902102798797998220837590246510135740250I;
46376937677490009712648124896970078050417018260538I;
...
53503534226472524250874054075591789781264330331690I]

And the 'AddNums' method is now:

let rec AddNums n =
    if n < 0 then 0I else AddNums (n-1) + bigNums.[n]

No biggies...

(Apologies for lack of code colouring...)


DefaultAppPool - Ha Ha!

I spent a large proportion of yesterday trying to debug why a website I was trying to publish wasn't working..

Upon copying the folder there, and converting it to an application, we browse to the site and lo, nothing there. Not a sausage... Just a blank page.

Hours on this..

Is it the web.config? - ahh no.

Is it the configuration of the server? - ahh no no.

Let's try again, create a new folder... add in a 'Hello world' html page

Browse to: Success!

ok, Convert to application - Browse to: Failure!

Turns out that IIS (in this case 7) allows you to convert / add an application to the server using the 'Default App Pool' even if that app pool doesn't exist. So - changing the app pool to the correct (and by that I mean one that exists) one, and now it all works...

Surely some kind of warning - "oh by the by - that app pool doesn't exist - are you sure you want to use it?" would have been in order?

grrrr


XElement case insensitive 'Element' extension

Just a small bit of code, I've been playing around with converting some Xml* code to Linq to Xml code, and pretty successfully achieved everything I wanted, one thing missing was the ability to retrieve an XElement ignoring case.

First - I'd like mention that yes I know Xml is case sensitive - and this is a bad thing to do - but I needed to do it due to some wierdness in the input xml...

Anyhews, below is the extension method I wrote to deal with this..

public static class XElementExtensions
{
    /// <summary>Gets the first (in document order) child element with the specified <see cref="XName"/>.</summary>
    /// <param name="element">The element.</param>
    /// <param name="name">The <see cref="XName"/> to match.</param>
    /// <param name="ignoreCase">If set to <c>true</c> case will be ignored whilst searching for the <see cref="XElement"/>.</param>
    /// <returns>A <see cref="XElement"/> that matches the specified <see cref="XName"/>, or null. </returns>
    public static XElement Element( this XElement element, XName name, bool ignoreCase )
    {
        var el = element.Element( name );
        if (el != null)
            return el;
 
        if (!ignoreCase)
            return null;
 
        var elements = element.Elements().Where( e => e.Name.LocalName.ToString().ToLowerInvariant() == name.ToString().ToLowerInvariant() );
        return elements.Count() == 0 ? null : elements.First();
    }
}

 

Cheers!


SQL Errror - Token-based validation failed

Soo… Long time no write…

A quick project was assigned to me and two other guys at work the other week – one of those quick 2-3 day projects, the ones were speed is paramount. Quality can be worked on after release… Sooo.. 3 parts, 3 of us, we split it 3 ways and all was good – one on database duty (using LINQ to SQL), one on UI (Adobe Flash 10) and me, on WCF service…

All was going well, the database was up and running, I was using the libraries to interact it with it without any problems, then we published the service to our dev webserver and attempted to connect to it. Nothing.

Ok, attempt to connect the UI to the service when hosted through VS2008 – no problem…

The dev service could see the database, no problems there, so we connected to the database itself and perused the logs and found this:

Date Source Severity Message
11/12/2009 15:05:44 Logon Unknown Login failed for user ‘USERNAME'. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT: 10.123.132.123]
11/12/2009 15:05:44 Logon Unknown Error: 18456<c/> Severity: 14<c/> State: 11.

 

Where the ‘USERNAME’ was the machine name of the development server.. So it looked like the service was attempting to connect to the database as the machine. But the connection string was using a SQL User, not integrated security…

<add name="OT.Properties.Settings.DbConnectionString" 
     connectionString="Server=dev-server;Database=TheDb;Uid=OT;Pwd=Password;" 
     providerName="System.Data.SqlClient" />

as you can see – it’s just using the default settings from a LINQ to SQL DBML file.. and it turns out that this is the underlying issue. By adding a new connection string:

<add name="TheDb" 
     connectionString="Server=dev-server;Database=TheDb;Uid=OT;Pwd=Password;" 
     providerName="System.Data.SqlClient" />

and then hooking up the database layer to use it the problem was solved.


Icon Editing

Finally nearing the release of the app I’ve been working on for a little while now, and we near the final polishing points – Icons etc and a problem with the VS2008 icon editor… The problem being that VS2008 seems to have settings of 4bit icons only…

To the rescue comes Paint.NET and the Icon/Cursor Plug-in (both FREE).. This allows you to edit icon files properly, save in 32bit up to 256x256 (which is probably gonna be big enough :))

It’s pretty simple to use – to the effect that I managed to create this awesome mouse pointer in less than 10 seconds (I know – surprising eh? looks like it would’ve taken hours!) spiffy pointer


StringFormat annoyances in VS2008

I’ve been using StringFormat in my xaml quite a bit recently, and whilst I’ve liked it, I’ve found that code which is valid tends to cause VS2008 to no longer be able to represent the designer (which some might say is a good thing)…

Basically, the following code:

<TextBlock Text="{Binding MyValue, StringFormat=The value is {0}}"/>

causes VS to basically say ‘no way’ and can no longer render the xaml. Pressing F5 shows the Window just fine… Soo… What can we do about it?

If we modify the ‘StringFormat’ section to read as such:

<TextBlock Text="{Binding MyValue, StringFormat='The value is {0}'}"/>

VS can represent it just fine… The difference? The single quote characters around the value of the StringFormat.

Both versions are valid xaml, just VS can’t represent the former.

Ahh well.


Windows 7 - Media Center Video Error

Right,

Just a quicky this one - I didn't see anything online about this when I was searching for the solution but - basically - I fired up Media Center and went to watch Live TV, and I got the following error message:

Video Error: Files needed to display video are not installed or not working correctly. Please restart Media Center and or restart the computer

Uh oh..
This was working last night...
All I'd done was remove myself from the homegroup on the machine...
Hmmmm

Reinstalling video codecs - no joy.
Reinstalling video drivers - no joy.

Bugger.
Quickly test the TV I wanted to record last night did infact record...

"Cannot find file"

eh???

Browse to the files in explorer - there they are.. though I notice I needed to elevate to Administrator to run it...

Hmmm

Close Media Center... restart - but run as administrator...

Recorded TV - ok
Live TV??? -- ok...

Weird..

WCF and LINQ to SQL (Part 4 – Updates)

If you’ve read parts 1, 2 and indeed 3 you’ll know we’ve covered the CRD of CRUD, today we will cover the ‘U’ – updates! Updates are more complex than the other scenario’s we’ve covered so far, but not unmanageable. Also – in fairness this is a very simple update, more complex updates will require more thought (duh!) but this should be a good starting point. Let’s get to it!

We’ll start on familiar ground – updating the interface, adding an ‘UpdateCar’ method:

 
[OperationContract]
void UpdateCar(Car car);

 

and then we’ll need to implement this in the service:

 
public void UpdateCar(Car car)
{
    _db.Cars.Attach(car, true);
    _db.SubmitChanges();
}

 

Now let’s test it to see how it works (remembering to update our service reference in the client!)

 

CarsServiceClient client = new CarsServiceClient();
Car car = client.GetCar(5);
car.Make = "Fiat";
client.UpdateCar(car);

 

Fire up the console… ouch! InvalidOperationException!

 

InvalidOp_Update1

Let’s try one of the other overloads of the ‘Attach’ method…

 

public void UpdateCar(Car car)
{
    _db.Cars.Attach(car, GetCar(car.ID));
    _db.SubmitChanges();
}

 

Run… fail.. bum. Different exception though, we got a ‘DuplicateKeyException’:

 

DupKey_Update

Gah! It appears we can’t attach the object back to the DataContext, so… what about attempting to copy the members?

 

public void UpdateCar(Car car)
{
    Car original = GetCar(car.ID);
    original.Make = car.Make;
    original.Model = car.Model;
    _db.SubmitChanges();
}

 

Yup, that works, but doesn’t copy the Owner / Previous Owners, to achieve those goals we’d need to do them property by property as well; for example, to do the owner:

 
public void UpdateCar(Car car)
{
    Car original = GetCar(car.ID);
    original.Make = car.Make;
    original.Model = car.Model;
 
    original.Owner.Surname = car.Owner.Surname;
    original.Owner.Title = car.Owner.Title;
 
    _db.SubmitChanges();
}

 

Messy. Now, this is due to our disconnected manner of working (which we can’t do anything about whilst using WCF), so it’s a coding hit and a pain, as if we add a new property to the car, we need to update our ‘update’ method to deal with it. I guess you could consider going down a reflection route and copying all the properties across. Though – that would still be a pain – checking for ‘EntitySet’ types etc. But that seems complicated.

To be honest, this is the most annoying aspect. I can’t see any way to connect an object that has been created on a client. Maybe someone else knows, hmph, well…  That about rounds up the WCF / LINQ CRUD series.. (well, to a point)…

Cheers

Me


WCF and LINQ to SQL (Part 3 (Deletes))

If you’ve read parts 1 and 2 you’ll know we’ve covered the CR of CRUD, today we will cover the ‘D’ – deletions. We’ll need to update our interface to actually provide this functionality:

[ServiceContract]
public interface ICarsService
{
    [OperationContract]
    Car GetCar(int id);
 
    [OperationContract]
    void SubmitCar(Car car);
 
    [OperationContract]
    void DeleteCar(int id);
}

I’ve decided to delete the car via the identifier we created initially, though there is nothing to stop us using a ‘Car’ instance.

Anyhews, so, let’s code this up:

public void DeleteCar(int id)
{
    var car = GetCar(id);
    if(car == null)
        throw new ArgumentException("Car unknown!");
 
    _db.Cars.DeleteOnSubmit(car);
    _db.SubmitChanges();
}

Right, to perform a deletion we need the car instance, so we can just get that from our current library code. So… let’s test this bad boy… Remember to ‘Update’ our service reference…

UpdateServiceReference

So, we’ll use the following code:

CarsServiceClient client = new CarsServiceClient();
var car6 = client.GetCar(6);
client.DeleteCar(car6.ID);

(of course this does rely on you having a car with an id of ‘6’ in your db)

Once you’ve got this working (i.e. you have a valid car id) you’ll hit this problem:

SqlException_FK Foreign key constraints!! How do we get around this?

Well, we need to delete the owner first (and whilst we’re at it, the ‘PreviousOwners'), so let’s update the code:

public void DeleteCar(int id)
{
    var car = GetCar(id);
    if(car == null)
        throw new ArgumentException("Car unknown!");
 
    _db.Owners.DeleteOnSubmit(car.Owner);
    foreach (var owner in car.PreviousOwners)
        _db.PreviousOwners.DeleteOnSubmit(owner);
 
    _db.Cars.DeleteOnSubmit(car);
    _db.SubmitChanges();
}

Now when we run the code, we succeed!

There is another way to do the deletion, and that’s to write a stored proc that does the deletion in the correct order, and then, in the CarsDataContext edit the ‘DeleteCar’ method to call the stored proc instead. But I’ll leave that to you :)

So… All that’s left is the Update part of CRUD… and hopefully I’ll get that done soon!

Cheers!


Happy Ada Lovelace Day 2009 – Michele Leroux Bustamante!

I few months ago I took a pledge to:

"I will publish a blog post on Tuesday 24th March about a woman in technology whom I admire but only if 1,000 other people will do the same."

to celebrate Ada Lovelace day.

That time has come!

mlbsepia Michele Leroux Bustamante – author of a book I deem as one of the best books I’ve bought to get me into SOA and learning WCF… Without it I wouldn’t have got half as far as I have! Now – aside from the selfish reason of the fact that she has helped me with the book – I admire her because of the clarity of the writing, and the ease with which she can (and does) explain a complicated topic like WCF.

I know it’s not a streaming blog post essay of epic proportions (mainly because quite frankly, I’m a crap writer!), but it is about a woman in technology that I do admire!

So – Cheers to you Ada, and to you Michele!