On Tuesday 18th, Victor and I will be presenting A Lap Around VS2010. Check which other talks are available and register here.
This is the event information:
- Horario: martes, 18 de noviembre de 2008 16:00 - 22:00 p.m.
- Lugar: ITTC. Sarmiento 1113 Piso 5. Buenos Aires Argentina.
- Registración
- Descripción:
Durante los días del 27 al 30 de Octubre se lleva a cabo la Professional Developer Conference en Los Angeles, Estados Unidos. Durante este evento Microsoft realiza grandes anuncios sobre novedades en la plataforma de desarrollo, presentando su visión de Cloud Computing, construyendo aplicaciones que desdibujan las barreras entre la PC, la Web y los dispositivos móviles, lo nuevo en VS 2010, .net Framework 4, distintos avances sobre Windows 7, la siguiente mayor versión de la plataforma cliente Windows y mucho más. En este evento, estaremos presentando algunas de las novedades develadas durante el evento, contando con disertantes asistentes al mismo.
My friends Brian and Juan will also be presenting :)
You'd think that after the serious leaks people was hitting with the XmlSerializer, the "new" (in .NET 2.0!!! but which many seem to forget about, just like AVOID doing new XmlTextReader in a PDC *keynote*) XmlSerializerFactory would do away with those.
Well, bad news: you need to be AS careful as you are with the XmlSerializer in order to avoid those leaks (which are BY DESIGN, BTW). Turns out that apparently the same designer made the same "by design" decisions with the XmlSerializerFactory.
For those not using the factory yet: it was basically meant to be the cache of XmlSerializer types that you had to do manually in the past). If provides a factory method with all the same overloads the XmlSerializer receives and hands you back an instance of a serializer, supposedly caching the generated types (as the documentation says: "Creates typed versions of the XmlSerializer for more efficient serialization."). You can read my friend Kirk's blog on how to use the factory.
Nowhere does the documentation mention that depending on which overloads you use, the cache will be in effect or not, JUST LIKE THE "good" old XmlSerializer!!!
VERY easy repro:
class Program
{
static void Main(string[] args)
{
var factory = new XmlSerializerFactory();
var cached1 = factory.CreateSerializer(typeof(Foo));
var cached2 = factory.CreateSerializer(typeof(Foo));
// IT WORKS!!! RIGHT???
Debug.Assert(cached1.GetType() == cached2.GetType());
var serializer1 = factory.CreateSerializer(typeof(Foo), new XmlRootAttribute("foo"));
var serializer2 = factory.CreateSerializer(typeof(Foo), new XmlRootAttribute("foo"));
var serializer3 = factory.CreateSerializer(typeof(Foo), new XmlRootAttribute("foo"));
var serializer4 = factory.CreateSerializer(typeof(Foo), new XmlRootAttribute("foo"));
var allsame = serializer1.GetType() == serializer2.GetType();
allsame &= serializer2.GetType() == serializer3.GetType();
allsame &= serializer3.GetType() == serializer4.GetType();
// FAIL!!!!!
Debug.Assert(allsame);
}
}
public class Foo { }
Now, I understand the myriad of overloads supported by the class are hard to manage, but how hard do you think it is to create a smart cache key that properly compares if the XmlRootAttribute I'm passing, which has only four properties to compare, is the same I passed before and therefore hand me a cached type??
Very dissapointing. I had to (once again) implement this myself (on the ULTIMATE serializable generics dictionary I'll EVER need to write, which I'll blog about sometime...). This time I even used dynamic method generation to have a blazingly fast instantiation of the cached generated type :). Another time I said...
Anyway, please vote for the bug so this gets fixed (hopefully it's not too late for C# 4.0!).
I kept getting a "Activation Error: Code 0x8007232b DNS Name does not exist" error whenever I tried to activate Windows 2008 Standard (which has been running great on my X61 laptop so far as the host OS!).
Weird procedure you have to follow to activate:
Activate Windows Server 2008 RTM (MSDN Subscriber Downloads version)
- Follow all the tips from Windows 2008 Workstation site. Microsoft has a KB article also that is useful.
- Get Windows Live Messenger bare MSI from Softpedia (it's a MS-signed installer, worked just fine for me)
- How to get Windows Live Writer on Windows 2008: this was a bit trickier, and involves importing a few registry keys (just copy the registry keys to a .reg file and import it).
- First you need a machine with WLW installed. Copy the entire folder to the new machine. I copied it to %ProgramFiles%\Windows Live\Writer, which is where it'd go if I could run the proper installer.
- The following registry keys are created by the "root" Windows Live installer:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Live\installer]
"WLXMarket"="en-us"
"WLXLanguage"="en"
"WLXVersion"="WL20"
- Next the keys for WLW on HKLM (make sure the InstallDir matches the right folder where you copied the binaries):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Live\Writer]
"InstallDir"="C:\\Program Files (x86)\\Windows Live\\Writer\\"
- Finally, export from your existing WLW installation the entire
HKEY_CURRENT_USER\Software\Microsoft\Windows Live\Writer key. That will bring in your current blog accounts and everything :). Make sure to fix any folders that might be different on your target machine (i.e. Documents and Settings, etc.)
- Add a shortcut to the start menu and you're done!
- Finally, forget about sleeping/hibernating your computer from the start menu:
Even though sleep and hibernation are supported, you have to Ctrl+Alt+Del and choose the respective option which now DOES show up in that screen Shutdown Options button:
So far it's been a blast using Windows 2008 in my laptop. Vista x64 was becoming truly unusable, even with a 7200RPM disc, 4GB RAM and 2.2Ghz proc.
I realized that I never blogged about this cool feature contributed by Slava to Moq-Contrib.
Auto-mocking containers was an idea originally (IIRC) from the guys at Eleutian, later on picked up by Jeremy Miller with Rhino Mocks and StructureMap.
The wiki document Slava put together on Automocking is a fantastic overview. Basically, you can have an (Autofac-powered) container create your objects under test with all its dependencies injected as mocks:
var factory = new MockFactory(MockBehavior.Loose);
var container = new AutoMockContainer(factory);
var tree = container.Create<Tree>();
Because it uses a MockFactory, it also integrates with the rest of the features in Moq that are available through the factory, such as consistent settings for mock behavior, whether to call base class implementations, and the default value behavior.
Go ahead and read the wiki and get the bits!
In my very recent previous post I said "mocking and stubbing easier than ever", but actually forgot to mention the stubbing part :S.
This one is not new for users of moq-contrib, but we decided to move this to the core Moq library as we get the question on how to stub properties often enough... :)
It's actually rather simple and easy to implement just by using Moq external API, but as a facility, here's what you can do:
var mock = new Mock<IHaveValue>();
// start "tracking" sets/gets to this property
mock.Stub(v => v.Value);
// alternatively, provide a default value for the stubbed property
mock.Stub(v => v.Value, 5);
// Now you can do:
IHaveValue hv = mock.Object;
// Initial value was stored
Assert.Equal(5, hv.Value);
// New value set which changes the initial value
hv.Value = 6;
Assert.Equal(6, hv.Value);
What is new in this version beyond the original moq-contrib stubbing, is the ability to stub all properties of the object in a single call:
var mock = new Mock<IFoo>();
mock.StubAll();
This feature integrates seamlessly with the default value behavior specified for the mock, as explained in the previous post, meaning that you can stub all properties and cause them to return new mocks when appropriate, also recursively (but lazily!), in a single call. This may be redundant to note, but it's just to point that the API and behavior is still consistent.
If you want to have some fun reading rather crazy reflection API usage to invoke various generic methods including ones receiving Func<T> and passing function pointers with it, go ahead. It was FUN :).
Next: out/ref parameters in Moq!!!
I've just released a new version of Moq which contains a few bug fixes but two extremely useful features: recursive mocks and mocked default values.
Recursive mocks
Quite often you have a root mock object from which other mocks should "hang" through property accesses, such as HttpContextBase.Response: you want the response object returned to also be a mock.
Setting such hierarchies before this release was quite verbose:
var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
context.Expect(c => c.Response).Returns(response.Object);
response.Expect(r => r.ContentType).Returns("application/xml");
In this new release, it's possible to just use your root object to set expectations on any path in the hierarchy, so the above turns to:
var context = new Mock<HttpContextBase>();
context.Expect(c => c.Response.ContentType).Returns("application/xml");
The auto-mocked properties have the same behavior as the "owning" mock.
I've found this extremely useful and right now it's also supported in TypeMock and soon (I hope) followed by Rhino too.
Mocked default values
In Moq, your mocks are by default "loose", so they never throw exceptions when they are invoked without a corresponding expectation. Most people find this very intuitive as a default, but sometimes wish some properties returned mocks instead. In spirit, this is similar to recursive mocks, but it's more of a lazy-on-demand creation of mocks as needed, without the need to set expectations on anyone.
Following the example above, you could create the context like so (note the added property to set the default value behavior):
var context = new Mock<HttpContextBase> { DefaultValue = DefaultValue.Mock };
var response = context.Response; // will be non-null, an auto-generated mock!
// I could set further expectations on this object, by retrieving its corresponding Mock
Mock.Get(response).Expect(r => r.ContentType).Returns("application/xml");
The setting is recursive, so if I request a property from the response mock that is also of a mock-able type, I'd get a mock too.
Both are closely related, and maybe they could both be called "recursive mocks" if you will.
One of the coolest things in Moq (IMO) continues to be the transparent continuum between fake/stub/mock which basically depends on how you use the one and only "moq" :).
On top of that, I got a really cool domain name for the project: http://moq.me
Feedback welcomed on both features! Next I have to write about future directions...
There's been some excitement lately about the introduction of a common IServiceLocator that all major DI containers apparently will provide.
Unless you're building an "extensible framework leveraging framework consumer selectable IoC containers", don't sweat it too much, the interface was NOT created for you!
Let me reiterate: adding a dependency on IServiceLocator to your classes is NOT a good idea. When you do so, instead of an explicit and self documenting dependency on an external object, you're tunneling this locator that now hides to the class consumers which are its true dependencies. This is BAD, as it requires users to go to your class documentation (and hope it's updated) rather than its constructor to see what it needs to operate. If you've done any kind of work extending VS you know how bad this can get.
I've seen comments that this is just a "purist" view and that the real world ain't like this and you still need it.
Somehow some people seem to think that we (those who have contributed some open source framework of sorts) don't work on real projects and live in an ideal world and make frameworks for these ideal situations which don't actually translate to your real world. That we somehow just dream about the ideal conditions and spit a framework accordingly.
Oh that's so wrong ;). I wish it were that way sometimes, though, hehe.
I speak from experience in actual projects (working on two of them simultaneously these days, one of them fairly large), and let me repeat: YOU DON'T NEED A DEPENDENCY ON IServiceLocator in your business objects.
What you might need is to change your DI framework of choice if it doesn't allow you to get rid of that dependency ;).
Let me elaborate on some of the situations that supposedly require so:
- Named instances: just move the named instance requirement outside the bz class and into the container configuration:
builder.Register<IBar>(c => new Bar(c.Resolve<IFoo>("a")));
- Need all instances of X: again, move the dependency out of your bz class and into configuration!
builder.Register<IBar>(c => new Bar( /* get an IEnumerable<T> from container, or whatever */ ));
- Need to create new instances of components inside your bz class (that is, you need a factory?): register a Func<T> factory for your component!
builder.RegisterGeneratedFactory<Func<IBar>>();
ctor Foo(Func<IBar> barFactory);
// Foo needs a new bar?
var b = barFactory();
If you can come up with a real world scenario (which does NOT involve authoring a framework such as ASP.NET MVC, MonoRail, etc.) where a good DI container cannot save you from having that dependency, only then I'll believe you need IServiceLocator.
I'd argue that people that should care/use such a thing is even less than 1%. That's why I wouldn't go about publicizing this thing so much, and you should hardly care about it. I can see it applied by (non-DI) framework authors to enable different DI frameworks to be plugged-in, but I hardly see how anyone doing "real world" work would benefit rather than detriment from its use.
There you have my rant too :)