Using wrappers to aid unit testing


As I alluded to about recently when blogging about JustMock, one of the most important attributes of unit tests has to be that they are readable; you can easily reason about them and see what they do. I also talking about Moq’s overly cumbersome and verbose approach to performing Setups on mocks – I rarely … Continue reading Using wrappers to aid unit testing

Advertisements

Performance or readability with Expression Trees in C#


I was fumbling around trying to create some expression trees on Friday and was working through some stuff with a colleague of mine (someone who actually knows how to do it better than me!) and I got to thinking about the characteristics of different ways of doing the same things in C# with respect to … Continue reading Performance or readability with Expression Trees in C#

Another example of using C# 4 dynamic typing


Here’s a good example of where using Dynamic is handy. Imagine I want to write an all-purpose Excel reader in .NET. This reader class should be able to take in a filename and return me an object which I can use to get data out of the spreadsheet. In itself, that’s not overly difficult using e.g. OLE DB to read from the spreadsheet, but there’s always some boiler-plate involved in creating a .net object to hold the result of the query (unless you want to use DataTables throughout your application), which means you have to create a class to hold the result, and a translator of some sort to go from a DataTable to that object. Enter the DynamicDataRow object. This handy object sits on top of a standard DataRow but allows dynamic property (column) access at runtime. You can consume it very easily: - Obviously, we know that the shape of the data will change depending on the spreadsheet content – but don’t want the actual ExcelReader code to change with different spreadsheets. The ExcelReader.LoadDocument code itself is very plain – it just does some simple OLE DB connection work to read the data into a bog-standard DataSet, and then returns an ExcelDocument object which takes in the DataTable containing the spreadsheet data and populates the Rows property with a DynamicDataRow object for each row in the Table. Notice that so far I’ve not discussed anything C#4 specific yet – just plain OLE DB and some properties setters etc. In fact, the only bit of C#4 is what we enumerate over i.e. where I have “dynamic row in document.Rows”. In this case, “row” is an object of type DynamicDataRow. This is a simple class which wraps around a normal DataRow but allows direct access to properties instead of the somewhat ugly column indexer notation that you get with a DataRow: - It’s a tiny class. All it does is inherit from DynamicObject and override the TryGetMember method to remove the need for indexer accessors and replace them with property accessors, so instead of row[“MyColumn”] you can now just do row.MyColumn. Again, though, from a client point of view, this is very easy to consume – look at the first code sample and realise that that will work for any spreadsheet whatsoever. Also notice how we treat “row” as dynamic, rather than DynamicDataRow (or object), as we want the property accessors to get intercepted by the TryGetMember method…

Can’t wait for C#4…


Following on from my posts on dynamic typing… this week I wrote a quick app to import some data from a load of XML files to a load of tables in a SQL database. The columns in the tables and the attributes in the xml file have a 1:1 mapping. So I firstly wrote some code which goes through a given table and reads the schema from the database and creates a C# type based on the schema (using sp_columns). Then I placed a ColumnAttribute on each column etc. etc., and then goes through the task of iterating through the XML data and creating objects of that new type, copy the data across (doing the odd data type conversion along the way), and finally use the standard LinqToSql DataContext to insert the data into the DB. But a lot of the code was somewhat ugly – messing about with TypeBuilders and FieldBuilders and the like – I’m sure that I could have done something much more elegant in C#4…. none of it was compile-time safe, it was all using reflection etc.. But it did work great anyway – apparently was used to migrate a good few thousand records of XML data into SQL relatively quickly 🙂

A Dynamic XML Document – Part 2


Continuing on from last post, how do we get the array-style [notation] on a dynamic object? Well, there’s a handy method that you can override on DynamicObject called TryGetIndex which does just that: 1: ///

2: /// Searches for any elements that have any attribute with the value specified. 3: /// 4: /// 5: /// 6: /// 7: /// 8: public override bool TryGetIndex (GetIndexBinder binder, object[] indexes, out object result) 9: { 10: var valueToSearchFor = indexes[0].ToString(); 11: var matchingItems = GetElementsByAttributeValue (valueToSearchFor); 12: if (matchingItems.Any ()) 13: { 14: result = new DynamicXmlDocument (matchingItems); 15: return true; 16: } 17: 18: result = null; 19: return false; 20: } 21: 22: private IEnumerable GetElementsByAttributeValue (string attributeValue) 23: { 24: var matchingItems = elements.Where (e => e.Attributes ().Any (att => att.Value == attributeValue)); 25: return matchingItems; 26: } Here, I’m searching for any elements that have any attributes with a value as per specified, and then setting the result to a new dynamic xml document based on that sequence. That’s really it, to be honest! The only things left are the Value getter, which just returns the value of the first element in the dxd, and the implementations of IEnumerable and IEnumerable : - 1: /// 2: /// Gets the contents of the first element in this document. 3: /// 4: public string Value 5: { 6: get { return elements.First ().Value; } 7: } 8: 9: IEnumerator IEnumerable.GetEnumerator () 10: { 11: foreach (var element in this.elements) 12: yield return new DynamicXmlDocument (element); 13: } 14: 15: IEnumerator IEnumerable.GetEnumerator () 16: { 17: foreach (var element in this.elements) 18: yield return new DynamicXmlDocument (element); 19: } I’m not that used to using the yield keyword – to be honest most collections I use day-to-day are the in-built IEnumerable ones, but I see how it’s being used above (this bit is basically taken from here. Anyway… the point being that with a relatively little amount of effort we have an object which can navigate an XML document very easily and more readably than old-style XML access, and with no real loss of type safety compared to those technologies, either.

Dynamic typing with C#4.0 part 2 – A Dynamic XML Document


Here’s a great example of where dynamic typing makes your code much more readable and logical: parsing an xml document. It turns out that someone has already done this – and I nicked a bit of his code (basically the implementation of IEnumerable) - but it’s funny how similar both of our code was before I found it (link is at end of this post). Here’s an example XML document: Gambardella, Matthew XML Developer's Guide Computer 44.95 2000-10-01 An in-depth look at creating applications with XML. Now, to parse that document, you could currently use either good old XmlDocument (and / or XmlReader), or the more modern XDocument in Linq to Xml. However, both of them and still inherently weakly typed, using strings passed into methods such as “Attribute (“MyAttr”) or Element (“MyElement”). I did see an alpha demo of a strongly-typed version of a Xml Document reader a while ago but haven’t heard anything of that recently. I recall seeing that VB9 also has some good XML support, but I’m exclusively a C# coder so let’s concentrate on that 😉 Anyway. So let’s see if we can make an XML document class in C#4 which will let us read the above XML document like this: 1: // Create our dynamic XML document based off a Linq-to-Xml XElement. 2: var xDocument = XDocument.Load ("Example.xml"); 3: dynamic dynamicXmlDocument = new DynamicXmlDocument (xDocument.Root); 4: 5: // Get the first five books 6: var books = dynamicXmlDocument.book as IEnumerable; 7: foreach (dynamic book in books.Take (5)) 8: { 9: // Print out details on each book 10: System.Console.WriteLine ("Id: {0}, Title: {1}, Price: {2}", 11: book.id, // Attribute access 12: book.title.Value, // Element access 13: book.price.Value); // Element access 14: } 15: 16: // Get a specific book 17: var specificBook = dynamicXmlDocument.book["bk107"]; 18: System.Console.WriteLine ("Id: {0}, Title: {1}", specificBook.id, specificBook.title.Value); 19: 20: System.Console.Read (); This actually wasn’t that difficult to write! Again, inheriting from DynamicObject and overriding a couple of methods, I was able to get this done in about three quarters of an hour. First thing is the class hierarchy, our constructors and single member field: 1: class DynamicXmlDocument : DynamicObject, IEnumerable, IEnumerable 2: { 3: IEnumerable elements; 4: 5: ///

6: /// Creates a new instance of the XML Dynamic Document based on a single XElement. 7: /// 8: /// 9: public DynamicXmlDocument (XElement element) 10: { 11: elements = new List { element }; 12: } 13: 14: /// 15: /// Creates a new instance of the XML Dynamic Document based on a sequence of XElements. 16: /// 17: /// 18: public DynamicXmlDocument (IEnumerable elements) 19: { 20: this.elements = new List (elements); 21: } Nothing too scary there, but notice how we implement IEnumerable and IEnumerable so that we can do the foreach and .Take (5) in the original example. The next bit is the first DynamicObject method we override, which gets called every time you make a property accessor request e.g. myDynamicDocument.book. The method looks for all sub-elements that match the parameter name, and if it finds at least one, returns a new dynamic xml document (dxd) based on them. If not, it looks for any attributes in the first element of the current dxd and returns the value if it finds that. Otherwise it returns null. 1: /// 2: /// Gets either all children the XML Dynamic Documents (i.e. elements), or the current element's attribute. 3: /// 4: /// Specifies the keyword to search on. 5: /// The resultant object. 6: /// True is a match was made. 7: public override bool TryGetMember (System.Dynamic.GetMemberBinder binder, out object result) 8: { 9: var elementNameToSearchFor = binder.Name; 10: var matchingChildElements = elements.Elements (elementNameToSearchFor); 11: if (matchingChildElements.Any()) 12: { 13: result = new DynamicXmlDocument (matchingChildElements); 14: return true; 15: } 16: 17: var attributeNameToSearchFor = binder.Name; 18: var attribute = elements.First ().Attribute (attributeNameToSearchFor); 19: if (attribute != null) 20: { 21: result = attribute.Value; 22: return true; 23: } 24: 25: result = null; 26: return false; 27: } The next question is how to get that array notation e.g. book[“123”] as per the example? That’ll be answered in the next post!