Monday, February 06, 2012
 
   
 
Welcome to my site

First let me say thanks for stopping by my site. My name is David Hanson-Graville and I am a IT consultant working in the UK. Let me make it clear, I am passionate about technology and specifically .net and its various forms. I've programmed in a range of langages, but I can say, I am now at my happiest when coding with c#. I hope my blog is an enjoyable & educational read and please feel free to email me at David.Hanson@OnTheBlog.net if you have any questions. 

LINQ to Reflection Part 2: Reading Fields Minimize
Location: BlogsOnTheBlog    
Posted by: David Hanson Fri, 25 Apr 2008 11:34:23 GMT
In part 1 of my LINQ to Reflection series I outlined some of the key drivers behind me creating a set of extension methods that can be used to query any CLR type. I also outlined that I am looking to extend this further with support for reading/writing of data, mocking, invocation, interception and other useful behaviours.  This post is purely focused on the reading of field data using the LINQ to Reflection extension methods.  
 
Before we get into the details of how we query data, we first need to create some tests data that will be used for each sample. Below is a method that is used to build object graph that is comprised simple and complex types with multiple child objects.  Note: We are already starting to use our LINQ to Reflection methods in order to create tests data.
 
        ///<summary>
        /// Sets up an object graph for our different test scenarios.
        ///</summary>
        public static Person GetTestData()
        {
            Person person = new Person();
            return FillPerson(person,3, 4);
        }
 
        ///<summary>
        /// Fills the person with test data.
        ///</summary>
        ///<param name="person">The person.</param>
        ///<param name="levelsDeep">The levels deep we wish to populate.</param>
        ///<returns>A person instance</returns>
        private static Person FillPerson(Person person,int noOfChildren, int levelsDeep)
        {
            //Update our name.
            person
                .Field<string>("_firstName").Update("Joe")
                .Field<string>("_lastName").Update("Blog " + levelsDeep.ToString());
                    
            //Add a Partner
            Person partner = new Person();
            partner.Partner = person;
            person.Partner = partner;
 
            //We have reached or level.
            if (levelsDeep == 0)
                return person;
            else
            {
                //Lets create the children for this person.
                for (int i = 0; i < noOfChildren; i++)
                {
                    Person child = new Person();
                    //Add children.
                    person.Children.Add(FillPerson(child, 4, levelsDeep - 1));
                }
            }
 
            return person;
        }
 
The result of this method is a person being created with children, grandchildren, great grandchildren and great great grandchildren. Each generation will have a lower number appended to their name. Therefore a 4 equates to the oldest and 0 equates to the youngest. This is shown in the locals window below.
 
 
Now that we have some tests data to work with it’s about time we starting looking at some LINQ to Reflection samples. As mentioned in part 1, LINQ to Reflection provides extension methods for the Object type. This therefore means, if you import the LINQ.Reflection namespace, every single CLR type in scope is queryable. This includes base types such as string, int, decimal, object & any other type. Below is a an example of the intellisense being displayed on a string class once the LINQ.Reflection namespace has been imported.
 
 
Having the extension methods available on all .net types & at any point is one of the features I consider the most compelling. You will also notices that the extension methods use .NET generics, this is vitally important as I felt type safety and intellisense support is invaluable when you are digging many levels deep into an object graph.  I am hoping as we start to delve deeper you start to see the benefits of these decisions.  
 
Sample 1 – Reading Fields from an instance.
 
string firstName = person.Field<string>("_firstName").Value;
DateTime DOB = person.Field<DateTime>("_dateOfBirth").Value;
Console.WriteLine("First Name: {0} - Year Born: {1}", firstName, DOB.Year);
 
This example shows how we can read fields held on an instanced type [Person]. FYI these fields are private. LINQ to Reflection allows you to read fields on any type whether private, protected, internal & public. In order to read a field we use the Field<T> extension method.  We pass the type argument to the Field method in order to strongly type the value we are going to be accessing person.Field<DateTime>. Next we need to pass the name of the field we are trying to access, we do this using the name parameter ("_dateOfBirth").The final part is to call the Value property which will return a strongly typed value from the field. The result of running this code is shown below.
 
First Name: Joe - Year Born: 1978
 
Sample 2 – Reading complex fields from an instance.
 
In the previous example we are accessing fields on our person instance using fairly simple types. However, the Field<T> method allows us to use generics therefore we can pass any type we desire into the type argument. Often fields that sit within an object are complex in nature, they maybe other entities, collections or connections etc. This example shows the Field<T> method being called in order to return a strongly typed collection of persons .Field<List<Person>>.  We then iterate around this collection writing out each person’s name and age.
 
List<Person> children = person.Field<List<Person>>("_children").Value;
 
foreach(Person child in children)
     Console.WriteLine("First Name: {0} - Year Born: {1}", person.Name, person.Age);
 
The output from this code is shown below.
 
First Name: Joe Blog 4 - Age: 29
First Name: Joe Blog 4 - Age: 29
First Name: Joe Blog 4 - Age: 29
 
Sample 3 – Reading a field where the type is inaccessibly.
 
At this point you may be wondering what you do in the situation whereby you do not know the type of the field. In these situations you can down cast the field to its lowest common denominator for example a custom collection could be converted to a List<T> or an entity could be downcast to an object. Below is an example of accessing a field that you do not know the type of.
 
person.Field<Object>("_dateOfBirth").Value;
 
 
Sample 4 – Obtaining a list of available fields.
 
During testing of your own objects you often know what internal fields are being used. Therefore obtaining the name is not an issue. However, some types you wont and therefore you need a way to interrogate the object in order to determine the field name. The Fields extension method provides this functionality.  It returns a collection of Linq.Reflection.Field objects which can be used to read values or alternatively drill down deeper. Below is an example of reading all fields on the string class.
 
foreach (Field<object> field in "hello" Fields())
    Console.WriteLine("Field Name: {0}", field.Name);
 
And the result of running this code is shown below.
 
Field Name: m_arrayLength
Field Name: m_stringLength
Field Name: m_firstChar
Field Name: Empty
Field Name: WhitespaceChars
Field Name: TrimHead
Field Name: TrimTail
Field Name: TrimBoth
Field Name: charPtrAlignConst
Field Name: alignConst
 
Sample 5 – Finding a field with LINQ to Reflection and LINQ to Objects.
 
This example shows how we can use our LINQ to reflection extension methods to obtain a list of Fields and then perform a LINQ query on our collection in order to find a specific field.
 
IEnumerable<Field<Object>> fields = "Hello"
                                        .Fields()
                                        .Where(field => field.Name == "alignConst");
 
foreach (Field<Object> f in fields)
    Console.WriteLine(f.Name);
 
The output from this code is shown below.
 
alignConst
 
 
Sample 6 – Reading fields from deep inside our object graph.
 
Now that you have seen how we can access fields on our top level object we will now look at how we can drill down into our object graph. As the Field<T> extension method returns a representation of a Field and that we can access the value of that field using the Value property, we can continue to dig deeper. Below is an example that well drill down each of the children collections that hangs of a person until we read the bottom.
 
Person greatGreatGrandson = person
                            .Field<List<Person>>("_children").Value[0]
                                .Field<List<Person>>("_children").Value[0]
                                    .Field<List<Person>>("_children").Value[0]
                                        .Field<List<Person>>("_children").Value[0];
 
Console.WriteLine("Great great grandson : {0}", greatGreatGrandson.Name);
 
The chaining of Field<T> methods allows us to step down the tree each step returning a strongly typed person collection. You can see this as we access the indexer on the collection. [0].. If we run this code we get the following result. The “Joe Blog 0” represents the last generation in our tree. Note... if we were to chain another Field method we would hit a null reference exception.
 
Great great grandson : Joe Blog 0
 
 
So that completes Part 2 of this blog series. From this you should be able to grasp the way that field data can be read from any type of object. Further, you can see how the power of chaining allows us to writing code that represents visually what we are trying to attain. You will see this pattern repeated later on when we look at property data, method and constants. In Part 3 however we will look at how we can perform updates on data by extending these samples.
 
  
Permalink |  Trackback

Comments (1)   Add Comment
LINQ to Reflection Part 3: Updating Fields    By TrackBack on Mon, 28 Apr 2008 13:30:07 GMT
In part 2 of this LINQ 2 Reflection series I took you through how we go about querying fields that may existing within an object graph. Before we proceed, it’s important to remember that a call to obj ...
# The Thinker


Your name:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Tweets Minimize
Twitter / LordHanson
  1. LordHanson: #southeastern have once again proved their rolling stock can reach new lows.

    Published Wed, 01 Feb 2012 08:09:05 +0000 by
  2. LordHanson: Checked in at The Cards http://t.co/LANfHukb

    Published Sun, 29 Jan 2012 11:04:51 +0000 by
  3. LordHanson: @BillGates Run for president Bill.

    Published Fri, 27 Jan 2012 08:41:35 +0000 by
  4. LordHanson: @swhelband Again!

    Published Fri, 27 Jan 2012 08:39:44 +0000 by
  5. LordHanson: The update for the Nokia Lumia recently has done wonders for battery life! Good job #Nokia #windowsphone

    Published Fri, 27 Jan 2012 08:36:27 +0000 by
  6. LordHanson: Checked in at Victoria Station http://t.co/L0BJ5smd

    Published Thu, 26 Jan 2012 08:35:41 +0000 by
  7. LordHanson: @pdl_uk VAT No: 924 5933 08 Shoulder again! Dang!

    Published Wed, 25 Jan 2012 21:47:45 +0000 by
  8. LordHanson: @tommyjmquinn I think that would be easier. Next Thursday ok?

    Published Wed, 25 Jan 2012 21:04:46 +0000 by
  9. LordHanson: @tommyjmquinn London bridge doable?

    Published Wed, 25 Jan 2012 20:32:34 +0000 by
  10. LordHanson: @tommyjmquinn so where's the meet?

    Published Wed, 25 Jan 2012 19:04:02 +0000 by
  11. LordHanson: @tommyjmquinn your choice mate. Somewhere easy to get to from Bankside. :-D

    Published Tue, 24 Jan 2012 22:01:20 +0000 by
  12. LordHanson: @tommyjmquinn so Darius, Justin and me confirmed. Thursday good for you? Waiting to hear from Sal.

    Published Tue, 24 Jan 2012 21:47:21 +0000 by
  13. LordHanson: @mark_mann which is illegal I thought!

    Published Tue, 24 Jan 2012 21:46:17 +0000 by
  14. LordHanson: Details on Windows Phone 8 confirms NT kernel http://t.co/5Qg1MILl

    Published Tue, 24 Jan 2012 21:34:11 +0000 by
  15. LordHanson: But next target for framework is #winrt. Need to see if my dependencies like DI, RX, ReactiveUi etc will work. Hmm

    Published Mon, 23 Jan 2012 08:33:16 +0000 by
  16. LordHanson: @pdl_uk hey Phil, how's marathon training going?

    Published Mon, 23 Jan 2012 08:31:37 +0000 by
  17. LordHanson: So I now have a framework for apps which targets .net, Silverlight and windows phone. Thankyou project linker!

    Published Mon, 23 Jan 2012 08:28:08 +0000 by
  18. LordHanson: For some reason dropped twitter for a month. Can't say I missed it really. Maybe I need to broaden my follow list!

    Published Mon, 23 Jan 2012 08:24:44 +0000 by
  19. LordHanson: Soo much hype over SIRI when it came out yet I never see anyone use it and don't know anybody who does either. #apple #sooverhyped

    Published Mon, 23 Jan 2012 08:23:18 +0000 by
  20. LordHanson: #southeastern customer satisfaction survey given to me today. This should be fun! Bit wait......no extremely poor option! Just very poor.

    Published Mon, 23 Jan 2012 08:20:09 +0000 by
Print  
Archive Minimize
Print  
Contact me Minimize
Print  
Microsoft Certs Minimize







Print  
Silverlight News Minimize
Silverlight - Google News
  1. Windows Phone 8 - Silverlight Apps Are Legacy - iProgrammer

    Published Fri, 03 Feb 2012 13:03:27 GMT by
  2. Super Bowl Streaming Fail - StreamingMedia.com

    Published Mon, 06 Feb 2012 05:59:33 GMT by
  3. Delphi Developers Rejoice at Silverlight, FireMonkey and VCL Coming Together ... - San Francisco Chronicle (press release)

    Published Tue, 31 Jan 2012 17:34:58 GMT by
  4. WP7 Upgrades and WP8 - Silverlight or C++ - iProgrammer

    Published Tue, 31 Jan 2012 17:21:58 GMT by
  5. Watch The 2012 Super Bowl Online - SportsGrid

    Published Sun, 05 Feb 2012 23:15:21 GMT by
  6. US viewers can watch Super Bowl on Mac, iOS - Macworld

    Published Sun, 05 Feb 2012 20:22:31 GMT by
  7. Hydra 4 Sharpens Its Teeth, Breathes New Fire - Dr. Dobb's

    Published Sun, 05 Feb 2012 17:25:01 GMT by
  8. Will Silverlight live or die? Microsoft won't say - InfoWorld

    Published Fri, 27 Jan 2012 11:00:46 GMT by
  9. Cablevision Flips Live TV To Laptops With Microsoft Silverlight - Multichannel News

    Published Fri, 27 Jan 2012 17:24:53 GMT by
  10. Do SharePoint & Silverlight Have a Future Together? - CMSWire

    Published Mon, 16 Jan 2012 17:29:27 GMT by
Print