Posts
58
Comments
103
Trackbacks
10
July 2007 Entries
Oklahoma Rocks

Move over Cleveland!  I must say that attending the recent Oklahoma Code Camp was one of the best decisions I've made in quite some time.  Raymond Lewallen managed to line up a set of rockstar speakers.  Thanks Ray!

It was great finally putting faces to names (Dave Laribee) while getting the chance to meet some of the people who have greatly influenced me in my day-to-day programming (Scott Bellware).  There was some serious Agile brain-trust at the event, and I managed to make some new connections (Dave Nicolette) which I think will prove very valuable over the long run.

I think Ben summed my feelings up the best.  Meeting a group of like-minded people has really solidified my beliefs.  The networking aspect alone was worth the price of a plane ticket and a hotel room.  I'm coming away a much stronger developer. 

Passion is contagious--the .NET community beware.

posted @ Monday, July 30, 2007 8:15 PM | Feedback (4)
Announcement: Agile in the Enterprise Talk

When: Monday, August 20th, 2007 @ 6pm

Where: The Nashville Agile Users Group

Location: Qualifacts at 2nd and Demonbreun (map) Give Joe Dickason a call at 615-618-6619 as he will be letting people in the building.

What: I will be giving a talk on Agile in the Enterprise. This includes a look at what agility and embracing change mean to application integration and one avenue to approach this tough problem. This will include a brief introduction to the enterprise service bus, messaging, and SOA.

posted @ Friday, July 27, 2007 4:33 PM | Feedback (0)
Book Review: Designing Object-Oriented Software

Considering this book was published more than 17 years ago, I'd say that the fact that it is still relevant today is an amazing tribute to both object-orientation as a programming paradigm and the concept of responsibility-driven design (which was introduced in this book).  Overall, however, I might suggest a .NET developer start with another book on object-oriented analysis and design.  This particular book tends to focus heavily on multiple inheritance, which is currently not available to those of us working in a managed world.  It does, however, give us a very good look at building an object-oriented application.  It introduces the concepts of classes, responsibilities, collaborations, subsystems, and object hierarchies quite well.  Some of the examples tend to be a bit exhaustive on detail (printing the actual CRC cards of the design), but I think this would be useful for a budding OO designer.  In short, this book is a classic, and it belongs on the shelf of every thoughtful designer.  I will be reading Rebecca Wirfs-Brock's newer book shortly, so I will let you know how they compare.

posted @ Wednesday, July 25, 2007 9:29 PM | Feedback (0)
Example: Inheritance vs Object Composition

If you pick a developer off the street and ask him what inheritance is, he will more than likely give you the correct answer.  If you take that same developer and ask him what object composition is, he may give you a puzzled look and shrug his shoulders.

Fundamentally, both are ways of extending your application.  Composition is preferred and inheritance is mostly just abused.

Extension By Inheritance

For our first code example, we are going to be extending a class in the .NET framework, the System.Random class.  You've probably used it to build a password generator in your application.  The object as it exists in the framework is only capable of choosing random numbers, but we can very easily extend it to choose pretty much anything at random.

    public class ExtendedRandom : Random, IRandom
    {
        public T Next<T>(IList<T> items)
        {
            int randomIndex = Next(0, items.Count - 1);
            return items[randomIndex];
        }
    }


As an interesting side note, many developers don't think to inherit from things in the framework.  You can actually get some really cool stuff that way.

The System.Random class doesn't implement an interface or abstract class by default, but since we are extending it by inheritance already, we can extract an interface and create an interface adapter at the same time.  Yep, it's a two-for-one special.  The interface buys us Test-Driven goodness.

    public interface IRandom
    {
        T Next<T>(IList<T> items);
        int Next();
        int Next(int minValue, int maxValue);
        int Next(int maxValue);
        double NextDouble();
        void NextBytes(byte[] buffer);
    }


Yes, it was that simple, but now what about composition?

Extension by Delegation (aka Object Composition)

Now that we have a nice random implementation, building a password generator is a cinch.  Our generator will use an IRandom to do its job.  This delegation of responsibility (random selection of numbers and characters) is at the heart of object composition. 

Here is what we want for our end product:

    public interface IGenerator
    {
        string Generate();
    }


Here's our [very simple] implementation:

    public class RandomGenerator : IGenerator
    {
        public RandomGenerator(int minLength, int maxLength, IRandom random, IEnumerable<char> characters)
        {
            _minLength = minLength;
            _maxLength = maxLength;
            _random = random;
            _characters = new List<char>(characters);
        }

        private readonly int _minLength;
        private readonly int _maxLength;
        private readonly IRandom _random;
        private readonly IList<char> _characters;

        public string Generate()
        {
            int length = _random.Next(_minLength, _maxLength);
            StringBuilder builder = new StringBuilder(length);
            for (int i = 0; i < length; i++ )
            {
                builder.Append(_random.Next(_characters));
            }
            return builder.ToString();
        }
    }


Viola!  We now have a very simple password generator which clearly exposes the difference between these two fundamental concepts in object-orientation.  If we check our classes against the other basic principles (Single Responsibility, Open/Closed Principle, etc), we see that we are in the clear.

Where do we go from here?

Let's build simple Password and PasswordFactory classes.  For this demonstation, we won't add any behavior to the Password class, but you can bet that we would for our real application.  Encapsulation is one of the fundamental concepts of object-orientation.  In a nutshell, encapsulation is the grouping of data and the methods which manipulate it into a single object.  Data without behavior is an object-wannabe.

Here's our first run of the Password:

    public interface IPassword
    {
        string Value { get; }
    }


And the [non-OOP] implementation:

    public class Password : IPassword
    {
        public Password(string value)
        {
            _value = value;
        }

        private string _value;

        public string Value
        {
            get { return _value; }
        }
    }


Pretty simple stuff, but how do we connect our IGenerator to our Password?  Enter the factory.  Here's our end goal:

    public interface IPasswordFactory
    {
        IPassword Generate();
        IPassword Create(string value);
    }


And now we tie it all together with composition:

    public class PasswordFactory : IPasswordFactory
    {
        public PasswordFactory(IGenerator generator)
        {
            _generator = generator;
        }

        private readonly IGenerator _generator;

        public IPassword Generate()
        {
            return Create(_generator.Generate());
        }

        public IPassword Create(string value)
        {
            return new Password(value);
        }
    }


Bingo!  We check off our principles of OOP, make sure all our unit tests are passing and call it a day!  Since all of our implementations depend on interfaces (and we didn't couple any implementation to another implementation), we now have a loosely-coupled subsystem for our application.  We can lean on a dependency-injection tool (such as StructureMap, Castle Windsor, or Spring.NET) to wire things together for us at runtime.

If you look closely, you might also notice the Strategy Pattern.  Yep!  The IGenerator is a strategy! 

If you look even closer, you might notice that the IPasswordFactory gives us a boundary to this subsystem in our application.  Any other part of the application which deals with passwords will only have to deal with this one type.  This simplification of relationships inside our application makes our application easier to maintain and understand.

posted @ Monday, July 23, 2007 11:05 PM | Feedback (8)
NHibernate SysCache Issues - Solved

I wanted to post this in case anyone down the road hits this issue.  It took a while to track down.  First, a little background:

The app is running NHibernate 1.2.0 in ASP.NET on Windows Server 2003 Enterprise.  Given that it's just a development environment, we chose to run the database server (Sql Server 2000) and the application (inside IIS) on the same machine.  This is while we wait for our new development servers to arrive.

The Problem

We had been running NHibernate perfectly in both development and production environments until last week, when caching started freaking out in development.  The application would be running fine until some unknown event occurred, at which point the NHibernate cache (SysCache) would start failing.  All queries would be serviced from the database.  The first thing I checked was memory usage.  The IIS worker process was using just over 100 MB of RAM.  The server has 6 GB total, so I immediately dismissed the possibility of memory pressure.  The team went into crisis mode as the end of our current iteration is on the first of August (which is only a week away), and we had no idea what was going on.

After quite a bit of digging, I whipped out PerfMon to check the ASP.NET cache performance monitors.  At first, everything appeared completely normal (our Cache API Hit Ratio was 78%).  Then I saw a nice big spike in the Cache API Turnover Rate.  The Cache API Turnover Rate tells us the amount of additions and removals from the cache.  When I saw the turnover rate spike and the number of Cache Entries stay static, I knew that ASP.NET was to blame.  It was evicting items from the cache as fast as NHibernate could add them.  The question is why.

After much googling, I finally found the answer.  The issue lies in the way which ASP.NET calculates memory pressure.  By default, when the total memory usage reaches 90%, ASP.NET starts trimming objects from the cache.  In our case, even with 6 GB of RAM (and only 100MB of usage by IIS), we were hitting the memory pressure mark.  This was mostly due to the memory hog we call a database server and all the other little things sitting in memory.  In our case, we had just over 600 MB of RAM free, but 600 MB free is the 90% mark (roughly speaking).  Ouch.

Lessons Learned: 

  • ASP.NET Caching and SQL Server on the same box don't mix!  SQL Server doesn't play well with others.
  • PerfMon is one of your best friends. Specifically, the ASP.NET performance counters.
  • Pressure = (Total Memory - Available Memory) / Total Memory (Default Pressure Limit: 0.90)  -- You can check this in Task Manager.
  • I'll be looking to add an administrative alert of some sort to our production middle tier at 85%.
  • You can change this default by changing the Cache settings in your web.config (or machine).

A good technical explanation can also be found here:

http://blogs.msdn.com/praveeny/archive/2006/12/11/asp-net-2-0-cache-objects-get-trimmed-when-you-have-low-available-memory.aspx

And a quick note of thanks to Ayende for answering some crazy emails from me. ;-)

posted @ Monday, July 23, 2007 5:13 PM | Feedback (0)
The iPhone: Will It Blend?

So everyone and his brother wants an iPhone.  They look sexy and appear to be able to do nearly anything, but the question remains, will it blend?

posted @ Sunday, July 22, 2007 10:47 PM | Feedback (1)
Oklahoma City Code Camp

I've been planning to attend the Oklahoma City Code Camp this coming weekend (July 27th) and finally booked my flights this weekend.  I have to say that this event is looking like quite the bash.  There are a number of names I'm looking forward to putting faces with.

Here's the shortlist:

David Laribee
Scott Bellware
Jean-Paul Boodhoo
Raymond Lewallen
Ben Scheirman
Jon Box

I was really looking forward to meeting Jeremy Miller, but it appears as though he's had to make a last minute cancellation.

There are lots of great sessions for the Agile/ALT.NET track.  Here is the agenda.

posted @ Sunday, July 22, 2007 1:56 PM | Feedback (1)
Tip: Impact Analysis Using the ObsoleteAttribute

Here's a quick trick I like to use when doing impact analysis on changing a type or member.  Instead of using the usual Find All for usages of the item, you can apply the ObsoleteAttribute instead.  By default, it will generate a compiler warning in each place where the obsolete member or type is used.  By setting the Error property to true, you can generate a compile error for each usage.

So, next time you have to make a fairly deep change to the system, and you want a quick way to gauge the impact, I suggest applying the ObsoleteAttribute to the member, setting the Error property to true, and doing a quick compile.  You will very quickly have a nice list of places in the application which will need to be updated.

One word of caution, there is one undocumented "feature" with this attribute.  If you leave it in your code during deployment (with Error property set to false obviously), the XmlSerializer will silently remove the obsolete member from your WSDL (like using the XmlIgnoreAttribute).  Watch out for that if you are working in a system with legacy WebServices.

posted @ Friday, July 20, 2007 6:31 PM | Feedback (0)
Agile Process Maturity

Our software development team was hit by a six sigma black belt today.  It came in the form of a lengthy process-maturity survey.  Needless to say, while we have many processes in place, we have a lack of formalism in terms of documentation.  This was quite apparent in our response to their survey.  While it seems to me that the end goals of an agile development process and a six sigma process are in unison, they appear (at least to me anyway) to take two different vehicles to get there.  Let's examine the core values of agility:

We Value:

    • Individuals and Interactions over processes and tools
    • Working software over comprehensive documentation
    • Customer collaboration over contract negotiation
    • Responding to change over following a plan

While there is value in the items on the right, we value the items on the left more.

A few items in particular seem incompatible to me.  By its very nature, six sigma seems to very much put process at its heart.  This includes defect measurement, comprehensive documentation (the next point), and following the plan (the final point).  This feels like going against the grain to me.  I do feel like certain agile practices, however, are very complementary to the six sigma goal of waste and defect reduction.  In particular, the use of test-driven development to bake in quality and reduce unnecessary cruft, the application of continuous integration for a repeatable build process, the close alignment of developers and business stakeholders for reduced waste and inefficiency, and a short, iterative release cycle for delivering incremental business value.  Ultimately though, I am not a Six Sigma practitioner and have not studied their teachings.  I do think, however, that we looked a lot worse on paper than is the case in real life.

I would ask you, dear reader, where is the intersection of Agile Development, Six Sigma, and CMM?  Have you had any experience with these practices in your current or former project?  Does Six Sigma or CMM embrace change?

posted @ Friday, July 20, 2007 1:47 AM | Feedback (1)
Book Review: Interface-Oriented Design by Ken Pugh

This was my second time through this book and overall I have to say that I enjoyed it.  Including the appendix, the book is just over 200 pages.  This makes it one of the shorter books I have on software design.  It's also one of the most readable.  Don't let its readability and shortness mislead you, however.  It addresses a topic which is both powerful and often overlooked, the power that interfaces have on application design.  If you are in the habit of practicing test-driven development, you have a good idea of what I'm referring to.

The content of the book does a good job covering the subject matter.  He compares and contrasts interface-based composition with inheritance, stateful vs stateless interfaces, translation between stateful and stateless interfaces, and a whole host of other relevant topics.  Some of the more interesting points in the book were: interfaces as object roles, fluent interfaces, procedural vs document-based interfaces, and a small introduction to some of the commonly used GoF patterns.  The topics on document-based interfaces were particularly relevant to my current project and his ability to sneak some SOA material in the appendix (and one of the examples) was also welcome.

If I had to classify this book, I would say that it's a light read if you are familiar with the basics.  It will be a bit tougher otherwise.  It isn't terribly in-depth, but it does bring to light a number of topics (ie.. breadth over depth).  If you need a breather from that pile of textbooks on your desk, this would be a good choice.

posted @ Friday, July 20, 2007 12:55 AM | Feedback (0)
On Animal Taxonomy and Inheritance Hierarchies

As object-oriented developers, we are told to prefer composition over inheritance.  But why?

As Ken Pugh states, refactoring into a hierarchy is much easier than refactoring out of a hierarchy.  Starting down the interface-based route, you can get a feel whether inheritance is a better implementation option without actually committing.  This holds true especially since inheritance is often abused.

A funny real-world parallel to this problem in software development is the naming of animal taxonomy.  There is/was great discussion around renaming all the animals in the world.  You see, the current naming system (the Linnaean system) uses a set of suffixes depending on the classification (ie... -ae).  The problem is that as new species are discovered, they have caused ripple effects in the hierarchy.  Adding a new parent into the hierarchy causes the children to change names (ie..the suffixes).  This wreaks havoc on biology books, search engines, and a whole host of other non-related items (including legislation such as the one which protects endangered species).  Needless to say, there are very real monetary effects to such a renaming.

This struck me as funny given that the same effect can be seen in software development.  Prematurely using inheritance can cause lots of problems, including ripple effects on dependent classes.  Many times this occurs as business requirements change (ie.. new species are discovered) or relationships are clarified.

I guess the biologists should take a lesson from OOP.  They should have chosen composition over implementation inheritance. ;-)

posted @ Sunday, July 15, 2007 1:50 PM | Feedback (3)
Getting Your Feet Wet with Messaging

I wanted to do a quick writeup about getting started with messaging.  First off, know that messaging looks odd.  It looked really odd to me the first time I saw it.  That was enough to get my curiosity up, and that's all it took.  I can say that learning messaging is a bit tough.  There's a lot to learn.  The transition in thinking from RPC to messaging is akin to the transition from procedural code to object-orientation.  That being said, if you have an interest in architecture or even the buzzword of the month, SOA, I highly recommend the following starting points.

First, Udi Dahan, a Microsoft Solutions Architect MVP, has a no BS look at SOA and messaging.  He touches on many factors and generally nails everything on the head.

Why you can't do SOA without messaging

Secondly, I'd like to direct your attention to a presentation given by Gregor Hohpe, a very well-known author and architect at Google.

Developing in a Service-Oriented World

Finally, pick up a copy of Gregor's book, Enterprise Integration Patterns.  It will show you how to do SOA properly and gives you a clear understanding of why SOA isn't just a Stupid Overhyped Acronymn.

If you, dear reader, have any links to share, please feel free to drop them in the comments.

posted @ Saturday, July 14, 2007 11:52 AM | Feedback (0)
It's Official: D-Day 2008

It was officially announced today.  February 27th, 2008 is D-Day.  No, it's not the end of the world.  Just the end of the world as we know it.  I'm officially titling February 27th "Deprecation Day."  Microsoft announced it as the date for launching Windows Server 2008, Visual Studio 2008, and Sql Server 2008.  That officially deprecates at least 60% of your brain.  I hope you have been diligently memorizing the latest WWFULOLRTFM api from Redmond, otherwise you will just be completely out of date.

The Press Release

What do you mean you aren't worthless?  You mean you have been investing in platform-neutral knowlege and shielding your application from change with abstraction?  That's just sexy.

Oh yeah, and those unit tests will come in pretty handy after you recompile with the new compiler, migrate the database, and deploy to a new OS.

posted @ Wednesday, July 11, 2007 9:53 PM | Feedback (0)
Wow, Smells Like Something Died

I was just working through a quick test when I hit a really nasty smell in the framework:

Starting the MbUnit Test Execution
Exploring TestStuff, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
MbUnit 1.0.2531.41788 Addin
Found 1 tests
[failure] SerializationTest.XmlListAdapter_ShouldSerializeWithSpecialNames
TestCase 'SerializationTest.XmlListAdapter_ShouldSerializeWithSpecialNames'
failed: To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. TestStuff.XmlListAdapter`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] does not implement Add(System.Object).
System.InvalidOperationException
Message: To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. TestStuff.XmlListAdapter`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] does not implement Add(System.Object).
Source: System.Xml

StackTrace:
at System.Xml.Serialization.TypeScope.GetEnumeratorElementType(Type type, TypeFlags& flags)
at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
C:\test\TestStuff\TestStuff\SerializationTest.cs(22,0): at TestStuff.SerializationTest.XmlListAdapter_ShouldSerializeWithSpecialNames()

Ouch!  That's one of the worst design violations I've come across in quite a while.

If you implement IEnumerable or IEnumerable<T>, you must also expose an Add() method on your object in order for it to be XmlSerialized.  That's quite the Gotcha!

posted @ Sunday, July 08, 2007 4:17 PM | Feedback (0)
DevLink 2007 in Nashville, TN (Oct 11/12)

I never been a big conference attendee (I'd rather spend $2k + travel expenses elsewhere), but I just wanted to highlight an upcoming conference here in Nashville, DevLink 2007.

DevLink is still new (this is year 2), but it's going to give all the big shows a run for their money.  Here's a few speaker highlights:


Brad Abrams

"Brad Abrams was a founding member of both the Common Language Runtime, and .NET Framework teams at Microsoft Corporation where he is currently the Group Program Manager for the UI Framework and Services team which is responsible for delivering the developer platform that spans both clients and web based applications as well as the common services that are available to all applications. Specific technologies owned by this team include ASP.NET, Atlas, and Windows Forms. Brad has been designing parts of the .NET Framework since 1998 when he started his framework design career building the BCL (Base Class Library) that ship as a core part of the .NET Framework. Brad was also the lead editor on the Common Language Specification (CLS), the .NET Framework Design Guidelines and the libraries in the ECMA\ISO CLI Standard. Brad has been deeply involved with the WinFX and Windows Vista efforts from their beginning. Brad co-authored Programming in the .NET Environment, and was editor on .NET Framework Standard Library Annotated Reference Vol1 and Vol2 and the Framework Design Guidelines.
[Shamelessly Stolen from .NET Rocks]

Rocky Lhotka

Rockford Lhotka is the author of numerous books, including the Expert Visual Basic .NET & C# Business Objects books. He is a Microsoft Software Legend, Regional Director, MVP and INETA speaker. Rockford speaks at many conferences and user groups around the world and is a columnist for MSDN Online. Rockford is the Principal Technology Evangelist for Magenic Technologies, one of the nation's premiere Microsoft Gold Certified Partners dedicated to solving today's most challenging business problems using 100% Microsoft tools and technology.

Scott Bellware (A Personal Favorite)

Scott Bellware is a .NET software professional living and working in Central Texas. He works primarily with C# focusing on object-oriented business applications, object-relational mapping and persistence, Test-Driven Development, and agile methodologies. He has been awarded MVP for C# in 2004, 2005, and 2006. Scott is the founder and leader of the AgileATX community of agile software practitioners in Austin. He founded the Austin .NET User Group in 2001, and served as chairman of the International .NET Association's Speaker Committee between 2003 and 2005. Scott teaches Test-Driven Development to .NET developers through a series of workshops presented in conjunction with .NET User Groups in the US and Canada.

Jean-Paul Boodhoo (Another Personal Favorite)

Jean-Paul S. Boodhoo is a .NET delivery expert who has been working with the .NET Framework since beta 1 of .NET 1.0. He spends his days working as an independent consultant; helping teams realize success through agile practices and pragmatic Behavior Driven Development techniques. He has a passion for sharing information on applied behavior driven development with .NET, and has written articles for Visual Studio magazine, DevX, Code, and MSDN that utilize BDD to pragmatically apply .NET. As well as presenting on popular podcast/screencast DotNetRocks and DNRTV Jean-Paul has had the opportunity to deliver webcasts for Microsoft on the topic of design patterns in the real world. He enjoys getting active in local user groups presenting ways that developers can harness the power of .NET to realize flexible, maintainable applications.He has a passion for empowering developers to break the stereotypical developer mold and take the effort to break into the developer community to make their own mark. His efforts in the community have earned him a Microsoft MVP award.

Ted Neward

Ted Neward is an independent software development architect and mentor in the Sacramento, California area. He is the author of a number of books, including "Server-Based Java Programming" (Manning), the forthcoming "Effective Enterprise Java" (Addison-Wesley) and "SSCLI Essentials" (OReilly) and co-author of "C# In a Nutshell" (OReilly) with Peter Drayton and Ben Albahari. He is also an instructor with DevelopMentor, where he teaches and authors both the Java and .NET curriculum. He speaks frequently for technology user groups (most often for the Sacramento Java User's Group), and writes technical papers for www.javageeks.com and www.clrgeeks.com. He currently labors on behalf of the University of California, Davis, architecting a rebuild of the Davis Accounting and Financial Information Services software system. Past clients include companies like Pacific Bell, EdFund, Synergex and Intuit.

Billy Hollis

Billy and Rockford Lhotka had the first VB.NET book on the market from Wrox Press. Since then, Billy has taught VB.NET classes and done consulting for major companies, as well as authoring (or co-authoring) at least 8 books on .NET. He is the MSDN Regional Director (RD) for Tennessee, and was RD of the year in 2001. He authors many articles, including a regular column at MSDN called Adventures in VB.NET

Ron Jacobs

Ron Jacobs is an Architect Evangelist in Microsoft's Architecture Strategy Team team based in Redmond, Washington.  After a long career as a developer, program manager for various Microsoft products and product manager for patterns & practices Ron became host of the Channel9 show ARCast. A popular conference speaker Ron brings together solid architectural content and a sense of humor together to help you succeed in building architecturally sound and secure applications.

Theses are only a few of the people I'm looking forward to hearing.  Here's a full list of the speakers along with the preliminary agenda.

So, you get to see all these great people along with the following:

  • Access to over 56 sessions, keynotes and additional chalk talks sessions
  • Meals included Continental Breakfast, Lunch and Snacks
  • Invitation to the Friday night social and dinner featuring comedian Rik Roberts
  • Free internet access available via wireless or connection lounge
  • Conference DVD with presentations, product demos and more
  • Opportunity to win an invitation to the V.I.P. dinner to meet the speakers (restrictions apply) 
  • Eligible to win prizes like software, books and maybe even a gaming system
  • Conference t-shirt and more

I'm not sure what else you could ask for, but there's more!

Full conference passes are only $50.  Yes, you read that right.  You get all that for only $50.

Given that Nashville is within 600 miles of 50% of the US population, that means it's probably close enough for you to attend.  I'd recommend checking out Southwest for airline tickets, they fly in and out of Nashville and are dirt cheap.  They don't get listed on Expedia, etc, so you have to check their site directly.  I'd recommend getting a hotel in West End (which is near a lot of nightlife).

Shoot me an email if you're heading this way.  I'll show you around town.  Nashville kicks ass!

Come join me here in Nashville on October 12th and 13th.

Oh, and did I mention the blogging contest?  Seriously though, I'm not sure why I'm telling you guys this.  The less of YOU that show up, the more face time I get with the presenters. ;-)

Hopefully this post can drag some people here for the conference.

posted @ Saturday, July 07, 2007 5:21 PM | Feedback (3)
Now That's Funny

So I spent a good bit of time this week in the MSDN forums.  If you've never visited, there's a forum for almost anything related to .NET development.  It's a great place to ask hard questions, as there are plenty of MVP's and Microsoftie's there.

Here's one of the conversations I caught this week:

Gokulan:

Hi All

I am trying to generate code from one of my xml schema using Xsd.exe.

it throws the following error:

C:\>xsd C:\statement.xsd /c /l:cs
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.
Error: Error generating classes for schema 'C:\statement'.
  - Group 'value' from targetNamespace='http://www.xyz.com/statement' has invalid definition: Circular group reference.

If you would like more help, please type "xsd /?".

Is there any solution for the problem with Circular group reference?

Stan Kitsis - MSFT:

Hi,

I'm not sure what kind of a solution you are looking for.  Circular group references are not allowed by the XML Schema spec: http://www.w3.org/TR/xmlschema-1/#coss-modelGroup

Stan Kitsis

Gokulan:

Hi Stan,

Thanks for your time.

Fancois Payette:

I am having a related problem. Xsd.exe croaks with invalid definition: circular group reference on the xhtml1-transitional.xsd. www.w3.org/2002/08/xhtml/xhtml1-transitional.xsd
you'd expect the w3 schema to follow the spec?

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1596582&SiteID=1

Now that's what I call funny. ;-)

posted @ Saturday, July 07, 2007 1:42 PM | Feedback (0)
Some Groundrules for Interfaces

I'm in the middle of rereading Ken Pugh's Interface-Oriented Design.  Consider this part note taking, part commentary.

  • An interface implementation shall do what its method says.
    • DO make the intent clear by the method name.
    • AVOID double negatives and vagueness.
  • An interface implementation should do no harm.
    • DO make reasonable use of system resources.
    • AVOID retring failed operations.  Don't get caught in a long chain of fail/retry operations.
  • If an implementation is unable to perform its responsibilities, it should notify its caller.
    • DO use exceptions for exceptional situations
    • AVOID exceptions that leak implementation details (ie.. encapsulate a file not found exception with something like ConfigurationSourceNotFoundException when building an implementation of IConfigurationStore).
  • Implementations should be tested with their contract.
    • DO practice unit testing (or even better) Test-Driven Development
    • AVOID "white-box" testing (writing tests against the guts of an implementation) where possible.

In my personal development, I have found 3 primary types of interfaces.

Interfaces Modeling Object Characteristics

A characteristic is a property or cluster of properties that you see repeated over and over again.  A Name or Id property is probably a good example.  A useful example of how to leverage this would be with a generic hashtable object.  You can build a HashSet<T> where T : INameable, and expose a Get(string name) property off the set.  You could also provide an implementation which uses the name as the hashcode instead of the object's GetHashCode.  This is useful for deduping items.

In a nutshell, introducing an interface with the common property cluster allows you to write generic classes/methods which manipulate, aggregate, group, or process based on the common properties.

Interfaces Modeling Object Capabilities

This is very useful for things such as the strategy pattern.  IComparable<T> and IEnumerator<T> are two very good examples of this.

Interfaces Modeling Complex Roles or Entities

Your typical business entity is a good example for this.  An ICustomer interface is considered a "fat interface" and therefore not as reusable as the others, but it still enables us to loosely couple.  This is a very good thing.

What's a good interface look like?

I'll stick with Juval Lowy's recommendation.  Five is a good round number of members to see on an interface.  Going lower would promote more reuse, but it would also mean building more interfaces.  There's a reuse/maintainability tradeoff there.

As for the ratio of properties to methods, Juval recommends a 2:1 ratio.  This means there should be roughly twice the number of methods.  This excludes, of course, property-only interfaces (as described above).

While the actual numbers are debatable (and will vary by application), it does give one somewhat of an indicator to go by.

If you are having trouble with the ratio of methods to properties, I might suggest reading up on the "Tell, Don't Ask" principle.

posted @ Tuesday, July 03, 2007 7:22 PM | Feedback (3)
Compuware Thought Leadership Presentation

I wanted to say thanks to the guys that dropped by my presentation last week.  I'm also going to drop my powerpoint here in case anyone else is interested.

There's a lot of material on object-oriented design, leading up to Dependency Injection.

Grab the powerpoint from here.

In retrospect, I think I will break this presentation up next time.  It covers too much material for a single presentation.

posted @ Monday, July 02, 2007 9:59 PM | Feedback (1)
Curiosities of the Framework

Working with Resharper and programming to interfaces, I have stumbled across a number of interesting interfaces in the framework.  Some of them are easy to determine their purpose.  Others are a bit harder.  Here are two interesting ones I've run across in the past few days:

System.IServiceProvider
Defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.

public interface IServiceProvider
{
    // Methods
    object GetService(Type serviceType);
}

System.ComponentModel.Design.IServiceContainer
Provides a container for services.


[ComVisible(true)] public interface IServiceContainer : IServiceProvider { // Methods void AddService(Type serviceType, ServiceCreatorCallback callback); void AddService(Type serviceType, object serviceInstance); void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote); void AddService(Type serviceType, object serviceInstance, bool promote); void RemoveService(Type serviceType); void RemoveService(Type serviceType, bool promote); }

Both of these screamed Dependency Injection Inversion of Control when I first saw them.  The Promote variable indicates whether the container will "promote" the service to it's parent container. 

The reference to ServiceCreatorCallback is an interesting design.  In this particular case, the author chose to use a delegate instead of an interface for his factory method.

[ComVisible(true), HostProtection(SecurityAction.LinkDemand, SharedState=true)]
public delegate object ServiceCreatorCallback(IServiceContainer container, Type serviceType);


The choice of delegate over interface actually promotes looser coupling.  It means the factory object does not have to implement the particular interface.  Given a factory object you can't change, if you go the interface or abstract class route for the contract, you have to create an Adapter.  Using the delegate route, you just create the delegate.  Of course, you could always go the crazy route by using an interface (IMyFactory) and creating a Adapter which uses a delegate (MyFactoryAdapter) to invoke the object it's adapting (OtherFactory). lol

Here's a fairly dated, but very cool article on The Truth About Delegates.

posted @ Monday, July 02, 2007 5:03 PM | Feedback (2)
Refactoring the Design

This comes on the heels of my last post.  The design from my previous post works well, but there were a couple trouble spots.  I'll point them out:

The input message was also the output message

This works well for small applications, and messages which don't take a large amount of data.  However, if you ever run into that situation where you have data you don't want passed back out (request data), you will quickly find yourself nulling out portions of the request.  This defeats the entire reason for returning the request.  In short, it enables the client to validate that the request that was received was the same as the request that it sent.  It can also help when you are working with a new integration partner for the first time.  As an example, if they can see that the data they are passing you is malformed, that elminates an entire debugging/tracing session for you.  The problem occurs when the message is large (say, several megabytes) and you don't want to let this overburden the network.

The request handler implies a synchronous invocation

This is more a topic of scalability and flexibility in how your service receives messages.  In a best case scenario, you should be able to handle both asynchronous and synchronous requests (or simply asynchronous requests along).

Here's the new interface:

    public interface IRequestHandler<T>
    {
        void Handle(T request, IMessageChannel channel);
    }

Removing the return value means we must have another way to return the response.  That's where our IMessageChannel comes in.

    public interface IMessageChannel
    {
        void Reply(Response response);
    }


When we go to add the asynchronous communication to our service, we won't need to change our Handlers.  In addition, we can expand on the MessageChannel with a Publish method.  This will enable our application to expose a publish/subscribe mechanism.  The nice thing about having the Publish message attached to the MessageChannel, is that we can now correspond publishes with the requests that initiated them.  This will be useful if we want the originator of the event to be filtered from the event itself (ie.. UpdateCustomerAddressRequest, CustomerAddressUpdateNotification).

For our webservices, we will keep things simple:

    [WebService(Namespace = "http://tempuri.org/")]
    public class Service : WebService
    {
        public Service()
        {
            _service = DependencyContainer.Resolve<IService>();
        }

        private readonly IService _service;

        [WebMethod]
        public PingResponse Ping(PingRequest request)
        {
            return (PingResponse) _service.SendAndReceive(request);
        }

        [WebMethod]
        public HelloResponse Hello(HelloRequest request)
        {
            return (HelloResponse)_service.SendAndReceive(request);
        }

        [WebMethod]
        public UnitOfWorkResponse ProcessWork(UnitOfWorkRequest request)
        {
            return (UnitOfWorkResponse) _service.SendAndReceive(request);
        }

        [WebMethod]
        public Response Process(Request request)
        {
            return _service.SendAndReceive(request);
        }
    }


For the implementation of the service, we are also very simple:

    public class Service : IService
    {
        public Response SendAndReceive(Request request)
        {
            Type messageType = request.GetType();
            Type handlerType = typeof(IRequestHandler<>).MakeGenericType(messageType);
            object handler = DependencyContainer.Resolve(handlerType);

            ReplyContainer channel = new ReplyContainer();
            object[] args = {request, channel};

            handlerType.GetMethod("Handle").Invoke(handler, args);

            Response response = channel.Response;
            if (response != null)
            {
                response.CorrelationId = request.RequestId;                
            }
            return response;
        }
    }

public class ReplyContainer : IMessageChannel { private Response _response; public Response Response { get { return _response; } set { _response = value; } } public void Reply(Response response) { _response = response; } }


You'll notice that we can enforce setting the correlation id inside the service.  This keeps us developers from forgetting to set the value inside a handler by accident.  A response timestamp might also be a useful common property to add.

One last code snippet: the new Unit Of Work

    public class UnitOfWorkHandler : IRequestHandler<UnitOfWorkRequest>
    {
        public UnitOfWorkHandler(IService service)
        {
            _service = service;
        }

        private readonly IService _service;

        public void Handle(UnitOfWorkRequest request, IMessageChannel channel)
        {
            List<Response> responses = new List<Response>(request.Requests.Length);
            for(int i = 0; i < request.Requests.Length; i++)
            {
                responses.Add(_service.SendAndReceive(request.Requests[i]));
            }
            UnitOfWorkResponse result = new UnitOfWorkResponse();
            result.WasSuccessful = true;
            result.Responses = responses.ToArray();
            result.Request = request;
            channel.Reply(result);
        }
    }

I'll attach the working proof of concept for anyone who's interested.

posted @ Sunday, July 01, 2007 10:27 PM | Feedback (0)