Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Azure, PHP, OpenXML, VSTS, ...

About the author

Maarten Balliauw is an MVP ASP.NET and is currently employed as .NET Software Engineer at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP.
More about me More about me
Send mail E-mail me


Microsoft Most Valuable Professional - MVP - ASP.NET

Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn RealDolmen - Rock-solid passion for ICT
I'm a speaker at TechDays Belgium and TechDays Finland

Search

Latest Twitter

    Follow me on Twitter...

    Disclaimer

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

    © Copyright Maarten Balliauw 2010

    Revised: ASP.NET MVC and the Managed Extensibility Framework (MEF)

    A while ago, I did a blog post on combining ASP.NET MVC and MEF (Managed Extensibility Framework), making it possible to “plug” controllers and views into your application as a module. I received a lot of positive feedback as well as a hard question from Dan Swatik who was experiencing a Server Error with this approach… Here’s a better approach to ASP.NET MVC and MEF.

    kick it on DotNetKicks.com

    The Exception

    Server Error

    The stack trace was being quite verbose on this one:

    InvalidOperationException

    The view at '~/Plugins/Views/Demo/Index.aspx' must derive from ViewPage, ViewPage<TViewData>, ViewUserControl, or ViewUserControl<TViewData>.

    at System.Web.Mvc.WebFormView.Render(ViewContext viewContext, TextWriter writer) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass11.<InvokeActionResultWithFilters>b__e() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass11.<>c__DisplayClass13.<InvokeActionResultWithFilters>b__10() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

    Our exception seemed to be thrown ONLY when the following conditions were met:

    • The View was NOT located in ~/Views but in ~/Plugins/Views (or other path)
    • The View created in our MEF plugin was strong-typed

    Problem one… Forgot to register ViewTypeParserFilter…

    Allright, go calling me stupid… Our ~/Plugins/Views folder was not containing the following Web.config file:

    <?xml version="1.0"?>
    <configuration>
      <system.web>
        <httpHandlers>
          <add path="*" verb="*"
              type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>

        <!--
            Enabling request validation in view pages would cause validation to occur
            after the input has already been processed by the controller. By default
            MVC performs request validation before a controller processes the input.
            To change this behavior apply the ValidateInputAttribute to a
            controller or action.
        -->
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <controls>
            <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
          </controls>
        </pages>
      </system.web>

      <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <handlers>
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
        </handlers>
      </system.webServer>
    </configuration>

    Now why would you need this one anyway? Well: first of all, you do not want your views to expose their source code. Therefore, we add the HttpNotFoundHandler for this folder. Next, we do not want request validation to happen again (because this is already done when invoking the controller). Next: we want the MvcViewTypeParserFilter to be used for enabling strong-typed views (more on this by Phil Haack).

    Problem two: MEF’s approach to plugins and ASP.NET’s approach to rendering views…

    When compiling a view, ASP.NET dynamically compiles the markup into a temporary assembly, after which it is rendered. This compilation process knows only the assemblies loaded by your web application’s AppDomain. Unfortunately, assemblies loaded by MEF are not available for this compilation process… I went ahead and checked with Reflector if we could do something about this on ASP.NET side: nope. The main classes we need for this are internal :-( The MEF side could be easily tweaked since its source code is available on CodePlex, but… it’s still subject to change and will be included in .NET 4.0 as a framework component, which would limit my customizations a bit for the future.

    Now let’s describe this problem as one, simple sentence: we need the MEF plugin assembly loaded in our current AppDomain, available for all other components in the web application.

    The solution to this: I want a MEF DirectoryCatalog to monitor my plugins folder and load/unload the assemblies in there dynamically. Loading should be no problem, but unloading… The assemblies will always be locked by my web server’s process! So let’s go for another approach: monitor the plugins folder, copy the new/modified assemblies to the web application’s /bin folder and instruct MEF to load its exports from there. The solution: WebServerDirectoryCatalog. Here’s the code:

    public sealed class WebServerDirectoryCatalog : ComposablePartCatalog
    {
        private FileSystemWatcher fileSystemWatcher;
        private DirectoryCatalog directoryCatalog;
        private string path;
        private string extension;

        public WebServerDirectoryCatalog(string path, string extension, string modulePattern)
        {
            Initialize(path, extension, modulePattern);
        }

        private void Initialize(string path, string extension, string modulePattern)
        {
            this.path = path;
            this.extension = extension;

            fileSystemWatcher = new FileSystemWatcher(path, modulePattern);
            fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
            fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created);
            fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted);
            fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed);
            fileSystemWatcher.IncludeSubdirectories = false;
            fileSystemWatcher.EnableRaisingEvents = true;

            Refresh();
        }

        void fileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            RemoveFromBin(e.OldName);
            Refresh();
        }

        void fileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            RemoveFromBin(e.Name);
            Refresh();
        }

        void fileSystemWatcher_Created(object sender, FileSystemEventArgs e)
        {
            Refresh();
        }

        void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Refresh();
        }

        private void Refresh()
        {
            // Determine /bin path
            string binPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");

            // Copy files to /bin
            foreach (string file in Directory.GetFiles(path, extension, SearchOption.TopDirectoryOnly))
            {
                try
                {
                    File.Copy(file, Path.Combine(binPath, Path.GetFileName(file)), true);
                }
                catch
                {
                    // Not that big deal... Blog readers will probably kill me for this bit of code :-)
                }
            }

            // Create new directory catalog
            directoryCatalog = new DirectoryCatalog(binPath, extension);
        }

        public override IQueryable<ComposablePartDefinition> Parts
        {
            get { return directoryCatalog.Parts; }
        }

        private void RemoveFromBin(string name)
        {
            string binPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
            File.Delete(Path.Combine(binPath, name));
        }
    }

    Download the example code

    First of all: this was tricky, and the solution to it is also a bit tricky. Use at your own risk!

    You can download the example code here: RevisedMvcMefDemo.zip (1.03 mb)

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | Debugging | General | ICT | Internet | MEF | MVC | Personal

    Verifying code and testing with Pex

    Pex, Automated White box testing for .NET

    Earlier this week, Katrien posted an update on the list of Belgian TechDays 2009 speakers. This post featured a summary on all sessions, of which one was titled “Pex – Automated White Box Testing for .NET”. Here’s the abstract:

    “Pex is an automated white box testing tool for .NET. Pex systematically tries to cover every reachable branch in a program by monitoring execution traces, and using a constraint solver to produce new test cases with different behavior. Pex can be applied to any existing .NET assembly without any pre-existing test suite. Pex will try to find counterexamples for all assertion statements in the code. Pex can be guided by hand-written parameterized unit tests, which are API usage scenarios with assertions. The result of the analysis is a test suite which can be persisted as unit tests in source code. The generated unit tests integrate with Visual Studio Team Test as well as other test frameworks. By construction, Pex produces small unit test suites with high code and assertion coverage, and reported failures always come with a test case that reproduces the issue. At Microsoft, this technique has proven highly effective in testing even an extremely well-tested component.”

    After reading the second sentence in this abstract, I was thinking: “SWEET! Let’s try!”. So here goes…

    Getting started

    First of all, download the academic release of Pex at http://research.microsoft.com/en-us/projects/Pex/. After installing this, Visual Studio 2008 (or 2010 if you are mr. or mrs. Cool), some context menus should be added. We will explore these later on in this post.

    What we will do next is analyzing a piece of code in a fictive library of string extension methods. The following method is intended to mimic VB6’s Left method.

    /// <summary>
    /// Return leftmost characters from string for a certain length
    /// </summary>
    /// <param name="current">Current string</param>
    /// <param name="length">Length to take</param>
    /// <returns>Leftmost characters from string</returns>
    public static string Left(this string current, int length)
    {
        if (length < 0)
        {
            throw new ArgumentOutOfRangeException("length", "Length should be >= 0");
        }

        return current.Substring(0, length);
    }

    Great coding! I even throw an ArgumentOutOfRangeException if I receive a faulty length parameter.

    Pexify this!

    Analyzing this with Pex can be done in 2 manners: by running Pex Explorations, which will open a new add-in in Visual Studio and show me some results, or by generating a unit test for this method. Since I know this is good code, unit tests are not needed. I’ll pick the first option: right-click the above method and pick “Run Pex Explorations”.

    Run Pex Explorations

    A new add-in window opens in Visual Studio, showing me the output of calling my method with 4 different parameter combinations:

    Pex Exploration Results

    Frustrated, I scream: “WHAT?!? I did write good code! Pex schmex!” According to Pex, I didn’t. And actually, it is right. Pex explored all code execution paths in my Left method, of which two paths are not returning the correct results. For example, calling Substring(0, 2) on an empty string will throw an uncaught ArgumentOutOfRangeException. Luckily, Pex is also there to help.

    When I right-click the first failing exploration, I can choose from some menu options. For example, I could assign this as a task to someone in Team Foundation Server.

    Pex Exploration Options In this case, I’ll just pick “Add precondition”. This will actually show me a window of code which might help avoiding this uncaught exception.

    Preview and Apply updates

    Nice! It actually avoids the uncaught exception and provides the user of my code with a new ArgumentException thrown at the right location and with the right reason. After doing this for both failing explorations, my code looks like this:

    /// <summary>
    /// Return leftmost characters from string for a certain length
    /// </summary>
    /// <param name="current">Current string</param>
    /// <param name="length">Length to take</param>
    /// <returns>Leftmost characters from string</returns>
    public static string Left(this string current, int length)
    {
        // <pex>
        if (current == (string)null)
            throw new ArgumentNullException("current");
        if (length < 0 || current.Length < length)
            throw new ArgumentException("length < 0 || current.Length < length");
        // </pex>

        return current.Substring(0, length);
    }

    Great! This should work for any input now, returning a clear exception message when someone does provide faulty parameters.

    Note that I could also run these explorations as a unit test. If someone introduces a new error, Pex will let me know.

    More information

    More information on Pex can be found on http://research.microsoft.com/en-us/projects/Pex/.

    kick it on DotNetKicks.com


    Categories: C# | Debugging | General | ICT | Internet | Pex | Quality code | Testing | TFS | VSTS

    ASP.NET MVC - Testing issues Q and A

    WTF? When playing around with the ASP.NET MVC framework and automated tests using Rhino Mocks, you will probably find yourself close to throwing your computer trough the nearest window. Here are some common issues and answers:

    Q: How to mock Request.Form?

    A: When testing a controller action which expects Request.Form to be a NameValueCollection, a NullReferenceException is thrown... This is due to the fact that Request.Form is null.

    Use Scott's helper classes for Rhino Mocks and add the following extension method:

    public static void SetupFormParameters(this HttpRequestBase request)
    {
        SetupResult.For(request.Form).Return(new NameValueCollection());
    }

    Q: I can't use ASP.NET Membership in my controller, every test seems to go bad...

    A: To test a controller using ASP.NET Membership, you should use a little trick. First of all, add a new property to your controller class:

    private MembershipProvider membershipProvider;

    public MembershipProvider MembershipProviderInstance {
        get {
            if (membershipProvider == null)
            {
                membershipProvider = Membership.Provider;
            }
            return membershipProvider;
        }
        set { membershipProvider = value; }
    }

    By doing this, you will enable the use of a mocked membership provider. Make sure you use this property in your controller instead of the standard Membership class (i.e. MembershipProviderInstance.ValidateUser(userName, password) instead of Membership.ValidateUser(userName, password)).

    Let's say you are testing a LoginController which should set an error message in the ViewData instance when authentication fails. You do this by creating a mocked MembershipProvider which is assigned to the controller. This mock object will be instructed to always shout "false" on the ValidateUser method of the MembershipProvider. Here's how:

    LoginController controller = new LoginController();
    var fakeViewEngine = new FakeViewEngine();
    controller.ViewEngine = fakeViewEngine;

    MockRepository mocks = new MockRepository();
    using (mocks.Record())
    {
        mocks.SetFakeControllerContext(controller);
        controller.HttpContext.Request.SetupFormParameters();

        System.Web.Security.MembershipProvider membershipProvider = mocks.DynamicMock<System.Web.Security.MembershipProvider>();
        SetupResult.For(membershipProvider.ValidateUser("", "")).IgnoreArguments().Return(false);

        controller.MembershipProviderInstance = membershipProvider;
    }
    using (mocks.Playback())
    {
        controller.HttpContext.Request.Form.Add("Username", "");
        controller.HttpContext.Request.Form.Add("Password", "");

        controller.Authenticate();

        Assert.AreEqual("Index", fakeViewEngine.ViewContext.ViewName);
        Assert.IsNotNull(
            ((IDictionary<string, object>)fakeViewEngine.ViewContext.ViewData)["ErrorMessage"]
        );
    }

    More questions? Feel free to ask! I'd be happy to answer them.

    kick it on DotNetKicks.com


    Data Driven Testing in Visual Studio 2008 - Part 2

    This is the second post in my series on Data Driven Testing in Visual Studio 2008. The first post focusses on Data Driven Testing in regular Unit Tests. This part will focus on the same in web testing.

    Web Testing

    I assume you have read my previous post and saw the cool user interface I created. Let's first add some code to that, focussing on the TextBox_TextChanged event handler that is linked to TextBox1 and TextBox2.

    public partial class _Default : System.Web.UI.Page
    {
        // ... other code ...

        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(TextBox1.Text.Trim()) && !string.IsNullOrEmpty(TextBox2.Text.Trim()))
            {
                int a;
                int b;
                int.TryParse(TextBox1.Text.Trim(), out a);
                int.TryParse(TextBox2.Text.Trim(), out b);

                Calculator calc = new Calculator();
                TextBox3.Text = calc.Add(a, b).ToString();
            }
            else
            {
                TextBox3.Text = "";
            }
        }
    }

    It is now easy to run this in a browser and play with it. You'll notice 1 + 1 equals 2, otherwise you copy-pasted the wrong code. You can now create a web test for this. Right-click the test project, "Add", "Web Test...". If everything works well your browser is now started with a giant toolbar named "Web Test Recorder" on the left. This toolbar will record a macro of what you are doing, so let's simply navigate to the web application we created, enter some numbers and whatch the calculation engine do the rest:

    Web Test Recorder

    You'll notice an entry on the left for each request that is being fired. When the result is shown, click "Stop" and let Visual Studio determine what happened behind the curtains of your browser. An overview of this test recording session should now be available in Visual Studio.

    Data Driven Web testing

    There's our web test! But it's not data driven yet... First thing to do is linking the database we created in part 1 by clicking the "Add datasource  Add Datasource" button. Finish the wizard by selecting the database and the correct table. Afterwards, you can pick one of the Form Post Parameters and assign the value from our newly added datasource. Do this for each step in our test: the first step should fill TextBox1, the second should fill TextBox1 and TextBox2.

    Bind Form Post Parameters

    In the last recorded step of our web test, add a validation rule. We want to check whether our sum is calculated correct and is shown in TextBox3. Pick the following options in the "Add Validation Rule" screen. For the "Expected Value" property, enter the variable name which comes from our data source: {{DataSource1.CalculatorTestAdd.expected}}

    image

    If you now run the test, you should see success all over the place! But there's one last step to do though... Visual Studio 2008 will only run this test for the first data row, not for all other rows! To overcome this poblem, select "Run Test (Pause Before Starting" instead of just "Run Test". You'll notice the following hyperlink in the IDE interface:

    Edit Run Settings

    Click "Edit run Settings" and pick "One run per data source row". There you go! Multiple test runs are now validated ans should result in an almost green-bulleted screen:

    image

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | Debugging | General | ICT | Testing | TFS | VSTS

    Data Driven Testing in Visual Studio 2008 - Part 1

    Last week, I blogged about code performance analysis in Visual Studio 2008. Since that topic provoked lots of comments (thank you Bart for associating "hotpaths" with "hotpants"), thought about doing another post on code quality in .NET.

    This post will be the first of two on Data Driven Testing. This part will focus on Data Driven Testing in regular Unit Tests. The second part will focus on the same in web testing.

    Data Driven Testing?

    We all know unit testing. These small tests are always based on some values, which are passed throug a routine you want to test and then validated with a known result. But what if you want to run that same test for a couple of times, wih different data and different expected values each time?

    Data Driven Testing comes in handy. Visual Studio 2008 offers the possibility to use a database with parameter values and expected values as the data source for a unit test. That way, you can run a unit test, for example, for all customers in a database and make sure each customer passes the unit test.

    Sounds nice! Show me how!

    You are here for the magic, I know. That's why I invented this nifty web application which looks like this:

    Example application

    This is a simple "Calculator" which provides a user interface that accepts 2 values, then passes these to a Calculator business object that calculates the sum of these two values. Here's the Calculator object:

    /// <summary>
    ///A test for Add
    ///</summary>
    [TestMethod()]
    public void AddTest()
    {
        Calculator target = new Calculator(); // TODO: Initialize to an appropriate value
        int a = 0; // TODO: Initialize to an appropriate value
        int b = 0; // TODO: Initialize to an appropriate value
        int expected = 0; // TODO: Initialize to an appropriate value
        int actual;
        actual = target.Add(a, b);
        Assert.AreEqual(expected, actual);
        Assert.Inconclusive("Verify the correctness of this test method.");
    }

    As you see, in a normal situation we would now fix these TODO items and have a unit test ready in no time. For this data driven test, let's first add a database to our project. Create column a, b and expected. These do not have to represent names in the unit test, but it's always more clear. Also, add some data.

    Data to test

    Test View Great, but how will our unit test use these values while running? Simply click the test to be bound to data, add the data source and table name properties. Next, read your data from the TestContext.DataRow property. The unit test will now look like this:

    /// <summary>
    ///A test for Add
    ///</summary>
    [DataSource("System.Data.SqlServerCe.3.5", "data source=|DataDirectory|\\Database1.sdf", "CalculatorTestAdd", DataAccessMethod.Sequential), DeploymentItem("TestProject1\\Database1.sdf"), TestMethod()]
    public void AddTest()
    {
        Calculator target = new Calculator();
        int a = (int)TestContext.DataRow["a"];
        int b = (int)TestContext.DataRow["b"];
        int expected = (int)TestContext.DataRow["expected"];
        int actual;
        actual = target.Add(a, b);
        Assert.AreEqual(expected, actual);
    }

    Now run this newly created test. After the test run, you will see that the test is run a couple of times, one time for each data row in he database. You can also drill down further and check which values failed and which were succesful. If you do not want Visual Studio to use each data row sequential, you can also use the random accessor and really create a random data driven test.

    Test results

    Tomorrow, I'll try to do this with a web test and test our web interface. Stay tuned!

    kick it on DotNetKicks.com


    Categories: ASP.NET | C# | Debugging | General | ICT | Testing | TFS | VSTS

    Code performance analysis in Visual Studio 2008

    Visual Studio developer, did you know you have a great performance analysis (profiling) tool at your fingertips? In Visual Studio 2008 this profiling tool has been placed in a separate menu item to increase visibility and usage. Allow me to show what this tool can do for you in this walktrough.

    An application with a smell…

    Before we can get started, we need a (simple) application with a “smell”. Create a new Windows application, drag a TextBox on the surface, and add the following code:

    private void Form1_Load(object sender, EventArgs e)
    {
        string s = "";
        for (int i = 0; i < 1500; i++)
        {
            s = s + " test";
        }
        textBox1.Text = s;
    }

    You should immediately see the smell in the above code. If you don’t: we are using string.Concat() for 1.500 times! This means a new string is created 1.500 times, and the old, intermediate strings, have to be disposed again. Smells like a nice memory issue to investigate!

    Profiling

    Performance wizardThe profiling tool is hidden under the Analyze menu in Visual Studio. After launching the Performance Wizard, you will see two options are available: sampling and instrumentation. In a “real-life” situation, you’ll first want to sample the entire application searching for performance spikes. Afterwards, you can investigate these spikes using instrumentation. Since we only have one simple application, let’s instrumentate immediately.

    Upon completing the wizard, the first thing we’ll do is changing some settings. Right-click the root node, and select Properties. Check the “Collect .NET object allocation information” and “Also collect .NET object lifetime information” to make our profiling session as complete as possible:

    Profiling property pages

    Launch with profilingYou can now start the performance session from the toolpane. Note that you have two options to start: Launch with profiling and Launch with profiling paused. The first will immediately start profiling, the latter will first start your application and wait for your sign to start profiling. This can be useful if you do not want to profile your application startup but only a certain event that is started afterwards.

    After the application run, simply close it and wait for the summary report to appear:

    Performance Report Summary 1

    WOW! Seems like string.Concat() is taking 97% of the application’s memory! That’s a smell indeed... But where is it coming from? In a larger application, it might not be clear which method is calling string.Concat() this many times. To discover where the problem is situated, there are 2 options…

    Discovering the smell – option 1

    Option 1 in discovering the smell is quite straight-forward. Right-click the item in the summary and pick Show functions calling Concat:

    Functions allocating most memory

    You are now transferred to the “Caller / Callee” view, where all methods doing a string.Concat() call are shown including memory usage and allocations. In this particular case, it’s easy to see where the issue might be situated. You can now right-click the entry and pick View source to be transferred to this possible performance killer.

    Possible performance killer

    Discovering the smell – option 2

    Visual Studio 2008 introduced a cool new way of discovering smells: hotpath tracking. When you move to the Call Tree view, you’ll notice a small flame icon in the toolbar. After clicking it, Visual Studio moves down the call tree following the high inclusive numbers. Each click takes you further down the tree and should uncover more details. Again, string.Concat() seems to be the problem!

    Hotpath tracking

    Fixing the smell

    We are about to fix the smell. Let’s rewrite our application code using StringBuilder:

    private void Form1_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1500; i++)
        {
            sb.Append(" test");
        }
        textBox1.Text = sb.ToString();
    }

    In theory, this should perform better. Let’s run our performance session again and have a look at the results:

    Performance Report Summary 2

    Compare Peformance ReportsSeems like we fixed the glitch! You can now investigate further if there are other problems, but for this walktrough, the application is healthy now. One extra feature though: performance session comparison (“diff”). Simply pick two performance reports, right-click and pick Compare performance reports. This tool will show all delta values (= differences) between the two sessions we ran earlier:

    Comparison report 

    Update 2008-02-14: Some people commented on not finding the Analyze menu. This is only available in the Developer or Team Edition of Visual Studio. Click here for a full comparison of all versions.

    Update 2008-05-29: Make sure to check my post on NDepend as well, as it offers even more insight in your code!

    kick it on DotNetKicks.com