Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!

DDD7 – Date official!

I’ve just received an email to say that the date for DDD7 has officially been released. At the time of writing the DDD website hasn’t been updated, but I can reveal that it will be on Saturday 22nd November 2008.

 

Technorati Tags: ,

Crazy Extension Method

Here is an example of a crazy extension method that alters the semantics of method calling.

First the extension method:

public static class MyExtensions
{
    public static bool IsNullOrEmpty(this string target)
    {
        return string.IsNullOrEmpty(target);
    }
}

Instead of calling the static method IsNullOrEmpty() on string, we are turning it around to allow it to be called on a string type like an instance method. However, as you can probably tell, it may be called when the reference to the string is null. Normally this would result in an exception to say that you are attempting to call a method on a null value. However, this is an extension method and it actually works with nulls! This is probably not the best idea in the world, to be diplomatic about it.

Here is some calling code:

string a = null;
Console.WriteLine(a.IsNullOrEmpty());

Normally, an exception will be thrown if IsNullOrEmpty() is a real method. However, it isn’t in this case and the application happily writes “True” to the console.

 

Event: LINQ to XML – Everything but the kitchen sinq

I’ll be speaking at the Scottish Developers event in Glasgow on the 10th June 2008 at the Continuing Professional Development Centre at Glasgow Caledonian University.

I’ve be giving an introduction to the new XML classes in .NET 3.5, how they work and what can be done with them. After the break I’ll then show how the new XML classes can be used in LINQ (Language INtegrated Query) in order to get data out in the way that you want.

If you want to know more about the event and to sign up please use this link: http://www.scottishdevelopers.com/modules/extcal/event.php?event=61  

Fizz-Buzz in LINQ

This just occurred to me. It is somewhat pointless, but I thought it was interesting:

static void Main(string[] args)
{
    var result = from say in Enumerable.Range(1, 100)
                 select (say % 15 == 0) ? "BuzzFizz" :
                    (say % 5 == 0) ? "Buzz" :
                        (say % 3 == 0) ? "Fizz" : say.ToString();
    foreach (string say in result)
        Console.WriteLine(say);
}
Technorati Tags: ,,

Getting values out of XML in .NET 3.5 (LINQ to XML series part 2)

In my last post I gave a brief introduction to some of the new XML classes available in .NET 3.5. In this post I’ll continue that introduction by explaining how to get information out of the XML.

First off, lets assume we have some XML that looks like this:

XElement root = new XElement("root",
    new XAttribute("Attribute", "TheValue"),
    new XElement("FirstChild"),
    new XElement("SecondChild", new XElement("Grandchild", "The content of the grandchild")));

or, if you prefer in XML format, like this:

<root Attribute=”TheValue”>

<FirstChild />

<SecondChild>

<Grandchild>The content of the grandchild</Grandchild>

</SecondChild>

</root>

There are a number of ways to get the content of the grandchild element. For example:

Console.WriteLine(root.Element("SecondChild").Element("Grandchild").Value);

Value returns a string which contains the content of the element specified. In the above case it will output:

The content of the grandchild

However, you need to watch out for when there are child elements of the thing you want the value of as their content is included when you get the value. For example, if the above XML is extended so that it looks like this:

<root Attribute=”TheValue”>

<FirstChild />

<SecondChild>

<Grandchild>The content of the grandchild

<Great-grandchild>GGC content</Great-grandchild>

<Grandchild>

</SecondChild>

</root>

And the above line of C# is executed again, the result is now:

The content of the grandchildGGC content

As you can see the content of the element you want plus its child elements are now returned. This may not necessarily be what you want.

There is a second way to get the content from an element. That is to use a casting operator. You can cast the element to a number of types. In this case to a string. for example:

Console.WriteLine((string)root.Element("SecondChild").Element("Grandchild"));

The result is the same as calling Value on the element.

Be careful here, because casting an element to a string will not have the same result as calling ToString() on an element. You can see that if you simply pass the element itself to writeline (which will then call ToString() for you). For example:

Console.WriteLine(root.Element("SecondChild").Element("Grandchild"));

The result is:

<Grandchild>The content of the grandchild

<Great-grandchild>GGC content</Great-grandchild>

</Grandchild>

The process is similar if you are dealing with attribute. Using the above XML as an example, an attribute value can be retrieved like this:

Console.WriteLine(root.Attribute("Attribute").Value);

Or, using the cast operator to a string like this:

Console.WriteLine((string)root.Attribute("Attribute"));

Both of the above pieces of code output the same thing: TheValue

If you were to call WriteLine on an XAttribute object you’ll see that the ToString() method returns something slightly different. It returns this: Attribute=”TheValue”

Lets say, for instance, that the Attribute had a value of 123.456, which is a valid number representation. I mentioned earlier about casting operators on XElement and XAttribute. Well, you can cast this to a double if you prefer to get the value in that type. There is no tedious converting in your own code as the framework can handle that for you. For example:

(double)root.Attribute("Attribute")

That’s it for this post. There will be more on XML and LINQ soon.

Introduction to LINQ to XML

Last year I wrote about the new languages features available in C# 3.0 (Anonymous Types, Extension Methods, Automatic Properties, A start on LINQ, Object Initialisers I, Object Initialisers II, & Object Initialisers III) and since then I’ve really got in to LINQ, especially LINQ to XML. The reason for that is that I hate XPath and I see LINQ to XML as a much easier way of querying XML files without faffing about with terse XPath strings. I would much rather have the ability to easily see what is going on with the query than have to figure out why my XPath isn’t working for me.

However, LINQ to XML is more than just new funky querying mechanisms. There is a whole new set of classes to deal with XML that are much easier and more intuitive than the classes that were provided back with .NET 1.0, in my opinion.

The main two classes in the new way of doing XML are XElement and XAttribute. For example, to create a new element:

XElement root = new XElement("root");

And to add an attribute to that element:

root.Add(new XAttribute(“AttributeName”, “TheValue”));

Which produces the result: <root AttributeName=”TheValue” />

If you look at the intellisense for XElement constructor you’ll see that none of the 5 overloads takes a string. The nearest is an XName. This is because there is an implicit conversion happening between a string and an XName so that creating XElements does not have to be so arduous. It would be quite irritating to have to declare XElement objects like this:

XElement root = new XElement(XName.Get("root"));

At this point you’ll find that all the VB developers will be gloating because VB9 contains a feature called XML Literals whereby the developer can just write XML directly into the source code file and VB will parse and compile it correctly. An incredibly handy feature I’m sure you’ll agree. But, since I’m a C# developer that’s what I’ll stick with – especially considering that the majority of demos of LINQ to XML I’ve seen are VB based.

If you look closely at XName’s Get method you’ll see that there are two overrides, one for an expanded name, and the other for a local name and a namespace name. The expanded name is just a string of the name with the namespace embedded in the string inside curly braces, like this:

XName.Get("{mynamespace}root");

If you prefer you can use the other overloaded version and provide two strings. The equivalent XName in that case would be created like this:

XName.Get("root", "mynamespace");

Now, you are probably wondering why a static method is being used rather than a constructor. This is because the XML classes are clever enough to reuse existing XName objects. If you create a second XName object with the same characteristics as an existing XName object it will just reuse the existing XName. For example, the following code will output “True” to the console:

XName name1 = XName.Get("{ns}MyName");
XName name2 = XName.Get("MyName", "ns");
Console.WriteLine(object.ReferenceEquals(name1, name2));

XName is immutable (it cannot change) so this is a perfectly acceptable thing to do.

The extended name notation also works if you are using strings while constructing your XElement. For example:

XElement root = new XElement("{mynamespace}root");

However, there is another way of applying namespaces in an XElement. You can use an XNamespace object and add it to the string. Like this:

XNamespace ns = XNamespace.Get("mynamespace");
XElement root = new XElement(ns + "root");

As you can probably tell the + operator has been overloaded so it can be used to add a namespace to a string to produce an XName.

Technorati Tags: ,,,,,

Data Protection Muppets

I’ve mentioned this topic on my blog before with regard to the Royal Bank of Scotland and Intelligent Finance but this time it was related to an insurance claim. The insurance company put me in contact with a company that would do the repairs and all they had to do was arrange a time and date. However, it wasn’t that simple.

Initially things seemed to be going well until the company in question phoned me to change the date because they wouldn’t have the materials in time. However, first they wanted to go through security screening.

Now, the conversation to this point had gone something like this:

Me: Hello
Them: Hello, is that Colin Mackay [pronounced kae – I HATE that!]
Me: Mackay [pronounced correctly – its a diphthong, a sliding or gliding vowel that goes from ‘ah’ to ‘ee’] Yes.
Them: This is Martindales. We just need to ask you some security questions before we proceed.
Me: How do I know you are who you say you are?
Them: We are Martindales, your insurance company has appointed us…

The conversation went from bad to worse as I tried to explain that what they are doing is socially conditioning people to hand out sensitive information and was then told that they “had to” ask these questions because of the data protection act. The act makes no such requirement. What they have to do is ensure that they are speaking to the correct person so they don’t divulge potentially sensitive information to the wrong person. However, the way they are going about it, while technically in line with the act, is most certainly not within the spirit of the act.

What made it worst was that when I was asked how they could continue the conversation and I gave the solution they had to ask me no fewer than 3 times how they were going to continue the conversation even although I had given them a solution. After that incident they decided they must not have like my simple solution and refused to communicate with me at all for a while.

My solution, incidentally, was this. They would phone me and indicate that they need to speak to me. I would then get the phone number from existing documentation (i.e. a trusted source) and phone their switchboard and ask to be put through to the person that needed to talk to me. They can then go through the security questions as I will then know I am talking to the correct party. When they phone me I have no way of knowing who I am talking to. They could be making it up. If they give me a phone number to use I won’t use it. I will only use trusted sources like documentation from my insurance company, or from the booklet that the insurance assessor left me.

Anyway, Martindales eventually decided that they did need to communicate with me about yet another change in date and sent me a letter. Pity it didn’t arrive until two days after the guy was supposed to show up. In fact he did almost arrive, and I only knew about it because they phoned me just to say that he was running a little late. Muppets!

 

Cool switch snippet

I was watching one of the MSDN Screencasts today and Mike Taulty put in a switch statement that pre-populated itself with valid values for each of the case statements within the switch. I hadn’t seen this before so I investigated further (in other words, I emailed Mike and asked him what he did). It turns out this is a feature that has been in since Visual Studio 2005 and I’d only just noticed.

Essentially, if you are switching on an enumerator the snippet will expand with all the case statements created for you as you can see by the animation below. To access this, follow these steps

  • Type “switch”, the intellisense will show the word “switch” with the torn document icon, indicating it is a snippet.
  • Press the tab key twice to expand the snippet, this will also highlight the text “switch_on”.
  • Change the “switch_on” text to the name of the variable on which you want to switch.
  • Press return twice, this will further expand the switch statement filling in all the cases from the enumerator.

For an example, see the animation below:

switch snippet

Technorati Tags: ,,