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

July 2007 - Posts

  • Reseting Defaults in StructureMap when Injecting Stubs

    This is just a short FYI post because this caused me some headache recently.

    One thing to keep in mind when you are using StrucutreMap and are Injecting Stubs into the ObjectFactory, you will want to reset the ObjectFactory engine after you done with your tests.

    To do this you will need to add this line of code.
    ObjectFactory.ResetDefaults();

    How you implement this and where you put it is up to you.  I simply put this as the last line of code in my tests, but you could put it in [TestFixtureTearDown] or if you wanted you could wrap your entire test in a try-finally block and put it there (I did not do this, did not think it was needed).

    BTW, the error message you will receive if you have stubs lingering around in your ObjectFactory is the following ‘This action is invalid when the mock object is in verified state’.

    Till next time

  • HowTo: Setting Expectations on Stubs using RhinoMocks

    When using a mocking tool like RhinoMocks, one of the features that it can provide is the ability to A) create a stub of an object and B) set expectations on Method/Property calls that are part of that method.  Doing this is pretty easy, but like all things there are some ‘gotcha’s’. 

    Below is a step by step on how to set expectations on a stub

    1. Create your mock Repository
      MockRepository mocker = new MockRepository();
       
    2. Create your stub
      ISomeInterface provider = mocker.Stub< ISomeInterface >();

      Note that I am using the mocker instance NOT MockRepository.GenerateStub.  This is because if you use the static method on the MockRepository object, you WILL NOT have your expectations set in the runtime engine correctly.

       
    3. Set your expectations
      Expect.Call(provider.SomeMethod(string.Empty, string.Empty)).IgnoreArguments().Return(false);

    4. Set everything in the Mock Engine
      mocker.ReplayAll();

    5. Test your stubbed expectation
      bool testValue = provider.SomeMethod();

    6. Check to see if your expectations were met
      mocker.VerifyAll();
       

    There you go, you now have a stub with expectations set.

    *** Note *** Please pay attention to the fact that if you use MockRepository.GenerateStub your expectation will NOT work correctly.

    Till next time,


    kick it on DotNetKicks.com
  • Rant: MCTS 70-536 Book/Practice tests has TOO many errors

    Ok, this is an official rant about the .Net Framework 2.0 70-536 Self-Paced Training Kit.

    I understand that writing a book is difficult, I understand that creating 302 practice test is also difficult.  Buy my god, people are using these materials as study aids to pass a cert.  Editors, proof read the DAMN book will you.  How am I supposed to study when the practice test has errors?

    Here is an example:

    Question:
    Blah, blah, blah about launching a thread in a way to minimize the impact on performance, choose all the answers that apply.

    Answer B is as follows
    ThreadStart myThreadDelegate = new ThreadStart( ThreadWork.DoWork);
    Thread myThread = new Thread( myThreadDelegate );
    myThread.StartLowPriority();

    Explanation:
    The Thread.StartLowPriority method does not exist.

    WHAT, if StartLowPriority does not exist, they why are you telling me that it is the correct answer... WTF

    I guess I would cut them some slack, but today our group came across 2 out of 30 questions that were WRONG.

    How am I going to feel confident if my study materials are WRONG?

    Rant Over, Till next time

  • Using RhinoMocks with StructureMap to mock expected calls

    What do you do when you are writing a test for a piece of code that calls out to an ‘out of your control’ service such as a web service or email server?  If you are like most of us, you simply allow your test to make the call and ‘hope’ that the service is up.  However, this is really bad.  Having your test make calls to a service that is out of your control can lead to ‘spontaneous’ breakages.  It also puts dependencies in your test, another bad thing.


    If you are using RhinoMocks (could also use NMock, but I like RhinoMocks) and StructureMap (could use any IoC/DI container, but I like StructureMap) it is pretty easy and straight forward to ‘Mock’ out those services.


    Quick background on this code. 
    This test was writing to verify that when a web service is down (IMilesServiceContract) that an email (IEmailer) will be sent.  Because I cannot force the service to be down, I have to ‘fake’ it out with Mocks.  And because I don’t care that the email actually gets sent I also will fake this out.

    Below is the code that will allow you to ‘Mock’ out a web service and them email service




    Code Explained

    Generating the stubs
    Because I don’t want to use the actual concrete classes, I am going to create stubs of them via RhinoMocks


    Setting the expectations
    Once I have the stubs created, I want to set the expectations on the methods for each of the stubs that I want to be called.  I don’t care about the actual parameter values used, so that is why I use the IgnoreArguments method.  It is here you set the default return value.


    Injecting the stubs into StructureMap
    In order for StructureMap to use the stubs, you need to ‘inject’ them in so that when the next call to create the object via the ObjectFactory is called the stubs will be returned.


    ReplayAll
    This tells the RhinoMocks engine that all setup work is finished and to set the mocking eninge

    Few Gotcha’s to look out for

    1. You must set any expectations PRIOR to using the object/stub.  Otherwise you will get an exception.
    2. It’s best/easiest to inject interfaces into StructureMap.  I have issues when ever I inject concrete classes.

     
    Till next time, 


    kick it on DotNetKicks.com
  • StructureMap Tip: Using Concrete classes as a PluginFamily

    Have ever wanted to use a concrete class as both the the PluginFamily and Plugable (information on StructureMap's attributes here) type in StructureMap?  I know I have, just today in fact (not the first time, but thought I would post about it this time) I needed to do just this.  Why would I want to use a concrete class as both PluginFamily and Plugable type you may ask.  Well in this case because I wanted to use DI to inject my configuration class into one of my objects (via constructor injection) and did not think it was worth the effort to create an interface.

    Normally if you were use an interface as the PluginFamily and a concrete class as the Plugable, your code would look something like below.

    Interface

    [PluginFamily("FamilyNameGoesHere")]
    public interface IFoo
    {

    Concrete

    [Pluggable("FamilyNameGoeshere")]
    public class Foo : IFoo
    {

    Do have your concrete class act as both you simply combine the two as such

    [PluginFamily("FamilyNameGoesHere"), Pluggable("FamilyNameGoeshere")]
    public class ConcreateWithNoInterface
    {

    Keep in mind, that when you do not use interfaces with DI, you are taking away a lot of the power and flexibility that DI provides you.  But there are cases from time to time where this situation comes into play.

    Till next time,


    kick it on DotNetKicks.com
  • Exellent TDD Post by Jeremy @ Codebetter.com

    Jeremy always has something insightful to say, and this is no exception.  Check out his TDD post about newbies on projects.

    http://codebetter.com/blogs/jeremy.miller/archive/2007/07/22/you-re-a-tdd-newbie-on-a-project-team-with-jeremy-what-do-you-do.aspx

    BTW, If all project leads/managers had this same approach or mind set, more higher quality software would be written.

  • Using Sharepoint's Web Services to QueryDocuments.

    For the latest thing I am doing at work I need to be able to grab some data from Sharepoint.  I have chosen to do this by consuming SPServices.asmx server that is available.  Because I was not able to find a decent post on the net on how to use/consume this service, I thought I would create my own.  For this post I am going to walk though using the QueryDocuments method.  As I use/consume more methods, I will try to post on those as well.

    Before you get started working with the Sharepoint Web Services, I would recommend you download the SDK from here.  I would then suggest you install it and poke around the CHM file.

    Service Location

    FYI, if you download the SDK, this will NOT install any assemblies on your drive (see my rant about this here). 

    You will be able to find the ASMX files on the box with Sharepoint install in the following location.
    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

    You will be able to find the ASMX interface via a browser here
    http://servername/_vti_bin/SPServices.asmx

    All the web services can also be found under each and every sub-site that is created. 
    Example
    http://servername/subsitename/_vti_bin/SPServices.asmx

    Consuming the service

    The purpose of this post is to not teach you how to consume the post, however you will only need to open up VS2005 and do an add Web Reference and you will be all set

    CAML

    The different Sharepoint Web services make have use of CAML (Collaborative Application Markup Language).  CAML is an XML-based language that is used in Microsoft Windows SharePoint Services to define the fields and views used sites and lists. CAML is also used to define tables in the Windows SharePoint Services database during site provisioning.

    Resources on CAML

    1. SDK - Within the SDK, there are is a good section on CAML.   Go to the index tab and search on CAML.
    2. How to use CAML here
    3. CAML query builder tool here

    Writing code to consume the service

    Once you have consumed the service, it is time to start coding against it.

    In order to successfully call the QueryDocuments method you will need to know a few things.

    1. What site/sub-site you are trying to query data from
    2. What library (assuming here document library)
    3. What field you are using in your query.

    Once you know the following, you are pretty much set.  Below is sample code that should help you connect and query data.  (BTW, this is NOT production code, but simple a dumping into one method for sake of this post)



    Here are a few lines explained

    EQUALS_QUERY_2PARAMS - This is the CAML query used to return data from the web service call.  This can be changed to fit your needs, see the CAML specs for more information about how to do this.

    service.Credentails - This needs to be set to DefaultCredentials in order to work.

    service.URL - Because the way that SharePoint stores data, you will need to set the URL at run time.  Sharepoint will only allow you to access the data from the given sub-site that your service is in.

    service.QueryDocuments - This is the call into the web service to get the actual data.

    foreach statement - When the service call returns, it returns a populated dataset object.  In order to get data out you will need to loop through and get each row.  There may be better ways, but this is simple and works.

    There you have it, a simple straight forward way to use the SPServices.asmx service from Sharepoint.

    Till next time,


    kick it on DotNetKicks.com
  • Lets hurry and get to QA so we can get our Requirements...:(

    I was chatting with a buddy last week and he told me that during a recent meeting, one of the consultants he was working made this statement.  'We need to hurry up and get to QA so we can get the requirements for this release'.  If that one sentence does not speak volumes, I don't know what does.

    When you get requirements during the 'QA cycle' (this shop is standard waterfall) does that make the QA cycle the elaboration phase? or the QA phase?

    I still have a smile on my face 2 days after hearing this one. :)

     

  • Doh, there are 4 hours I will never get back

    Today, I was working on one of my first ever (actually, it is my 2nd) WCF services.  This service was meant to be pretty simple, 1 method with 4 param's.  It should not take that long, or will it.

    To get the service started, I began by writing the library that the service would actually consume, the business value if you will.  Writing this took about 3-4 hours, but in the end it was pretty solid.  Along with the library there are 18 tests to prove (hopefully) that I did not miss anything. 

    So now on to the service.  Because I am so new at this, I decided that I would copy the old service and tweak it for the new usage.  This took all of 10 minutes, great, I'm pumped.  It was time to test it. 

    In order to test this, I created a new project (wanted to act as if I was an actual consumer) that referenced the service.  I whipped up a simple test to test my service.  Here we go... It failed (of course, nothing can be that easy).  Why did it fail, oh yea.  Because none of my interfaces (or concrete objects for that matter) had public setters on properties.  In order for serialization to work correctly I had to add these.  I really hate that, but what can you do.  After a few more tries I was cooking with fire.  Or was I?

    My service was working, but it was not returning data... Odd.  So, I re-ran my original unit test to make sure nothing was broken, and nope, all green.  So what could it be.  Again, being then newbie at this I did what most newbie's would do, try one thing, nope, then another, nope.  After about 2 hours of this I contacted my good buddy Joey for some help.  He was very helpful, pointed me in the direction of some nice WCF tools.  But sadly, I still had the issue.

    Fast forward another 2 hours and I finally found the issue.  In my WCF service (btw, the method in the service is a whopping 2 lines of code) I had mistakenly used the same entry param twice in my method call. DOH

    It took me 4 hours to determine that my error was caused by 2 things. 

    1. I used the same param in 2 spots in a method
    2. I did not have a unit test for my service method...(btw, this was the real issue)

    So, what is the moral of the story.  Unit Tests SAVE TIME.

    On a positive note, I did learn a few things along the way, so it was not all a waste.

    Till next time :(

  • Tools I use as a .Net Developer

    Every now and again I come across a posting where someone will list out the tools they use.  I thought I would do so as well.

    Development/Framework tools

    Commercial Tools

    OSS/Free Tools

    Well, here is my list.  I am sure I forgot something.  Let me know what tools you use.

    Till next time,
     


    kick it on DotNetKicks.com
  • Rant: Sharepoint SDK Installation

    Today I needed to install the sharepoint SDK because I need to write some code to access it.  So I installed the OfficeServerSDK.exe setup which contains all the SDK stuff.  After it is installed I had to ‘find’ where on my drive it was placed.  After some hunting, I found it on my E: drive.  Great.

    Inside the new directory is a great big .chm file.  I opened this bad boy up and it looked great.  There is more information inside this chm than I can process in a life time.  However, NOWHERE does it tell you where to find the damn .dll’s with the sdk.

    So I set out searching my box for Microsoft.sharepoint.dll.  It was NOT found.  I started searching the net to only come across this post (found here).  Turns out the .dll’s are NOT installed with the sdk, WTF.  I had to go look on the server where WSS was installed in order to find them.  But the only way to find the file was to do an entire search for Microsoft.Sharepoint.dll on the hard drive.  I finally found it at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

    What SDK does not install the damn assemblies…..

    Ok, My rant is over.

  • Something odd about this code

    Today I was trying to root out a bug when I noticed a little red ReSharper icon in my right hand gutter.  I took a look because I knew the code compiled, but according to ReSharper there was some buggy code.  So I clicked the icon to have a look.

    Let me know if you see what is wrong with this (the code has been changed to protect the innocent) ......

    Here is the 'odd' code 


    Hey, at least there was not a 'default' block :(

    Oh well, it is all good.

    Till next time.

  • C# 3.0 Extension Methods, a Simple HowTo#

    I finally got around to installing Orcas on my laptop this weekend.  You are probably asking yourself, what took so long?  Simple, my laptop did not have the spare 14gigs needed in order to get it up and running.  It took some pretty major house cleaning in order to get enough spare space.  Oh well, on to the post.

    So, what exactly is an Extension Method?  From the C# 3.0 Specs (found here) they are 'static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods.'. 

    To put it simpler terms they are methods that allow a developer to Extend any existing CLR type without the need to subclass that type.

    A few notes from the C# Specs

    • Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible
    • Extension members of other kinds, such as properties, events, and operators, are being considered but are currently not supported

    Steps to creating an Extension Method

    1. The class that holds the Extension Method MUST be static
    2. The method that is the Extension Method MUST be static

    Ok, on to the code...

    Creating your first Extension Method

    You should notice something different about the above extension method.  The 'this' keyword.  The 'this' is a modifier on the method so the CLR knows the types on which the extension is allowed. 

    The next modifier is the CLR types the extension method can be used by.  The above extension CANNOT be used by any other type then string.  The value of the input param will be the current value of the variable (Be careful for null's).

    For fun, create a double variable and try to use it.  You cannot. 

    Using your Extension Method

    In the above code, I have used my extension method on the string variable I created.  You will notice that I did not have to do anything special in order to access the Extension Method.  NOTE: If the extension method is NOT in the same namespace, you will have to import/reference that namespace in order to use it.

    As you can see from this example, using Extension Methods is pretty straight forward and easy.  But be careful not to over use these.  Just because you CAN create/use Extension Methods does not mean you MUST use them.  Like anything else, if you don't have a solid reason for using something, DON'T.

    Quick links

    • C# 3.0 Specs here
    • For real-world examples on when/how to use Extension methods check out Scott Gu's blog here.

    kick it on DotNetKicks.com
  • Mocking a Web Service Proxy

    Today I finally had to create a mock of a web service proxy, what fun.  Of course the first go at it failed because I did not think about the fact that the web service proxy is NOT serializable.  This sucked, so what was I to do.

    Well, fortunately for me web service proxy classes are partial’s, so I am able to ‘tweek’ the class.

    Basically what I did was created a new partial class on my web service proxy as well as an interface for the partial class.  I then went in to my consuming code for the web service and modified it to use the interface, not the concrete class.  After these simple changes, I can now mock my web service when needed and use the actual at run time.

    Creating the interface for my web service


    Implementing the interface on my new partial class


    Creating the test


    BTW, if there is a better, easier way to do this, please let me know

    kick it on DotNetKicks.com
  • Regionerate, a Code Layout tool for C#

    Anyone who has coded with me knows that I am pretty anal about code layout and #regions in my class files (Lou, Ken I am sure you will attest to that).  I like to have my code organized so that I can quickly find stuff later and I think #regions are the greatest thing since sliced bread to archive this.

    Today I received an email from Omer, the author of the Code Layout tool Regionerate, for C#.  He asked me to take a look at Regionerate and I was happy to do so.  I went out to his site (found here) to take a look.  One of the first things I noticed was that he has created a screen cast to easily show what Regionerate does (found here).  After watching the screen cast and poking around the site I decided to give it a download (found here) and try it myself.

    Once I had the Regionerate installed, I started to play around with it.  I quickly noticed that Omer has done a great job making this very easy to use.  You can access the product via the right click menu or the tools menu.

    Out of the box the Regionerate comes with a standard code layout template that is pretty good.  However, it is not my coding style.  So I decided to create my own layout (which can easily be done via the Tool menu), and what do you know, he has a quick tutorial on how to get started creating your own layout (found here).  I followed the tutorial and within minutes had my own layout up and running.  Since the layout file is an .XML file, creating the layouts is VERY simple.  One great thing that Omer has done is added GREAT intellisense for VS for creating your layout file.  This makes creating your layout files SUPER easy.

    For a product that is still in pre-Release Candidate mode, it is a very polished and professional tool.  I look forward to adding this product to my toolbelt.  Great job Omer.

    You can find Regionerate here.

    kick it on DotNetKicks.com
More Posts Next page »

Our Sponsors

Red-Gate!