Sunday, January 31, 2010

Add reference dialog in VS2010

Sometimes a simple improvement can give a lot of benefit. I can’t count the time that I was just waiting for the list of assemblies to pop up after clicking the Add reference… option in Visual Studio.

In Visual Studio 2010 they’ve made two improvements to this:

  1. The Add reference dialog opens up by default on the Project tab
  2. The assemblies are loaded on a background thread, preventing the UI from blocking.

Thank you, Microsoft.

Read more about it here.

How we do things

It’s always interesting to read how other development shops organize their work, implement methodologies and practices. Scott C Reynolds created a blog series on how his team operates, from planning to production, and about the lessons they’ve learned, the mistakes they’ve made and the improvements they’ve done.

  • Introduction to our team, and where we came from.
  • Evolving our Planning Practice
  • How We Do Planning Today
  • Evolving TDD/BDD Practice
  • Testing Part 2
  • Specification Part 1
  • Specification Part 2 - Using Appropriate Tools
  • Team Room
  • Username authentication in WCF

    Imagine following requirements:

    • You want to send data to a WCF service in a secure way
    • To maximize compatibility you have to use basic HttpBinding
    • You want to authenticate using a username/password combination

    In WCF the only option you have based on these requirements is the use of SSL.

    On server side you have to configure your service using the TransportWithMessageCredential security mode. Configure your binding as specified below:

       1:  <bindings>
       2:        <basicHttpBinding>
       3:          <binding name=”SecureHttps>
       4:            <security mode=”TransportWithMessageCredential>
       5:              <message clientCredentialType=”UserName/>
       6:            </security>
       7:          </binding>
       8:        </basicHttpBinding>
       9:  </bindings>


    Verification of the client credentials can be done using for example the ASP.NET membership provider or you can specify your own custom authenticator.

       1:  <serviceCredentials>
       2:              <userNameAuthentication userNamePasswordValidationMode=”Custom
       3:                customUserNamePasswordValidatorType="Services.CustomUserNamePasswordValidator, Services/>
       4:  </serviceCredentials>

    Create then the following class:

       1:   
       2:  public class CustomUsernamePasswordValidator : UserNamePasswordValidator 
       3:  {
       4:          public override void Validate(string userName, string password)
       5:          {
       6:              //your validation here
       7:          }
       8:  }



    And if you are using the generated proxy on the client side, the only remaining thing you have to do is specifying some client credentials:

       1:  using(var serviceProxy=new SecureService())
       2:  {
       3:        serviceProxy.ClientCredentials.UserName.UserName="Test";
       4:        serviceProxy.ClientCredentials.UserName.Password="Test";
       5:       //Call service operation
       6:  }

    NDbUnit- Invalid object name

    For our integration testing, we are using NDbUnit, a free open source .NET library for managing database state during testing. It ensures that our database is always in a consistent state before we start the execution of our tests. It uses an XSD schema to describe the database tables and an XML file can be used to provide the content.

    After configuring everything, we initialized our database using following code

       1:  var mySqlDatabase = new NDbUnit.Core.SqlClient.SqlDbUnitTest(@"server=;user=;password=;initial catalog=");
       2:  mySqlDatabase.ReadXmlSchema(@"./Test.xsd");
       3:  mySqlDatabase.ReadXml("./Data.xml");
       4:  mySqlDatabase.PerformDbOperation(NDbUnit.Core.DbOperationFlag.CleanInsertIdentity);

    But instead of populating our database with the correct values, we got an Invalid Object Name exception for each table. We found out that NDbUnit uses the default schema of the user specified in the connection string to look for the tables. So if you are using a different schema NDbUnit will not succeed in executing its scripts.



    Something to keep in mind…

    Saturday, January 30, 2010

    I can’t remember that reporting server url when using multiple instances.

    When using Microsoft Reporting services, 2 url’s are important:

    1. The url of the report manager website (By default http://[DatabaseServerName]/Reports )
    2. The url of the report server(By default http://[DatabaseServerName]/ReportServer )

    Easy and straightforward. But if you have multiple database instances on your server, the naming schema is a little bit more complex.

    So a quick reminder to myself, for a server with multiple database instances:

    1. The url of the report manager website becomes http://[DatabaseServerName]/Reports$[InstanceName]
    2. The url of the report server becomes http://[DatabaseServerName]/ReportServer$[InstanceName]

    TechDays 2010 Belgium

    Ive been confirmed for a session at TechDays 2010 Belgium(www.techdays.be). I’ll be talking about:

    Making TDD work using Visual Studio 2010

    Visual Studio 2010 brings with it several enhancements to help cut development friction and enable the developer to focus on the task at hand: writing high-quality code.
    Join Bart in a session where he dives deep in Visual Studio 2010 to show the improvements being made to better enable test-driven development. Obviously this session could not be complete with a proper introduction about Test Driven Development, introduction of mocks, principles of testable code and a quick peek into Behavior Driven Development(BDD). So… get ready for a joyful test experience.

    So if you are interested in how you, as a developer can write better, more testable code , come and listen. You ain’t gonna regret it ;-)

    Sunday, January 17, 2010

    Error while creating a new Team Project in TFS 2010

    One of my colleagues couldn’t create a new Team Project although he was assigned the Project Collection Administrator role.

    After some investigation we found that the problem was caused by SharePoint. Just assigning the Project Collection Administrator role isn’t enough. The user must have site collection administrator rights on the collection http://yourtfsserver/sites/DefaultCollection/  level.

    No more magic strings in NHibernate 3.0

    One of the many options to create and execute queries using NHibernate is the ICriteria API. A big disadvantage that makes refactoring harder is the use of magic strings to specify properties, etc.

       1:  .Add(Expression.Eq("Name", "Smith"))

    NHibernate 3.0 introduces the QueryOver api, which combines the use of Extension Methods and Lambda Expressions  to provide a statically typesafe wrapper round the ICriteria API. It uses Lambda Expressions to provide some extra syntax to remove the 'magic strings' from your ICriteria queries.

    So, the previous example becomes:

       1:  .Where<Person>(p => p.Name == "Smith")

    With this kind of syntax there are no 'magic strings', and refactoring tools like 'Find All References', and 'Refactor->Rename' work perfectly.

    Read more about this in Richard Brown’s great post.

    ASP.NET MVC 2 series

    Scott Guthrie started a blog series about all the great new features in ASP.NET MVC 2. Following topics are planned:

  • New Strongly Typed HTML Helpers (posted: Jan 10th, 2010)
  • Enhanced Model Validation support across both server and client (posted: Jan 15th, 2010) 
  • Auto-Scaffold UI Helpers with Template Customization
  • Support for partitioning large applications into “Areas”
  • Asynchronous Controllers support (post coming soon)
  • Support for rendering sub-sections of a page/site using Html.RenderAction
  • Lots of new helper functions, utilities, and API enhancements
  • Improved Visual Studio tooling support
  • Certainly check it out here.

    Exclude specific files from TFS source control

    Last week one of my co-workers was looking for a way to exclude a specific file from TFS source control.

    We found the following 2 options:

    1. On a single file level:
      1. Select the file you want to exclude in the Solution Explorer.
      2. Open the File menu, click Source Control and choose the Exclude from Source Control option.
    2. On the folder level: By using cloaking you can hide a specific workspace folder.
      1. On the File menu, click Source Control, and then select Workspaces.

      2. In the Manage Workspaces dialog box, click the workspace you want to apply cloaking to, and then click Edit.

      3. In the Edit Workspaces dialog box, in the Working folders list, either highlight the folder mapping located under Source Control Folder and Local Folder that you want to cloak, or create a new one. Under Status, change the setting from Active to Cloaked.
      4. Click OK to close Edit Workspaces and Close to close Manage Workspaces.

    Visual Studio 2010 and .NET Framework 4 Training Kit (January 2010 Release)

    Microsoft updated their Training Kit for Visual Studio 2010 and .NET Framework 4.0 Beta 2. Download the January 2010 Release here.

    The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2010 features and a variety of framework technologies including:

    • C# 4.0
    • Visual Basic 10
    • F#
    • Parallel Extensions
    • Windows Communication Foundation
    • Windows Workflow
    • Windows Presentation Foundation
    • ASP.NET 4
    • Windows 7
    • Entity Framework
    • ADO.NET Data Services
    • Managed Extensibility Framework
    • Visual Studio Team System

    Thursday, January 14, 2010

    Visual Studio 2010 Quick Reference Guidance

    The Visual Studio ALM Rangers updated their Quick Reference Guidance for Team Foundation Server (TFS) 2010 and Visual Studio (VS) 2010.

    It consists of compact cheat sheets for TFS 2010 and VS)2010, addressing the core problem of teams in the field who are unaware of Visual Studio and Team Foundation Server capabilities or have little time to invest in detailed education.
    The artifacts include an overview document and poster that allows you to quickly focus on individual areas like testing, by providing crisp and compact guidance sheets and quick reference posters.

    Disable logging in WSS 3.0

    After a server failure I discovered that Windows Sharepoint Services was creating gigabytes of log files where after our server died with a ‘no more disk space’ error.

    WSS V3 out of the box has extensive logging activity, Logs can be usually found in this directory  C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

    If you are running WSS V3, you can disable logging activity by doing the following:

    • Go to WSS V3 Central Administration -> Operations -> Logging and Reporting

    • Click on Diagnostic Logging

      1. Customer Experience Improvement Program: select No, I don't wish to participate

      2. Error Reports: select Ignore errors and don't collect information.

      3. Trace log: clear the entire Path.

      4. Click OK

    • Click on Usage Analysis Processing

      1. Uncheck Enable logging

      2. Click OK

    • Click on Information Management Policy Usage Reports

      1. Uncheck Enable recurring policy usage reports

    Please remember that once you have disabled logging it will be impossible to troubleshoot any WSS errors.

      Change the Service Account for Team Foundation Server 2010

      I still remember the trouble I had to change the service account on Team Foundation Server 2008.  So I’m really glad to see how easy this became in Team Foundation Server 2010.

      1. Open the administration console for Team Foundation. For more information, see Open the Team Foundation Administration Console.

      2. Expand the server name and click Application Tier.

      3. In the Application Tier pane, click Change Service Account. The Update Service Account window opens.

      4. Perform one of the following steps:

        1. If you want to use a system account, click System Account, and then choose a system account from the drop-down list.

          If your server is a member of an Active Directory domain, the default choice is Network Service. If your server is a member of a workgroup, the default choice will be Local Service. Depending on your deployment, the default might be the only choice.

          System accounts do not have passwords. If you choose to use a system account for TFSService, you should not type a password in the password field.

        2. If you want to use a domain or workgroup account, click User Account, type the name of the account in Account Name, and then type the password of the account in Password.

      5. Click OK.

      Exception handling in ASP.NET MVC 2

      In ASP.NET MVC, handling errors in your controller actions or controller action results can be done using Exception filters. So I applied the HandleError actionfilter on top of my controller. When this exception filter handles an exception, it creates an instance of the HandleErrorInfo class and sets the Model property of the ViewDataDictionary instance when rendering the Error view.

         1:  [HandleError]
         2:  public class HomeController : Controller
         3:  {
         4:      public void Index()
         5:      {
         6:           throw new Exception("Test");
         7:      }
         8:  }


      However no exception was catched after applying this filter. After some research I noticed that that this filter doesn’t catch exceptions in debug builds when custom errors are not enabled. The filter simply checks the value of HttpContext.IsCustomErrorEnabled to determine whether to handle the exception.

      So open up your web.config and change the CustomErrors mode to On.

         1:  <system.web> 
         2:    <customErrors mode="On"> 
         3:    </customErrors> 

      Using SSL with ASP.NET MVC 2

      In ASP.NET MVC 1 you had to create a custom Authorization Filter to enable SSL. In ASP.NET MVC 2 the work is done for you. Just apply the RequireHttps actionfilter on top of your controller and all calls to your action methods will use SSL.

      The attribute checks if the request is secure, and if not redirect to a secure version of the request. It’s also a good idea to set the Order parameter to 1. This ensures that the check for the use of SSL is executed before the check for the role. This helps ensure that credentials are only sent over SSL.

         1:  public AccountController: Controller
         2:  {
         3:     [RequireHttps(Order=1), Authorize(Roles="Users",Order=2)]
         4:     public ActionResult Login()
         5:     {
         6:        // Add login logic
         7:        return View();
         8:     }
         9:  }

      Diagnose build errors using TFS Build 2010 Beta 2

      Troubleshooting a failing build can be hard. In TFS Build 2010 Beta 1, you had a Show Property Values link on your build log. This shows the log, but in addition it shows each in/out property for each activity.

      ShowPropertyValues

      In TFS Build 2010 Beta 2, this property is gone. So how can you still get this useful extra information?

      As this feature slows down the build a lot, you have to explicitly enable it when you queue your build. Right click on the Build you want to run, select Queue new build and go to the Parameters tab of the Queue Build window. Change the logging verbosity to Diagnostics to get the highest detail of logging during a build.

      Logging Verbosity

      Sunday, January 10, 2010

      Using the AsyncController in ASP.NET MVC 2

      On the Web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request.

      If you have multiple long-running requests, all available threads might be blocked and the Web server rejects any additional request with an HTTP 503 status (Server Too Busy).

      To solve this issue in ASP.NET MVC, actions can be processed asynchronously by deriving your controllers from the AsyncController class.

      For example, let’s convert this code sample into a more efficient asynchronous alternative:

         1:  public class HomeController: Controller 
         2:  {
         3:      public ActionResult LongRunningAction() 
         4:      {
         5:          DoLengthyOperation();
         6:          return View();
         7:      }
         8:   
         9:      private void DoLengthyOperation()
        10:      {
        11:          Thread.Sleep(5000);
        12:      }
        13:   
        14:  }

      To convert this synchronous action method to an asynchronous action method involves the following steps:


      1. Instead of deriving the controller from Controller, derive it from AsyncController. Controllers that derive from AsyncController enable ASP.NET to process asynchronous requests, and they can still service synchronous action methods.


      2. Create two methods for the action. The method that initiates the asynchronous process must have a name that consists of the action and the suffix "Async". The method that is invoked when the asynchronous process finishes (the callback method) must have a name that consists of the action and the suffix "Completed". In the previous example, the LongRunningAction method has been turned into two methods: LongRunningActionAsync and LongRunningActionCompleted.

        The LongRunningActionAsync method returns void. The LongRunningActionCompleted method returns an ActionResult instance. Although the action consists of two methods, it is accessed using the same URL as for a synchronous action method (for example, Home/LongRunningAction). Methods such as RedirectToAction and RenderAction will also refer to the action method as LongRunningAction and not LongRunningActionAsync.

        The parameters that are passed to LongRunningActionAsync use the normal parameter binding mechanisms. The parameters that are passed to LongRunningActionCompleted use the Parameters dictionary.


      3. Replace the synchronous call in the original ActionResult method with an asynchronous call in the asynchronous action method.

         1:  public class HomeController : AsyncController 
         2:  {
         3:      public void LongRunningActionAsync() 
         4:      {
         5:          AsyncManager.OutstandingOperations.Increment();
         6:          Task.Factory.StartNew(() => DoLengthyOperation());
         7:      }
         8:   
         9:      private void DoLengthyOperation()
        10:      {
        11:          Thread.Sleep(5000);
        12:          AsyncManager.Parameters["message"] = "hello world";
        13:          AsyncManager.OutstandingOperations.Decrement();
        14:      }
        15:   
        16:   
        17:      public ActionResult LongRunningActionCompleted(string message) 
        18:      {
        19:          return View();
        20:      }
        21:  }

      More information here.

      A small change a day keeps the angry code reviewer away (and your code cleaner)

      Sooner or later we all have to inherit an existing code base full of complex, ugly code constructions that go on for pages and pages. Your boss asked you to do a ‘minor’ change to this codebase. You open up the hood to make this change and… you discover an enormous mess. Working on this kind of codebase can be tiring and joyless. But if you decide to make this code base better each day than it was the day before, you can change this awful experience in a joyful  learning process.

      That can mean refactoring a long method into several smaller, well named methods. It can mean removing inheritance hierarchies that never belonged in the object model. It can be fixing a long-broken unit test, and so on…

      If you do these changes incrementally, they will come for “free.” Refactoring one method is something you can do in the time you would normally spend getting another cup of coffee or chatting with a co-worker about the latest news. And making one small improvement is motivating. You can clearly see the difference in that one thing you’ve fixed as soon as the change is made.

      So if you start working on some dirty code, instead of complaining about it and introducing a quick work around, clean up the code a little bit so each time you have to open up this code base, it becomes better.

      Saturday, January 9, 2010

      Sending Email with System.Net.Mail

      Sending mails using the .NET’s SmtpClient API is very easy and straightforward. Alas the same doesn’t count for mocking the client in your unit test. So most of the time I create an extra layer of abstraction and wrap the SmtpClient in an IEmailService.  And this works fine for my unit tests.

      But for my integration tests I follow a different strategy. By default, the SmtpClient takes mail server settings from your web.config or app.config file.

      To configure it to send e-mail through a particular SMTP server, add the following to your web.config file:

         1:  <configuration>
         2:     <system.net>
         3:        <mailSettings>
         4:           <smtp deliveryMethod="Network">
         5:              <network host="smtp.example.com"/>
         6:           </smtp>
         7:        </mailSettings>
         8:     </system.net>
         9:  </configuration>

      But this means that an actual mail server has to be configured to run my integration tests and even worse that some test mails will be send out to everyone.

      Instead it would be better if you could write mails to a local directory, so you can see what’s happening without having to set up an actual mail server. This is done very easily, change your  config to use these settings:

         1:  <configuration>
         2:     <system.net>
         3:        <mailSettings>
         4:           <smtp deliveryMethod="SpecifiedPickupDirectory">
         5:              <specifiedPickupDirectory pickupDirectoryLocation="c:\emails" />
         6:           </smtp>
         7:        </mailSettings>
         8:     </system.net>
         9:  </configuration>
        10:   

      This will write .eml files to the specified folder, which must already exist and be writable. If you double-click .eml files in Windows Explorer, they’ll open in Outlook Express or Windows Mail.

      Remove a test case from the Visual Studio 2010 Test and Lab Manager UPDATE

      I blogged about removing a test case before. I suggested to use the power tools to remove the work item. I found out today that in Visual Studio 2010 this is no longer needed. You can use witadmin provided you’ve admin permissions. witadmin is a command-line utility and is located in %Program Files%\Microsoft Visual Studio 10.0\Common7\IDE.

      A sample how to use this command:

         1:  witadmin destroywi /collection:COLLECTIONURL /id:10


      Thursday, January 7, 2010

      Uploading files using ASP.NET MVC 2

      In ASP.NET MVC 1 you had to check the Request.Files property when you want to upload one or more files from your web application.

         1:  public class HomeController : Controller
         2:  {
         3:    public ActionResult ProcessFiles()
         4:    {
         5:      foreach (string file in Request.Files)
         6:      {
         7:            //Process files
         8:      }
         9:      return View();
        10:    }
        11:  }

      As this is not directly helping to make a testable controller action, they were some initiatives to make this testable.

      In ASP.NET MVC 2 you get by default a ModelBinder that extracts the files from the Request and assign it to a parameter of your controller action method.

         1:  public class HomeController : Controller
         2:  {
         3:    public ActionResult ProcessFiles(IEnumerable<HttpPostedFileBase> files)
         4:    {
         5:      foreach (var file in files)
         6:      {
         7:        //Process files
         8:      }
         9:      return View();
        10:    }
        11:  }

      Beautiful isn’t it?

      Failed to queue test run in Visual Studio 2010

      After creating some coded UI tests,  I queued these tests to run locally on my machine. But instead of running the tests, the test run failed with following error message:

      Failed to queue test run 'XXXXX 2010-01-7 20:41:17': Agent service cannot start the agent process on agent 'XXXX'.

      No idea what causes this error, but after closing and restarting Visual Studio the tests were running fine.

      Strange?!

      Video record your test session using Microsoft Test and Lab Manager

      One of the great capabilities of Microsoft Test and Laba Manager is the possibility to video record your tests. Before you can get this feature up and running, some extra installation steps have to be done.

      The steps:

      1. If your are using Windows 2008 R2 enable the Desktop Experience feature using Server Manager

      a. Open Server Manager and select Features, then click the Add Features link on the right side of the screen.
      servermanager1

      b. Select the Desktop Experience checkbox, then “Next” your way through the wizard until you’re done.
      servermanager2

      2. Download and install Media Encoder (always use x32 regardless of your OS)

      http://www.microsoft.com/windows/windowsmedia/forpros/encoder/default.mspx

      3. If you are using Windows Vista, 7 or 2008 R2 Install the Media Encoder hotfix

      http://support.microsoft.com/kb/929182

      Note: to install the KB hotfix, you MUST use RUN AS administrator, otherwise the installation will fail.

      4. Enable Video Recording in Microsoft Test and Lab Manager

      Back to basics: the HTML form

      As I’m using ASP.NET MVC 2 for a recent project, I finally got back to the essence of web programming, no more strange page lifecycle, viewstate and weird html rendered as output but instead plain ‘simple’ html.

      One of the most important tags is of course the <form>.

      They are three things you need to remember:

      1. You can use the method attribute of <form> to specify the HTTP method to use for  submission (GET or POST).
      2. You can use the action attribute of the <form> to submit information to any URL.
      3. You can have multiple <form> tags on a single page.

      So what were those HTTP methods again?

      Both POST and GET are designed to do what they sound like – GET a response, or POST some information and receive a response.  HTTP POST is the best method to use when you are submitting information to a web server and changing state in your application. On the other hand, an HTTP GET operation operation is the best way to submit information to a server when you are not changing state inside the application.

      If you want to read more about the form control and how you can/should use it with ASP.NET MVC, I can recommend this excellent post by Scott Allen.

      Saturday, January 2, 2010

      Creating custom HTML helpers for ASP.NET MVC

      Creating your own HTML helpers for ASP.NET MVC is very easy. If you understand extension methods and know how to use the TagBuilder class, you’re good to go.

      A simple example creating a HtmlHelper method to render image tags:

         1:  public static class HtmlHelperExtensions   
         2:  {   
         3:          public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)   
         4:          {   
         5:              // Create tag builder   
         6:              var builder = new TagBuilder("img");   
         7:                 
         8:              // Create valid id   
         9:              builder.GenerateId(id);   
        10:    
        11:              // Add attributes   
        12:              builder.MergeAttribute("src", url);   
        13:              builder.MergeAttribute("alt", alternateText);   
        14:              builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));   
        15:    
        16:              // Render tag   
        17:              return builder.ToString(TagRenderMode.SelfClosing);   
        18:          }   
        19:    
        20:  } 

      And if you don’t know where to start, check the  Using the TagBuilder Class to Build HTML Helpers tutorial.

      Distributed Transaction Coordinator (DTC) Timeout

      When running a very expensive query, I always got timeouts when running this query on Friday's ;-) (Yes, I’m loving the predictability of our DB2 database)

      The first thing I did to prevent the query from timing out was increasing the DbCommand timeout property:

         1:  var command=new DB2Command();
         2:  //Increase timeout to 300 seconds
         3:  command.CommandTimeout=300;


      But after 60 seconds the query still timed out. So as I was using this query inside a TransactionScope, I also increased the transaction timeout:

         1:  //Initialize the transactionscope with a 300 seconds timeout interval
         2:  using(var transactionScope=new TransactionScope(TransactionScopeOption.Required,new TimeSpan(0,5,0))
         3:  {
         4:  ...
         5:  }


      And even that was not enough, so I finally also increased the timeout interval of the DTC:

      The Transactions Timeout value is located in the My Computer Properties dialog, which can be available in "Administrative Tools -> Component Service -> Computer -> My Computer ->
      Right-click My Computer and then click Properties".