Try-Catch-FAIL

Failure is inevitable.

Client-Side Validation with ASP.NET MVC 2.0 Futures

clock March 12, 2010 16:26 by author Matt

Just a quick post to hopefully save others some time.  ASP.NET MVC 2.0 has built-in support for client-side validation, but it doesn’t work with the expression-based BeginForm HtmlHelper methods that are available in the ASP.NET MVC Futures assembly.  I also don’t like that I have to call a separate helper method to set my form up for validation.  To address these two limitations, I wrote my own extension method:

public static class ValidationHelper
{
    private const string LAST_FORM_ID_KEY = "_lastFormId";

    public static MvcForm BeginValidatedForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action)
            where TController : Controller
    {
        helper.EnableClientValidation();

        var id = GetNextFormId(helper);

        TagBuilder builder = new TagBuilder("form");
        string str = helper.BuildUrlFromExpression(action);
        builder.MergeAttribute("action", str);
        builder.MergeAttribute("method", "POST");
        builder.GenerateId(id);
        helper.ViewContext.HttpContext.Response.Write(builder.ToString(TagRenderMode.StartTag));

        var form = new MvcForm(helper.ViewContext);

        helper.ViewContext.FormContext.FormId = id;

        return form;
    }

    private static string GetNextFormId(HtmlHelper helper)
    {
        int count = (int) (helper.ViewContext.HttpContext.Items[LAST_FORM_ID_KEY] ?? 0);
        count++;

        helper.ViewContext.HttpContext.Items[LAST_FORM_ID_KEY] = count;

        return string.Format("form{0}", count);
    }
}

Now you can simply do like this:

<h1>Sign-up</h1>

<p>Signing up is easy <em>and</em> free!</p>

<% using (Html.BeginValidatedForm<SignupController>(c => c.Create(null)))
{ %>
    <fieldset>
        <div>
            <p>1) Choose a username:</p>
            <%=Html.EditorFor(m => m.Username) %><%=Html.ValidationMessageFor(c => c.Username) %>
        </div>
        <div>
            <p>2) What's your E-mail address? <span class="note">(<a href="#">Why do we need this?</a>)</span></p>
            <%=Html.EditorFor(m => m.Email)%><%=Html.ValidationMessageFor(c => c.Email) %>
        </div>
        <%=Html.SubmitButton("submit", "Start Raging Now!") %>
    </fieldset>
<%} %>

and get client-side validation (assuming you’ve set everything else up correctly).

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Vote for me at CodeStock!

clock March 12, 2010 03:21 by author Matt

Voting is now open for CodeStock 2010 sessions!  I have three sessions submitted this year.  If you live in the Southeast, this conference is a real steal.  Early registration is just $55.  That’s $55 for a two-day conference, “buffet style” lunches, and a shirt.  Not bad!  If you register early, please consider voting for my sessions if they sound interesting to you:

Reducing Coupling through Inversion of Control, Dependency Injection, and Event Aggregation with StructureMap

Adding powerful search capabilities to your application with Lucene.NET and NHibernate Search

Improve your unit tests - a practical guide to Moq

Also be sure to check out James “poprhythm” Kolpack’s sessions as well:

Parallel Computing in .NET 4 with Visual Studio 2010

Windows PowerShell Introduction

Thanks, and I hope to see you at CodeStock!

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Two things missing from C#

clock March 11, 2010 08:07 by author Matt

While building some ugly code to walk the Lucene.NET Query graph, I found myself needing two bits of functionality from C# that it sadly doesn’t provide.  There are arguments for and against each of these, but they certainly would have saved me some pain today.

Switching off of System.Type

The Lucene query graph is a nasty beast.  There’s an abstract base Query class, but no common way to iterate through the graph and extract criteria.  Instead, you have to process each concrete type separately.  An easy way to do this would be to use a switch statement off of the concrete query type and execute the corresponding logic to process the type.  Unfortunately, the C# switch statement only supports types that are convertible to Integer (and strings).  There are solutions, such as this, but why isn’t it built in to the framework?  Peter Hallam explains the reasons, but I don’t agree with most of his argument. Visual Basic’s equivalent of a switch statement allows for case statements to “overlap”, and it doesn’t seem to be causing catastrophic problems there.  I think it’s actually quite intuitive to expect that only the first matching case statement would be executed.  In any case, I’d love to see this added to C#.

Using ‘yield return’ to directly return an IEnumerable

The ‘yield return’ statement is incredibly useful, but I’ve found myself on multiple occasions using it to enumerate a hierarchical object graph.  In such situations, it’s quite annoying that I can’t just ‘yield return’ the entire child object IEnumerable list at once.  Instead, I have to manually iterate the child list and ‘yield return’ each result individually.  I see no reason (at all) why this extra step should be necessary.   Wes describes a possible way to implement this feature, and there’s a (closed as won’t fix) issue on Microsoft Connect with a slew of votes.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


A troublesome brew: NHibernate + FluentNHibernate + SQLite on .NET 4.0

clock March 9, 2010 15:20 by author Matt

Mixing NHibernate, Fluent NHibernate, and SQLite on .NET 4.0 RC will lead to some major headaches.  There’s an easy fix, but it doesn’t work if you are using Resharper’s test runner.  If you’re using my personal favorite test runner, TestDriven.NET though, the fix is actually quite easy. 

We decided to use .NET 4.0 for the new super secret social networking site we’re working on, and since we’re starting out with a relational DB under the hood (that we fully plan to swap out for a NoSQL alternative later), we’re using NHibernate.  I hate NHibernate’s XML maps, so we’re also using FluentNHibernate.  When I’m using NHibernate, I like to use SQLite’s in-memory database for my unit tests, so now we’re looking at making three pieces of OSS play nice together on a not-quite-finished version of the .NET Framework.  Oh, and I’m also using Resharper 5.0 EAP.  :)

Getting things started is easy enough.  I grabbed the latest production release of NHibernate along with a compatible version of Fluent NHibernate.  I also grabbed the latest SQLite .NET assembly.  After adding references to the required bits, here’s my NHibernate bootstrapper:

public static class NHibernateBootstrapper
{
    private static Configuration _currentConfig;

    private static FluentConfiguration ConfigureMappings()
    {
        return Fluently.Configure()
            .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
            .ExposeConfiguration(c => _currentConfig = c);
    }

    public static ISessionFactory CreateSessionFactoryForTests()
    {
        return ConfigureMappings()
            .Database(SQLiteConfiguration.Standard.ShowSql().InMemory())
            .BuildSessionFactory();
    }

    public static ISessionFactory CreateSessionFactoryForProduction()
    {
        return ConfigureMappings()
            .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("RageFeedData")))
            .BuildSessionFactory();
    }

    public static void CreateSchema(ISession session)
    {
        var exporter = new SchemaExport(_currentConfig);
        exporter.Execute(true, true, false, session.Connection, null);
    }

    public static void UpdateSchema()
    {
        var updater = new SchemaUpdate(_currentConfig);

        updater.Execute(true, true);
    }
}

And here’s my unit tests:

public abstract class InMemoryDatabaseFixture
{
    public ISession Session { get; private set; }

    [SetUp]
    public virtual void Prepare()
    {
        var factory = NHibernateBootstrapper.CreateSessionFactoryForTests();
        Session = factory.OpenSession();
        NHibernateBootstrapper.CreateSchema(Session);
    }

    [TearDown]
    public virtual void Cleanup()
    {
        Session.Dispose();
    }
}

[TestFixture]
public class RageletPersistanceTests : InMemoryDatabaseFixture
{
    [Test]
    public void CanCorrectlyPersistRagelet()
    {
        new PersistenceSpecification<Ragelet>(Session)
            .CheckProperty(r => r.Content, "Test content")
            .VerifyTheMappings();
    }
}

Simple enough, right? 

boom

Sadly, this fails gloriously when run with ReSharper’s test runner:

Mixed mode assembly is built against version 'v2.0.50727' of the runtime
and cannot be loaded in the 4.0 runtime without additional configuration information.

I found a solution, but it doesn’t work with Resharper 5.0 EAP.  I’m thinking that Resharper isn’t using the app.config file, but perhaps it’s something else.  Fortunately, running the tests with TestDriven.NET (my favorite test runner) worked perfectly.

Unfortunately, I wasted the better part of two weeks of “free time” trying to get things recompiled so that they would work without the app.config entry.  There are several breaking changes in .NET 4.0 apparently, and nothing that I tried worked.  Hopefully this isn’t a sign of pains to come. 

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Easily override ToString using Moq

clock February 23, 2010 05:40 by author Matt

I recently discovered a rather annoying limitation in Moq: you cannot setup expectations on the ToString method.  For a good discussion of the issue, check out Sean’s post.  His solution was to add ToString explicitly to the interface you are mocking, but I don’t want to dirty up my interfaces unnecessarily.  Fortunately, Moq does allow you to create mocks that implement multiple interfaces, so you could move the ToString method to a dummy interface, and use Mock<T>.As to setup expectations on the dummy interface.  That’s the approach I took, but I wrapped it up in a nice extension method:

public static class MoqExtensions
{
    public static ISetup<IToStringable, string> SetupToString<TMock>(this Mock<TMock> mock) where TMock : class
    {
        return mock.As<IToStringable>().Setup(m => m.ToString());
    }
    
    //Our dummy nested interface.
    public interface IToStringable
    {
        /// <summary>
        /// ToString.
        /// </summary>
        /// <returns></returns>
        string ToString();
    }
}

Now I can setup expectations on ToString by simply using:

[Test]
public void ExpectationOnToStringIsMet()
{
    var widget = new Mock<IWidget>();
    widget.SetupToString().Returns("My value").Verifiable();

    Assert.That(widget.Object.ToString(), Is.EqualTo("My value"));

    widget.Verify();
}
Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Extending Moq: returning multiple results via lambdas

clock February 22, 2010 05:06 by author Matt

I have on several occasions wished that I could setup expectations in Moq for subsequent calls to a method.  For example, I might want Moq to return one value the first time a method is called, but a different value the second and third times.  Phil Haack has a nice way to achieve this, but his implementation only allows you to return a result.  What if you need something more advanced?  What if you want to return a value on the first call, throw an exception on the second, and return a value again on the third?  I ran into exactly this situation while testing out some error-handling logic in a class.  Here’s how I achieved it.

public static class MoqExtensions
{
    public static IReturnsResult<TMockType> Returns<TMockType, TReturnType>(this IReturns<TMockType, TReturnType> expression, params Func<TReturnType>[] results) 
        where TMockType : class
    {
        int nextResult = 0;

        return expression.Returns(() => results[nextResult++]());
    }
}

This adds a new Returns method you can use with Moq in place of one of the built-in Return methods.  It allows you to specify an arbitrary number of Func’s to be executed.  Instead of using Moq to return the Func’s directly, it creates a new Func (via a lambda expression) that will iterate over the result Func’s specified.  It does this via a closure around the results and the index of the next result.  Note that it accepts a ‘params’ array, so calling it still looks (fairly) clean:

[Test]
public void ContinuesWorkingIfErrorEventIsHandled()
{
    mResultSet.Setup(r => r.GetNextResult()).Returns((Func<IResult>)(() => { throw new NotImplementedException(); }), () => null);

    //Run...
    
    mResultSet.Verify(r => r.GetNextResult(), Times.Exactly(2));
}

That’s all there is to it!

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Using StructureMap to provide strongly-typed access to AppSettings

clock February 11, 2010 10:19 by author Matt

I’ve been using StructureMap for the last couple of months.  I love it, and my only regret is that I didn’t start using it sooner.  I always felt like I wrote clean, testable code before, but I can see a noticeable improvement since jumping on the IoC container bandwagon. If you aren’t using an IoC container and are working on anything above a trivially simple app, you should look in to it. 

Anyway, I’m knee deep in rewriting our crawler infrastructure, and I found myself working with some classes that need access to external configuration data.  The config data is all fairly simple stuff, for example: “the path to plug-ins”, “the number of threads to use here”, “the amount of time to wait before timing out”.  We can argue about whether these things should actually be configurable outside of the code later, let’s just assume that they have to be for now.  Well, in certain configurations, our crawler pulls these settings from the app.config file.   In others, the settings are pulled from a configuration database.  That immediately means that the code can’t just reference ConfigurationManager.AppSettings, it needs to access an abstraction, we’ll call it a configuration provider.  Through the magic of IoC, all these configurable classes need to do is declare a dependency on this configuration provider, and the container will make sure they’re given whatever concrete config provider we have configured.  This is an improvement over our previous approach, where we were declaring our config provider at the top-level of the application, then passing it down, down, down the call stack to the implementations that actually needed it.  StructureMap has made things simpler, but it’s actually possible to improve things even further.

The very first version of our configuration provider abstraction looked something like this:

public interface IConfigurationProvider
{
    string this[string settingName]
    {
        get;
    }
}

Users of the provider (and by users here, I mean calling classes, not people) ended up sharing a lot of duplicate logic: extract a setting, make sure it’s there, try to convert it to the correct type, and substitute a default if all else fails.  We improved things a bit with the second version of the abstraction:

public interface IConfigurationProvider
{
    bool GetIntSetting(string name, out int holder, int defaultSetting);

    bool GetStringSetting(string name, out string holder, string defaultSetting);

    bool GetBooleanSetting(string name, out bool holder, bool defaultSetting);

    bool GetDoubleSetting(string name, out double holder, double defaultSetting);
    
    bool GetFloatSetting(string name, out float holder, float defaultSetting);
}

This is better, now callers can get their settings in a single line of code, but there was still a lot of repetitive logic across the various users.  There’s also a lot of magic strings in there.  These can be encapsulated in consts, but they’re still there.  Testing things that depend on these providers is also a little more difficult than it should be, though we do have a few classes to help. 

A better solution would not depend on strings, would remove the burden of extracting settings from the caller, and be easy to mock or replace for testing.  Perhaps something like this:

public class WidgetFactory
{
    ...
    public WidgetFactory(WidgetFactorySettings settings) 
    {
        this.Settings = settings;
    }
    ...
}

Here, my class is saying “I depend on this configuration data”, and it would be swell if the IoC container could populate it magically with the correct settings.  With just a small change, this actually becomes very easy to do:

public class WidgetFactory
{
    ...
    public WidgetFactory(IConfiguration<WidgetFactorySettings> config) 
    {
        this.Settings = config.Settings;
    }
    ...
}

The interface for the provider is quite simple:

public interface IConfiguration<TSettings> where TSettings : new()
{
    TSettings Settings { get; }
}

At run-time, the IoC container will try to find a type to satisfy this dependency.  No, you don’t have to create concrete types for everything that will ever need configuration data.  All you need is one generic type per configuration source.  Here’s a generic provider for extracting data from an app.config file:

public class AppConfigConfiguration<TSettings> : IConfiguration<TSettings> where TSettings : new()
{
    public TSettings Settings { get; private set; }

    public AppConfigConfiguration() : this(ConfigurationManager.AppSettings)
    {
    }

    //You can easily unit test this class by giving it a NameValueCollection.
    internal AppConfigConfiguration(NameValueCollection appSettings)
    {
        Settings = new TSettings();

        //Get properties we can potentially write from
        var properties = from prop in typeof (TSettings).GetProperties()
                         where prop.CanWrite
                         where prop.CanRead
                         let setting = appSettings[typeof (TSettings).Name + "." + prop.Name]
                         where setting != null
                         where TypeDescriptor.GetConverter(prop.PropertyType).CanConvertFrom(typeof (string))
                         let value = TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromString(setting)
                         select new {prop, value};

        //Assign the properties.
        properties.ForEach(p => p.prop.SetValue(Settings, p.value, null));
    }
}

This provider uses a little bit of reflection and a little bit of LINQ to do it’s heavy lifting.  It grabs all the public properties off of the generic TSettings type, then scans for values matching the format “{TypeName}.{PropertyName}”.  If a match is found, and the value can be converted to the property’s concrete type, it is assigned. 

We still need to give StructureMap a little bit of direction about how to resolve the IConfiguration<TSettings> type:

ObjectFactory.Container.Configure(
    config =>
    {
        //We want to pull our configuration data from the app.config file.
        config.For(typeof (IConfiguration<>)).Use(typeof (AppConfigConfiguration<>));
    }
);

Now, anything that depends on an IConfiguration<whatever> will receive an AppConfigConfiguration<whatever>.   If we want classes to pull their configuration data from a database instead, we simply adjust our StructureMap bootstrapping.  Nothing else in the entire system has to change.

So, there you have it: a strongly-typed, generic, IoC-friendly way to handle your configuration data.  Thoughts?

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


MLSharp 1.0 Alpha Released

clock February 7, 2010 05:41 by author Matt

I’ve finally written a little bit of documentation on MLSharp, fixed a few bugs/glitches, and packaged it all up into the first official release.  I consider the software Alpha quality (meaning it has known bugs, limitations, may set fire to your house, etc), but I have used it in several projects successfully.  Please give it a look, and let me know if you find it useful. 

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


A Newbie’s Experiences with NDepend

clock February 4, 2010 11:10 by author Matt

Disclaimer: Yes, I was given a pro license to NDepend.  However, what follows are my honest impressions of version 2.12.1 of the tool on a real .NET 3.5 project.  I have not evaluated the recent beta, so some of the issues noted below may be fixed in a more recent build. 

To Patrick Smacchia: I apologize for taking so long to provide feedback on NDepend.  I hope you find the feedback below useful.  Thanks for giving me the chance to check out this cool tool!

NDependHome

NDepend is a complex and powerful tool for static code analysis.  The basic idea is that you feed it your .NET assemblies, then you use the rich set of visualizations, Code Query Language (CQL) reports, and code coverage tools to analyze your codebase.  When I say “rich set of visualizations,” I mean it.  There are a slew of reports that are both eye-candy and useful at the same time.  Within a few minutes of analyzing my first project, I had already discovered useful information, including an obsolete class as well as a unit test that was missing it’s Test attribute. 

The power NDepend comes at a cost.  The interface is immediately overwhelming, and though there is ample documentation available online, it still takes a while to discover all the tool’s capabilities.  It also has a few quirks that can be irritating, and the UI feels a bit “glitchy” at times.  Despite these weaknesses, I found the tool to be immensely powerful (CQL is awesome), and I can definitely see where it will be handy in the future.  Read on if you want to know more.

Getting Started

When I launched NDepend, I notice that it looked and felt a lot like Visual Studio.  It had the familiar “Recent Projects” pane on the left as well as links to common actions.  There was a “Getting Started” pane with links to NDepend screencasts, and a button to install Visual Studio and Reflector integration.  It also had a pane that to let you know if an update is available, a small but nice touch.  I really like it when an application makes it easy for me to stay up to date.

Creating a new project was easy enough.  After creating my project, I was able to add assemblies using any of several methods.  I could drag-and-drop assemblies directly from Windows Explorer, I could add them manually by browsing, or (my favorite) I could add them by specifying a Visual Studio solution file.

Things took a turn for the strange here.  At first, NDepend reported that it was unable to load any of the assemblies for my solution.  It was nice enough to indicate why, apparently there were multiple versions of the assemblies buried in my solution.  After some digging, I discovered that I had built my solution under the AnyCpu platform a loooooooong time ago.  I had since switched to targeting the x86 platform, so I had some obsolete build output nested under my projects.  This same “error” occurred even when trying to load the assemblies manually; apparently NDepend was still detecting assemblies with the same name but different versions.  Once I figured it out, resolving the issue was easy: I just removed the obsolete output directories.  It would be nice if NDepend was a little smarter about loading assemblies, but at least it has good error messages.   

Even after resolving the version conflicts, I had trouble getting NDepend to load the console application from my solution.  I had to manually drag-and-drop the exe into the assembly list, at which point it recognized it just fine.

The “Getting Started” experience is flexible and intuitive, but there are enough issues to make the process mildly frustrating for a first time user. 

The Analysis

Running an analysis was surprisingly fast.  Granted, I’m on a hefty workstation, but it still seemed blazingly fast considering what it was doing.  The analysis generated an HTML report that included metrics, visualizations, graphs, tables, and the results of numerous CQL queries. 

The HTML report is great for sharing the output of NDepend or for reviewing the analysis offline, but the NDepend tool itself enables you to interactively analyze your application.  Be warned, though, that the default view can be overwhelming at first:

AnalysisHome

Even with high resolution monitors and the window maximized, this view is probably not going to be all that useful.  Instead, you will likely find one of the configured alternative views more useful, such as the Dependency Matrix view:

DependencyMatrix

I still found this view to be too cluttered, but like Visual Studio, NDepend’s UI is very customizable.  However, unlike Visual Studio, it took a lot of trial and error to get things laid out the way I liked.  The docking behavior seemed much more finicky than Visual Studio, and on multiple occasions attempting to pin/unpin an item would cause the layout to shift in unexpected ways.  Even resizing the window caused strange behaviors at times.  Still, after some massaging, I arrived at a less overwhelming layout:

SimplifiedView

One feature I’d like to see in NDepend is a “Save Custom View” command, that way I can save and restore my preferred layout for use in the future.  Why is this feature important?  Because it took me all of about 5 minutes to screw something up after getting my view the way I liked it, requiring me to “Reset Views” back to the default. :(

Overall, in my opinion the UI itself is the weakest area of NDepend.  Yes, it’s functional, but there are some very noticeable usability problems here.  I’m sure it is quite challenge to develop and maintain a UI that exposes all the capabilities of NDepend, but I think some additional work is warranted here.

Visualizations

While the UI might need some work, it doesn’t detract (too much) from what NDepend actually does really well, and that’s analyze your code base.  The “Metrics” visualization gives you a map of sorts depicting your project by whatever metric you are interested in.  Want to see your types by number of instructions?

TypeByInstructions

How about your methods by lines of code?

MethodByLinesOfCode

Or by cyclomatic complexity?

MethodByComplexity

I can also generate a nice map of my project dependencies (again, I can customize the visualization to emphasize different metrics):

DependencyGraph

These visualizations make it very easy to find areas of your project that warrant attention by simply glancing at the graphics.  Unfortunately, the usability elephant raises his head here.  A few things stick out worse than others.  First, the behavior of the “Export to PNG” button is consistently inconsistent between the visualizations.  On one view, the button brings up a dialog to save a snapshot to the file of your choosing.  On another, it instantly exports the file and loads it up in Windows Media Viewer.  I also had to make frequent use of the “Fit to Window” command on the Metrics visualization because I would accidentally click on the visualization, causing it to scroll unintentionally.  These aren’t things that are going to turn someone off of using the tool, but they are still problems that should be addressed. 

The rich visualizations make it easy to spot areas of your code base that need attention.  While there are some usability problems here, they’re pretty minor and easy to overlook.

Code Query Language

The final piece that I want to talk about is CQL and the library of built-in constraints and checks that ship with NDepend.  According to the website, there are 83 metrics available in CQL, and NDepend ships with queries to help you find potentially problematic areas quickly: 

CqlReports

As you can see, this particular project has quite a few issues I might want to look into further. :)  A cool feature of the CQL queries pane is that selecting one will update the “Metrics” visualization, with types matching the query highlighting blue as in the following screenshot:

CqlMetrics

This lets you quickly assess how wide-spread an issue is in your codebase.  For details, you can use the CQL Query results window.  Double-clicking an item in the results will open the corresponding location in your source code, so it’s very quick and easy to drill down from a CQL query to the underlying code.

One thing to note: many of the constraints that I checked were actually configured only to return the top 10 methods/types/whatever, so a constraint with a “10” next to it usually means “at least 10”. Keep that in mind as you are glancing through the constraints. 

NDepend does seem to count properties as methods.  While technically true (even auto properties are implemented as a pair of methods that access an automagically generated field), this can lead to unexpectedly high values for metrics such as “lack of cohesion” on types that expose many properties (such as view models in an ASP.NET MVC application). 

There were a few things that I couldn’t figure out how to do (yet).  For example, I wanted to build a CQL query to find all public methods that were part of a class marked with the NUnit TestFixture attribute who didn’t have a Test attribute applied to them.  I suspect that there is a way to express this query, it just requires someone better with CQL than I am. :)

The built-in CQL queries can help you find trouble areas in your code base as well as determine how systemic a problem is.  The syntax is clean and SQL-like.  There are a few things that are difficult (at least for a novice) to express using the language, but the built-in queries are likely to cover 90% of what you would want to look at anyway.

Things I haven’t tried yet…

My review focused on the visual version of NDepend.  NDepend also has a command-line version, an MSBuild task, and a NAnt task.  There’s also an XLST transform for using NDepend output with CruiseControl.NET.  Since NDepend generates a nice HTML report, it can easily be integrated into other CI servers as well, such as TeamCity.

NDepend also has Visual Studio and Reflector integration.  While I use both tools, I did not (yet) test out the integration. 

Overall

NDepend is a very deep tool with a lot of functionality.  I feel like I’ve just scratched the surface.  You will probably be hearing more about NDepend in the future as I continue to dig deeper into its capabilities. 

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


The trials and tribulations of using MSDeploy with PowerShell

clock February 1, 2010 09:21 by author Matt

I can sum my experience with trying to use MSDeploy and Powershell together with a single word: hell.  MSDeploy.exe does not play nicely with PowerShell, but thanks to some help from James and a lot of trial-and-error, I’ve got it sort-of working now.  Here’s a tail of my journey.  Hopefully you, brave reader, will learn from my mistakes.  THAR BE DRAGONS HERE.

It began with the automation of deployments

This journey started from a desire to automate our deployment processes.  We have three different software applications that we host under a SaaS model, and only one of those has a deployment that even remotely qualifies as semi-automated.  Making deployment less painful typically leads to more frequent deployments and happier developers, so I set out to automate things.  I have previously used MSBuild and PowerShell to automate things, but that was several years ago, and the tools have changed.  Today, we have a new tool to help with deploying web applications: the Microsoft Web Deployment Tool, or MSDeploy. FTA:

The Web Deployment Tool simplifies the migration, management and deployment of IIS Web servers, Web applications and Web sites.

Basically, MSDeploy gives us some great functionality for remote deployments.  With it, I can deploy files, execute commands remotely, run SQL scripts, etc.  On paper, this seemed like a great tool.  Using it, I should be able to deploy applications without having to log on to the target servers at all

So, with MSDeploy installed and ready, I decided I would use PowerShell to drive things instead of MSBuild or batch scripting.  After all, PowerShell is the future of the Windows Shell. And MSDeploy is new hawtness.  So the two will surely play nice together, right?  Right?

You seek the 2.0 shell?

Before starting, I decided I would install PowerShell 2.0.  It was required for one of the tools I was using (which I’ll cover in a future post).  I was running Vista with PowerShell 1.0 installed.  So I hit up Google to find the 2.0 release:

PowerShellGoogle

Hmm, none of the top results looked like a download page for the final version.  I didn’t want a CTP, I wanted the final version.  Bing was not much better:

PowerShellBing

Bing returned a blog post indicating that the RTW version shipped, but no link in the first few results (yes, I am one of those searchers who only scans the first few hits before abandoning my query and trying a different one).  I finally found the PowerShell portal on TechNet, which did include a link to download PowerShell 2.0.  PS2 is part of the Windows Management Framework, which is intuitively* disguised as KB968929. Suggestion to Microsoft: how about making it a little less difficult to find PowerShell?

*SarcasmLevel = int.MaxValue;

There can be no alliance between PS and MSDeploy

Despite the initial frustration of finding and installing the latest PowerShell, I had high hopes that things were going to go smoother now.  I had numerous examples of how to use MSDeploy.exe from the command-line, and the documentation actually seemed pretty solid.  You can imagine my surprise when I tried running a simple example and was greeted by the following:

powershellFail

Note: The comments are mine, not MSDeploy output.  There is no MSDeploy output.  Nothing.  At all.  Until I forcibly end msdeploy, I can type whatever I want, and it just sits there quietly.

I’m not a PowerShell guru, but I don’t think that is normal behavior.  I found a handful of blog and message forum posts scattered across the web reporting similar behavior when using MSDeploy with PowerShell.  After reading the IIS blog, I started to suspect that using MSDeploy with PowerShell, at least through the command line, was actually not supportedThis really dashed my hopes:

And let us know if you want to use Web Deploy with PowerShell, we're interested in hearing about what tasks you'd like to accomplish and why!

I bet the use cases for MSDeploy with PowerShell are the same as using MSDeploy from the old CMD shell.  I’m really surprised that PowerShell is apparently not fully supported right out of the box.  I think Microsoft did realize that people might want to use the tools together. Why else would they have had PowerShell cmdlets in the early preview releases?  Unfortunately, these cmdlets were removed from the final version (see the last comment).

More digging around led me to some actual working examples of using MSDeploy with PowerShell, but it seemed a lot less elegant than running msdeploy.exe. 

An old friend comes to the rescue!

Despite this setback, I wasn’t ready to give up yet.  My initial solution was to wrap msdeploy.exe in a (very) simple batch script that I could invoke from PowerShell, but James gave me a better solution: invoke msdeploy.exe through cmd.exe directly!  I created a function to wrap the invocation, like so:

function PushToTarget([string]$server, [string]$remotePath, [string]$localPath) {
    cmd.exe /C $("msdeploy.exe -verb:sync -source:contentPath=`"{0}`" -dest:computerName=`"{1}`",contentPath=`"{2}`" -whatif" -f $localPath, $server, $remotePath )
}

Now I can use MSDeploy to sync files to my production servers.  In a future post, I’ll show you how capability fits in to our larger deployment process.

Share or Bookmark this post…
  • del.icio.us
  • DotNetKicks
  • Digg
  • msdn Social
  • Reddit
  • StumbleUpon

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


About Matt

I am an overworked (and apparently overpaid) software developer with aspirations of acquiring a PhD in Computer Science. I started off coding in C over a decade ago.  Since then, I've migrated from C to C++ and branched out to C#, PHP, VB.NET, JavaScript, and worked with a wide assortment of other languages that I hope to never deal with again (I'm looking at you, COBOL). Oh, and yes, I've written some Java.  Does that make me a bad person?

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2009

Sign in