Archive for category Coding
Squeezing some memory for classic ASP
Some colleagues of mine are maintaining a large business application that uses the technology stack of classic ASP 3.0 and COM components written in Visual Basic 6. Changing the application itself to use more recent technology is not an option at the moment. Being a totally non-cutting-edge task, it turned out quite interesting in the end.
Memory limitations
There’s one really problematic aspect in running this app: some features are quite hungry for memory. With a lot of concurrency going on, memory consumption has become the reason to add more servers to the server farm for some times now. Each of the servers is running a 32bit version of Windows Server, and is equipped with 4GB of RAM.
Now on a 32bit OS, the maximum amount of usable memory is 4GB in total, and half of that is reserved for the kernel. That makes 2GB left for all applications altogether.
IIS will not allocate all of this to applications. There is a memory limit that throttles the memory usage to 60% of what’s available (see here for more background, thanks Jason Follas) This percentage setting can be set in the machine.config file: . Increasing this limit to 75% or 80% is doable on a dedicated web server (the key word is “dedicated” here. No additional services, please.)
Using the 4 gigabyte tuning (“/4GT”, formerly known as “/3G” boot switch), it is possible to let Windows use only 1GB for the OS kernel, and yield 3GB for applications. While this increases the memory available for the IIS worker processes, the OS becomes quite limited; running a load test after applying the setting is paramount (and I always found it scary).
These optimizations are good for some extra percent – but we were looking for a solution that would get the problem resolved for good. And that does not go without jumping the 4GB limitation on the server.
PAE looked promising, but with 64bit processors and operating systems well adopted, PAE looked like a bridging legacy technology, and moving to a 64bit environment a more forward-facing step.
Classic ASP on 64bit
There is no 64bit version of VB6, and there never will be. So if an ASP application needs to instantiate components written with VB6, it needs to run in a 32bit process. IIS 7 and IIS 7.5 support switching a worker process to 32bit on the Application Pool. This means that individual applications can be run as 32bit processes. But is that a good idea, compared to simply running on a 32bit operating system?
On a 64bit machine, there is of course a limit in how much memory can be assigned to a 32bit process that is imposed by the length of the address pointer, this limit is 4GB. But in contrast to the 32bit OS where this applies to the whole operating system, these 4GB are available to every process individually. So instead of 1.5 GB, there are 4 GB of memory available out of the box, without any advanced settings or modification.
Now to utilize the full amount of memory that a machine has to offer, you can run multiple of these processes. When a load balancing solution is already in place, you can simply replace the previously used physical machines by web sites on the same server, each with a different IP address. Each of the web site runs in a different application pool, in its own 32bit process. Each of these processes manages its own 4GB of memory. As IIS does not allocate all of this memory, it’s safe to run four web sites on a server with 16GB of RAM.
Application Request Routing as local load balancer
If no existing load balancer is in place, IIS Application Request Routing (“ARR”) can be used to distribute requests between the web sites on the server locally. With this model, the web sites that run the ASP applications are bound against local IP addresses: in addition to the external IP address on a physical network adapter, a loopback adapter is installed. A range of private IP addresses (like 192.168.42.x/255.255.255.0) is assigned to the loopback adapter. In addition to the web sites for the ASP application, there needs to be one web site that is bound against the external IP address. This web site should point to an empty directory so that there is no interference between resources available on that web site, and URLs that are handled by the application web sites.
In the configuration of ARR, a web farm addresses each of the web sites on the server as an individual server. ARR creates a default routing rule that routes all incoming requests to the web farm that consists of the local web sites. There is a problem with this rule however: because the application web sites are local, ARR will recognize requests coming into these sites too. This creates a closed loop. ARR needs to ignore requests that come into the local web sites: a condition is added to the default routing rule that it only kicks in when the server IP address is not within the local network address range used for the application web sites.
If the classic ASP session is used, clients need to be sent to the same web site every time; the ASP session is stored in the context of the worker process. This is achieved by activating Client Affinity in ARR – ARR sets a cookie itself, and uses this cookie to determine the web site to send clients to.
Format all files in project
Yesterday I discovered an awesomely useful Visual Studio macro: it applies that code formatting rules to all files in the whole solutions. Code formatting includes indentation, spacing, tabs vs. spaces: all the things that people tend to get irate about. By default, these formatting rules are applied only when you write new code. To apply them to an existing page, there’s the command Edit --> Format Document with the keyboard chord Ctrl-K, Ctrl-D. Now this macro goes and opens all files and applies this command – a very good idea to do before a major commit.
Sub FormatProject()
For Each Proj As Project In DTE.Solution.Projects
For Each Item As ProjectItem In Proj.ProjectItems
Dim window As EnvDTE.Window
Try
window = Item.Open()
window.Activate()
DTE.ExecuteCommand("Edit.FormatDocument", "")
Catch ex As Exception
End Try
Next
Next
End Sub
Found as a comment by saraford to this MSDN post from 2005.
So are you a MEF type of guy?
When I first looked into MEF, I could not help but share the sentiment that others had also expressed: it felt a little unclean. Not as dirty as a GOTO, but there was some RADish smell about it.
Any dependency injection (“DI”) framework does at least one thing: resolve the location of a piece of code so that other pieces of code do not have to know where it is. A classical DI framework like Spring.NET or Unity share a standard approach:
- Every service (a class that does something, and not only contains state) implements an interface.
- The exact type of the service – its name and assembly – and initialization parameters are added to a registry. While XML files are often used for defining this registry, there are other flavors as well; in any case, there is a central and explicit definition of what the application consists of.
- Everyone who uses the service exposes a dependency on it via its interface. A property of a constructor parameter is used by the DI framework to pass an instance of the service.
Some DI framework use attributes to define which property is relevant for the DI container, some don’t. Some use XML registry files, others offer a catalog definition by code. A variety of frameworks is available in production quality. So the choice of the perfect DI framework often becomes a highly subjective matter, largely influenced by a personal style. My favorite flavor is Spring.NET, no attributes, XML registry, and autowire by name.
Style aside, when a project has been developed with a dependency injection framework in place, it is likely that:
- It lends itself to unit testing. A DI framework promotes the idea of decoupling units of functionality. This makes writing tests after the implementation significantly easier. (Now let’s not argue if it’s better to write tests before implementation and accept that a lot of developers just do it that way.)
- There is decent separation of concerns. A key principle of DI is that you pass dependencies as interface implementations – this alone makes you think about what the correct interfaces are.
- You know what is inside the application. The registry can be read like the yellow pages of your application: what services exist, and even – if you stick to a verbose style without autowiring – where they are used.
Now comes MEF. With MEF, there is no registry; it just searches through all that is there and dynamically composes its catalog. In addition, MEF does not only let you use objects as the resource that can be located by the framework, but also property values, and even methods. This versatility makes MEF a hugely productive piece of infrastructure.
It makes the applying DI easy in situations where you don’t control the lifetime of objects. Think of WCF. WWF. Silverlight controls. With a classical DI framework, applying ServiceLocator is the only way out – MEF does not require any special patterns.
The application can be extended without changing a shared resource (the DI registry). This resolves a major pain point when you develop in an environment that you do not own – either something that explicitly offers a plug-in model, or when you provide customizations to a third-party system.
MEF is peer to peer Dependency Injection
The downsize however is that MEF does not enforce or encourage better testability, class design, or discoverability of functions. And this is where the smell wafts in: where a classical DI framework can act as a catalyst around which Good Code crystallizes. MEF does not require any coding patterns to support it, and hence does not have this potential.
But that’s not a bad thing either. Because what is gained is the ability to decouple the implementation of functionality and where it is located, and that’s the primary and ultimate goal of the inversion of control pattern. With MEF, this goal can be more easily achieved in scenarios that would otherwise be complex, or require support from additional patterns like Service Locator. Now it’s a common observation that people prefer things that are easy over those that are hard, it’s likely that you’re going to see more applications that utilize DI with MEF that otherwise would not.
DI frameworks exert a positive force on the code structure. But that’s not what they’re there for.
While the usage of a DI framework can lead to an overall higher code quality, there are much stronger drivers for these goals. The best way to get to an application that lends itself to unit testing is to write unit tests. For a testable class design, it does not matter that much if the first version of the class has been written in a testable fashion as long as developers are not afraid to refactor it while they are writing the tests.
In the role of a development manager who’s worried about poor separation, I’d recommend looking at the affluent and effluent coupling code metric: classes should have some dependencies and low complexity, otherwise they’re likely to do too much (or have no dependencies and a lot of types that are dependent on it: then it’s a low-level service). NDepend is a great tool for measuring this kind of metrics. NDepend can also find out MEF abuses for you; let’s say you don’t want methods to be used as exports.
And then there is one big advantage of MEF: it’s something like the batteries-included, official DI framework for .NET. This is quite powerful because it’s going to be covered in training materials, code samples, and maybe even developer certification tests. When you hire a developer into your product, you won’t have to train them on your specific flavor of framework, or worry if there has been any exposition to the technique at all.
Also found this: An export provider that allows defining MEF exports with attributes, in an external XML file.
NUnit for Silverlight: Skipping 2.5.7
I just looked at porting NUnit 2.5.7 for Silverlight, but decided on skipping this release. Inside the NUnit framework itself, there are hardly any changes except some minor refactoring. The only significant addition is a TestContext class that provides information about the test that’s currently running. Sweet, but even Charlie Poole describes it as “experimental” at the moment, and it requires support from the actual test runner.
Instead, I’ll finally figure out the licensing, get the code to a robust hosting platform, and clean up some of the code. Alright?
Like the Yellow Pages for NHibernate
I’ve just listened to Scott Hanselman‘s podcast Hanselminutes Episode 225: Learning about NHibernate 3. with Jason Dentler.If you’re already into NHibernate, you won’t really learn so much new. But if you think about familiarizing yourself with NHibernate, it’s a must-listen.
Scott points out correctly that one thing where NHibernate does not shine is that it’s kind of hard to get a complete view of all the different projects and documentation spread out across the Internet. In reaction, Jason produces the most complete list of resources that I’ve seen in one place. In 35 minutes you’ll know most about where to look, and what to expect from NHibernate. The show notes contain links to most of the mentioned web sites.
[Re] Using Hints for Generic MEF Exports
It seems like I’m becoming a Jeremy Likness fanboy, but this ties in too nicely with what I’m currently playing around with:
Replacing components with MEF
What I’m trying to do
Not many businesses in the world operate in the very same way. When you’re selling a line of business application, more often than not, the standard implementation does not exactly match what the customer wants. Providing the application with a wealth of configuration options helps, but you can only offer as an option what you can foresee; and sometimes people have surprising ideas. Yes, some of these ideas are bad and it’s best to talk the customer into an area of sanity again, but in an equal number of cases, you just didn’t think of it.
So to make sure that your application is going to cope with unforeseen change, it’s good practice to make parts interchangeable, and Dependency Injection is the agreed tool for accomplishing this. The metaphor of an interchangeable part is simple enough: you’ve got an interface, and two implementations for it. The implementation that ships with the standard product can be exchanged with a custom one.
Interesting enough, a lot of Dependency Injection Frameworks (“DIFs”) do not really shine when you want to accomplish this. The problem is that a lot of DIFs use the interface of the component as the key in their catalog, and do not allow two identical key, with the result that you cannot have two implementations of the same interface. MEF has a slightly different reason, but puts up some resistance nonetheless. What I’m trying to build here is a way to provide frictionless replaceable components with MEF.
Define a priority for exports
Here we’re got an interface for an add-in component, and a class that uses it:
public interface IMyAddin
{
}
public class Consumer
{
[Import]
public IMyAddin MyAddin { get; set; }
}
In a lot of DI frameworks, having multiple implementations for a single interface is not possible: the DI container simply would not know which one to choose. MEF however does not have the slightest problem with multiple exports for the same contract. In fact, having multiple parts with the same export definition is how you can use MEF to provide different components via a plug-in interface.
In order to let an import receive multiple components, an [ImportMany] attribute is applied to a property that is set up as an enumeration. The class that declares the ImportMany import can then decide which of the implementations to use or instantiate. This is a very powerful concept, and I like it quite a lot that there explicit control – MEF provides the infrastructure, but does not force business logic into the framework.
[ImportMany]
public IEnumerable<IMyAddin> AllMyAddins { get; set; }
In the scenario of this article however, each and every dependency setter property would need to be declared as a collection, marked with [ImportMany], and there would need to be imperative logic that choses the right implementation for the collaborator. This is obviously a lot of overhead, and worse: forces infrastructural responsibilities into business logic. Nope, not a good idea. The import properties should not need to change.
If the imports cannot change, we’ve got the exports. In our scenario, the implementation of an interface either belongs to a standard product or a customization. The exported component knows what it is: it can declare itself to be either a low-priority standard implementation, or a high-priority customization.
Now MEF supports Metadata that describes additional, user-defined properties for exports. The metadata consists of simple key-value pairs, and is defined as an additional attribute. So we can mark exports with a priority by providing metadata:
[Export( typeof( IMyAddin ) )]
[ExportMetadata( "Priority", 0 )]
public class LowPriorityAddin : IMyAddin
{
}
[Export( typeof( IMyAddin ) )]
[ExportMetadata( "Priority", 5 )]
public class HighPriorityAddin : IMyAddin
{
}
Choosing the export with the highest priority
So what we’ve got is the ability to declare the priority of an export, and an import that the part with the highest priority is assigned to. Someone needs to decide which is the that part.
Between the export and the import, there is the catalog, and the container. The catalog has an extensibility point that is very well suited. All catalogs derive from the abstract base class ComposablePartCatalog, which provides a virtual method GetExports: it returns the parts that match an import definition. By overriding this method, we can manipulate the assignment to an import so that when multiple exports are defined, only the one with the highest priority is returned. So:
Let’s build a catalog.
This implementation of a MEF catalog provides some logic to look up an export’s priority, and if there is more than one of the same contract, only returns the one with the highest priority. If no priority is defined on an export, it counts as a zero.
using System;
using System.Linq;
using System.ComponentModel.Composition.Primitives;
using System.Collections.Generic;
namespace GreenIcicle.ReplacementExport
{
/// <summary>
/// An implementation of a MEF part catalog that lets parts of the same
/// contract be replaced with other implementations based on a Priority
/// of the export.
///</summary>;
/// <remarks>;
/// This is a decorator around an existing catalog.
/// </remarks>
public class ReplaceablePartCatalog : ComposablePartCatalog
{
private ComposablePartCatalog m_Catalog;
/// <summary>
/// Creates a new ReplaceablePartCatalog around an existing catalog.
/// The catalog that this class decorates is provides in the constructor
/// paramater "catalog".
/// <summary>
public ReplaceablePartCatalog( ComposablePartCatalog catalog )
{
m_Catalog = catalog;
}
/// <summary>
/// Returns the exports in the catalog that match a given definition of an import.
/// This method is called every time MEF tries to satisfy an import.
///</summary>
public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports( ImportDefinition importDef )
{
// We only need to care about replacements when the import
// requires just one export to be satisfied - in the case that an
// ImportMany is defined, use the standard bahavior and return
// all matching exports.
if( importDef.Cardinality != ImportCardinality.ExactlyOne )
{
return base.GetExports( importDef );
}
// We know we need to return exactly one import, now find the matching
// tuple of a part and its export definition
Tuple<ComposablePartDefinition, ExportDefinition> matchingExport = null;
int matchPriority = -1;
// Walk through all parts in that catalog...
foreach( ComposablePartDefinition partDef in Parts )
{
// ... and for each part, examine if any export definition matches the
// requested import definition.
foreach( ExportDefinition exportDef in partDef.ExportDefinitions )
{
if( importDef.IsConstraintSatisfiedBy( exportDef ) )
{
// See if there is a Priority defined in the export's metadata.
// If this is the case, replace the current matching export
// if it has a lower priority. If there
// is no priortity defined, assume a value of 0.
object priorityMetadata;
exportDef.Metadata.TryGetValue( "Priority", out priorityMetadata );
int priority = ToInt( priorityMetadata );
// If the priority of the current export is equal to the
// previously found export, remove it: in this case
// there are two exports with the same priority, and
// it's not possible to decide which one to use.
if( priority == matchPriority )
{
matchingExport = null;
}
// If the priority of the current export is better than
// the previously found export, replace it.
if( priority > matchPriority )
{
matchingExport = new Tuple<ComposablePartDefinition, ExportDefinition>( partDef, exportDef );
matchPriority = priority;
}
}
}
}
// The return value of this method is an enumeration with one element,
// or when no matching export could be found, zero elements.
IList<Tuple<ComposablePartDefinition, ExportDefinition>> result
= new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
if( matchingExport != null )
{
result.Add( matchingExport );
}
return result;
}
/// <summary>
/// Returns the parts available in the catalog.
/// </summary>
public override IQueryable<ComposablePartDefinition> Parts
{
get
{
return m_Catalog.Parts;
}
}
/// <summary>
/// Converts an untyped value into a int. If the object is null
/// or cannot be converted to an int, returns 0 (zero).
/// </summary>
protected static int ToInt( object value )
{
if( value == null )
{
return 0;
}
int result = 0;
Int32.TryParse( value.ToString(), out result );
return result;
}
}
}
The lame part about this catalog is that it handles multiple exports with the same priority as if there if there was not a single one, obfuscating the real cause of the problem. If you feel inclined to use this in some production code, you should change this; if you don’t, you’ve hereby be warned.
An interesting detail is that if the changed implementation of GetExports checks the ImportCardinality, and falls back to the base class implementation if not exactly one part is required to satisfy the import. This is done so that [ImportMany] imports still get all suitable parts, and not just the one with the highest priority.
Trying it out
Now we want to see the whole thing work. This test takes two classes that have the same export contract, and tries to satisfy a single property import; one of the exports has a higher priority ans wins.
[Export( typeof( IMyAddin ) )]
public class StandardAddin : IMyAddin
{
}
[Export( typeof( IMyAddin ) )]
[ExportMetadata( "Priority", 5 )]
public class HighPrioAddin : IMyAddin
{
}
public class Consumer
{
[Import]
public IMyAddin MyAddin { get; set; }
}
[TestClass]
public class ReplaceableContainerTest
{
[TestMethod]
public void CreateContainer_ImportWithHighPriority_ReplacementWins()
{
// Arrange
// -----
TypeCatalog typeCat = new TypeCatalog(
typeof( StandardAddin ),
typeof( HighPrioAddin ),
typeof( Consumer ) );
ReplacablePartCatalog cat = new ReplacablePartCatalog( typeCat );
CompositionContainer container = new CompositionContainer( cat );
Consumer consumer = new Consumer();
// Act
// -----
container.SatisfyImportsOnce( consumer );
// Assert
// -----
Assert.IsNotNull( consumer.MyAddin );
Assert.AreSame( typeof( HighPrioAddin ), consumer.MyAddin.GetType() );
}
}
woo-hoo! We can see that no CompositionException has been thrown (which is what happens when there is a problem with satisfying an import), and that a HighPrioAddin object has been created and assigned.
A better Export attribute
What I don’t like that far is that you have to define the Priotity metadata for every export, and that you have to type “Priority” right every time – an typo or otherwise invalid metadata declaration would not even lead to a runtime error, the priority would silently be set to zero.
Luckily, MEF supports custom export (and import) attributes. These are very easy to create: Derive from the base class of the attribute, and mark it with the [Metadata] attribute, and it’s possible to have a strongly-typed Priority value with a decent default value. When the attribute is used, MEF turns every public property of such a class into an entry in the export metadata dictionary. Please also note that the custom attribute is marked with “AllowMultiple = false”. The default is that the same attribute can appear multiple times – this would create multiple definitions of the priority, and hence, the metadata value in the dictionary would be an array of integer.
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
namespace GreenIcicle.ReplacementExport
{
/// <summary>;
/// Marks an export as a replacement for another export with the same contract.
/// </summary>;
[MetadataAttribute]
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method,
AllowMultiple = false )]
public class ReplacementExportAttribute : ExportAttribute
{
#region Constructors
public ReplacementExportAttribute()
{
Priority = 5;
}
public ReplacementExportAttribute( Type contractType )
: base( contractType )
{
Priority = 5;
}
public ReplacementExportAttribute( string contractName )
: base( contractName )
{
Priority = 5;
}
public ReplacementExportAttribute( string contractName, Type contractType )
: base( contractName, contractType )
{
Priority = 5;
}
#endregion
[DefaultValue( 5 )]
public int Priority
{
get;
set;
}
}
}
Using this custom attribute, these two export definitions become equivalent:
[Export( typeof( IMyAddin ) )]
[ExportMetadata( "Priority", 5 )]
public class LowPriorityAddin1 : IMyAddin
{
}
[ReplacementExport( typeof( IMyAddin ) )]
public class HighPriorityAddin2 : IMyAddin
{
}
Rounding it up
So with quite little effort, we can customize MEF to use either one or another implementation of the same component, without changing any business logic code, and have just a nice attribute to differntiate between low-priority and high-priority exports.
My Own Private Hype Cycle
- NoSql: After finally reading Ayende‘s blog posts and this CodeProject article, I downloaded RavenDB yesterday and crushed down in the park to take it for a spin. I’m quite convinced that letting go of the strictness of relational databases is something that will really take us a whole step forward, and now I’m superexcited about how well RavenDB works that I even told my father in law. So please bear with me, I’m sure it’s going to wear off.
- Android Development: I’ve got the SDK, I’ve got the phone, I’ve got some ideas for halfway useful apps (at least useful for me): what’s holding me up? Java is. Or in fact, my limited abilities with it. I find everything taking twice as long as it should, and while this makes a good learning experience, it’s not really what I’m after at the moment. I don’t plan a career as an Android developer, I just want to get an educated feeling of how it is on the form factor, and what patterns apply.
- MEF: I feel like getting the hang on it now, some judgement on when and how expose parts, and the contrast between MEF and a classical DI framework like Spring or Unity. MEF is going to make it into some productive code sooner or later now.
- .NET 4: Yup, I think it has left the learning phase for the larger part.
MEF in Silverlight: a perfect sample app
Jeremy Likness has created something that is quite close to being the perfect sample application: It has about the third of the scale of a real-world application: not just the usual two forms, but also not the size of a book. There’s a lot of concepts used in the right way, but you don’t need to read the manual before you get through it. The whole thing looks like something that you would write as proof-of-concept for a real project. I think Jeremy has really met the perfect balance of size, complexity, and simplicity.
Oh, and it is about using MEF in Silverlight that really make sense.
Here’s the link: http://csharperimage.jeremylikness.com/2010/06/advanced-silverlight-applications-using.html
NDepend: My new hammer for code reviews
Welcome a new member in my toolbox: NDepend. If you haven’t seen it yet: it is a tool for static code analysis for .NET code – static code analysis meaning that it looks at a set of assemblies and source code and tries to figure out how it all hangs together, and tells you something about its inner characteristics. It can for example tell you which are the most referenced or the most complex classes in your project, and if the way that your project is really structured is similar to the way you think it is. NDepend also sports the most busy, dense, chaotic and against-any-expectation user interface that I have ever seen, and you too.
I have been using NDepend once in a while for some while, but more on an on and off basis. I basically used it as a means of due diligence on code that I do not know, but have to get my feet into. NDepend can give you an overview of the structure of a large piece of software, and some of its problems, in 15 minutes. Now, I found a reason to use it on an at least weekly basis.
I’m currently involved in a project where multiple SCRUM teams are working on the same code base. When a Sprint (that is a project step in a time box of four weeks, but you should really know that) ends, the team runs a demo with the product owner (“PO”), who decides if the result are acceptable. Each Sprint is on its own code line. Now after the PO gives her OK, the code can go to the MAIN code line: the content of the product that is going out to the customer (it’s not that simple, but you get the picture).
Now the PO does not really care about code quality, unit test coverage and quality, or the completeness of test plans. So before the code that comes out of a Sprint is released to MAIN, it is reviewed by an independent group of developers, and this is where I’m involved. Not all code from the Sprint is reviewed, about 10% are normally sufficient to see if a team has put enough emphasis on clean and structured work. But how do you find out what has been changed, and how do you pick the 10% that are most relevant?
The approach until now is to get the list of changed files from the source control system, and pick the files to review by making a guess. The problem is that the list of changed files does not tell you how much has changed – often, there has been just an adjustment in the code formatting or the correction of a typo that caused the checkin.
And this is where NDepend is hugely helpful. It can not only run an analysis on a single project, it can get you the difference between two analysis results. In order to determine what has changed in the Sprint, you run an analysis on the state of the MAIN code line, and take that as the baseline for a differential analysis of the Sprint code line. What you get immediately is a ranking of types and methods that have been added or changed, in the order of the magnitude of the change, across multiple assemblies. That alone make a huge difference in the quality of the code review, and the time you need to get there.
And that is only the start. The most powerful feature of NDepend is that you can run queries in a SQL-style lingo against the code analysis. This for example creates a warning when you’ve got methods with too many (logical) lines of code:
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE NbLinesOfCode > 30 ORDER BY NbLinesOfCode DESC
NDepend comes with a good set of these predefined queries, and you can write your own. Let’s say we want to get the classes with little comments, but only in code that has been added or modified within the Sprint:
SELECT TOP 50 METHODS WHERE
(WasAdded OR CommentsWereChanged ) // Only modified and new
AND (
NbLinesOfCode > 20 // A lot of code
OR CyclomaticComplexity > 15 // A lot of paths
OR NbVariables > 8 // Many variables
)
AND !IsGeneratedByCompiler // Exclude anonymous types
ORDER BY NbLinesOfCode DESC
In addition, you can actively search for things that you do not wish to see, like
- References to MVVM ViewModels
- References on concrete classes rather than on interfaces
- FxCop suppression attributes
- Usage of NotImplementedException
- Low unit test coverage
The only real limitation I’ve ssen is that a query can either run against types, methods, namespaces, or fields, but not against a mixture. You can for example not search for property setters that do not use the PropertyChanged event in types that implement INotifyPropertyChanged.
NDepend is free for limited usage for evaluation, academic, and open source projects; for commercial projects or the full feature set you’ll have to buy reasonably priced licenses.
Oh yes, and: NDepend can be targeted at Silverlight 3 and Silverlight 4 as well as normal .NET code.

