Thursday, October 29, 2009

12 ASP.NET MVC best practices

People keep posting their best practices about ASP.NET MVC usage. Simone Chiaretta made a presentation about the stuff he finds important when using ASP.NET MVC.

Maybe it becomes time that I post my list of best practices? Will be continued...

NHibernate knol

As a frequent user of NHibernate, I find it a little bit disappointing that there's only one book out there, although it's a very good one.

Luckily for us, Fabio Maulo did a great job creating a knol about NHibernate. A must read for every NHibernate lover!

Spawn a web server against a local folder to preview a web application

Phill Haack wrote a blog post about quickly spawning a web server against a local folder to preview a web application. It adds a right click menu to start a web server pointing to any folder.

Usefull stuff!

Configure an MSBuild script to read file data

Today I had to configure an MSBuild script to read some data from a file. First I was looking for a custom task to achieve this goal. But I found that this functionality is out-of-the-box available in MSBuild.

You can read from a file into a variable using:

   1:  <ReadLinesFromFile File="c:\ReleaseNumber.txt">
   2:  <Output TaskParameter="Lines"
   3:  ItemName="ReleaseNumber" />
   4:  </ReadLinesFromFile>


This will store the contents of the file "ReleaseNumber.txt" in a  property "ReleaseNumber". You can then use this property in other places inside your build file:

   1:  "@(ReleaseNumber)"

 

You can also write to files:

   1:  <WriteLinesToFile File="Log.txt" Lines="This is a log value." Overwrite="false" />

Saturday, October 24, 2009

Improving type safety for INotifyPropertyChanged without expressions

Type safety is important. Isn’t it one of the reasons why you should use a static typed language like C#?  But if you’re using the INotifyPropertyChanged interface, you allready have left that type safety. Why? Because it expects you to pass on the propertyname. Easiest way to do this is just using a string parameter.

   1:  public event PropertyChangedEventHandler PropertyChanged;
   2:   
   3:      private void NotifyPropertyChanged(String propertyName)
   4:      {
   5:          if (PropertyChanged != null)
   6:          {
   7:              PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
   8:          }
   9:      }


But what if you refactor your code and change the name of the property? The string value will remain the same and the compiler will not warn you. But your code will no longer work.

A solution could be the use of expression to pass on the propertyname in a type safe way.


   1:  protected void NotifyPropertyChanged(Expression<Func<T,object>> x)   
   2:  {   
   3:          var body = x.Body as MemberExpression;   
   4:          string propertyName =  body.Member.Name;   
   5:             
   6:          if this.PropertyChanged;   != null)   
   7:          {     
   8:              this.PropertyChanged;   (this, new PropertyChangedEventArgs(propertyName));   
   9:          }   
  10:  }   



There is, however, an alternative that works on previous versions of .NET and doesn’t involve expression trees. It essentially involves creating a delegate of the target method, and using the delegate properties to get to the corresponding MethodInfo as mentioned on Daniel Cazzulino’s  blog. I didn’t tried it out yet, but as soon as I created an example, I’ll update this post.

VSTO here I come

For one of my current clients, I’ll have to start looking at the  Microsoft Visual Studio Tools for the Microsoft Office System(VSTO). I used to work with macro’s and the COM API’s for Office before. It was not really my best experience , so I was not too eager to start using VSTO.

How could I be more wrong? It’s amazing how good these tools are integrated in the Office system. I’m really starting to like it. Some invaluable resources that helped me a lot:

Expect to get a lot more posts about VSTO in the near future.

ReportViewer got an upgrade in Visual Studio 2010

Microsoft plans to release significantly updated and improved versions of both the Winforms and ASP.NET Report Viewer controls in Visual Studio 2010.  This is going to include the long awaited local mode support for the new report processing engine, originally released with SQL Server Reporting Services 2008.  Most importantly, this provides RDL 2008 features (e.g. tablix, enhanced charts, gauge, rich text) in local mode without connection to a report server.  If you wanted to use RDL 2008 features with the report viewer controls available before, server mode was your only viable option, because report processing is performed remotely on a Reporting Services 2008 server. 

Below are some of the other new features or changes who are coming as well.

  • Support for the 2008 RDL schema in local mode.  This will give you all of the new features available in RDL in SQL Server 2008, including tablix, rich text, updated chart visualizations, gauge, and many others.  The updated report design surface for local mode will also be included.
  • Support for ASP.Net AJAX.  The report viewer will use AJAX to update its various regions (report, toolbar, etc).  You will also allow be able to include the entire ReportViewer control in an UpdatePanel.
  • Updated API.  A number of new events and methods to help are added, including a new JavaScript API for interacting with the ReportViewer in the browser.
  • Significantly improved browser compatibility.  A huge amount of effort is put into improving support across browsers. 
  • Usability and “look and feel” enhancements.  The viewer got a minor facelift.

C# and it’s lifecycle

Everything becomes obsolete sooner or later. The same thing counts for programming languages.  The lifecycle of a programming language can be divided in 7 phases:

  • Conception
  • Adoption
  • Acceptance
  • Maturation
  • Inefficiency
  • Deprecation
  • Decay

Scot Allen is starting an in interesting discussion about the language phase where C# is today.

Can things only get worse after C# 4.0? Or will there still be some interesting evolutions for the C# programming language? Maybe the dynamic keyword is just a sign for what will be next…

Wednesday, October 21, 2009

31 days of refactoring

After Sean Chambers very interesting blog series 31 days of refactoring,   Simone Chiaretta converted the series into an eBook.

VSTS 2010 Beta 2 Training Kit released

The Beta 2 version of Visual Studio 2010 Training Kit is now live.

This training kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize a variety of Visual Studio 2010 and .NET Framework 4 technologies.

The Beta 2 release of the Training Kit contains 15 presentations, 19 hands-on labs, and 13 demos. Many technologies are covered in this release, including: C# 4, VB 10, F#, Parallel Extensions, Windows Communication Foundation, Windows Workflow, Windows Presentation Foundation, ASP.NET 4, Entity Framework, ADO.NET Data Services, Managed Extensibility Framework, and Visual Studio Ultimate.

Laws of dependency injection

As a heavy user of dependency injection, I’m always careful when applying it. “If you have a hammer, everything looks like a nail.”  Nikola Malovic mentions on his blog the following laws about the usage of an IOC container.

Nikola’s 5 laws of IoC:

  1. “Store in IoC container only services. Do not store any entities.”
  2. "Any class having more then 3 dependencies should be questioned for SRP violation"
  3. “Every dependency of the class has to be presented in a transparent manner in a class constructor.”
  4. “Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies.”
  5. “IoC container should be explicitly used only in Bootstrapper. Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container."

Although I don’t agree with all of his laws, he makes some good points.

Sunday, October 18, 2009

Generic Comparer

A requirement in most of our applications is a default sorting for our codetable data. For example if you want to populate a combobox with all the countries in the world, it must be sorted by default in alphabetical order.

I heard my colleagues discussing about it during one of our whiteboard design meetings. Possibilities passed by from using a custom attribute to a metadata class. While they were discussing I build the following solution; a generic comparer.

Specify the properties to sort on using expressions and pass it on to the Sort method. No direct coupling between a class and it's sorting, type safety and extensible. What do you need more?

The implementation of the Comparer is very simple, it just iterate over the expressions array and compares each property in both objects: 

   1:  public class GenericComparer<T> : IComparer<T>
   2:  {
   3:          private readonly Func<T, IComparable>[] _expressions;
   4:   
   5:          public GenericComparer(params Func<T, IComparable>[] expressions)
   6:          {
   7:              _expressions = expressions;
   8:          }
   9:   
  10:          public int Compare(T x, T y)
  11:          {
  12:              foreach (var expression in _expressions)
  13:              {
  14:                  int result = Compare(expression.Invoke(x), expression.Invoke(y));
  15:                  if (result != 0)
  16:                      return result;
  17:              }
  18:              return 0;
  19:          }
  20:   
  21:          private int Compare(IComparable x, IComparable y)
  22:          {
  23:              if (x == null && y == null)
  24:                  return 0;
  25:              if (x == null)
  26:                  return -1;
  27:              if (y == null)
  28:                  return 1;
  29:              return x.CompareTo(y);
  30:          }
  31:   }

And an example:

   1:  countries.Sort(new GenericComparer<Country>(c => c.CountryCode, c => p.Name));

Database Change Notification in Oracle

The SQL Server driver for ADO.NET has the SqlDependency class. It enables applications to receive notifications when there is a change in a query result set, schema objects, or the state of the database. Using SqlDependency, an application can maintain the validity of the client-side cache easily. At one of my clients we aren't using SQL Server but Oracle. As I searched throught the standard ADO.NET driver for Oracle (System.Data.Oracle) I couldn't find a similar class.

After some digging on the Oracle site I found that Oracle has a separate driver for .NET next to the standard ADO.NET driver. If you download the Oracle Data Provider for .NET (Oracle.DataAccess) you'll find the OracleDependency class that has the same functionality as the SqlDependency class.

A simple example to show this functionality:

   1:   public class Notification    
   2:      {     
   3:          public static bool IsNotified = false; 
   4:    
   5:          public static void Main(string[] args)      
   6:          {       
   7:              //To Run this sample, make sure that the connecting user hase change notification privilege   
   8:              string constr = "User Id=scott;Password=tiger;Data Source=oracle";            
   9:              OracleDependency dep = null; 
  10:    
  11:              try       
  12:              {         
  13:                  using(var con = new OracleConnection(constr))
  14:                  {
  15:                      var cmd = new OracleCommand("select * from table", con);         
  16:                      con.Open(); 
  17:                      
  18:                      OracleDependency.Port = 1005; 
  19:                      dep = new OracleDependency(cmd);
  20:                      dep.OnChange += Notification.OnMyNotificaton; 
  21:   
  22:                      cmd.ExecuteNonQuery(); 
  23:   
  24:                      var txn = con.BeginTransaction();   
  25:   
  26:                      string updateCmdText = "update table set column1 = 1 where column2 = 2";         
  27:                      OracleCommand updateCmd = new OracleCommand(updateCmdText, con);         
  28:                      updateCmd.ExecuteNonQuery();         
  29:                      txn.Commit();       
  30:                  }
  31:              }
  32:              catch (Exception e)       
  33:              {         
  34:                  Console.WriteLine(e.Message);       
  35:              } 
  36:   
  37:              // Loop while waiting for notification       
  38:              while(Notification.IsNotified == false)       
  39:              {         
  40:                  Thread.Sleep(100);       
  41:              }   
  42:          }       
  43:          
  44:          public static void OnMyNotificaton(object sender, OnChangeEventArgs arg)
  45:          {
  46:              Console.WriteLine("Notification Received"); 
  47:              DataTable changeDetails = arg.Details;  
  48:              Console.WriteLine("Data has changed in {0}", changeDetails.Rows[0]["ResourceName"]);
  49:              Notification.IsNotified = true;     
  50:          }
  51:      } 

 

As every change notification registration consumes database memory, storage or network resources, or some combination thereof, it's important to be carefull when using this feature. In order to scale well with a large number of mid-tier clients, use it only for a few tables that change infrequently.

How to Run Programs as a Domain User from a Non-domain Computer

As a consultant I spend my days in multiple companies. Given that I work for multiple clients, I can’t join my laptop to any particular client’s domain. In most cases, not being joined to a client’s domain doesn’t make one iota of difference. You need to access a network share or printer, browser to it and you will be prompted for domain credentials. But if you have to connect for example to a SQL Server Instance through the Management Studio, you cannot enter domain credentials.

I found this blog post from James Kovacs where he found a solution to access SQL Server Management Studio using a domain account. Nice!

Why can't I edit my WinForms control?

Last week, one of my developers came to me with a strange question. He had to change one of our existing WinForms views. There was one label that he couldn't edit. When he tried to access this control in code, the Intellisense would not show up. I came by to have a look.

As I found out, a control has a GenerateMember property. If you change this property to false, the control code is generated by the designer as a local member of the InitializeComponent() method and therefore is not accessable outside the context of this method. And that was exactly the problem he had. He accidently changed the default value from true to false. By changing it back, a class level member is generated and he could access the control again from other places.

Sunday, October 11, 2009

Enable code coverage on your TFS Build server

One of the nice features of Visual Studio is the integrated code coverage. It gives you a nice view how much of your code is covered by (unit) tests. After enabling this feature on my local Visual Studio environment, I noticed that this setting was not automatically duplicated to our build environment.

You have one extra step to enable the code coverage functionality on your build server. Add the following line in TFSBuild.proj after <RunConfigAnalysis> tag.

   1:  <RunConfigFile>$(SolutionRoot)\YourAppDir\LocalTestRun.testrunconfig</RunConfigFile>

By default, the Microsoft.TeamFoundation.Build.targets files defines the SolutionRoot property as:

SolutionRoot = $(BuildDirectoryPath)\$(TeamProject)\$(TeamBuild)\BuildType\..\Sources

So if you have created a new Build Type under a team project named TestProject and set the New Build Type Wizard’s values to the following:

  • Team Build Name = CI Build
  • BuildPath = C:\Build

the resulting final SolutionRoot property would be C:\Build\TestProject\CI Build\Sources.

Saturday, October 10, 2009

Using the HelpProvider to show an HTML help page

In .NET WinForms a HelpProvider component is available to let you add help functionality to your application. While I tried to use this component in one of my applications, I noticed it is poorly documented. I hope this post can help you get started.

The HelpProvider

HelpProvider is an Expander Provider class that contains a number of hashtables to externally add help related properties to windows forms controls. The HelpNamespace string property identifies a help system and must be set to use HelpKeyword/HelpNavigator. It is NOT a namespace. It can be a uri or local file name or possibly other things as well.

The four directly manipulated hashtable properties are:

  • ShowHelp – a Boolean flag that enables the display of help through the HelpProvider.
  • HelpString – a string to display in a pop-up window. Typically activated by clicking on the control when the cursor is a “?” or when the control has focus and HelpNamespace is null.
  • HelpKeyword – a string to identify the help request passed to a help system. Optional. Used to steer a help system to the correct point.
  • HelpNavigator – an enumeration value that guides the help system in what to do with the HelpKeyword.

The HelpProvider registers event handlers on the control’s HelpRequested and QueryAccessibilityHelp events if enabled and minimally configured.

The Help class provides the actual methods for displaying help.

   1:  Help.ShowPopup(parent, caption, location)
   2:   
   3:  Help.ShowHelp(parent, helpNamespace[, helpNavigator[, helpKeyword]])


If HelpNamespace uses “http:” or “https:” schemes then only HelpNavigator.Topic can be used which appends “#”+HelpKeyword onto HelpNamespace.

Diving into the StoryTeller trunk

Björn Rochel has written a series of blog posts on elements of the StoryTeller code base. If you want to learn more about presentation patterns, autowiring and UI management have a look.

Wednesday, October 7, 2009

Limiting the users in the Assigned To field on a Work Item

By default, the Assigned To field on a work item shows all users known to TFS (members of the TFS Everyone group). Most of the time you want to limit this list to the users of a specific Team Project.

To do this export the work item type from your project with the WITExport tool. If you want to assign work items to groups, replace the definition of Assigned To with the following XML. This expands all users and groups defined in the project contributors group in the Assigned To pick list.

   1:  <FIELD name="Assigned To" refname="System.AssignedTo" type="String">
   2:  <ALLOWEDVALUES expanditems="true">
   3:        <LISTITEM value = "[Project]\Contributors" />
   4:  </ALLOWEDVALUES>
   5:  </FIELD>


Afterwards you can import the changed workitem definition by using the WITImport tool.

Why project managers are underpaid?

Last week, Mitch Lacey was in Belgium to deliver a Scrum training at Ordina. The last day of this training I had the opportunity to give a session about the role of a project manager in a Scrum project. If you're interested in the slidedeck, it's available here.
Scrum - Why PM are underpaid

Scrum in 10 minutes

One of my colleagues send me a link to this YouTube video. Watch to learn(almost) everything you need to know about Scrum.

TDD for Dummies

As I was reading through some old stuff to prepare a presentation, I found this old blog post of Jeremy Miller about TDD. He really was cranky the day he wrote it, but the message he wants to deliver has a lot of value.

How do we get ClickOnce working with Team Build?

By default, the Team Build server will only compile your assemblies. Creating the necessary manifests, application and setup files necessary to deploy a clickonce application is not executed by default. Enabling this feature is very easy. Edit the TFSBuild.proj file and copy the “SolutionToBuild” line, and put it below, and rename it to “SolutionToPublish”.

   1:  <SolutionToPublish Include="$(BuildProjectFolderPath)/Source/MySolution.sln">
   2:        <Targets></Targets>
   3:        <Properties></Properties>
   4:      </SolutionToPublish>



Team Build will then build the code and place a versioned ClickOnce directory in the drop folder that you can then copy over to your deployment location.

Hosting an ASP.NET 3.5 website on IIS 7

Although using IIS is not that hard, I had some issues to get my website deployed. As I didn't install the webserver, it took me a while to find out which features were missing. The following steps can help you checking if your server is ASP.NET 3.5 ready:

Install the Web Server Role

  • In Role Services, select ASP.NET and continue.

Install the .NET 3.5 Framework

Publish Your Application

  • In Visual Studio, publish your web project to a local folder, like on the desktop.

  • Copy that folder to a local folder on the webserver, maybe somewhere like c:\apps.

  • From the IIS Manager, right click your Default Web Site and "Add Application".

Enable ASP.NET Impersonation on your Website

  • IIS -> Your website -> Authentication -> Enable ASP.NET Impersonation.

Test your Application

  • Open a browser, and try http://localhost, verify that the IIS 7 page comes up and you know IIS 7 is installed correctly.

  • Then test your application by browsing to http://localhost/your_application.

Troubleshooting

  • If you receive .NET 3.5.0.0 reference errors or csc.exe not found, make sure you've installed the .NET 3.5 framework.

  • If your web page does not display correctly, or images are missing, check all of your url links.  For all of your url links, use an absolute path like "~/Images/".

  • If you receive an error connecting to a local database, "Invalid login for NT AUTHORITY/NETWORK SERVICE"... open SQL Management Studio, add a new login, find the NETWORK SERVICE credential and grant that login db_owner permissions for your database(or use a dedicated user for your application pool).

Sunday, October 4, 2009

Healthy Team Habits with Team System

David Starr from Pluralsight wrote an article about how to use Team System to drive positive organizational change. Check it out.

Saturday, October 3, 2009

97 things every programmer should know

After 97 Things Every Architect Should Know the 97 Things series continues with the things that every programmer should know. The Things are collected in a wiki, and everybody is welcome to contribute and comment on the entries.

12 Practices to be a Better Developer

The 12 Practices

  1. Source Control - If you don’t store your code in source control, you’re putting your company at risk.
  2. Test-Driven Development produces higher-quality code. Behavior Driven Design - Behavior is documentation for other developers and users.
  3. Build Systems - Building is more than just compiling code.
  4. Continuous Integration - Check in early and often.
  5. Real Time Code Review - Two heads are better than one.
  6. Refactoring: Easy as red light green light.
  7. Read Code - "You don’t become a better writer by just writing." Scott Hanselman
  8. Code In Increments - Real programmers work for hours and hours straight, without a break, without even looking up. Don’t break your flow to stop and compile: just keep typing! :)
  9. Sharpen your skills by learning a new language.
  10. Learn SOLID
    • Single Responsibility Principle - There should never be more than one reason for a class to change.
    • Open Closed Principle - A class should be open for extension but closed for modification.
    • Liscov Substitution Principle - Subtypes must be substitutable for their base types.
    • Interface Segregation Principle - Clients should not be forced to depend upon interfaces that they do not use.
    • Dependency Inversion Principle - High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.
  11. Know when to unlearn. The ways you learned when you first started are clearly the best ways. Not much has changed since then, really. :)
  12. Be a Mentor

Read further here: 12 Practices to be a Better Developer

IP address restrictions in IIS

At one of my clients we wanted to prevent that test clients could call our production services. Thanks to the fact that we are using WCF services hosted in IIS, this could easily be accomplished.

  • Open the  IIS Manager(InetMgr).
  • Select the website where you want to apply the IP restrictions, right-click and select Properties.
  • Go to the Directory Security Tab.

clip_image002

  • Click on the Edit button in the IP address and domain name restrictions groupbox.

clip_image004

  • Change the default configuration to  Denied access.
  • Afterwards clickon on Add… to configure the range of IP addresses who connect to this website.

clip_image006

  • Complete the correct subnet mask. Click 3 x Ok, and the changes are applied.

TFS Workflow Control

One of the nice features in Team System Web Access is the visualization of the workitem workflow. Team Explorer users had to miss this feature.

Michel Perfetti just released a custom work item control that does exactly what TSWA does…

Workflow_in_wi

Download the control from codeplex: http://tfsworkflowcontrol.codeplex.com/

.NET 4.0 becomes lazy...

If you just think, you have discovered all the exciting new features in .NET 4.0, you always find some new bits of nice functionality.

Lazy<T> is one of those features.

It brings lazy loading to the core of the .NET framework. Suppose that you have an object that is very expensive to create and use. You don’t want to create it everytime your application runs. You only want to create it when you need it. Lazy<T> makes this easy.  You just create a lazy wrapper on the expensive object:

   1:  Lazy<ExpensiveResource> ownedResource = new Lazy<ExpensiveResource>(); 

To get the expensive object just use the ownedResource.Value property. The first time you access ownedResource.Value, the expensive resource will get allocated, but not before.

And the API designers did a really good job and added two very useful constructions:

First, Lazy<T> has an overloaded constructor that allows you to specify a Func<T>. This makes it possible to use a factory method to construct your object. No new() constraint that limits the usability of this class.

   1:  public Lazy(Func<T> valueFactory) 

Second, there are two other constructors in Lazy<T>:

   1:  public Lazy(LazyExecutionMode mode); 
   2:  public Lazy(Func<T> valueFactory, LazyExecutionMode mode); 


These two constructors indicate that you are running in a multi-threaded environment, and the lazy construction of the owned object must be synchronized. So you are assured that only one thread will actually create the object.

It makes me wonder what other things are out there in the .NET 4.0 Framework...