Archive

Archive for the ‘.NET’ Category

Solution: The operation could not be completed. Invalid FORMATETC structure

July 2nd, 2009 No comments

This morning I ran into a ASP.NET bug in Visual Studio. Dragging a custom server control on an aspx file was not possible since I had ‘an invalid FORMATETC structure’ (what the …. is that?!). The message box alerting me something is really really wrong is this one:

The FORMATETC bug

Trying to solve the bug, I  found the following attribute to be the problem: [ToolboxItem(true)]. Just delete the attribute, rebuild the application and the problem/bug disappears!

Good luck! Happy coding!

How to detect installed CLR versions and how they are used…

June 2nd, 2009 1 comment

It has been a while since I posted anything on my blog. Sorry for keeping you on hold ;) ! I think the blog will be filled with some information shortly, since I am still overthinking all the great stuff I saw on Tech-Ed North America a couple of weeks ago (first I had to overcome the jetlag, then the weather in The Netherlands, etc. etc. :) ). Enough nonsense for now!

While attending a session by Scott Hanselman on everything new in .NET 4.0 he showed a wonderful small tip, not only useful for the few of us already working on Visual Studio 2010: when working in the VS.NET Command Prompt, there is a small but useful command called ‘CLRVER’. It shows all .NET versions installed on your computer. Also, as an addition to this command, you can show active runtime processes using the -all switch. Nice piece of code! Enjoy!

Logging duration with System.Diagnostics.StopWatch instead of using DateTime.Now

January 9th, 2009 2 comments

Still using two DateTime.Now calls to determine the duration of a certain call execution, like beneath?

DateTime start = DateTime.Now;
DoSomeCall();
double secondsToLog = (DateTime.Now - start).TotalSeconds;

This is not at all necessary: using the StopWatch class. The StopWatch class is more efficient than any other solution provided or created in .NET since it uses low-level API calls and supports a high-resolution performance counter (when there is hardware and software support).

Stopwatch watch = new Stopwatch();
watch.Start();
DoSomeCall();
watch.Stop();
double secondsToLog = watch.Elapsed.TotalSeconds;

Multicast delegate invocation

October 10th, 2008 No comments

Today I remembered the need to blog again. It sounds weird, but it isn’t :) … A while ago I ran into a failing multicast delegate and decided to blog it. Since I ran into one again today and having to look up my previous solution again the hard way, I discovered I should have done it immediately. Check the story below:

Multicast delegates are great. Today I had to implement a custom user control (insurance cost calculation) with several child controls (one for each prospect) which depend on each other (e.g. parent and children). I use a delegate to notify the parent control that one of it’s children selections has changed.

The original call:

public event EventHandler SelectionChanged;

/// <summary>
/// This method cares for correct event handling
/// </summary>
private void OnSelectionChanged()
{
  // The SelectionChanged event will be null if there are no subscribers.
  if (SelectionChanged != null) SelectionChanged(this, EventArgs.Empty);
}

For some dumb reason I ran into a NRE using the delegate. Guess what happened? Subsequent delegate subscribers did not get fired anymore. The reason is that a delegate that fails for some reason, fails entirely. After researching the problem again, I changed the code provided hereabove with the following piece of code:

public event EventHandler SelectionChanged;

/// <summary>
/// This method cares for correct event handling, including the protection against
/// failing individual event subscribers
/// </summary>
private void OnSelectionChanged()
{
  // The SelectionChanged event will be null if there are no subscribers.
  if (SelectionChanged != null)
  {
    try
    {
      Delegate[] list = SelectionChanged.GetInvocationList();
      foreach (Delegate del in list)
      {
        try
        {
          // Only the current subscriber will file, the rest of the delegate's
          // invocation will proceed as normal.
          EventHandler handler = (EventHandler) del;
          handler(this, EventArgs.Empty);
        }
        catch { }
      }
    }
    catch { }
  }
}

LINQ to XML with XPath

June 30th, 2008 No comments

Since a while I am really convinced LINQ is great. Okay, it has its limitations, but since a couple of weeks those limitations start to get challenges :) .

Since I assume that you know pure LINQ to XML, extension methods, etc. etc. already (contact me if I am wrong – I will be glad if I can be of some help), I will not dive too deap into it. Instead, I show some nice examples on LINQ to SQL with XPath. I locate the examples around an XML file with book information, as shown below.

<?xml version="1.0" encoding="utf-8" ?>
<books>
<book id="1">
<title>Book 01</title>
<author>Bert Loedeman</author>
<price>$ 19.99</price>
</book>
<book id="2">
<title>Book 02</title>
<author>Bert Loedeman</author>
<price>€ 24.99</price>
</book>
<book id="3">
<title>Book 03</title>
<author>Bert Loedeman</author>
<price>€ 10.00</price>
</book>
<book id="4">
<title>Book 04</title>
<author>Some author</author>
<price>$ 19.99</price>
</book>
</books>

What I am going to do, is to show how to reach my goals using pure LINQ to XML and how to reach the same goals using LINQ combined with XPath. First of all, to be able to use XPath in combination with LINQ, it is important to include a reference to the System.Xml.XPath namespace. Including this reference leads to a couple of XPath related extension methods which are available on all XML entities, like XDocument and XElement.

Let’s start with the most simple LINQ query, loading all books from our XML file and writing their titles to the console.

var books =
    from book in doc.Descendants("book")
    select book&lt;/code&gt;&lt;/div&gt;
&lt;code&gt;Console.WriteLine();
foreach(var book in books)
{
    XElement element = book.Element("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

This query can easily be altered to support XPath, as you can see from the next picture.

// Needs namespace System.Xml.XPath.
var books =
from book in doc.XPathSelectElements("//book")
select book;

Console.WriteLine();
foreach (var book in books)
{
    XElement element = book.XPathSelectElement("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

Although this example does not show any extra value for using XPath, it is already nice to be able to use XPath. Let’s move to a slightly more complex situation and only select the book with ID 4.

var bookWithIdFour =
    from book in doc.Descendants("book")
    where (int)book.Attribute("id") == 4
    select book;

Console.WriteLine();
foreach (var book in bookWithIdFour)
{
    XElement element = book.XPathSelectElement("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

As you can see, we introduce a where clause on our query. Totally legitimate, but have a look at the possibilities using XPath:

var bookWithIdFour =
    from book in doc.XPathSelectElements("//book")
    where (bool)book.XPathEvaluate("@id=4")
    select book;

Console.WriteLine();
foreach (var book in bookWithIdFour)
{
    XElement element = book.XPathSelectElement("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

var bookWithIdFour1 =
    from book in doc.XPathSelectElements("//book[@id=4]")
    select book;

Console.WriteLine();
foreach (var book in bookWithIdFour1)
{
    XElement element = book.XPathSelectElement("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

var bookWithIdFour2 =
    from book in doc.XPathSelectElements("//book")
    where (int)book.XPathSelectElement("@id") == 4
    select book;
    // where clause failes: only functions with XElements, not with XAttribute!

Console.WriteLine();
foreach (var book in bookWithIdFour2)
{
    XElement element = book.XPathSelectElement("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

At first, you can use XPath the way you would use pure LINQ to XML. Nothing has to be different. There is one reason though, to use the second method: consider a situation where it is not sure that the user searching for your books enters an ID at all. The original LINQ to XML query has to be written twice to deal with this situation, the second XPath example can be altered with ease removing the [@id=...] part if wanted, making LINQ a little more nice to use ;)

When I assembled this blog posting, I would have expected to have the third XPath example functioning as well. Unfortunately, it does not work: The XPath functions, apart from XPathEvaluate, do not work with anything different from XElement as their return value. Would you still want to use XPath this way, consider the XPathEvaluate function, as shown below:

var bookWithIdFour2 =
    from book in doc.XPathSelectElements("//book")
    where (bool)book.XPathEvaluate("@id=4")
    select book;

Console.WriteLine();
foreach (var book in bookWithIdFour2)
{
    XElement element = book.XPathSelectElement("title");
    Console.WriteLine(element == null ? "Not found" : element.Value);
}

Considering all that I have shown hereabove, I like XPath already, especially for its flexibility and easiness to use. However, there is more use for XPath using LINQ, that makes XPath even more interesting: there is a possibility to use the XPathNavigator class with LINQ to XML too. To show you how it works, I create the same query, selecting the title of the book with ID 4, this time using the XPathNavigator.

var booksNavigator =
    from book in doc.XPathSelectElements("//book")
    where (bool)book.XPathEvaluate("@id=4")
    select book.CreateNavigator();

Console.WriteLine();
foreach (var book in booksNavigator)
{
    XPathNodeIterator iterator = book. SelectChildren("title", "");
    while (iterator.MoveNext())
    {
        Console.WriteLine(iterator.Current == null
                ? "Not found"
                : iterator.Current.Value);
    }
}

Just remember the CreateNavigator() function on the XElement entity and you are able to use all XPath wealth in functions like Select, SelectChildren, ValueAs… (typed values), etc. etc.

Concluding everything, I am sure XPath is a most valuable feature set to pure LINQ to XML. Without it, I would have had a hard time to implement real difficult situations like dynamic queries, which has been addressed using XPath. I hope I could make you enthousiastic as well :) ! Feel free to post any comments you like (on-topic please ;) ).

Technorati tags: