Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool

May 2008 - Posts

  • What the &@$#* is a 'Best Practice' anyway?

    As a profession we like to throw the term 'Best Practice' around quit a bit.  But what the hell does this term really mean?  Because I know that it does not mean any of the following;

    • This way is the only way it will work
    • This is the way that 'every one else' does it
    • This has been proven to work the best
    • .......

    No, the term 'Best Practice' does not mean any of the above.  About the only thing the term means is 'I have found that doing XYZ in ABC way works the best for me'.  But just because it works for you, or even works for a group of people that does not mean it is 'Best Practice'. 

    Lets take a look at a few examples so I can illustrate my point.

    Agile is Best Practice

    Even though I believe that following Agile techniques (TDD, CI, Iterations, Planning, etc, etc) makes me a more productive developer and allows me to produce better code, I will not go as far as saying that 'Agile is Best Practice' in terms of developing software.   What I will say is that for me, in my situations I have found that writing software in an Agile manner has worked out well for me.

    So, you may be asking, what is the difference between saying it is 'Best Practice' and it working out the best for me.  Simple.  I remember being on pure 'Waterfall' based project were we did not have a single test, delivered the product in 'big bang' fashion and we were successful.  The product was released to over 1000 stores over the course of 2 years, with a new release about every 6 months.

    Following Patterns is Best Practice

    We all know that if your application does not follow a patterns it is doomed to fail, right?  The problem is that this statement is a lie.  Simply following a pattern, or using the latest technique does not guarantee success.  In fact, putting in a pattern or technique in which you are not familiar with can cause massive pain and heartache.

    I have been on projects in the past that implemented very little in terms of patterns, or even layering and they were successful, sure they may not have been as extendable or maintainable as they could have been, but we still released the project and it was used

    Remember the term 'Best Practice' is a lie meant to make you feel better about yourself and your code..  There is no 'best practice'  there is only what has worked well for some, but just because it worked well for some, does not mean it will work well for you.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • How to Foo-up your RSS feed with a single /

    So today I got an IM from Chris Sutton telling me that my RSS feed for DimeCasts.Net was not working.  So being the paranoid guy I am, I immediately started to run in circles like Chicken Little yelling "The Sky is falling, the Sky is falling".  It was not till I became horse and ran out of breath did I realize I needed to fix the thing.

    The first thing I did of course was to test the thing, and sure enough Chris was NOT lying (you never know about those guys from Iowa), but what was the cause.  I knew it had worked the day before, what happened.  Oh yea, I actually setup the RSS generation to be a automated process, not manual.

    Because I am so new to RSS, and have never created a feed document before I did not want to take the time to learn some third party API (like rss.net) so I hand rolled my own logic to build the XML Document (don't worry, apart from the data access, it is all of 20-25 lines of code).  Turns out that I put an extra '/' in the URL in the link node under the channel (below in RED).
    <channel>
       <title>DimeCasts.Net -- Inform and Educate in ~ 10 minutes or less</title>
       <link>http://www.DimeCasts.Net/</link>

    For some reason (again, not an RSS guru) when this happens the URL's for each item gets fooed up.  After a few simple keystrokes the problem was fixed, and as it turns out the sky was not falling.

    So what is the moral of this story?  No matter how 'simple' the change, shit can go wrong in a hurry.

    Till next time

    (P.S., check out DimeCasts.Net)

  • DimeCasts.Net day one in the rear view mirror

    WOW, what a fun 24 hours.  Yesterday was arguably the most fun 'deployment' day of my career.  And not simply because it was a project I created, but because it was a project that I am passionate about.

    Releasing DimeCasts.net yesterday was such a high, but what made it even better was all the positive feedback I have received from this.  I thought I would share some day one stats from the site.

    Stats

    Total # of Downloads? 747 (times the download link was clicked)
    Total Unique IP's w/ Downloads? 235

    Total # Page Views

    7700+

    Total # Visits

    5100+

    Total # of KB transferred

    7.2 gig (S3 here I come)

    Browser Breakdown

    Firefox (54%) IE (37%)
       

    What is next

    Well, I am going to continue to add episodes, but that was a given.  But most importantly I am going to continue to add features.  I already have updated the site a few times to add some subtle features, but I also have a backlog of 10+ things I would like to add.

    Some of them include:

    • Streaming video's
    • Ipod/Zune support
    • Recommend a topic feature

    Hope everyone likes the site, please let me know your thoughts.

    Till next time,

  • [ANN] Dimecasts.net is Alive and Kicking

    A few weeks ago while putting together a screencast series on how to use NUnit (and a basic intro to testing) I got the bright idea to launch a new site.  I wanted to create a site that allows myself (and others in the future) to create, host and share short (about 10 minutes -- hence the name dimecasts.net) screencast's (I call them episodes) on how to do various different things.

    I started bouncing this idea of other developers which I trust, and the feedback was awesome so I moved forward with the idea.

    So, who is my target audience with these episodes....everyone.  My thoughts are to create episodes that tackle everyday coding issues as well as show how to use various tools (NUnit, Mocking tools, IoC, etc).  I want the episodes to range from 100 level (Intro to XYZ) all the way to 400 level (mastering XYZ) and I want them to be short and to the point. 

    I am launching DimeCasts.Net with 4 episodes, but have 10 more in post production ready to roll.  I plan on rolling 1-2 a week (depending on my and others schedules) till we run out of ideas.

    Here are the 4 initial episodes

    Overview on how to use NUnit

    This screencast is an introduction to NUnit as well as a brief overview of testing with NUnit.  In this episode you will learn the following:

    1. Use the NUnit IDE
    2. Create simple tests with NUnit
    3. Debug a test via the VS IDE

    Overview on NUnit's Attributes

    In this episode we will learn how to use some of the different attributes that are built into the NUnit testing framework.
    The attributes we will review are:

    • Test
    • TestFixtureSetup
    • TestFixtureTeardown
    • Setup
    • Teardown
    • Ignore
    • Explicit
    • ExpectedException

    Creating tests with NUnit

    In this episode we will cover the basics on how to create various unit test using the NUnit testing framework.  We will also review the different Assert helper classes that are part of the testing framework.

    Unit testing events with NUnit

    In this episode we will cover how to test events that are raised from an object.  We will cover multiple different ways to do this.

    Please let me know what you think.  What you like, what you do not, or what you would like to see.

    Till next time,

  • Keeping your tests up to date

    While putting together one of my last posts one thought kept scrolling through my head.  This was the idea that when you modify your code, you need to make sure your that the intent of your tests still are correct.  I know this concept may seem trivial, but how many of us actually do this.

    I think most testing practitioners will agree that simply because a test passes green it does not mean that the test is valid and that the code under test is validly tested.  It would not be to hard to imagine a scenario where your tests still pass after you have made changes to the code/class under test, but because your tests still run green you think you are in the clear.

    Now I know you what you are thinking.  You are thinking that if I am changing my code I should be doing so via tests, and you are correct.  But you may be only touching a single test, when multiple tests may be affected.  So we need to just quickly verify all the other tests.

    Developers (myself included) need to really get into the habit of verifying affected tests when they change code, regardless of the results of their tests. To be honest, I feel that writing quality tests is harder then writing quality code (more on this here).

    Just my thoughts.

    Till next time,

  • Using Linq's DataContext to (re)create your database for testing

    If you happen to be using Linq2Sql and are also someone who tests, I have something for you.  You can use Linq's DataContext to create your database and then populate it with test data prior to each test run.  Note that you can do this same thing when using other OR/M tools such as NHIbernate, so this is nothing new or revolutionary.

    Before I get into the 'How To' on doing this, I would like to go over the 'Why' I should do this.

    When building out your test suit on any data driven application you are going to need to test data access at some point.  There are really 3 solutions to this problem.

    1. Simply query for known, existing data
      Although this works, this leads to very weak and brittle tests for obvious reasons.
    2. Create/use/delete the data for each of your tests
      This is a better choice, but leads to very heavy tests and can also lead to bad or orphaned data.  Which can be a major pain point if this is done in your development environment.
    3. Rebuild the db and test data for each test run.
      To me, this is the best choice as you get a clean slate and any orphaned data will be destroyed after each run.  No harm, no foul

    Ok, on to the How to of this post.

    The first thing you need to do is setup your tests to have your test fixture have FixtureSetup/FixtureTearDown methods to perform building/destroying of the database.

    private TestsInit _testsInit;
    
    [TestFixtureSetUp]
    public void FixtureSetup()
    {
        _testsInit = ObjectFactory.GetInstance< TestsInit >();
        _testsInit.InitDatabase();
    }
    
    [TestFixtureTearDown]
    public void FixtureTeardown()
    {
        _testsInit.DestroyDatabase();
    }

    Once you have your Setup/TearDown implemented you need to create the logic to build the database and insert test data.

    public void InitDatabase()
    {
        var dbContext = new DBContextDataContext( ConfigurationReader.ConnectionString_ForTests );
     
        CreateDatabase( dbContext );
        CreateTypeData( dbContext );
        CreateTestEpisode( dbContext );
    }
    
    public void DestroyDatabase()
    {
        var dbContext = new DBContextDataContext( ConfigurationReader.ConnectionString_ForTests );
    
        DeleteDatabase( dbContext );
    }
    
    private void CreateDatabase( DataContext dbContext )
    {
        DeleteDatabase( dbContext );
    
        dbContext.CreateDatabase();            
    }
    
    public void CreateTypeData( DBContextDataContext dbContext )
    {
        dbContext.ExecuteCommand( "INSERT INTO [LevelType]( Name ) VALUES ( 'Type 1' )" );
        .....
        dbContext.ExecuteCommand( "INSERT INTO [TagTypes]( Name ) VALUES ( 'Type 4' )" );
    }
    
    private void CreateTestEpisode( DBContextDataContext dbContext )
    {
        Episode episode = new Episode {LevelTypeID = 1, Name = "Test 1", Description = "Desc 1", EpisodeNumber = 1, EpisodeDate = DateTime.Now};
        ....
    
        episode.EpisodeDownloadInformations = new EntitySet< EpisodeDownloadInformation >
                                                  {
                                                      new EpisodeDownloadInformation{ FileName = "Foo.wmv", Size = 9.25m, Time = "10:00" }
                                                  };
    
        dbContext.Episodes.InsertOnSubmit( episode );
        dbContext.SubmitChanges();
    }
    
    
    private void DeleteDatabase( DataContext dbContext )
    {
        if ( dbContext.DatabaseExists() )
        {
            dbContext.DeleteDatabase();
        }
    }

    One thing to be careful of here is that you are using an alternate connection string, not the one for your dev/stage/production environment or you will NOT be a happy developer.  Also notice that I both using the ExecuteCmmand statement as well as the object model to insert the test data.  This is done simply to show the concept.  You could also simple script up all the inserts and put them into an external file.  The way you do it is up to you.

    So there you go, you now know how you can use the DataContext to build/destroy your db structure for each test run.

    Till next time,

  • Thoughts on writing quality test code vs writing quality application code

    Anyone that is a practitioner of testing or specially TDD knows that the quality of your tests are a direct measure in the assumed quality of your tested code.  Better put, if your tests suck, you can assume very low quality from your code.

    So what is harder, writing quality code or writing quality tests?  My vote is that writing quality test code is harder then writing quality application code.

    When it comes to writing 'quality application code' the measure of quality is really in the eye of the developer.  What one person calls good code may be called crap by another developer.  But as long as the code meets the business needs, it should be at least considered quality (if not simply functional) code. 

    However, creating quality test code is a little more measurable.  One possible way to measure this is by code coverage (please do not take that statement as high code coverage equals high quality as this is NOT the case).  Another is to simple make sure the tests exercises as many different business scenarios as practical (notice here I did not say possible because at some point you reach the point of diminishing returns and should just stop).  Finally, if you keep your tests compact and focused you should be able to create quality tests.

    To me the real measure of quality test code is how maintainable is it?  Is it very painful to refactor when the code under test needs to change?  If you can maintain your test code with very little friction or effort, they I would say chances are high you have high quality test code.

    Hints your test code may be poor quality.

    • Test code does not test the intent of the code
    • Test code becomes to brittle to maintain going forward
    • Test code is heavy (those testing multiple things)
    • You dread making changes to your code base for fear of having to modify your test code.

    Hints your test code may be of high (er) quality

    • Causes very little friction during future code changes
    • Test code is light weight, tests only a single concept
    • You do not dread making changes to your code base for fear of having to modify your test code.

    So, what do you think?  Which is harder and why?

    Till next time,

  • Strict Mocking Semantics Is the only way to Mock

    Recently I was giving a Mocking presentation and I made the statement that I prefer strict mocking semantics over loose semantics.  At the end of presentation one of the members of the audience raised point to my liking strict over loose.  We had a great discussion and I thought I would regurgitate it here and give my reasons for liking strict over loose.

    Definition of Strict Replay Semantics:
    Only the methods that were explicitly recorded are accepted as valid. This mean that any call that is not expected would cause an exception and fail the test. All the expected methods must be called if the object is to pass verification.

    Definition of Loose Replay Semantics:
    Any method call during the replay state is accepted and if there is no special handling setup for this method a null or zero is returned. All the expected methods must be called if the object is to pass verification.

    Pros of Strict Replay

    • Developer creating the test must know EXACTLY what the codes does they are testing
    • Will cause the test to fail in the future if anyone changes the underlying code
    • Creates a 'what you see is what you get' scenario in your tests.  Meaning that if you do not setup an expectation you will NOT have success.

    Cons of Strict Replay

    • May appear to make the test brittle
    • Requires the developer to know EXACTLY what the code does (yes this is also a pro).  Sadly a lot of developers are too lazy to completely understand the code they are creating, hence this being a con.
    • May create a lot of 'noise' (I.e. a lot of mock setups) if your code is not loosely coupled (this is a con, but is really a result of a code smell)

    Replay of the conversation
    During my presentation I had made comment that I prefer strict semantics over loose and simply left it at that.  I did not really go into detail, but at the end of the session one of the audience members wanted to dive deeper into the why, so we did.

    He made a very good observation in regards to strict mocking and that was that my test will fail if it was originally setup to expect a call to the 'db mock' 2 times, but later the method was modified to only need 1 call.  I agreed with his observation, but told him I actually see this as a good thing. 

    When we create a test we are testing our code base at that point in time.  We are also testing business rules at that point in time.  When ever I setup my mocks (create expectations) I am doing so with knowledge that a given dependency will ONLY be called N number of times.  If I need to refactor/enhance that method/logic and I change the number of times my dependency will be called, I want my test to fail.  This failing test should prompt me to review my test logic to ensure that I am still testing the intent of the method.

    By this logic, strict mocking semantics is the best way to go.  If I had used loose semantics my original test would still pass when it should fail potentially hiding flaws in my test logic.  Remember green tests does not equal good code coverage.

    Till next time,

    ***** Updated *****
    Removed a misinterpreted statement from Ayende over at Rhino
    ***** Updated *****

  • XLinq'n in the new world - Speed comparison with Xml/XPath

    Originally this series was meant to be titled 'Any thing you can do I can do better', but to be honest after writing the Xml/XPath examples I realized the XLinq is really no better per say than Xml/XPath.  However, what XLinq does bring to the table that Xml/XPath does not:

    • Does not need to use the XPath query syntax
    • Reads like English (mostly) when creating queries
    • Lower barrier to entry for someone new to Xml (my opinion)

    For Part 1 of this series check here
    For Part 2 of this series check here
    For Part 3 of this series check here

    In Part 4 of this little mini-series we will examine the speed differences between XLinq and Xml/XPath.

    Before I get started I will show you a sample of the XML document I am using.  The sample document I am using today is 5.25mb in size.

    <?xml version='1.0'?>
    <root>
      <system>
        <list>
          <subscribers>
            <subscriber Type="Random">
              <id>63425813</id>
              <Email__Address>FakeAddress@comcast.net</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>RAY</First__Name>
              <Last__Name>Bob</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>33232</PIPIN>
              <UID>418444</UID>
              <ProgNum>0</ProgNum>
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
        <list>
          <subscribers>
              <subscriber>
              <id>1271728821</id>
              <Email__Address>FakeAddress@yahoo.com</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>JOHN</First__Name>
              <Last__Name>Foo</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>1254512</PIPIN>
              <UID>1033488</UID>
              <ProgNum />
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
      </system>
    </root>

    Example 1 - Loading a XML document from Resource Stream

    There is no real code to show here, but I do have some speed numbers to chat about.  I ran my test 2 times. The first time I loaded into a XLinq object first then into an XmlDocument object and for the second run, I swapped the order.

    As it turns out the first document to load each time is slower, but you can get a look at the speed difference by looking at the delta between each load time.

    Load Time

    XmlDocument 515.00 327.72 187.27 (Delta)
    XLinq 358.94 546.2135 187.27 (Delta)

    By looking at the above, there is no real speed difference, which I expected. (Time above is in milliseconds)

    Example 2 - Finding a Unique value in the Xml Document

    For this example I decided to try to find a single node inside my larger xml file.  In order to try to get good sample I ran each test 5 times and the times below are the average of all those runs

    Run time (5 run avg)

    XLinq 44.62
    Xml/XPath 125.65

    I have to say that I was kinda surprised by the results.  I figured that the Xml/XPath way would be a little faster, but turns out it is 3 times slower. (Time above is in milliseconds). ** NOTE *** The times above do NOT include the time needed to load the XML document into the correct object model.

    From the information in this mini-series i would conclude that if you need to do any type of XML reading/manipulation/creation I would make the jump over to using XLinq as your preferred way of doing so.

    Till next time,

  • XLinq'n in the new world - Structure Modification comparisons with Xml/XPath

    Originally this series was meant to be titled 'Any thing you can do I can do better', but to be honest after writing the Xml/XPath examples I realized the XLinq is really no better per say than Xml/XPath.  However, what XLinq does bring to the table that Xml/XPath does not:

    • Does not need to use the XPath query syntax
    • Reads like English (mostly) when creating queries
    • Lower barrier to entry for someone new to Xml (my opinion)

    For Part 1 of this series check here
    For Part 2 of this series check here

    In Part 3 of this little mini series we will examine some common data creation scenario's and how XLinq's syntax compares to that of standard Xml/XPath access.  In general will we review how to modify the structure of an existing Xml document.

    Before I get started I will show you a sample of the XML document I am using.

    <?xml version='1.0'?>
    <root>
      <system>
        <list>
          <subscribers>
            <subscriber Type="Random">
              <id>63425813</id>
              <Email__Address>FakeAddress@comcast.net</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>RAY</First__Name>
              <Last__Name>Bob</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>33232</PIPIN>
              <UID>418444</UID>
              <ProgNum>0</ProgNum>
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
        <list>
          <subscribers>
              <subscriber>
              <id>1271728821</id>
              <Email__Address>FakeAddress@yahoo.com</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>JOHN</First__Name>
              <Last__Name>Foo</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>1254512</PIPIN>
              <UID>1033488</UID>
              <ProgNum />
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
      </system>
    </root>

    Example 1 - Adding a New Node w/ Element

    via Xml/XPath

    // notice the @ is missing on the status -- this is how u search a node
    XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
    XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//list" );
    
    foreach ( XmlElement element in xmlNodeList )
    {
        XmlNode newNode = xmlDocument.CreateNode( XmlNodeType.Element, "NewElement", string.Empty );
        XmlAttribute nodeAttribute = xmlDocument.CreateAttribute( "MyAttribute" );
        nodeAttribute.Value = "MyValue";
    
        newNode.Attributes.Append( nodeAttribute );
    
        element.AppendChild( newNode );
    }

    Via XLinq

    XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();
    
    IEnumerable item = from doc in xDocument.Descendants( "list" )
                                 select doc;
    
    foreach ( XElement xElement in item )
    {
        xElement.Add( new XElement( "NewElement",
                                    new XAttribute( "MyAttribute", "MyValue" ),
                                    new XElement( "ChildElement", "ChildValue")) );
    }
    
    //ChildValue

    One of the big differences you will notice when trying to add nodes/elements to an existing Xml doc with XLinq vs. Xml/XPath is the that with XLinq it is more 'fluent' then with Xml/XPath.  To add nodes/elements with Xml/XPath you need to create the nodes/elements via the XMLdocument object.

    Example 2 - Deleting and Node w/ Elements

    via Xml/XPath

    // notice the @ is missing on the status -- this is how u search a node
    XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
    XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//subscribers/subscriber[Status='InActive']" );
    
    foreach ( XmlElement element in xmlNodeList )
    {
        element.RemoveAll();
    }

    Via XLinq

    XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();
    
    IEnumerable< XElement > item = from doc in xDocument.Descendants( "subscriber" )
                                   let status = (string) doc.Element( "Status" )
                                   where status == "InActive"
                                   select doc;
    
    foreach ( XElement xElement in item )
    {
        xElement.Remove();
    }

    Besides the way you navigate to the node/element you would like to remove the syntax to delete/remove the nodes are really no different.  But, again with XLinq you do not need to know XPath in order to navigate to the correct location in the document.

    Well, this pretty much wraps up my little mini-series on XLinq'n in the new world.  I hope that in the past 3 posts you have learned a little about how to use XLinq and how it differs from Xml/XPath.

    Till next time,

  • XLinq'n in the new world - Data manipulation comparisons with Xml/XPath

    Originally this series was meant to be titled 'Any thing you can do I can do better', but to be honest after writing the Xml/XPath examples I realized the XLinq is really no better per say than Xml/XPath.  However, what XLinq does bring to the table that Xml/XPath does not:

    • Does not need to use the XPath query syntax
    • Reads like English (mostly) when creating queries
    • Lower barrier to entry for someone new to Xml (my opinion)

    For Part 1 of this series check here

    In Part 2 of this little mini series we will examine some common data manipulation scenario's and how XLinq's syntax compares to that of standard Xml/XPath access.  In general will we review how do update the content of both elements and attributes in an XML document.

    Before I get started I will show you a sample of the XML document I am using.

    <?xml version='1.0'?>
    <root>
      <system>
        <list>
          <subscribers>
            <subscriber Type="Random">
              <id>63425813</id>
              <Email__Address>FakeAddress@comcast.net</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>RAY</First__Name>
              <Last__Name>Bob</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>33232</PIPIN>
              <UID>418444</UID>
              <ProgNum>0</ProgNum>
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
        <list>
          <subscribers>
              <subscriber>
              <id>1271728821</id>
              <Email__Address>FakeAddress@yahoo.com</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>JOHN</First__Name>
              <Last__Name>Foo</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>1254512</PIPIN>
              <UID>1033488</UID>
              <ProgNum />
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
      </system>
    </root>

    Example 1 - Updating Element Values

    via Xml/XPath

    // notice the @ is missing on the status -- this is how u search a node
    XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
    XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//subscribers/subscriber[Status='InActive']" );
    
    // Attribute value before updates
    // 
    // 
    
    foreach ( XmlElement element in xmlNodeList )
    {
        // this will only set the value.  if the node does NOT exist you will get an exception.
        element.SelectSingleNode( "//Status" ).InnerText = "Active";
    }
    
    // Attribute values afterupdate
    // 

    via XLinq

    XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();
    
    var item = from doc in xDocument.Descendants( "subscriber" )
               let status = ( string )doc.Element( "Status" )
               where status == "InActive"
               select doc;
    
    // Attribute value before updates
    // InActive
    
    foreach ( XElement xElement in item )
    {
        // this will set the value or create it if the element does not exist
        xElement.SetElementValue( "Status", "Active" );
    
        // Another option is to go after the element directly, but this requires a 
        //  null check first
        if ( xElement.Element( "Status" ) != null )
        {
            xElement.Element( "Status" ).SetValue( "Active" );
        }
    
    }
    
    // Attribute values after update
    // Active

    As you can see the differences between using XLinq and Xml/XPath for updating elements is not the big.  However, again you have to know/understand how to use XPath to find your nodes.  There is ONE thing you need to be aware of though.  When trying to update an element via XPath the element MUST exist.  If it does not you will get a runtime exception.  With XLinq there is a way to do this and not have to worry about that.  To me that is pretty nice.

    Example 2 - Updating Attribute Values

    via Xml/XPath

    // notice the @ is missing on the status -- this is how u search a node
    XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
    XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//subscribers/subscriber[Status='InActive']" );
    
    // Attribute value before updates
    // 
    
    foreach ( XmlElement element in xmlNodeList )
    {
        // this will set the value or create it if the attribute does not exist
        element.SetAttribute( "Type", "SomeValue" );
    }
    
    // Attribute values afterupdate
    // 

    via XLinq

    XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();
    
    var item = from doc in xDocument.Descendants( "subscriber" )
               let status = ( string )doc.Element( "Status" )
               where status == "InActive"
               select doc;
    
    // Attribute value before updates
    // 
    
    foreach ( XElement xElement in item )
    {
        // this will set the value or create it if the attribute does not exist
        xElement.SetAttributeValue( "Type", "MyValue" );
    
        // Another option is to go after the attribute directly, but this requires a 
        //  null check first
        if ( xElement.Attribute( "Type" ) != null )
        {
            xElement.Attribute( "Type" ).SetValue( "SomeValue" );
        }
        
    }
    
    // Attribute values afterupdate
    // 

    Above shows you that updating attributes are almost identical and in this case there is no need to know/understand XPath in order to select the single node you are trying to update.

    Well, above I have shown you a few simple examples that compare Xml/Path to XLinq, I hope you find this useful.  The next post will compare how to modify the structure of a document using the both Xml/XPath and XLinq.

    Till next time,

  • XLinq'n in the new world - Data access comparisons with Xml/XPath

    Originally this series was meant to be titled 'Any thing you can do I can do better', but to be honest after writing the Xml/XPath examples I realized the XLinq is really no better per say than Xml/XPath.  However, what XLinq does bring to the table that Xml/XPath does not:

    • Does not need to use the XPath query syntax
    • Reads like English (mostly) when creating queries
    • Lower barrier to entry for someone new to Xml (my opinion)

    In Part 1 of this little mini series we will examine some common data access scenario's and how XLinq's syntax compares to that of standard Xml/XPath access.

    Before I get started I will show you a sample of the XML document I am using.

    <?xml version='1.0'?>
    <root>
      <system>
        <list>
          <subscribers>
            <subscriber Type="Random">
              <id>63425813</id>
              <Email__Address>FakeAddress@comcast.net</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>RAY</First__Name>
              <Last__Name>Bob</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>33232</PIPIN>
              <UID>418444</UID>
              <ProgNum>0</ProgNum>
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
        <list>
          <subscribers>
              <subscriber>
              <id>1271728821</id>
              <Email__Address>FakeAddress@yahoo.com</Email__Address>
              <EmailType>HTML</EmailType>
              <Status>InActive</Status>
              <First__Name>JOHN</First__Name>
              <Last__Name>Foo</Last__Name>
              <PIN__Code>NaN</PIN__Code>
              <PIPIN>1254512</PIPIN>
              <UID>1033488</UID>
              <ProgNum />
              <Title />
              <Username />
              <Password />
            </subscriber>
          </subscribers>
        </list>
      </system>
    </root>

    Example 1 - Simple data access

    via Xml/XPath

    XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
    
    // notice the @ is on the status -- this is how u search a element
    Int32 listCount = xmlDocument.SelectNodes( "//list" ).Count;
    Int32 subscribersCount = xmlDocument.SelectNodes( "//subscriber[@Type='Random']" ).Count;

    via XLinq

    XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();
    
    Int32 listCount = xDocument.Descendants( "list" ).Count();
    Int32 subscribersCount = xDocument.Descendants( "subscriber" ).Attributes( "Type" ).Where( e => e.Value == "Random" ).Count();

    As you can see both examples are pretty light on the code and are pretty straight forward.  This is one case where the new XLinq syntax is really no better/simpler then the Xml/XPath syntax.  The issue with the XPath syntax is that

    Example 2 - Get a list of nodes that match our search criteria

    via Xml/Xpath

    // notice the @ is missing on the status -- this is how u search a node
    XmlDocument xmlDocument = XmlHelper.GetRawSnippetAsXmlDocument();
    XmlNodeList xmlNodeList = xmlDocument.SelectNodes( "//subscribers/subscriber[Status='InActive']" );
    
    foreach ( XmlElement element in xmlNodeList )
    {
        var id = element.SelectSingleNode( "//id" ).InnerText;
        var type = element.Attributes[ "Type" ].Value;
    }

    via XLinq

    XDocument xDocument = XmlHelper.GetRawSnippetAsXDocument();
    
    var item = from doc in xDocument.Descendants( "subscriber" )
               let status = (string)doc.Element( "Status" )
               where status == "InActive"
               select doc;
    
    foreach ( XElement xElement in item )
    {
        var id = xElement.Element( "id" ).Value;
        var type = xElement.Attribute( "Type" ).Value;
    }

    Now here is an example where I think the XLinq syntax is cleaner and easier to understand.  There is no need to know or understand the XPath syntax, which can be a pain to learn.  Also here you see how XLinq looks a lot like standard SQL syntax and should be familiar to most developers.

    Well, above I have shown you a few simple examples that compare Xml/Path to XLinq, I hope you find this useful.  The next post will compare how to update/add data to a document using the both Xml/XPath and XLinq.

    Till next time,

  • Using Moq with StructureMap causing a 220 error

    While writing some code today I thought I would give Moq a shot in place of RhinoMocks.  One thing I was very happy about was that I found it very easy to pickup, which is a plus. 

    However, I did want to mention one small gotcha I ran into.  I was trying to inject a mock into StructureMap via the ObjectFactory.InjectStub() like i have done numerous times in the past.  However this time i received the following SM error.

    StructureMap.StructureMapException: StructureMap Exception Code:  220
    Cannot "Stub" type ......Repositories.ITrackingRepository with an object of type Moq.Mock`1

    The good news is this error is real easy to overcome.  Below you will find the 'breaking code' along with the 'working code'

    Breaking Code

    public void TrackEpisodeDetailsView_ExpectCallToRepository()
    {
        var mockTrackingRepository = new Mock();
    
        mockTrackingRepository.Expect( x => x.LogEpisodeDetailsView( It.IsAny(), It.IsAny() ) ).Returns( new TrackingEpisodeView() );
    
        ObjectFactory.InjectStub( typeof(ITrackingRepository), mockTrackingRepository );
    
        var tracking = new Tracking();
    
        tracking.TrackEpisodeDetailsView( 1, "" );
    
    }

    Working Code

    public void TrackEpisodeDetailsView_ExpectCallToRepository()
    {
        var mockTrackingRepository = new Mock();
    
        mockTrackingRepository.Expect( x => x.LogEpisodeDetailsView( It.IsAny(), It.IsAny() ) ).Returns( new TrackingEpisodeView() );
    
        ObjectFactory.InjectStub( typeof(ITrackingRepository), mockTrackingRepository.Object );
    
        var tracking = new Tracking();
    
        tracking.TrackEpisodeDetailsView( 1, "" );
    
    }

    You will notice the one slight change.  When passing the mock into the InjectStub method you need to use the mock.Object property to actually return the mock instance, not the Moq wrapper.

    Till next time,

  • May 14th Chicago Alt.Net meeting is right around the corner.

    Just a friendly reminder about our next meeting which is scheduled for May 14th.  Dan Sniderman from Magenic will be speaking on TFS and some of the things it can do for your team.  Should be a good session. 

    After his session will will break out into a more 'open spaces' style conversation and chat about what topics are brought up.

    As normal our meeting will be held at the Absolute Solutions office downtown and will start at 6:30pm.

    203 N. LaSalle, M18,
    Chicago, IL 60601

    For more info about this meeting and the plans check out the link below.

    http://tech.groups.yahoo.com/group/ChicagoAltNet/message/46

    Hope every can make it, sadly I cannot as I will be in rout to Michigan for a wedding... oh joy.

    Till next time,

  • ReSharper 4.0 vs CodeRush/Refactor! -- Smack Down results

    In case you did not read one of my past posts where I threatened to break up with R# 4.0 I have moved away from using ReSharper for the time being.  Now just to clear something up, I was still using ReSharper 3.1 with any VS 2005 work.  I just stopped using it for vs 2008, but now I am back

    During my time away from R#, I made the switch to CodeRush/Refactor! and the great guys over at DevExpress were gracious enough to provide me a license so I could do a solid comparison.

    In this corner we have ReSharper 4.0 EAP

    Pros

    • The built in UnitTest running is a beautiful thing.  I feel naked when I do not have this feature.
    • The built in Code Analysis (red, yellow, green) is very mature and does exactly what I want
    • Kick ass code completion/formatting rules.

    Cons

    • Crashes all the damn time
    • Each nightly build was appearing to be worse then the one before it
    • Memory hog
    • The UI is a bit clunky and sometimes non-intuitive (compared to CodeRush)
    • Still does not support .Net 3.5 syntax for the most part (Linq and Lambda's)

    In this corner we have CodeRush/DevExpress!

    Pros

    • The UI is super slick and ultra polished.
    • The way that tool 'learns' from your usage is great

    Cons

    • No built in UnitTest Runner.  I was using TD.Net to get the same result, but that is not as nice as R#'s
    • The Code Analysis is not as mature.  I am told that is priority #1 for the team, so looking for great things in the future.
    • Does not have any built in code completing/formatting.  Have to use the VS IDE rules.

    So, who won the smackdown????? Both of them won.

    Both tools have some great features along with some draw backs.  What I have finally decided to do was use them both, well kinda.  I have removed Refactor! as it and R# do NOT play nice together, but have left on Code Rush.  In order to get CodeRush and R# to work well you do need to make configuration changes, but once you have done that the 2 tools work real nice together.

    For the time being I am going to stick to this dual prong approach because I feel that R# just gets me more (they better understand how I like to code).  However, when the next release of Refactor! comes out and they have full support for .Net 3.5 I will give them another chance.

    Till next time,

More Posts Next page »

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News