Monday, January 31, 2011

Altering VS Project Properties the easy way

Often I need to "batch" alter visual studio project properties for very large solutions. Example we decided to disable mandatory xml comments on all 275 visual studio projects we have. The following sample can give you an idea of how easy it is to write a small program to do this:-)

Monday, January 10, 2011

recursively call a function...

The following code fragment calls recursively a function calculating the sum of the Info integer property of every node in the tree...



If you like your func inside the method then in order to get rid of the definite assignment issue (the use of a local variable which isn't definitely assigned).

Wednesday, October 27, 2010

The Joel Test: 12 Steps to Better Code by Joel Spolsky



The Joel Test (http://www.joelonsoftware.com/articles/fog0000000043.html)


  1. Do you use source control?
  2. Can you make a build in one step?
  3. Do you make daily builds?
  4. Do you have a bug database?
  5. Do you fix bugs before writing new code?
  6. Do you have an up-to-date schedule?
  7. Do you have a spec?
  8. Do programmers have quiet working conditions?
  9. Do you use the best tools money can buy?
  10. Do you have testers?
  11. Do new candidates write code during their interview?
  12. Do you do hallway usability testing?
I strongly recommend this post! Read it :-)

patterns & practices: Prism – A lap around build events!

We all not and understand the notion of a Visual Studio Project and a Visual Studio Solution.

solutionsandprojects

The point is that a solution has many projects and a project can belong to many solutions.

Solution & Project format

The format of a Visual Studio Project is MSBuild. The format of a Visual Studio Solution is something proprietary. It’s not even xml, it reminds me a basic(ish) lookSmileBy the way I never understood the reason that they didn’t use MsBuild also for solutions. The following is simply a random solution file.

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MVVM", "MVVM\MVVM.csproj", "{5071C191-7663-422C-AE32-4B638F6C12FA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MVVM.Test", "MVVM.Test\MVVM.Test.csproj", "{2399D68D-7791-4979-B1F7-FD17A6399E2B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5071C191-7663-422C-AE32-4B638F6C12FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5071C191-7663-422C-AE32-4B638F6C12FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5071C191-7663-422C-AE32-4B638F6C12FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5071C191-7663-422C-AE32-4B638F6C12FA}.Release|Any CPU.Build.0 = Release|Any CPU
{2399D68D-7791-4979-B1F7-FD17A6399E2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2399D68D-7791-4979-B1F7-FD17A6399E2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2399D68D-7791-4979-B1F7-FD17A6399E2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2399D68D-7791-4979-B1F7-FD17A6399E2B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

 


Build Events


What is a build event? Well by default every project gets to override two build events: Pre-Build and Post-Build. You can attach your own batch functionality here. Personally if you understand MsBuild well enough then there are better and more MsBuild friendly ways to do this. I consider this the poor mans approach to hook before and after the build. Stay tuned I will soon right a post on this…


VisualStudioProperties


Visual Studio provides also some help for you. If you click the “edit” buttons then you will get a simple editor with a list of “Macros”.


macros


These macros are nothing more than PropertyGroups inside the hierarchy of MsBuild files that define the project. No wonder the convention for referening to any of these is $(macro_name).


Don’t abuse the build events


Wow, some very hard words. Abuse the build events? Well it can happen! Let’s take an example of a known open source project: Prism. You can download the sources at http://compositewpf.codeplex.com/


Prism offers some nicely written AcceptanceTests. I strongly recommend it for better understanding of UI Test Automation. Now the problem they try to address for the AcceptanceTest developer is solution decoupling. The AcceptanceTest Project being a black box, has no dependencies on any of the sources. On the other side the AcceptanceTest developer needs the possibility to make sure that the sources are build before executing the tests. In order to address this the Prism team has use a post-build event on the AcceptanceTest project.

$(MSBuildBinPath)\msbuild.exe "$(SolutionDir)..\MVVM.sln" /p:configuration=$(ConfigurationName)

The problems with this approach are the following:


  • You are obliged to build your app every single time you build your tests. In a larger system you partition solutions in order to avoid having to load (or build) too many projects. The cycle of change-build-run needs to be as fast as possible.
  • Making use of the $(SolutionDir) macro is not wise. Why? Well as I mention in the beginning of my post there can be a many-to-many relation between solutions and projects. As it’s easy to understand using the $(SolutionDir) macro forces you to be able to build the project ONLY within the context of the solution. Otherwise the relative path has a high risk to be wrong.
  • A better approach is you really like to use build events would be to use the $(ProjectPath) macro.

In a bigger system you will NEVER build solutions. Typically you build groups of projects in a well defined sequence. I include a sample of how to do this. My recommendation: don’t build solutions, build projects.

Sunday, October 24, 2010

Configuration Patterns (a lap around ent lib configuration)

I have being following the work of the Patterns & Practices team for many years now. My initial motivation was the Logging Application Block. Although the team has made significant progress the last 6-7 years it seems to me that they have being making circles in the area of configuration. Let me explain what I mean.

The Facade pattern (http://en.wikipedia.org/wiki/Facade_pattern)

A facade is an object that provides a simplified interface to a larger body of code. A facade can:
  • make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
  • make code that uses the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).

 

The Adapter Pattern (http://en.wikipedia.org/wiki/Adapter_pattern)

The adapter pattern (often referred to as the wrapper pattern or simply a wrapper) translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer but your consumer requires a 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value.

Configuration equals to code

To my understanding a configuration file is nothing but source code. The fact that it’s format is XML for example and not csharp, doesn’t mean it is less important than the rest of your source code. As a rule of thumb: anything that alters the behavior of your system at runtime is source code. A good example is XAML, I guess nobody will disagree that XAML is source code. On the other side the customers table on your database is not source code. So if we have all agreed that the configuration of your logging facility is source code, I don’t understand why the two patterns above do not apply to configuration files also.

Configuration Façade Pattern

Let’s assume that your logging facility has say a complex and over engineered schema like the one that the Logging application block has. How can you shield your app from complexity, both in code and config?
  • In the few first iterations use the block as it is. Don’t try to upfront decide what features of the logging block you need and don’t rush into simplifying the configuration schema. You run into a serious risk here: you are aborting completely an agile approach and you risk loosing valuable time during the initial iterations with less significant issues such as your logging. In addition such cross-cutting concerns require the full attention of the high level architect. Well guess what: the architect has mainly to worry about the domain in the beginning of a project. Wrong decisions in the domain area cannot be easily reverted. the most important think in software development is to build a creative collaboration between technical and domain experts to iteratively cut ever closer to the conceptual heart of the problem.
  • Once you have delivered some bits and you have the team aligned and running it’s then time to start taking care of cross-domain facilities. Make a thorough investigation of what features of the logger you currently use. Most likely you will not need any more features from the block. Then based on your findings create a simple interface (something like an ILoggerFacade) that abstracts all you need from the logger. In addition create a simple xml schema to define the configuration you need for your logger. Try to keep it simple and as flat as possible.
  • Keeping the log configuration schema simple might be challenging. You as an architect might have problems with dev leads or crazy devs who cannot think out-of-the-box. They will argue that you need to leave a “window of opportunity” open for the future. I always answer back that the widest window of opportunity is simplicity.
When you design your configuration schema (I call also it Configuration Facade) you should also always have in mind your users. How is the app deployed? Where? Who is using it?
  • A web app needs to provide a configuration façade flexible enough to allow IT staff to alter it. I believe that the config tool that ent lib provides is a developer tool not something that IT can really utilize. The existence of the tool cannot hide the complexity of the xml schema.
  • On the other hand a desktop app needs to be able to be configured within the main user interface. You cannot expect your user to use another tool (say the ent lib config tool) to twist the log settings. Further more if things get really bad and your you are providing end-user support, then you should make sure that your support staff is in a position to guide the user through a simple process to change some settings.

Configuration Adapter Pattern

Let’s assume that you need to use a different log library. If you have a simple logger façade then inferring an adapter to do the switch is fairly simple. Don’t forget, the configuration. You also need to deal with config files. If you have a good and simple configuration façade then making a configuration adapter is also very simple. The problem I often have when changing from one library to another is all configuration. Don’t “vendor lock” your self. Don’t directly use the ent lib configuration. It will not be easy to change. Believe me.

3rdparty cherry picking / consistent configuration

There is no question that you need to have the possibility to cherry pick your 3rd party. Example: use logger from one vendor and caching from another. The ent lib has being designed to be cherry picked…. except the configuration. Why? Well because every 3rd party has a different configuration schema. Again: think your users… they have to be confronted with so many different xml config schemas. It doesn’t look consistent. It’s even confusing for developers. In addition your own app will need some kind of configuration. How many schemas are you going to maintain? Another issue is that in some cases you need the flexibility to play with config files at build and install time. The more files you have the more difficult and risky this process becomes.

StockTraderRI (a simple example)

The bla – bla – blabity above is pointless without an example. Instead of making my own sample, I have chosen to demonstrate the configuration patterns inside the latest (V4 drop 10) StockTraderRI application that ships with Prism. What we will do is replace the log configuration with our own adapter. The prism team has done an excellent job isolating the code from the logging block in this sample.
public class EnterpriseLibraryLoggerAdapter : ILoggerFacade
{
#region ILoggerFacade Members
public void Log(string message, Category category, Priority priority)
{
Logger.Write(message, category.ToString(), (int)priority);
}
#endregion
}
The immediate benefit we have from this simple adapter (could also call it facade) is that out of the 13 projects this solution has only one project needs references to “Microsoft.Practices.EnterpriseLibrary.Logging.dll”. This is simply beautiful design! Now we will do mthe same for the configuration.
public class EnterpriseLibraryLoggerAdapterConfiguration : ConfigurationSection
{
public Configure()
{
var builder = new ConfigurationSourceBuilder();

builder.ConfigureLogging()
.LogToCategoryNamed("General")
.SendTo.FlatFile("General Log File")
.FormatWith(new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate("Timestamp: {timestamp}...{newline})}"))
.ToFile(FileName);

var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
}

[ConfigurationProperty("fileName")]
public string FileName
{
get { return this["fileName"] as string; }
}
}
I have kept the sample simple so the only parameter I configure for now is the file name. It’s not difficult to add more! Next you need to add the new typed section. Note the goodness here! You don’t need to add complex and loaded sections from ent lib. You have total control!
<configuration>
<configSections>
<section name="logAdapter" 
type="StockTraderRI.EnterpriseLibraryLoggerAdapterConfiguration,StockTraderRI"/>
<!--more sections follow-->
You also need of course to specify the settings for the section.
<logAdapter fileName="general.log" />
Somewhere you need to instantiate the ConfigSection in code and call the configure method
var section = (SomeConfig)ConfigurationManager.GetSection("logAdapter");
section.Configure();
This is it. Only for comparison I will show you what used to be inside the sample in respect to logging. I call this kind of configuration “THICK GLUE”. Don’t infer glue inside your application. Believe me it’s not a good idea. By the way: the glue is not harassing only you. It causes more pain to the patterns and practices team. Just imagine: they have to support all that, they have lost the right and the freedom to move on!

Log Format tips

If you are developing an application that is a web app or if you provide support for your desktop app the read the following lines very carefully.
The format of your log files is also an interface! You cannot change it anytime you like. Log files are usually read by IT staff and 1st level support staff before the ticket arrives to you as a bug. What most organizations do is attach log files together with the issues/bugs in order that they can search later in time (kind-of knowledge base). In addition you need to provide instructions to IT and support staff about how to interpret the log files at a high level. This is why I believe that the possibility to alter the format is a super-flexible way via configuration can be very tricky. So unless you have concrete requirements that formats need to change by configuration… hard code a simple format.

Conclusion

The ideas mentioned do not only apply to p&p libraries. WCF configuration is another example. I use WCF extensively. I have noticed that from all the noise inside the wcf config files (especially the client ones) nobody ever touches anything if the developer is not present. So what I do with WCF config files is exactly the same. Configuration Facades and Configuration Adapters!
I used the logging block of p&p as an example because I simply love the work and effort of this team!

Feedback

That’s all folks! The drop for the first iteration of this paper. Please send me feedbackSmile
I will post soon another related idea that I call configuration injection. It’s basically the idea of injecting typed configuration at a module level using either Unity extensions or the prism module catalog. Stay tuned.

Visual Studio 2010–Community Wallpapers

 

Logo Microsoft Visual Studio

If you are in love with visual studio… just as much as I am then you will definitely love this link!

http://vs2010wallpapers.com/

A non-Microsoft site, filled with Community Created Visual Studio 2010 Wallpapers!

imageimageimage

… and many many more! Check it outSmile

Saturday, October 23, 2010

patterns & practices Symposium Redmond 2010


The patterns and practices symposium in Redmond this year was just great. What I like about the p&p conferences is the personal contact that you get to have with the team. This is practically impossible in any bigger event. I have attended this event 4 years in row... had to travel all the way from Europe for this. It was worth it!




Tuesday, October 19, 2010

Speed up your Unity Container!

The Unity Application Block (Unity) http://www.codeplex.com/unity is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.
Unity offers supports 3 types of injection: Property, Constructor and Method Injection.
If you are prepared to trade Property and Method Injection for better performance... then continue reading. I will describe in simple steps how to disable Property and Method Injection.
Sadly you will need to comment out 4 lines from the Unity sources and recompile. I hope someday the Unity dev team provides the possibility to specify what types of injections your container should support upon container creation.

Step 1: UnityDefaultStrategiesExtension.cs


You need to comment out the following 4 lines:

Context.BuildPlanStrategies.AddNew(
UnityBuildStage.Initialization);

Context.BuildPlanStrategies.AddNew(
UnityBuildStage.Initialization);


Context.Policies.SetDefault(
new DefaultUnityPropertySelectorPolicy());

Context.Policies.SetDefault(
new DefaultUnityMethodSelectorPolicy());




Step 2: Recompile

Tuesday, September 28, 2010

Well Defined Model: Model+ViewViewModel

The formal ModelViewViewModel pattern defines only 3 parts, the “View” and “ViewModel” are clearly defined and the rest we simply call “Model”.  Is this enough? Absolutely not. There is a lot more to worry about than simply separating the visuals from code!
When building a composite application it’s vital to assign well define the responsibilities on each part and then stick with the rules you have defined.
I call the pattern “Model+” since in this case the Model has being well defined. So from this paper don’t expect anything special about the “View”-“ViewModel” pair. We all think we understand this one; the “Model” part is the key were all the problems arise!
The following design addresses many scenarios in a composite application. It’s simply one design, nothing more. You can find the source code with a sample application under: https://bakopanos.googlecode.com/svn/trunk/prism
The sample is a modified version of the original sample that ships with the Prism quickstarts.

Controller

The controller is responsible to create views and position the views on the appropriate placeholders. For example if you are using Prism (Composite WPF) these placeholders are called Regions and there is a RegionManager and a RegionRegistry to deal with regions. Another concern that the controller has is to activate views. For example activate the tab page in a tabstrip that contains the view you would like to show. It's appropriate to say that the controller orchestrates the User Interface Process.
It’s important to make sure that you decouple UIP from all the rest. This is the reason that an eventaggregator comes very handy here. The controller can subscribe to strongly types events and get notified about changes in the state. Typically in most cases this will be notification about selected item in a workflow or dirty items.

View

In order to implement correctly the Model-View-ViewModel pattern (Fowler: PresentationModel) you really need to restrict the View to only the visuals. The Passive View doesn’t require any unit testing and the visual designer can work decoupled from the developer.

ViewModel

When I think about ViewModels I really see them as facades. I am aware that most people see workflows as the place where all logic goes; the problem is that if you put too much in a ViewModel then better consider a ModelViewController approach. What I see sometimes is ViewModels being sub classed in order to allow reuse. To my understanding this is by definition wrong. A ViewModel should simply aggregate all that the view needs to display and provide them to the view in a simple structure. You can also have logic there that has to do with the current view, but nothing more.

WorkItem

The work item is the key to a composite application. Why? Because the workitem is where you store your state. Let’s consider an example: Your application should change to the current customer. In other words after you select the customer in a list box, anything that you do in any screen should consider that specific customer. So if you get a bug assigned to you that somewhere in the application the customer is not displayed properly, where is the place where you first look? What part of your architecture remembers that? To my understanding this should be the WorkItem.  The ViewModel binds the selected item to the workitem, and when the selected item changes the workitem publishes an event. The interested controllers register for that event and drive in turn any UIP.

Services

BEWARE: services should be stateless. This is very important. If you would like your application to be easily changed and tested then model anything that has to do with state in a WorkItem.
There are two categories of services:
·         Infrastructure Services, basically cross-domain functionality. Example ILogService
·         Services, that interact with the business/service layer in order to support the application with domain specific functionality. Example IProjectService

Saturday, September 11, 2010

Functional Construction Pattern: Parsing a csv file.

The Functional Construction Pattern is used to construct a tree or graph of objects, with a code structure similar to what is used in functional programming languages. It is also called the Transform Pattern because it's used to create a new object graph based on a given one. Using the functional construction pattern you write code that is a lot more declarative (the structure of the generated object graph is visible in the code). One drawback is that code is not as easy to debug. In order to understand the pattern let's take the example of parsing a csv file into a collection of objects.

Sample csv file

Imperative approach for parsing a csv file

Declarative approach for parsing a csv file

Declarative approach for parsing a csv file, a more concise style

Streaming approach to save resources

When dealling with large files, better stream than read to end in order to reduce the memory used by your application.

Lines extension method

The following extension method (used previously) returns an IEnumerable reader.