Archives

Archives / 2008 / April
  • Upcoming Functional Programming/F# Talks

    Well, I certainly have an ambitious May schedule ahead of me.  Most of course will be revolving around functional programming and F# as it seems to be finally catching on.  I've been noticing a bunch from the Java and Ruby communities becoming interested in such things as Scala, Haskell, OCaml, Erlang and F#.  I was rather heartened by this as some in the Ruby world like here and here coming back to the static world for ways of representing data and functions in different ways.  Of course Lisp and Scheme (IronLisp and IronScheme) still manages to eek in the rebirth, but still remains on the outside.

    I will be speaking at the Northern Virginia Code Camp on May 17th for a total of two topics:

    • Improve your C# with Functional Programming and F# concepts
      Learn how .NET 3.5 takes ideas from Functional Programming and how you can apply lessons learned from it and F# respectively.

    • Introduction to Functional Programming and F#
      Come learn about functional programming, an older paradigm that Object Oriented Programming, and the ideas around it.  This talk will cover the basics including high-order functions, functions as values, immutability, currying, pattern matching and more.  Learn how to mesh ideas from functional programming with imperative programming in F# and .NET.

    So, if you're in the DC area, go ahead and register here and show your support for the community.

    Also, I will be taking some time to spend up in Philadelphia this month at the next Philly ALT.NET meeting to also talk about F#.  Still ironing out the details on that one in regards to the DC ALT.NET meeting in May.  Either way, should be a good time!

    kick it on DotNetKicks.com

    Read more...

  • Making Spec# a Priority

    During ALT.NET Open Spaces, Seattle, I spent a bit of time with Rustan Leino and Mike Barnett from the Spec# team at Microsoft Research.  This was to help introduce Design by Contract (DbC) and Spec# to the ALT.NET audience who may not have seen it before through me or Greg Young.  I covered it in detail on my old blog here.

    Spec# at ALT.NET Open Spaces, Seattle

    As I said before I took a bit of time during Saturday to spend some time with the Spec# guys.  I spent much of the morning with them in the IronRuby session explaining dynamic languages versus static ones.  They had the session at 11:30, the second session of the day, in direct competition with the Functional Programming talk I had planned with Dustin Campbell.  Greg was nice enough to record much of the session on a handheld camera and you can find that here.  It's not the best quality, but you can understand most of it, so I'm pretty happy. 

    The things that were covered in this session were:

    • Spec# overview
    • Non-null Types
    • Preconditions
    • Postconditions
    • Invariants
    • Compile-Time checking versus Runtime checking
    • Visual Studio Integration
    All in all, I thought it was one of the best sessions and I'm glad they came out.  Hopefully we'll see more from them in the future.

    Scott Hanselman also recorded a session with the Spec# guys for Episode 128.  This is a much better interview than on DotNetRocks Episode 237 that Rustan did last year. This actually gets into the technical guts of the matter in a much better way, so go ahead and give it a listen.  I was fortunate enough to be in the room at the time to listen.

    The New Release

    Mike and Rustan recently released a new version of Spec# back on April 11th so now Visual Studio 2008 is supported.  You must remember though, this is still using the Spec# compiler that's only C# 2.0 compliant.  So, anything using lambdas, extension methods, LINQ or anything like that is not supported.  As always, you can find the installs here

    As with before, both the Spec# mode (stripped down mode) and C# mode are supported.  What's really interesting is the inferred contracts.  From an algorithm that Mike and Rustan worked on, they have the ability to scan a method to determine its preconditions and postconditions.  It's not perfect, but to have that kind of Intellisense is really powerful.



    What you can see is that the GetEnumerator method ensures that the result is new.  Keep in mind, result is a keyword which states what the return value is for a method.  It also says that the owner of IEnumerator will be the same as before.  Object ownership is one of the more difficult things to comprehend with Spec# but equally powerful.

    Another concept that's pretty interesting is the ability to make all reference types non-null by default in C# or in Spec# modes.  Instead of having to mark your non-null types with an exclamation mark (!), instead you can mark your nullable types with a question mark (?) much as you would with the System.Nullable<T> generic class.  All it takes is the flip of a switch in Spec#:



    Or in the C# mode:



    And then you have all the Spec# goodness.

    Why It's Important

    So, why have I been harping on this?  To be able to express DbC as part of my method signature is extremely important to me.  To be able to express my preconditions (what I require), postconditions (what I ensure), my invariants (what state will change) is a pretty powerful concept.  Not to mention, to enforce immutability and method purity is also a pretty strong concept, especially in the times of multi-core processing.  More on that subject later.

    Focus on Behaviors

    What Spec# can bring to the table is the ability to knock out a bit of your unit tests.  Now, I don't mean all of them, but what about the ones that check for null values?  Are they valid if you already put in your method signature to require a non-null value or use the ! symbol to denote a non-null type?  Those edge cases aren't really valid anymore.  The ability to track your invariants is the same as well as your postconditions.  Instead, what that does is frees you up to consider the behaviors of your code, what you should have been testing anyways.

    Immutability

    Immutability plays a big part in Spec# as well.  To some extent, I'll cover more in a Domain Driven Design post, but instead will get some things out of the way here.  Eric Lippert, C# team member, has stated that immutable data structures are the way of the future in C# going forward.  Spec# can make that move a bit more painless?  How you might ask?  Well, the ImmutableAttribute lays out that explicitly.  Let's do a simple ReadOnlyDictionary in Spec#, taking full advantage of Spec#'s attributes, preconditions and postconditions:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Microsoft.Contracts;

    namespace Microsoft.Samples
    {
        [Immutable]
        public class ReadOnlyDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey!, TValue>> where TKey : class
        {
            private readonly IDictionary<TKey!, TValue>! dictionary;
       
            public ReadOnlyDictionary(IDictionary<TKey!, TValue>! dictionary)
            {
                this.dictionary = dictionary;
            }
           
            public TValue this[TKey! key]
            {
                get
                    requires ContainsKey(key);
                { return dictionary[key]; }
            }
           
            [Pure]
            public bool ContainsKey(TKey! key)
            {
                return dictionary.ContainsKey(key);
            }

            void ICollection<KeyValuePair<TKey!,TValue>>.Add(KeyValuePair<TKey!, TValue> item)
            {
                throw new NotImplementedException();
            }

            void ICollection<KeyValuePair<TKey!,TValue>>.Clear()
            {
                throw new NotImplementedException();
            }

            [Pure]
            public bool Contains(KeyValuePair<TKey!, TValue> item)
            {
                return dictionary.Contains(item);
            }

            [Pure]
            public void CopyTo(KeyValuePair<TKey!, TValue>[]! array, int arrayIndex)
                requires arrayIndex >=0 && arrayIndex < Count;
            {
                dictionary.CopyTo(array, arrayIndex);
            }

            [Pure]
            public int Count
            {
                get
                    ensures result >= 0;
                    { return dictionary.Count; }
            }

            [Pure]
            public bool IsReadOnly
            {
                get
                    ensures result == true;
                    { return true; }
            }

            [Pure]
            bool ICollection<KeyValuePair<TKey!,TValue>>.Remove(KeyValuePair<TKey!, TValue> item)
            {
                throw new NotImplementedException();
            }

            [Pure]
            public IEnumerator<KeyValuePair<TKey!, TValue>>! GetEnumerator()
            {
                return dictionary.GetEnumerator();
            }

            [Pure]
            IEnumerator! System.Collections.IEnumerable.GetEnumerator()
            {
                return dictionary.GetEnumerator();
            }
        }
    }

    As you can see, I marked the class itself as immutable.  But as well, I removed anything that might change the state of our dictionary, as well as mark things with non-null values.  That's a little extra on top, but still very readable.  I'll be covering more in the near future as it applies to Domain Driven Design.

    Call to Action

    So, the call to action is clear, make Spec# a priority to get it in C# going forward.  Greg Young has started the campaign, so we need to get it moving!

    kick it on DotNetKicks.com

    Read more...

  • let Matt = CodeBetter + 1

    Joining the CodeBetter Community....

    #light

    type FullName = string * string

    let FullNameToString (name : FullName) =
      let first, last = name in
      first + " " + last
     
    let blogger = FullNameToString("Matthew", "Podwysocki")

    I'm pretty excited to be joining the CodeBetter gang after following for so many years.  I want to thank Jeremy Miller, Brendan Tompkins, Dave Laribee, Greg Young and others for welcoming me to the fold.  No, this blog won't be going away, but instead will also serve as a host for my posts.

    So Who Are You and Why Are You Here?

    So, just to introduce myself, I work for Microsoft in the Washington DC area.  I'm active in the developer community in whether it be in the .NET space, Ruby, or less mainstream languages (F#, Haskell, OCaml, Lisp, etc).  I also run the DC ALT.NET group since the November timeframe of last year and helped plan the latest incarnation in Seattle. 

    The number one reason I'm here is to help better myself.  Deep down, I'm a language geek with any of the aforementioned languages.  I'm one of those who strives to learn a language every year, but not just learn it, let it sink in.  That's really the key.  Sure, I can learn a certain dialect, but it's not quite being a native speaker.  That's how I can take those practices back to my other languages to try to apply lessons learned such as functional programming paradigms (pattern matching, currying, first order functions, etc).

    I also have a pretty deep interest in TDD/BDD, Domain Driven Design and of course one of Greg Young's topics, messaging.  Right now in the world of messaging, I think we're in a pretty important time in the development world when messaging, multi-threaded processing and such is going to be more mainstream and hopefully less hard than it is now.

    I'm also a tinkerer at heart.  I'm looking at testing frameworks to help make my TDD experiences easier.  I'm looking at IoC containers to help make my system just a bit more configurable.  I'll look at the tests to see how each one does what it is.  That's the fun part about it.

    I'm also on the fringe with such topics as Spec# and Design by Contract.  I'd love nothing more than to see many of the things being done at Microsoft Research become a bit more mainstream and not just seen as a place where we might see something 10 years down the line.  Topics such as Spec#, F# and others have real importance now and it's best to play with them, give them our feedback and such.

    So What Do You Want From Me?

    Here's the thing, since I'm always looking to better myself, I'll need your help along the way.  I value your feedback along the way and hopefully we'll learn from each other.  Now that this is out of the way, time for more serious topics...

    kick it on DotNetKicks.com

    Read more...

  • xUnit.net Goes 1.0 and Unit Testing F#

    As I've said before on my previous blogs, I'm very much into F# and functional programming lately.  With that, I'm still in the mode of TDD.  Just because you enter a new programming paradigm, doesn't mean you throw away your XP and TDD roots.  Instead, I find it just as valuable if not even more so when switching to a new model.

    xUnit.net 1.0 Goes Live

    As Brad Wilson said earlier this week, xUnit.net released version 1.0.  You can read more about the announcement here.  Since the RC3 timeframe, it was pretty much feature complete, so there hasn't been much change since that time.  Instead, the focus was on polishing the existing functionality and including the integration with ASP.NET MVC, Resharper 3.1 and TestDriven.NET.  The GUI runner, such as it is has been pretty limited, but ok for most purposes. 

    Many questions used to arise, why xUnit.net?  Why do we need yet another framework out there?  Why not just add onto the existing ones in the market?  I think with the 1.0 release, the critics in this release to do things a bit differently than MbUnit and NUnit have approached things.  For example, the Assert.Throws<TException>, not having to decorate the classes with [TestFixture] and a few other things come to mind as well as being very extensible.  It's a smaller framework, but I really don't have a problem with that.  With most of the other frameworks, I don't use half of it anyways.

    So, why do I care as much as I do about this one over say others at the moment?  Well, it's great that we have such choices in the market now.  As Scott Hanselman said at ALT.NET Open Spaces, Seattle, he's a StructureMap, Moq and xUnit.net guy.   I'll get into the reason shortly enough.

    The Traditional Way

    When you think of doing your unit or behavior tests, you often need a class and decorate with attributes, have a initialize and teardown and all that goodness.  Since F# is considered a multi-purpose language, this works just fine.  That's the beauty of F# and hopefully will drive its adoption into the marketplace.  So, consider the following functions with the appropriate tests in a more traditional way such as NUnit within Gallio.  I am trying out Gallio so that I can see how well it reacts to F# as well as just kicking the tires.  I highly recommend you at least check it out.

    Anyhow, back to the code.  Let's take a simple example of a naive routing table through pattern matching, to see whether a call is allowed or not.  Like I said, naive, but proves a point with pattern matching.

    #light

    #R @"D:\Program Files\Gallio\bin\NUnit\nunit.core.dll"
    #R @"D:\Program Files\Gallio\bin\NUnit\nunit.framework.dll"

    let FilterCall protocol port =
      match(protocol, port) with
      | "tcp", _ when port = 21 || port = 23 || port = 25 -> true
      | "http", _ when port = 80 || port = 8080 -> true
      | "https", 443 -> true
      | _ -> false
     
    open NUnit.Framework

    [<TestFixture>]
    type PatternMatchingFixture = class
      [<Test>]
      member x.FilterCall_HttpWithPort8888_ShouldReturnFalse() =
        Assert.IsFalse(FilterCall "http" 8888)
       
      [<Test>]
      member x.FilterCall_TcpWithPort23_ShouldReturnTruee() =
        Assert.IsTrue(FilterCall "tcp" 23) 
    end

    Unfortunately of course for me, the Gallio Icarus Runner doesn't really work well for me at the moment with F# integration.  Instead, I get all sorts of issues when doing so.  This is where I get the large FAIL.



    This seems to repeat itself unfortunately for the xUnit.net and MbUnit integration as well, so it's not quite ready for primetime in the F# space.  Also, when I exit the application, there is a Gallio session runner that keeps running in memory and therefore I can't perform any builds.  So, I have to manually go into Task Manager and kill the process.  Not the best experience I've ever had...  So, for now, the limited functionality in the xUnit.net GUI Runner works for me.

    The More Functional Way

    Instead, we see a lot of pomp and circumstance that we just don't need.  In the functional world, a lot of the time, we don't want or need to create these classes just to test our functions.  After all, most of what we do has no side effects or at least should be (and are code smells mostly if they are not, but that's another post for another time).

    At the request of Harry Pierson, another F# aficionado and IronPython PM, talked to Brad and Jim Newkirk about adding static function unit test capabilities to xUnit.net.  And sure enough, we now have them, so let's compress the above code into something that looks more like F#.

    #light

    #R @"D:\Tools\xunit-1.0\xunit.dll"

    open Xunit

    let FilterCall protocol port =
      match(protocol, port) with
      | "tcp", _ when port = 21 || port = 23 || port = 25 -> true
      | "http", _ when port = 80 || port = 8080 -> true
      | "https", 443 -> true
      | _ -> false
     
    [<Fact>]
    let FilterCall_TcpWithPort23_ShouldReturnTrue () =
      Assert.True(FilterCall "tcp" 23)

    [<Fact>]
    let FilterCall_HttpWithPort8888_ShouldReturnFalse () =
      Assert.False(FilterCall "http" 8888)

    So, as you can see, I compressed the code quite a bit from here.  Since I'm doing functions and nothing more with just some basic pattern matching, this approach works perfectly.  That's why I am a fan of this.  Open up the GUI runner or just the ever popular console runner, and run it through and sure enough, we get some positive results.



    The interesting thing to see upcoming is how well the TDD space will play in the functional programming space.  I don't think it should be any different of an experience, but time will tell.

    Where to Go?

    From here, where do we go?  Well, I'm sure the GUI Runner of xUnit.net will get better over time, but the Gallio folks are pushing for the Icarus Runner.  Right now, only the xUnit.net runner works for me, so that's what I'm going to stick with at the moment. 

    An interesting thought occurred to me though.  Are the unit tests we're doing mostly nowadays purely functional anyways?  Would it make sense to test some C# code in F# to produce cleaner code?  Not sure, but I like the idea of having that choice.  Or even for that matter, writing my unit tests in Ruby for my staticly typed C# code.  Within the .NET framework space, the possibilities are vast.  And that's the really cool thing about it.  But will we see an IronPython or IronRuby testing framework within the .NET space?

    kick it on DotNetKicks.com

    Read more...

  • ALT.NET Open Spaces Closing Day Recap

    In my previous post, I talked about some of the happenings from the day two experience.  Day three was only a half day with only two sessions.  So, it was best to make the best of times anyhow.  Once again, it snowed again, rather heavily at times, so nature's cruel joke on ALT.NET.

    Impromptu Sessions

    One of the best sessions was an impromptu session with Jeremy Miller on the StoryTeller tool and his future plans for it.  If you're not familiar with it, it is a tool used to manage and create automated testing over the FitNesse Dot Net libraries and helps in an acceptance test driven development environment.  Anyhow, a number of us managed to corner him at one point during the day and sure enough he had his laptop available.  From there, we were able to encourage him to work on it some more as well as learn about where to go from where it is right now.  Jeremy covers more about it here.  Sometimes these impromtu sessions are some of the more valuable interactions to be had at events such as these.

    More Video To Be Had

    It seems that almost everyone had a camera at the event.  Greg Young and Dave Laribee managed to capture a bit of the sessions on video.  That's a great thing because I honestly wish I could have cloned myself and gone to more sessions.  Hopefully more of this will be forthcoming.  Dave posted Greg Young's fishbowl conversation on Architecture Futures which you can see here

    Other videos that are on this list are from John Lam's IronRuby session, Udi Dahan with ScottGu and Chad Myers talking about Microsoft and Open Source Software and so on.  You can find them at the end of Greg's video.

    Software Design Has Failed, What Can We Do About It?

    Scott Koon, aka LazyCoder, convened with JP Boodhoo a session on how software design has failed us.  This turned into a fishbowl conversation as well since there was a lot to be said.  The basic points revolved around the large amount of software failures.  What causes them?  Are they technological issues?  People issues?  Politics?  Many people brought their opinions to bear, and it was interesting that the point that I brought is that at the end of the day, customer satisfaction is the metric that matters.  Are we listening to them?  In the Agile methodology world, customer satisfaction is the only metric.  Yes, we can talk about TDD/BDD, DDD and so on, but are we actually putting software into the hands of the user that they actually want?

    I'm not forgetting of course the ideals around mentoring and helping make the team stronger.  Those issues are important as well.  Do we do pair programming?  Do we hold brown bag sessions?  All of those suggestions are key to helping grow a stronger team.  But, also it helps grow the team as a more cohesive unit that's not afraid to ask questions, pair up and avoid flailing.

    F# and Concurrency

    Roy Osherove convened a session on concurrency and functional programming as the last topic I was going to attend.  When we start to deal with multi-core environments, threading issues come to bear more frequently.  Are we utilizing the CPUs to the maximum or are we still just sitting on that one thread, and barely using the machine to its capacity?  Those are many of the issues we face.  In Software Engineering Radio Episode 14, Ted Neward talks to this very point quite frankly that multi-threaded programming is hard.  There are no two ways about it.  But, when we talk about functional programming, some of that is solved.  Why?  Immutability by default is one of the key strong points of FP.  Instead, you have to go out of your way to make a value to be mutable.  Is this something we'll see in C# 4.0?  Spec# has something to say about it.  And once again, another topic for discussion.  I keep putting these things on my plate...

    Anyhow, Harry Pierson and I helped run this session.  Harry had some of his parsing code that he has posted on his blog to show off.  I think that did the trick well to show some advanced things such as high order functions, pattern matching, anonymous functions and so on.  Instead, if you wish to learn more, I'll probably cover it here in some detail, but you can check chapter 13 of Don Syme's "Expert F#" book to learn more in the mean time.

    Action Items

    Some action items came up from this event that I think are rather important.  Because ALT.NET is a community looking to improve itself, there are naturally some things that help.  Here are a few that I can think of:

    1. Keep the conversation going
      Just because the conference ended doesn't mean the conversations that started there have to.
    2. Start a local group
      After the session was done, the altdotnet mailing list came alive with people wanting to create that ALT.NET groups like I did in DC, Brian Donahue did in Philly and Jeremy Jarrell did in Pittsburgh.

    3. Support the community
      Ray Houston laid out a challenge for those who use Open Source products to donate to them.  This doesn't mean only money, but time as well.  Many projects are in need of some assistance, and all it takes is for someone to ask.

    4. Challenge Assumptions and Bring Change
      It was said best during the conference "If you can't change your job, change your job".  Don't let these discussions that happened here just stay there.  Bring them to your work place, bring change for the better.  Question why things are done the way they are.

    Wrapping it Up

    I'm glad to have been a part of this event in Seattle.  It couldn't have been with a better bunch of people who are willing to better themselves, challenge themselves and their assumptions and bring change to the developer community.  There was a lot to learn this past weekend and each conversation brought up a new angle.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • ALT.NET Open Spaces, Seattle Day 2 Recap

    In my previous installment of recapping the events from ALT.NET Open Spaces, Seattle, I covered pretty much the opening ceremonies as it were.  The weather was definitely interesting the entire weekend.  Who would believe that we had snow, hail and rain for most of the time we were there in the latter half of April?  Mind you it didn't stick, but if you believe in God, there is something to be said of ALT.NET coming to town.

    Coverage Galore

    Jeffrey Palermo was gracious enough to capture the opening ceremonies on video for all to see.  Here are some of the videos and they are well worth watching.  Really gives you an idea of how to run a good Open Spaces.  Doc did a wonderful job as a facilitator for the event.  And yes, that's me in the black coat in the background setting up for the event.

    Dave Laribee also has a ton of video as well.  Most recently, the Fishbowl conversation about the polyglot programmer has been posted here.  The debate starts with Jeremy Miller, Ted Neward, Charlie Calvert, Scott Hanselman and others.  Really good conversation posted.
    So, as you can see from the videos it was a pretty diverse crowd.  And, hey, we managed to get all of 5 women there too!  Peter Laudati posted the schedule here which was initialed by all who wanted to see that particular discussion.

    IronRuby Session

    Since John Lam wasn't around on Friday for the topic submittal, I so graciously put his name in for him.  Luckily he agreed so we were good to go for the first session.  We didn't have any canned presentations which is nice.  Instead, John focused more on how far IronRuby has yet to go.  It was interesting that he is using the Rubinius specs in order to validate IronRuby.  Also of note, it was pretty cool to see that Spec# has been used for the IronRuby compiler.

    Covering Spec#

    Unfortunately, the functional programming talk that I planned with Dustin Campbell was put right along side the Spec# talk, so I had to make a choice.  I picked Spec# as it was the first Open Spaces they had done.  As I said before, one of the major things I wanted to talk about was Spec# at ALT.NET.  Both Greg Young and I were pretty interested in getting Rustan Leino and Mike Barnett to show off the technology to the masses.  And what better way than to show a bunch of geeks like us this technology.  Anyhow, Mike and Rustan did a really good presentation to show off Spec# to a mass audience.  For those not familiar with Spec#, I did a whole series on this on my old blog here.  Basically, the intent of Spec# is to provide Design by Contract specifications in your classes and have that exposed to the outside world.  So, no more guessing about the preconditions, postconditions and invariants of your system, instead, we can be pretty explicit about it.

    The problem that they are facing is that Spec# is not just an additive to the C# compiler, instead it's a separate compiler that is compliant with the C# 2.0 specification.  The problem is that C# 3.0 introduces a few more items, albeit mostly syntactic sugar for the most part, and yet Mike is really one of the only guys doing the Spec# compiler.  So, making it C# 3.0 compliant is a pretty daunting task.  Instead, a future focus is on making language neutral pieces available to all .NET languages just as we saw briefly in the System.Core.dll assembly under the Microsoft.Contracts namespace.  The point of inviting them was to help bring their cause to a wider audience.  Anders Hejlsberg and Mads Torgersen need to put this on their mind as to how to incorporate, and I'll make sure it's widely known.

    It was great to see Scott Hanselman quite excited about the technology and hopefully you'll see more of it from him soon.  Also, stay tuned to InfoQ for more Spec# related items as well.  I intend to cover things again shortly to talk about some other new things in Spec# as well as the new release.  Stay tuned for that...

    ASP.NET MVC

    Phil Haack and Brad Abrams hosted a discussion on ASP.NET MVC which was pretty positive overall.  There has been a number, around 5% that Microsoft has been throwing out there as a number of people that would be adopting ASP.NET MVC over traditional web forms.  The audience was rightly skeptical of such a number and wish that they would cut it out.  Instead, it could have the effect of scaring away people from adopting this framework as their choice for ASP.NET web applications.  I can totally understand that the numbers could be there due to the ISV market which make controls for ASP.NET web forms which is something that the MVC framework doesn't support.  Another request was to support open source javascript frameworks better.  But overall, Phil and Brad were pretty receptive and it was an overall positive experience.

    Are We Innovating?

    Scott Hanselman convened a talk asking "Are We Innovating or Are We Just Porting?" in which that very question was asked.  If you look at the open source frameworks that exist within the .NET space, it's not hard to see what he's talking about:
    • JUnit => NUnit, MbUnit, xUnit.net
    • Hibernate => NHibernate
    • Spring => Spring.NET
    • Ruby on Rails => MonoRail
    • jMock => NMock, Rhino Mocks, Moq
    • Ant => NAnt, MSBuild
    • And the list goes on...
    But when you look at the list the other way around, we really don't see it going the other way.  Is it because that in the Java world, frameworks weren't provided by Sun as they were for Microsoft?  Or was it something else?  The answer of course isn't easy and maybe it's not in the frameworks area that we need to look.  For example such applications as Paint.NET is truly innovative in my opinion.  I wouldn't have half the picture content on this blog as easily without it.  Also, some open source blogging engines work quite well as well.  So, there is innovation, but if you look to recent times, have we caught up?

    To Be Continued...

    kick it on DotNetKicks.com

    Read more...

  • DC ALT.NET Meeting 4/23/2008 - Jay Flowers and CI Factory

    Now that we've somewhat recovered from ALT.NET Open Spaces, Seattle, it's time for another DC ALT.NET meeting.  I'm currently finishing up my wrapups for Seattle still and I'm sure I have months worth of material from there.  Anyhow, this time Jay Flowers will be talking to us about Continuous Integration and CI Factory which was postponed from last month due to schedule conflicts.  As always we have the first hour or whenever the conversation ends for our main topic and the rest is Open Spaces.  Food will be served as well.

    Below are the details for the meeting:

    Time:
    4/23/2008 - 7PM-9PM

    Location:
    2201 Wilson Blvd
    Arlington, VA 22201

    Parking/Metro:
    Best parking on N. Veitch St
    Courthouse Metro the best bet

    As always you can find out more by joining the mailing list here.  Hope to see a great crowd there and to continue some of the great discussions that were held in Seattle.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • ALT.NET Open Spaces, Seattle Day 1 Recap

    ALT.NET Open Spaces, Seattle has come to a close.  What a great time it was and it met every expectation if not exceeded them.  Currently I'm in the Seattle airport waiting for my flight home which just got re-arranged.  Anyhow, I'd like to wrap up my thoughts for the first day of the event.

    Setting It Up

    I arrived one day early for the event to make sure we were set up appropriately.  I was able to meet up with Dave Laribee, Glenn Block, Scott Bellware, Jeremy Miller, Greg Young, Scott C Reynolds, Ray Lewallen, Patrick Smacchia and others.  Everyone was already burned out from the MVP Summit, so I wasn't sure how well people would be for the event.  But it was great to talk to Sam Gentile and I'm glad he's back in the fold with ALT.NET as he announced earlier last week here

    Even though a lot of people were tired, we had plenty of help to set up for the event.  Of course the joke is that "How many ALT.NETers does it take to go to Costco?"...

    Kicking It Off

    One couldn't ask for a more prepared and outstanding facilitator in Steven "Doc" List.  What an amazing job he did to bring the Open Spaces together.  The event started with a description of Open Spaces Technology.  if you're not familiar with the Open Spaces, Technology Format, here are the four basic principles:

    • Whoever comes are the right people
    • Whatever happens is the only thing that could have
    • Whenever it starts is the right time
    • When it's over, it's over
    With that getting kicked off, we then laid out the pens and sticky paper to write the sessions.  The idea is to write down your idea on the sticky paper and then get to the middle of the room and announce your talk that you will facilitate.  Of course some subjects may be very similar and can be combined, which happened quite a bit actually.

    The Sessions

    I met with Mike Barnett from the Spec# team who was one of the many people I had invited to this event.  Spec# as you may have figured from my blog is a passion of mine.  It is one of my goals to publicize it enough and to make sure that people are aware of this wonderful technology that the product teams such as Mads Torgersen and Anders Hejlsberg notice.  Anyhow, Mike went up and announced a session on Spec# and static verification.  I'll cover more of that in subsequent posts again.  Start your letter writing campaigns now!

    Dustin Campbell also was in attendance and he and I chatted about F# and doing a session on functional programming and F#.  It was going to be a great session, but unfortunately when the schedule was finalized, I couldn't possibly attend the Spec# and functional programming and F# talk.  I was a little disappointed by that, but luckily Roy Osherove suggested a talk about "Concurrency and Functional Programming" which I was more than willing and able to help out on. I also pulled Harry Pierson, the new Program Manager for IronPython to help in such a session.

    Since John Lam wasn't in attendance that night, I volunteered him for a session on IronRuby and the DLR which he was more than happy to oblige.  We scheduled that for the first session on Saturday.  I'll cover each of these in detail in subsequent posts. 

    The Fishbowl

    From there, we went to a fishbowl style conversation in which there are a number of chairs in the middle of the room.  There must be all but one of the chairs filled at any given time.  Any person may in turn come and take a seat and another person must leave to keep the balance.  The discussion started with Scott Hanselman, Ted Neward, Charlie Calvert and Martin Fowler talking about the Polyglot Programmer.  Ted Neward couldn't be there for the whole event, unfortunately as he was also doing No Fluff Just Stuff this weekend as well with Venkat Subramaniam, Neal Ford and others.  Luckily I got some time to talk to Ted about some F# related items as well as his upcoming trip to Reston, VA for No Fluff Just Stuff next weekend.  So, if you're in the area and interested in seeing Ted and Venkat, that's the place to go!  But anyways, the event was great and a lot of people pitched in.  There are so many to name, I'd just run out of space.

    To Be Continued....

    kick it on DotNetKicks.com

    Read more...

  • Off to Seattle and ALT.NET Open Spaces, Seattle

    Well, the day has finally come where I'm heading to ALT.NET Open Spaces, Seattle.  It's been a long time of planning for this day with all the other guys mentioned on the site.  The weather's not looking so great with a possibility of snow on Saturday.  Not looking forward to that part as I'm leaving sunny, beautiful Washington DC where it is around 75F or so right now.

    I hope to be live blogging much of the event, well as much as I can.  I you're on Twitter, you can follow me at mattpodwysocki.  Looking forward to seeing everyone there!

    kick it on DotNetKicks.com

    Read more...

  • NOVARUG with Dave Thomas (PragDave) Recap

    Last night I attended the Northern Virginia Ruby Users Group (NovaRUG) meeting in Reston last night with Dave Thomas (PragDave) and Chad Fowler.  It was a completely packed house and the temperatures were a bit hight in the room, but it was well worth the sweating to attend.

    Paul Barry presented first on Merb and gave a really good demonstration of some of the capabilities in comparison to Ruby on Rails.  If you're not familiar with Merb, it is a lightweight Model View Controller framework written in Ruby.  It was written by Ezra Zygmuntowicz in response to trying and giving up on making Ruby on Rails thread safe.  You can find his presentation materials here.

    It was mentioned that there will be a Ruby conference in the Northern Virginia area upcoming  I'd like to see if we can get some IronRuby in there instead of all those Java guys with JRuby.  We'll see what happens, but for right now, everything seems to be in flux.  Stay tuned!

    Next up, Dave Thomas talked about the Ruby object model with a very good presentation.  Below you can find some of my pictures I took from the event.  Forgive the quality of the images, but you can tell that it was a crowded place!  Anyhow, it was a really good talk about the object model, how the scoping of self and the resolution of classes and methods are done deep down in Ruby.  It was an excellent presentation and I was definitely excited by his passion for the community and the technology.

    First we have Dave talking about the inheritance chain of Ruby objects.



    Then here's Dave talking about the method resolution.



    I had a chance to chat with Dave afterwards on F# as he has been looking into OCaml lately, where F# got most of its functionality from.  It's his hope that F# succeeds and I ultimately think it will.  So, I told him to give it a try.  Anyhow, it was a great night and good to reach out to the community.  The DC area has a pretty rich community of .NET, Ruby and Java programmers that's really refreshing to see.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • Metaprogramming in F#

    Tonight I will be heading to the Northern Virginia Ruby Users Group (NoVARUG) meeting tonight with Dave Thomas (PragDave) talking about metaprogramming in Ruby.  Should be a great time and I'm sure it will be full tonight.   For those interested in some introduction to metaprogramming in Ruby, here's a good link to help get you started.

    Metaprogramming in F#?

    One of the many things that has interested me in F# is that it was originally written as a language to write other languages.  This of course leads me to a discussion of F# and metaprogramming.  Is it a fit?  There are a couple of links well worth visiting and then at a future date, we'll come back to the subject.

    Before the links, most of the language oriented stuff comes from quotations.  Quotations are a little block of code which turns a particular piece of code into an expression tree.  This language tree can then be transformed, optimized and even compiled into different languages.  There are two types of these quotations, raw and typed.  Typed Quotations contain static typing information whereas the raw do not.  For a good introduction to these, check out Tomas Petricek's post here.

    I hope when I get a further chance, I'll dig into it a bit more here.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • Adventures in F# - F# 101 Part 8 (Mutables and Reference Cells)

    Time for another adventure in F#, covering some of the basics of functional programming and F# in particular.  Today we'll manage to look more at regular .NET integration and .NET programming.  With the previous efforts, we've looked more at functional programming and in turn F# specific things, but want to show that you can do anything normally in F# that you can in C#.  To me, F# is the perfect all-purpose language because it can do a lot of the things C# can do, but in turn, F# can do things much more elegantly than C# can, such as Pattern Matching.

    Where We Are

    Before we begin today, let's catch up to where we are today:

    Today's topic will be covering imperative and object oriented programming in F#.  There is a lot to cover, so let's get started.  But there are a few administrative things to get out of the way first.

    Learning F# ala Ted Neward?

    Ted Neward recently announced on DotNetRocks Episode 332  that he's in the process of creating a class for F# for Pluralsight.  That should be interesting to those who are interested in this series, as well as F# in general.  Right now the community is rather small, so efforts like this should be rather rewarding I would hope.  Ted's a pretty brilliant guy, so I'd imagine only the best.  I'm hoping more details come out soon. 

    Pattern Matching in C#

    Part of this series is intended to bring such concepts as Pattern Matching, Currying and other Functional Programming concepts to the C# developer.  After all, the more C# language evolves, the more it seems to fall into the Functional Programming category.  In previous posts, I showed how to relate currying to C# and it was less elegant than F# to say the least.

    But, let's look at Pattern Matching.  Bart De Smet has been posting recently on his blog about bringing the beauty of pattern matching to C#.  So far it's been a good six posts into it and I urge you to go ahead and take a look at this series. 
    But when you read the series, it's all about getting into the low level and compiling expression trees to make the same simple beauty that is F#.  Sure, it can be done in C#, but nowhere near as elegant.  Performance is another issue that comes to mind with these.

    Imperative Programming in F#

    This section I'll lay out some of the basics of imperative style programming before I get into the full object oriented approach to programming.  So, we'll cover just a few topics and then I'll feel comfortable moving onto the real parts of creating classes and such.  We'll cover such things as void types and mutability in this section.

    The unit Type

    One of the first things I forgot to mention when describing F# functions and values in the unit type.  Think of this as the void type in C# that you are used to.  It's the type that doesn't accept or return a value.  First, let's look at the typical C# program with the void type for Hello World.

        class Program

        {

            static void Main(string[] args)

            {

                Console.WriteLine("Hello World");

            }

        }


    Now, let's go ahead and look at it from the F# perspective.

    #light

    let main() =
      printfn "Hello World"

    main()


    As you will see when you hover over our code is that it is a unit type.  That in itself isn't all that interesting.  But, what we'll run into is problems when functions return a value, but we're not all that interested in them.  What happens?  Well, F# will complain that your return value isn't compatible with the unit type, which is essentially true.  So, how do you get around that?  Let's walk through a simple unit test of a Stack written in F# and unit testing with the xUnit.net framework.

    #light

    #R @"D:\Tools\xunit-build-1252\xunit.dll"

    open System
    open System.Collections.Generic
    open Xunit

    type Stack<'t> = class
      val elements : LinkedList<'t>
     
      new() = { elements = new LinkedList<'t>() }
     
      member x.IsEmpty
        with get() = x.elements.Count = 0
      
      member x.Push element =
        x.elements.AddFirst(element:'t)
      
      member x.Top
        with get() =
          if x.elements.Count = 0 then
            raise (InvalidOperationException("cannot top an empty stack"))
          x.elements.First.Value
        
      member x.Pop() =
        let top = x.Top
        x.elements.RemoveFirst()
        top
    end

    [<Fact>] 
    let PopEmpty () =
      let stack = new Stack<string>()
      Assert.Throws<InvalidOperationException>(fun () -> stack.Pop() |> ignore )


    The real interesting part you should pay attention to is the last line.  As you can see, I am using the forward operator to indicate that I really don't care what the function returns, just that I'm interested in that it executes.  This is most likely during such functions that have some sort of side effect to them.  I could also use the ignore function instead of the forward operator such as this:

    [<Fact>] 
    let PopEmpty () =
      let stack = new Stack<string>()
      Assert.Throws<InvalidOperationException>(fun () -> ignore(stack.Pop()) )

     


    This is very helpful in these cases where we really don't care about the return value, instead want to mutate the state of our given object, such as removing a value from a collection and so on.

    Mutables

    As I said in many posts before, by default all "variables" by which I mean values in F# are immutable.  This is a standard in functional programming and all in the ML family.  You can easily redefine a value by using the let keyword, but not actually mutate its state.  But, since F# is a multi-purpose language on the .NET platform, mutable state can be had.  To take advantage of this, mark your value as mutable.  Then to change the value, just use the <- operator to reassign the value.  Below is a simple example of this:

    #light

    let mutable answer = 42
    printfn "Answer is %i" answer
    answer <- 8
    printfn "Answer is %i" answer

     


    A key difference from the reassignment is that you cannot change the value type.  Whereas I can redefine answer by keep using the let keyword, I can only keep my answer in this above example of the int type. 

    This can also apply to record types as well where you can change the fields.  In the last installment, we talked about record types.  Well, by default there as well, the fields for the record type are immutable.  But, as with before, that can be changed.  I of course like to caution people that mutable state takes a lot of the value proposition away from the side effect free programming that you gain with F# by default.  But, nevertheless, you can still do it as noted below:

    #light

    type Person = { FirstName : string; mutable LastName : string; mutable IsMarried : bool }

    let friend = { FirstName = "Courtney"; LastName = "Cox"; IsMarried = false }
    friend.LastName <- "Cox-Arquette"
    friend.IsMarried <- true 


    What I was able to do was define a Person record and change a couple of fields while using the <- operator and defining the fields as mutable.  Yes, I could have used some scientific calculation or something, but this was easy.

    Reference Cells

    The last thing I want to touch on in this post is reference cells.  You can think of these much as pointers in other languages or reference types.  These of course can be of any type.  The idea behind using these is to make updating fields as easy as possible.  As with mutable fields, you cannot change the type once it has been assigned.  To use these, you need to remember three basic operators
    • ref - Allocates a reference cell
    • := - Mutates a reference cell
    • ! - Reads the reference cell
    Below is a quick example of mutation through reference cells:

    #light

    let x = ref 2
    x := !x + 25
    printfn "%i" !x


    What the code example above lets me do is define a reference to the number 2.  Then I can change that reference by reading the current x value and adding 25.  Then I mutate the existing x value with the result.

    Conclusion

    This is just meant to be a brief overview to some imperative programming constructs that you might see in .NET, Java, C, C++ and so on.  F# is a first class language all the way with constructs that support these things as well as your normal functional programming constructs.  I hope we get to cover some of this at ALT.NET Open Spaces, Seattle at some point because I'm sure a lot of people will be interested.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • ALT.NET on DotNetRocks and the Community

    Dave Laribee and Jeremy Miller recently recorded an episode on DotNetRocks and was just posted today.  Episode 333 "It's the ALT.NET Show" can be found here.  It's a great show that explains ALT.NET for those who may not really know what it is outside of some of the arguments on the altdotnet mailing list.  This includes discussions on open source frameworks, agile practices, refactoring and so on. 

    It's great to see the reaction from this show at least from my perspective.  To see the job we're doing from Josh Holmes, Glenn Block, me and others from within to reach out and also present ideas and bridge the gaps.  It's been very rewarding to be a part of that.

    We're only just a few days away from ALT.NET Open Spaces, Seattle.  All of those who are attending should have received a notice of such this morning.  I'll be arriving in Seattle on Thursday afternoon to help set up for the event so if anyone wants to hang out beforehand let me know.

    Bringing It To The Community

    Anyhow, this weekend I did my best to bring some of those ALT.NET practices to the CMAP Code Camp and we had a pretty good turnout.  This time I talked about refactoring to patterns, dependency injection and inversion of control containers.  I'm hoping to do the same for the Northern Virginia Code Camp coming up on May 17th.  Brian Donahue has been rather successful doing so with the Philly Code Camps as well.  That reminds me that I'm coming up there in mid-May to do an F# session.  Should be a fun time.

    kick it on DotNetKicks.com

    Read more...

  • CMAP Code Camp Wrap Up - Dependency Injection and IoC Containers

    I really enjoyed speaking at this past weekend's CMAP Code Camp.  I hope you all enjoyed my presentation on "Loosen Your Dependencies with Dependency Injection and Inversion of Control Containers".  It was a great discussion to have with everyone and I like to learn there as much as I teach. 

    I also enjoyed teaming up with Scott Allen on his "A Gentle Introduction to Mocking" where we talked about mocks versus stubs, test pattens and mock frameworks such as Rhino Mocks and Moq.  Hopefully we'll be doing some more ping-pong sessions in the future.

    Once again, I'd like to plug my DC ALT.NET group that I run.  Our next meeting is scheduled for April 23rd and the topic will be Continuous Integration with Jay Flowers.  We'll announce the location shortly for our group.  You can go ahead and sign up for our mailing list here.

    Anyhow, here are some resources that can help point you in the right direction.  This includes articles, blogs and such that I find will be useful in your journey to better understand these things:

    My presentation materials have just been uploaded to my SkyDrive.  The PowerPoint presentation can be found here and the code samples can be found here.

    If you note, I my code uses the following products in order to get it to run:
    Feedback is always appreciated.

    kick it on DotNetKicks.com

    Read more...

  • Unity Community Contributions and Interception

    Now that Unity has been released into the wild, there has definitely been a bit of interest swirling around it.  One of my key wants for a good IoC container is basic interception capabilities.  My criteria for evaluating a container usually comes down to the following:

    • Configurability (XML, DSL, Code)
    • Dependency Resolution, usually opinionated
    • Lifetime Management (Per Thread, Pooled, Singleton, Transient, etc)
    • Extensibility for Interception
    So, I realized that Unity was missing some of these things in the first go around.  Since Unity was built on top of ObjectBuilder2, a next generation version of the often maligned ObjectBuilder which also included some sample DI containers and a flexible interception model.  Today's post will cover that and a bit more.  I realize that I still am working on a post of AOP in the Enterprise and Spring.NET which is coming soon.

    Where We Are


    But, before we begin today, let's see what we've already covered in the past:
    Now that we've look at the history of this series, let's go ahead and get started.

    Unity Contributions

    Since Unity was released last Friday, there has been a community effort much like the ASP.NET MVC Contributions, MVCContrib, called Unity Community Contributions.  This project is intended to fill in the gaps where the community feels that Unity can be extended, much like most other IoC containers.  As I stated above, one of those crucial things that I thought was missing was taking the ObjectBuilder2 Interception model and applying it towards Unity.  I wasn't interested as much in the Policy Injection Application Block, although nice, is a bit heavyweight for the basic operations I would like.  Instead, the OB2 would suffice for most things that I'd want with a container.  So, that led me to another topic...

    ObjectBuilder2 Interception == Unity Interception?

    Since I was particularly motivated to see the OB2 Interception model pushed into Unity, I decided to give it a go myself.  For the most part, I was successful in a way, but I wasn't using the right extensibility model.  From that point, I got in contact with Scott Densmore, a PM within the Patterns & Practices group and one of the authors of ObjectBuilder2 along with Brad Wilson.  From that point, he was able to take the original OB2 Interception model and fit it nicely into the Unity extensibility model.  The code is now available on the Unity Community Contributions and you can find those commits by Scott here.

    So, let's take a look at what it entails.  As I tell most people, you learn the most about the software with good unit, I mean behavioral tests where I can really grok the intent of the code much better than most documentation.  I encourage most people to do the same.  I'd rather stay away from those projects that don't have tests to back up their work.

    Like I said before, ObjectBuilder2 had several ways of intercepting calls.  There are several interception strategies worth mentioning:
    • Virtual Method interception
    • Interface Method interception
    • .NET Remoting interception (MarshalByRefObject)
    From that, you have two ways of registering your interest for interception:
    • Intercept via code
    • Intercept via attributes
    Now that we've laid down the basics, let's take a look at some of the unit tests.  You'll notice that xUnit.net was used for the unit tests.  Yes, I know, I've mentioned it a few times lately.  Anyhow, let's look first at virtual method interception.

    Before we get started on that, in order to perform interception, we need to implement the IInterceptionHandler interface.  For the unit tests, this will be used to record the various actions that happened during the interception process.  But you can imagine it to do any number of things such as logging, transaction management, security and so on.  Any of those cross cutting concerns, really.

        public delegate IMethodReturn InovkeHandlerDelegate(IMethodInvocation call,
                                                            GetNextHandlerDelegate getNext);

        public delegate InovkeHandlerDelegate GetNextHandlerDelegate();

        public interface IInterceptionHandler
        {
            IMethodReturn Invoke(IMethodInvocation call,
                                 GetNextHandlerDelegate getNext);
        }
    }


       public class RecordingHandler : IInterceptionHandler
        {
            readonly string message;

            [InjectionConstructor]
            public RecordingHandler()
            {
                message = "";
            }

            public RecordingHandler(string message)
            {
                this.message = string.Format(" ({0})", message);
            }

            public IMethodReturn Invoke(IMethodInvocation call,
                                        GetNextHandlerDelegate getNext)
            {
                Recorder.Records.Add("Before Method" + message);
                IMethodReturn result = getNext().Invoke(call, getNext);
                Recorder.Records.Add("After Method" + message);
                return result;
            }
        }


    We have the ability through the Invoke method to do things before the method as well as after.  Should we need to modify values before the method is called, we can go ahead and do so.  Now that we looked at that, let's get to some unit tests.  First off, let's look at interception through just code.  I like this approach as opposed to attributes due to not cluttering the domain model and making it more configurable at run time.

                [Fact]
                public void InterceptViaCode()
                {
                    Recorder.Records.Clear();
                    IUnityContainer container = new UnityContainer();
                    container.AddNewExtension<InterceptionExtension>();
                   container.Configure<IInterceptionConfiguration>().InterceptVirtual<SpyVirtual>

                       (typeof(SpyVirtual).GetMethod("InterceptedMethod"), new RecordingHandler());

                    SpyVirtual obj = container.Resolve<SpyVirtual>();
                    obj.InterceptedMethod();
                    obj.NonInterceptedMethod();

                    Assert.Equal(4, Recorder.Records.Count);
                    Assert.Equal("Before Method", Recorder.Records[0]);
                    Assert.Equal("In Method", Recorder.Records[1]);
                    Assert.Equal("After Method", Recorder.Records[2]);
                    Assert.Equal("In Non-Intercepted Method", Recorder.Records[3]);
                }


                public class SpyVirtual
                {
                    public virtual void InterceptedMethod()
                    {
                        Recorder.Records.Add("In Method");
                    }

                    public void NonInterceptedMethod()
                    {
                        Recorder.Records.Add("In Non-Intercepted Method");
                    }

                    public virtual void ThrowsException()
                    {
                        Recorder.Records.Add("In Method");
                        throw new Exception("This is my exception!");
                    }
                }


    As you see above, we can simply register our interest through the registration of the InterceptionExtension and then set up the configuration through the IInterceptionConfiguration.  From that point, we then say which kind of interception we want whether it be virtual, remoting or interfaces.  We specify the method we want to intercept by name.

    You can also do the interception through the use of attributes.  From this point, we need to decorate our methods with the attribute and the particular interception handler we want to use.  We need to be aware of which interception strategy we're using as well when we decorate our classes.  You can intercept methods as well as property accessors by decorating the get or set.  Below is a simple example of a virtual interceptor registration.

                 public class SpyVirtualAttributes
                {
                    [VirtualIntercept(typeof(RecordingHandler))]
                    public virtual void InterceptedMethod()
                    {
                        Recorder.Records.Add("In Method");
                    }
                }



    I'm not going to post all of the tests, but I want to give you an idea of the power of this.  It's still early in the process and there is some cleanup still going on.  But, I encourage you to pick up the source, read it, grok it, give it a try and give feedback.

    Conclusion

    As you can see, the extensibility model of Unity works in that we can add interception to Unity.  So, we can start thinking about moving our cross cutting concerns to these layers should we so choose if Unity is your container of choice.  There are plenty of containers out there to choose from, so it's best to give them all a try and pick one based upon features, programming style, and heck, maybe even licensing.  I'll be showing some of this stuff off tomorrow at the CMAP Code Camp, so if you'll be at my 1PM session, be prepared.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • xUnit.net RC3 Just Released

    Well, Brad Wilson and Jim Newkirk must really be busy lately.  After I talked about the release of xUnit.net RC2, just today, Brad announced the release of RC3.  As always, you can find the latest bits here.  This fixes a number of bugs and adds CruiseControl.NET and ASP.NET MVC Preview 2 support as well in addition to the Resharper 3.1 and TestDriven.NET support.  For more information about it, check out Brad's post here.  More or less, they are feature complete for version 1.0 and the only that I think really is needed at this point is a decent GUI runner and that's well acknowledged as something they are working on.  Visual Studio integration would be nice as well...

    For my other posts in this series, check them out here:

    If you were in attendance at last night's RockNUG appearance, all tests for my demos were using xUnit.net, so I am actively using it right now and will be for my CMAP Code Camp appearance this weekend.  However, I did not show the GUI runner because, well, it's not there yet, and instead, the console runner works just fine, thank you.  So, go ahead and pick up the latest bits and give the team feedback!

    One last note regarding Brad, he was recently interviewed by Scott Swigart and Sean Campbell over at How Software Is Built and gives some interesting insights in the open source world inside and outside Microsoft and his contributions to it.  Very good interview and well worth the time to read.

    kick it on DotNetKicks.com

    Read more...

  • RockNUG IoC Container Presentation Wrapup

    I want to thank the fine folks at the Rockville .NET Users Group (RockNUG) and Dean Fiala for giving me the opportunity to speak last night.  It was a record crowd last night, so I'm glad that people were interested in Loose Coupling, Design Patterns, Test Driven Development, Behavior Driven Development and Inversion of Control containers.  I hope everyone got some good information, and if not interested in using containers, design patterns and such, at least know they exist and have their use.  Based on the feedback I've already received, it was warming and why I like presenting at user groups, so that both of us can learn.

    Once again, I'd like to plug my DC ALT.NET group that I run.  Our next meeting is scheduled for April 23rd and the topic will be Continuous Integration with Jay Flowers.  We'll announce the location shortly for our group.  You can go ahead and sign up for our mailing list here.

    Anyhow, here are some resources that can help point you in the right direction.  This includes articles, blogs and such that I find will be useful in your journey to better understand these things:

    After my CMAP Code Camp session over the weekend, I will go ahead and post my slides and code samples for your enjoyment as well as discuss further some more resources.  So, if you're in the Columbia, MD area this weekend and haven't signed up, go ahead and do so.  Hope to see a great crowd there!

    kick it on DotNetKicks.com

    Read more...

  • NoVARUG Meeting April 16th - Dave Thomas (PragDave)

    The Northern Virginia Ruby Users Group (NoVARUG) will be holding their next meeting next week with a special speaker in Dave Thomas (PragDave).  Dave is in town teaching Advanced Rails Studio in Reston and will be kind enough to come talk about the Ruby Object model and how it facilitates metaprogramming.

    The details are as follows:

    Subject:
    Dave Thomas - The Ruby Object Model and Metaprogramming

    Date:
    April 16th, 2008 - 7-9PM

    Location:
    FGM Inc
    12021 Sunset Hills Road
    Suite 400
    Reston, VA 20190

    Hope to see a good crowd there!  I know I'm very interested in this subject and hope to dive deeper soon.  That reminds me I need to do some of metaprogramming in F# as well.

    kick it on DotNetKicks.com

    Read more...

  • Unity 1.0 Released into the Wild

    As Chris Tavares mentioned in his blog, Unity 1.0 has been released a couple of days earlier than the April 7th release date mentioned by Grigori Melnik earlier.  Scott Densmore also announced this as well as working on porting the inteception from ObjectBuilder2 which I talked about earlier in some of my Unity and IoC containers posts.  Looking forward to that post as we've shared some emails on the subject.

    Would You Like To Know More?

    For those looking for my posts on the matter, I've covered it quite extensively with the comparison to other IoC containers as well as IoC containers in general:


    Anyhow, if interesting in more Unity content, check out David Hayden's Unity IoC and MVC screencast as well as others on the subject here.

    Speaking of which, I'm going to be a busy man indeed with my upcoming speaking schedule on IoC containers, not necessarily Unity in particular, but all of them, the background and decoupling your applications.  Here is the complete schedule for this month:
    I hope to contribute some at ALT.NET Open Spaces, Seattle as well on a few subjects and DC ALT.NET on April 23rd as well.  Should be a great time and feedback is always appreciated.

    kick it on DotNetKicks.com

    Read more...

  • Relooking at xUnit.net RC2

    UPDATE: More posts on the subject

    Earlier this week, I wrote about the latest release of xUnit.net RC2.  Since that time, Brad Wilson and Jim Newkirk released a new version to fix some of the issues with regards to TestDriven.NET integration and ASP.NET MVC integration.    You can read more about the issues here.  As always you can get the latest bits here

    The Installer

    If you browse to the releases page of xUnit.net, you will notice an installer.  This installer will help integrate xUnit.net with Resharper 3.1 for Visual Studio 2005 and 2008, TestDriven.NET and ASP.NET MVC.  Just click the installer and a screen like below will show.  Note that I have Resharper 4.0 nightly builds instead of 3.1, so those features aren't activated just yet, unfortunately. 



    Since I didn't have anything else but ASP.NET MVC Preview 2 installed, that's all I got enabled.  It only takes a few seconds to enable.

    ASP.NET MVC

    Now that I got the ASP.NET MVC plugin installed for xUnit, I can go ahead and open Visual Studio 2008 and create a new ASP.NET MVC application.  When it automatically creates the test project for me, I have the option now of using xUnit.net instead of that lesser one that came in here by default.



    Once I do that, it will create some tests of the HomeController and Routes by default as noted below:



    But in order for this to work out of the box, there is some work you need to do.  Your tests will not compile by default because you need to change the namespace includes on top to include your application's namespace.  Not a huge issue mind you, but a little more work than usual.  Here's what it will look like:

    using MVC_APPLICATION_NAMESPACE.Controllers; // This using directive needs to point to the namespace of your MVC project

    using Xunit;

     

    namespace PetShopTests.Controllers

    {

        public class HomeControllerFacts

        {

            public class Index

            {

                [Fact]

                public void RendersTheIndexView()

                {

                    TestableHomeController controller = new TestableHomeController();

     

                    controller.Index();

     

                    Assert.Equal("Index", controller.RenderView_ViewName);

                }

            }


    So, all you need to do is replace the MVC_APPLICATION_NAMESPACE with your own namespace and problem solved!  But out of the box, you have some working unit tests and some good guidance on how to get started.  If you're curious on how the integration actually works, check out this post here.

    GUI Runner

    As Brad had stated earlier, there is a simple, yet effective GUI runner for xUnit.net.  So far there's not much to it, other than to load an assembly and run all associated tests.  To give you an example, I wrote some F# code and now I want to run some tests against it.  So, here is the code I used for these simple tests.  Yes, you can go ahead and yell at me for doing OO things in a functional language, but it's here to prove a point that you can.

    #light

    #R @"E:\Tools\xunit-build-1223-samples\Samples\xunit\xunit.dll"

    open System
    open System.Collections.Generic
    open Xunit

    type Stack<'t> = class
      val elements : LinkedList<'t>
     
      new() = { elements = new LinkedList<'t>() }
     
      member x.IsEmpty
        with get() = x.elements.Count = 0
       
      member x.Push element =
        x.elements.AddFirst(element:'t)
       
      member x.Top
        with get() =
          if x.elements.Count = 0 then
            raise (InvalidOperationException("cannot top an empty stack"))
          x.elements.First.Value
         
      member x.Pop =
        let top = x.Top
        x.elements.RemoveFirst()
        top
    end

    [<Fact>]  
    let NoElementsShouldBeEmpty () =
      let stack = new Stack<string>()
      Assert.True(stack.IsEmpty)

     

    [<Fact>]
    let PushAnElementShouldNotBeEmpty() =
      let stack = new Stack<string>()
      stack.Push("first element")
      Assert.False(stack.IsEmpty)


    And now, open the xunit.gui.exe and select your assembly you want to run.  I chose my fsharpsamples.dll that I've been working with on my F# samples.  Now, let's give these two tests a run to see how they do.



    As you can see, not much information is given to me other than the number of passed tests, the time taken and my assembly under test.  Not much information, but enough to get started.

    Conclusion

    As you can see, a bit of progress has been made on xUnit.net and here's hoping the version 1.0 full release is coming soon.  As I look at it more and more, I'm definitely starting to like it.  I haven't had to create as many extensions as I would have to do with MSTest such as Assert.Throws<T> and so on.  So, I encourage you to go ahead and once again, give it a look and give feedback to the team.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • Adventures in F# - F# 101 Part 7 (Creating Types)

    Time for another adventure in F#, covering some of the basics of functional programming and F# in particular.  This is intended at looking at the foundations of F# as well as how it relates to .NET and IL on the back end.  I realize I need to spread more of the F# goodness around, so I'm hoping that I can work to bring it at least to the FringeDC user group.  Their main meetings are every three months, so hopefully I'll get some time in to do that.   Once I get that set up, I'll be sure to let everyone know.

    Where We Are

    Before we begin today, let's catch up to where we are today:

    Today's topic will be covering creating custom types in F#.  There is a lot to cover, so let's get started.

    Types of Types?

    If you're familiar with OCaml, the type system in F# should look rather familiar.  For a brief introduction to how OCaml works, check out Dr. Jon Harrop's OCaml for Scientists introduction here.  We have several categories of types in base F#.  The first category is the tuples or records, and the second type are unions.

    Tuples

    The most simple type in F# is a tuple.  A tuple is a compound type composed of a fixed sequence of other types.  Each value is separated by a comma and can be referred to by a single identifier.  The values from the tuple can be retrieved by putting commas on the other side of the equals.  Below is a quick sample of this concept:

    #light

    let coin = "heads", "tails"
    let c1, _ = coin
    let _, c2 = coin

    print_string c1
    print_string c2


    What I did to look up the values was to use the _ to indicate I wasn't interested in the other values.  Hence my c1 got me heads and c2 got me tails.  As always, I'm always curious how it compiles down to C# and how it gets represented in IL, so let's take a look at the coin type that I created.



    Nothing really fancy, as we created a tuple of type string and string which held our "heads" and "tails" value.  Like I said before, tuples are the simplest type in F#.  In fact, as you saw above I didn't even need to use the type keyword to specify I was creating a new type.  However, I can choose to use the type keyword so that I can create a type alias which can be very useful for method signature constraint.  Below is a simple sample of doing that.

    #light

    type Point3D = double * double * double

    let pointPrinter(p : Point3D) =
      let x, y, z = p in
      "x:" + x.ToString() + " y:" + y.ToString() + " z:" + z.ToString()

    let pointString = pointPrinter(2.3, 5.3, 9.8)
    print_string pointString


    As you can see from above, I created a 3D point which contains an x, y and z axis.  Then I constrained the pointPrinter function to take that as a constraint so that I can format it properly.  Then of course I do all the great things I normally would do by printing it out to the console.  But, if you want to take a look at what this pointPrinter function does behind the scenes, wonder no longer.



    Quite an interesting mouthful, I must admit, but that's what you get when you deal with immutable types such as strings.

    Records

    Record types are also a user defined data structure within F#.  These are similar to tuples, but differ because each piece of data (field) inside a record must be named as well as the keyword type must be used.  Think of this much as a .NET class with simple properties.  What's interesting is that these fields that it creates for us aren't forced to be unique.  Let's go ahead and show a simple example of a Person record that we may want to create.

    #light

    open System

    type Person =
      {
        FirstName : string;
        MiddleName : string;
        LastName : string;
        DateOfBirth : DateTime;
      }
     
    let person1 = { FirstName="Robert"; MiddleName="William"; LastName="Jones"; DateOfBirth = new DateTime(1960, 12, 12); }
    let person2 =
      { new Person
        with FirstName = "William"
        and MiddleName = "Franklin"
        and LastName = "Smith"
        and DateOfBirth = new DateTime(1970, 1, 23)
      }


    print_string person1.FirstName

    print_string person2.FirstName


    What I have done is created a Person record with a FirstName, MiddleName, LastName and a DateOfBirth field.  Pretty simple.  Now, we have two ways of creating an instance of this type.  When I created person1, I just simply just set each field separated by a semicolon.  On the other hand, since I'm not explicitly naming a type, there could be conflicts due to multiple types containing the same fields.  Should I want to be more explicit, I can specify it using the longhand way with using the new operator and setting each property with the with keyword and followed by an and on each subsequent line to fill in all the other values.  Such a conflict would look like this:

    #light

    type point2D = { X:double; Y:double }
    type coordinate2D = { X:double; Y:double }

    let myPoint = { X = 2.5; Y = 3.2; }


    What the above sample will default to is that myPoint will be of type coordinate2D.  Hover over and let Intellisense do its magic.  Interesting, huh?  That's why we should be explicit about our data structures should something like this arise.

    Discriminated Unions

    The next category of F# type that will be discussed is the discriminated union.  This type is a data structure that can bring together values but have different meanings or structures.  Only one of these types can be used at once, however.  Think of it more of a type which is almost "case" like.  Each piece of that is called a discriminator.  A quick example of this would be something like distance where it could be measured in miles or kilometers, but not both at the same time.  The structure of this data is the same, but have different meanings to the program.

    Let's look at some quick examples of this:

    #light

    type Distance =
      | Kilometer of double
      | Mile of double
     
    let distance1 = Mile 26.2
    let distance2 = Kilometer 10.0

    let convertDistanceToMile x =
      match x with
      | Mile x -> x
      | Kilometer x -> x * 1.609344
     
    let convertDistanceToKilometer x =
      match x with
      | Mile x -> x * 0.621371192
      | Kilometer x -> x
     
    let convertedDistance1 = convertDistanceToKilometer distance1
    let convertedDistance2 = convertDistanceToMile distance2


    As you can see from above, I created a Distance discriminated union that defines both miles and kilometers.  Both discriminators are of type double.  So, I wrote a function to convert from one to the other.  It's just a simple pattern matching statement.  If you've read my previous posts, you should be caught up to date with this.

    I could also parameterize this data differently, meaning that each discriminator can hold a different value. 

    #light

    type Carrier = string
    type Route = int
    type Make = string
    type Model = string
    type Year = int

    type ModeOfTransport =
      | Airplane of Carrier * Route
      | Bus of Carrier * Route
      | Car of Make * Model
     
    let mode1 = Car("Audi", "A4")
    let mode2 = Airplane("United", 222)


    As you can see, I type aliased a few things such as Carrier, Route, Make, Model and so on.  After that, I defined my ModeOfTransport to be by bus, car or airplane.  A pretty simple example. 

    I can also specify the type of arguments later, by specifying them as generics.  One of them you may have already run across is the option type.  To declare one, just use the <'a> or whichever letter you so choose.  Let do a recursive example of a tree.

    #light

    type Tree<'t> =
      | TreeNode of 't Tree * 't Tree
      | TreeValue of 't

    let tree =
      TreeNode(
        TreeNode(TreeValue 0, TreeValue 1),
        TreeNode(TreeValue 2, TreeValue 3))


    From the above statement, I created a tree of nodes quite easily using this union type.  These types can get complicated quickly, however when you get into language oriented programming, so we're just dipping our toes in at the moment.

    .NET Types?

    Yes, you can also create .NET types as well just as easily, although with a few major details.  For example, the mutable types which is not by default in F#.  I'll cover that in the next post.

    Conclusion

    As you can see, there are a few basic types in F#.  They are mostly for holding analytical data, traversing them and so on.  These are interesting and serve as the basis of what you will do in F# when you need to store and analyze data, especially custom types.  In the next installment, I hope to cover some .NET specific topics such as creating .NET types.  Until next time...

    kick it on DotNetKicks.com

    Read more...

  • Covering NUnit 2.4.7

    It's interesting that a flurry of releases of testing frameworks have been released lately with Gallio, xUnit.net and of course NUnit.  Charlie Poole recently announced on a lot of the discussion boards I belong to recently that NUnit 2.4.7 was recently released.  You can read all about what's been added here with the release notes. 

    What's New and Interesting?

    What's interesting about this release?  Well, NUnit no longer depends on log4net, thus getting rid of some dependency issues with regards to the applications under test.  What's also interesting is that addition of the RowTest extension to allow  multiple sets of arguments to be given to a test.  This is the first one that's ever been incorporated into the core of NUnit.

    Static Tests in NUnit?

    As Andy Stopford noted in my blog yesterday regarding xUnit.net, Charlie recently checked in code to allow static methods for static methods to be tests as well as Setup and TearDown to be static as well.  Jim Newkirk, the man behind NUnit and co-creator of xUnit.net, favors that approach of allowing statics.  To me, I don't care as much with regards to Startup and TearDown with statics as most of my statics for testing F# is side effect free programming.  As it should be with functional programming.  Anyhow, what I'd like to see in NUnit is the support for something that I can do in xUnit.net:

    #light

    #R @"D:\Program Files\NUnit 2.4.7\bin\nunit.core.dll"
    #R @"D:\Program Files\NUnit 2.4.7\bin\nunit.framework.dll"

    open NUnit.Framework

    let rec fib n =
      match n with
      | 0 | 1 -> 0
      | n -> fib(n-2) + fib(n-1)
      | n when n < 0 -> failwith "Cannot be less than zero"

    [<TestFixture>]
    let FibOfOneShouldReturnZero() =
      let fibResult = fib(1)
      Assert.AreEqual(fibResult, 0)


    If I saw something like this, I'd be a happy man.  But until then, I can dream...

    Conclusion

    Go ahead and pick up your copy today of NUnit.  It's been the old standby for many of my projects throughout my career and served me quite well.  Next time I'll cover Gallio a little bit as I have neglected it, but it's a huge release.


    kick it on DotNetKicks.com

    Read more...