Skip to main content

Posts

Showing posts from January, 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: The Add reference dialog opens up by default on the Project tab 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 authenti...

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 ...

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

When using Microsoft Reporting services, 2 url’s are important: The url of the report manager website (By default http://[DatabaseServerName]/Reports ) 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: The url of the report manager website becomes http:// [DatabaseServerName]/Reports$[InstanceName] 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 ;-)

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: On a single file level: Select the file you want to exclude in the Solution Explorer . Open the File menu, click Source Control and choose the Exclude from Source Control option. On the folder level: By using cloaking you can hide a specific workspace folder. On the File menu, click Source Control , and then select Workspaces . In the Manage Workspaces dialog box, click the workspace you want to apply cloaking to, and then click Edit . 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 . Click OK to close Edit Workspaces and Close to close Manage Work...

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

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 Customer Experience Improvement Program : select No, I don't wish to participate Error Reports : select Ignore errors and don't collect information. Trace log : clear the entire Path . Click OK Click on Usage Analysis Processing Uncheck Enable logging Click OK ...

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. Open the administration console for Team Foundation. For more information, see Open the Team Foundation Administration Console . Expand the server name and click Application Tier. In the Application Tier pane, click Change Service Account. The Update Service Account window opens. Perform one of the following steps: 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 c...

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 > ...

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. 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.

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...

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 ca...

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 ...

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

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 i...

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. b. Select the Desktop Experience checkbox, then “Next” your way through the wizard until you’re done. 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 ...

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: You can use the method attribute of <form> to specify the HTTP method to use for  submission (GET or POST). You can use the action attribute of the <form> to submit information to any URL. 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 ser...

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...

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 ...