Microsoft’s Ron Jacobs posted the Microsoft.Activities.UnitTesting library to CodePlex. See the documentation page for examples.
I tried the WorkflowServiceTestHost and it works. You can host a workflow service in your unit test project and make calls to its WCF activities. One of the examples shows using tracking to verify state. It’s a bit slow, but it does not require deploying to IIS.
I didn’t get the MemoryStore working yet, and I haven’t tried the XamlInjector (mocking activities - what a cool idea!).
I tried the free ActiveRoles Management Shell for Active Directory yesterday; it worked well for my needs.
I have read-only rights to AD at work, so my sole interest was querying AD (such as “what members are in group X"). It handles that fairly intuitively, but it does assume a basic level of PowerShell knowledge.
Iowa Code Camp is coming up (November 6, 2010 in Des Moines); register now!
I’m playing with the new features of C#/.NET 4.0; this is some code I wrote in LINQPad to try out the System.Lazy<T> class.
void Main()
{
Console.WriteLine("Running...");
Expensive one = GimmeOne;
Expensive two = GimmeOne;
if (one == two) Console.WriteLine("Same instance");
}
private static readonly Lazy<Expensive> _lazy =
new Lazy<Expensive>();
// If constructor arguments, use:
// new Lazy<Expensive>(() => new Expensive(args));
Expensive GimmeOne
{
get
{
return _lazy.Value; // thread safe
}
}
class Expensive
{
public Expensive()
{
Console.WriteLine("Creating expensive instance");
}
}
Output:
Running... Creating expensive instance Same instance
Update - October 14, 2010
The private field does not have to be static; there’s seldom a need for a true Singleton.
The other day I was creating a WinForms application, and it kept blowing up at runtime on a line that referenced Properties.Resources.SomeExistingResource with:
System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure “MyNamespace.Properties.Resources.resources” was correctly embedded or linked into assembly “MyApp” at compile time, or that all the satellite assemblies required are loadable and fully signed.
A fellow developer (Phil) and I figured it out, with help from a Stack Overflow article.
There’s a literal string in Resources.Designer.cs (under Properties/Resources.resx in Solution Explorer) that’s automatically updated based on the value of the Default Namespace in the project properties (Application tab) in Visual Studio 2010. Normally the namespace of this auto-generated Resources class is kept synchronized with this value. In my case I was using a custom project template, and apparently they got out of sync.
Timwi and others offer alternate solutions in the Stack Overflow article linked above. In my case I just had to change the Default Namespace to match the namespace in the file.
C#/.NET 4.0 has some nice features, including the Tuple classes. While generic tuples do not override the == operator, they do override Equals. This allows tuples composed of primitive types to be compared.
An interesting use of this is in refactoring LINQ queries, some of which can get quite long. The problem is that multiple-key joins are generally performed with anonymous types (because they override Equals/GetHashCode to compare properties), but anonymous types cannot be returned from methods (unless the return type is dynamic). Queries may also select anonymous types.
Tuples provide a neat solution to this. Here is a contrived example, which assumes legacy data with multi-column keys. (Note that this is LINQ to Objects, not LINQ to SQL.) I probably would not refactor to this degree in production code, as the Item1/Item2 portions are unclear. Note the elegant join in GetOrdersWithCustomers, though.
internal class Program
{
private static void Main()
{
IEnumerable<Customer> customers = GetCustomers();
IEnumerable<Order> orders = GetOrders();
IEnumerable<Item> items = GetItems();
/* Original:
var query =
from order in orders
join customer in customers
on
new
{
order.CustomerType,
order.CustomerId
}
equals
new
{
CustomerType = customer.Type,
CustomerId = customer.Id
}
join item in items
on order.Id equals item.OrderId
select
new
{
OrderId = order.Id,
CustomerName = customer.Name,
item.Product
};
*/
// Refactored:
var ordersWithCustomers =
GetOrdersWithCustomers(orders, customers);
var query =
from x in ordersWithCustomers
join item in items
on x.Item1.Id equals item.OrderId
select
new
{
OrderId = x.Item1.Id,
CustomerName = x.Item2.Name,
item.Product
};
foreach (var record in query)
{
Console.WriteLine(record);
}
}
private static IEnumerable<Tuple<Order, Customer>>
GetOrdersWithCustomers(
IEnumerable<Order> orders,
IEnumerable<Customer> customers)
{
return
from order in orders
join customer in customers
on order.GetCustomerKey()
equals customer.GetKey()
select
new Tuple<Order, Customer>
(order, customer);
}
private static IEnumerable<Item> GetItems()
{
return
new List<Item>
{
new Item
{
OrderId = 10,
Product = "TenOne"
},
new Item
{
OrderId = 10,
Product = "TenTwo"
},
new Item
{
OrderId = 20,
Product = "TwentyOne"
}
};
}
private static IEnumerable<Order> GetOrders()
{
return
new List<Order>
{
new Order
{
Id = 10,
CustomerType = "A",
CustomerId = 1
},
new Order
{
Id = 20,
CustomerType = "A",
CustomerId = 2
}
};
}
private static IEnumerable<Customer> GetCustomers()
{
return
new List<Customer>
{
new Customer
{
Type = "A",
Id = 1,
Name = "Bob"
},
new Customer
{
Type = "B",
Id = 1,
Name = "Hobo"
},
new Customer
{
Type = "A",
Id = 2,
Name = "Bill"
},
new Customer
{
Type = "B",
Id = 2,
Name = "Shotgun"
}
};
}
}
internal class Customer
{
public string Type { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public Tuple<string, int> GetKey()
{
return new Tuple<string, int>(Type, Id);
}
}
internal class Order
{
public int Id { get; set; }
public string CustomerType { get; set; }
public int CustomerId { get; set; }
public Tuple<string, int> GetCustomerKey()
{
return new Tuple<string, int>
(CustomerType, CustomerId);
}
}
internal class Item
{
public int OrderId { get; set; }
public string Product { get; set; }
} Microsoft chose to bundle FxCop v10 with the Windows 7 SDK, which is pretty huge. Matthew1471 offers an excellent tip on his blog: .NET FxCop 10 Install from CAB. This lets you extract the small setup file and just install FxCop! It works fine.
What’s more, you can install FxCop to a folder under your source control tree, check in the folder, then uninstall FxCop. This lets all your developers (and your build server) run FxCop without installing it. This also works; I tried it today with TeamCity. You just have to change the FxCop installation root.
EDIT: Kriz mentioned an issue in the comments; other people have also encountered this. I don’t know of anyone at work who has, though. The missing interop assembly doesn’t appear to install in the GAC with Visual Studio, either. I don’t have an answer, but it’s working for us.
I love LINQPad. It is incredibly useful for quick .NET coding spikes (whether or not they use LINQ) and for ad-hoc database queries (although I wish it were easy to set the isolation level). I’ve purchased and recommend the autocompletion (IntelliSense), and our office recently bought a pack of licenses too.
I found a limitation today in trying to answer a Stack Overflow question, along with a workaround.
C# extension methods cannot be defined in a nested class. LINQPad wraps your code in a class behind the scenes. It’s smart enough to detect “nested” static extension-hosting classes, and appears to exclude those from its internal class. This works well - unless your extension methods reference other classes nested in LINQPad:
// Set language combobox to "C# Program"
void Main()
{
new Local().AddFoo().Dump();
}
// Really a nested class
public class Local {}
public static class Extensions
{
// Type or namespace name 'Local' could not be found
public static string AddFoo(this Local local)
{
return local.ToString() + "Foo";
}
}
The workaround is to complete the hidden wrapper class with a closing brace, then leave off the last closing brace (since LINQPad will add one):
void Main()
{
new Local().AddFoo().Dump();
}
} // Extra closing brace
public class Local {}
public static class Extensions
{
public static string AddFoo(this Local local)
{
return local.ToString() + "Foo";
}
// Leave off the last closing brace
I figured this out based on the article Add Extension Methods in LinqPad. This is tested with LINQPad v4.20. You can vote for my feature suggestion if you like. (Personally I’d rather you voted for setting the isolation level.)
Two of us at work have had issues installing Developer Express components in Visual Studio 2008. We get “Cannot Register Toolbox Items” and have to manually add the components to the toolbox.
Apparently this is a known issue caused by the drivers for the Microsoft wireless mouse, and has been since 2008 (we’re installing the new components).
I find it hard to believe that Microsoft would not have fixed this if it were affecting all tool vendors.
As an aside, the DevX install GAC’d both the Web and XPO components that I deselected from the install.
I finally broke down and joined Twitter. Since Steve Gibson joined, I figured it was past time.
@BillSorensen
Unity 2.0 is out, and has some very nice features. Two of the coolest are InjectionFactory and Automatic Factories. Nice code samples and tutorials exist, but here’s an example of combining the two features.
using System;
using Microsoft.Practices.Unity;
namespace Unity2Example
{
class Program
{
static void Main()
{
using (var container = new UnityContainer())
{
container
.RegisterType<IService, ConcreteService>(
new InjectionFactory(c => ServiceFactory()));
Model model = container.Resolve<Model>();
Console.WriteLine("\nCalling Execute...");
model.Execute();
Console.WriteLine("\nCalling Execute...");
model.Execute();
}
}
static IService ServiceFactory()
{
Console.WriteLine("ServiceFactory called.");
return new ConcreteService();
}
}
interface IService
{
void MakeTheCall();
}
class ConcreteService : IService
{
public ConcreteService()
{
Console.WriteLine("ConcreteService instantiated.");
}
public void MakeTheCall()
{
Console.WriteLine(
"ConcreteService makes the call.");
}
}
class Model
{
public Model(Func<IService> serviceFinder)
{
Console.WriteLine("Model instantiated.");
_serviceFinder = serviceFinder;
}
public void Execute()
{
_serviceFinder().MakeTheCall();
}
private readonly Func<IService> _serviceFinder;
}
}
This will display:
Model instantiated. Calling Execute... ServiceFactory called. ConcreteService instantiated. ConcreteService makes the call. Calling Execute... ServiceFactory called. ConcreteService instantiated. ConcreteService makes the call.
Essentially we’re injecting a Service Locator into our model. My use case for this was injecting an object where the object reference could change (it needed to be deserialized at certain times). This way the dependent class would always get the most current version. It turned out I already had a class that could act as a Service Locator with the addition of an interface, so I injected that instead (it seemed simpler). I think this combination may come in useful someday, though.
In C# 4.0, you can return anonymous types from methods by using the dynamic keyword.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetHello().Name); // Works.
var one = GetHello();
var two = GetHello();
if (one.Equals(two))
{
Console.WriteLine("They are equal!");
// Hit - they are equal!
}
else
{
Console.WriteLine("They are NOT equal.");
}
}
static dynamic GetHello()
{
return new { Name = "Bob" };
}
}
Note that Equals still works as expected.
I think this will make it possible to refactor long LINQ statements that use anonymous types, breaking them up into calls to private methods. (Clearly this could be abused as well.)
Update - December 11, 2011
There’s some protection against abuse - anonymous types are internal. Thanks to Marc Gravell for pointing this out.
Iowa Code Camp is coming up fast!
There’s also a new .NET group starting up in Iowa City.
My Chumby arrived today. It’s a tiny computer with a touchscreen and wireless capabilities. Out of the box it can play Flash “widgets” and stream music.
The cool part is that it runs Linux and can be customized. You can develop Flash widgets for it, but there are plenty of other hacks. I’ve already SSH’d into it and created a simple CGI script for its built-in web server (in vi no less!).
I want to see if I can have it show the build status of our continuous integration server at work. While I may not leave it as a permanent fixture in the office, it would be a fun project.
Update - March 25, 2010
Our company requires the use of a proxy server to connect to the Internet. No exceptions. Chumby does not support proxy servers. End of story. :(
Update - March 29, 2010
The story picks up again. :) I found this post on the chumbysphere forum, and the advice from techgermz for no authentication worked. I did a chmod +x on the script just in case, but I’m not sure if that was necessary. I didn’t try streaming music.
I’m still having a problem where the screen goes blank and the menu button doesn’t work (but the internal web server still responds) after it’s online for a couple of hours at work. I’m currently testing it at home to see if I can replicate the issue on a non-proxied WiFi network.
Our continuous integration server was running slower than usual. One of our chief IT guys figured it out; the antivirus software installed on it was set to scan all folders. Every check out, every build, every copy apparently triggered a scan. While it’s a good idea to scan the final deployment folders, exclude the rest of the folders for a significant improvement in build times.
We use TeamCity, but this is applicable to any CI software.
Thanks to Eric and Rob for this tip!
Working Effectively with Legacy Code by Michael Feathers is a key resource for anyone who has to work with less-than-pleasant code. Feathers defines legacy code as code without tests, and his main goal is to get automated tests in place. The last section of the book contains a catalog of dependency-breaking techniques to make this possible.
Examples are in Java, C++, C and C# (plus one in Ruby). C and C++ developers will likely find this book invaluable, as a number of the techniques target challenges in those languages.
The book is very readable, due in large part to the friendly writing style of Mr. Feathers. Experienced developers will smile (or perhaps shudder in remembrance) at section names like “The Case of the Irritating Global Dependency.” Most code examples are short and to the point, although it does help if the reader is conversant in at least one C-style language.
The text suffers from the occasional typographical error, which I found distracting.
Developers who do not see value in automated tests may find little of interest in this book. If you don’t fall into that category, order your copy today!
With all the discussions of software craftsmanship and SOLID principles lately, I’d like to list the guidelines (not absolute rules!) I find most useful. These are listed in order of importance, highest to lowest.
Key Principles and Practices of Software Development
Frequent Anti-patterns of Software Development
Remember that the right answer is often “it depends.” Almost everything is a trade-off. Use your own judgment. Think!
Thanks to everyone who reviewed my initial draft, and to Robert ("Uncle Bob") Martin for inspiration.
Comments are welcome.
I have a great deal of respect for “Uncle” Bob Martin. He’s done a tremendous amount to bring professionalism and craftsmanship to software development. I’ve heard him speak, and he definitely knows more than I do. But in this one small area of programming, I think he’s off-target. Decide for yourselves.
Dependency Injection Inversion (Uncle Bob)
Some of the follow-ups:
Poor use of DI versus need for DI (Jimmy Bogard)
Dependency Injection Inversion Rejection (Davy Brion)
Constructor over-injection anti-pattern (Jeffrey Palermo)
I agree most closely with Jimmy Bogard on this (Davy Brion makes some good points too). In Jeffrey Palermo’s post, I side with Alwin in his comment - why not just pass an interface to the factory?
EDIT: Here’s a nice rebuttal to Jeffrey Palermo’s post that discusses better alternatives to Alwin’s solution:
Rebuttal: Constructor over-injection anti-pattern (Mark Seemann)
EDIT: Another response to Uncle Bob:
Rejecting Dependency Injection Inversion (Ayende)
EDIT: And another related post by Mark Seemann:
Dependency Injection Inversion in .NET
EDIT: Yet another interesting post by Mr. Seemann (I think I’ll pick up his book):
Development Central is the blog of Bill Sorensen, a professional software developer. Much of this will relate to C#, .NET, and OOP in general.
Disclaimer
These postings are provided "AS IS" with no warranties and confer no rights.