AutoFixture 2 With() isn't working as it did in AutoFixture 1? - autofixture

I'm porting my tests to AutoFixture 2.0, and I've run in to some strange behavior that I can neither explain nor fix. This simple test is failing for me:
var autoFixtures = new Fixture();
var file = autoFixtures.Build<File>()
.With(f => f.Name, "bleh.txt")
.CreateAnonymous();
Assert.That(file.Name, Is.EqualTo("bleh.txt")); // Fail?!
The test succeeds if I change Name to another property of File, which leads me to think that I have some sort of customization present for Name that wasn't working when I was using AutoFixture 1.0. I've scoured my code, though, and I can't find anything like that.
Enabling tracing doesn't seem to help much.
autoFixtures.Behaviors.Add(new TracingBehavior());
displays, among other stuff:
Requested: System.String Name
Requested: Ploeh.AutoFixture.Kernel.SeededRequest
Created: Ploeh.AutoFixture.Kernel.NoSpecimen
Requested: Ploeh.AutoFixture.Kernel.SeededRequest
Requested: System.String
Created: Ploeh.AutoFixture.Kernel.NoSpecimen
Requested: System.String
Created: 8a022fda-fa4e-49b7-b0c2-285fef765386
Created: Name8a022fda-fa4e-49b7-b0c2-285fef765386
Created: Name8a022fda-fa4e-49b7-b0c2-285fef765386
FWIW, Name is declared as a virtual property of File's base class, and then overridden in File as such:
public abstract class Item
{
public virtual string Name { get; set; }
...
}
public class File : Item
{
public override string Name { get; set; }
...
}
If anyone has any ideas on something I might try, or somewhere I might have inadvertently customized the behavior of the Name property, I would be most appreciative!

You just found a bug in AutoFixture 2.0. I have now resolved it and pushed the changes to the repository (changeset 3efe812aecd1), so if you download the latest source and compile it, it should work.
In case you are interested, it was related to a virtual property being overridden by a child class - apparently not something I do very often.
Sorry about the bug. Please let me know if the issue hasn't been resolved, or if you have other questions.

Related

Localization in MEF: export attribute does not support a resource (WPF - C#)

I have an application with a plugin architecture using MEF. For every exported part there is an attribute with the part's name, and I want to have the names translated, because I use these strings to display the available parts in ListBoxes (or the like).
So, I tried to set the 'Name = Strings.SomeText" in the [Export] annotation, but I get the following error:
"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"
Is there a solution to this? I find the use of the Metadata very useful (I do lazy loading) and I would not want to redesign everything just to get a few texts translated.
Any ideas? Thanks.
Unfortunately you can't directly provide the translated text to the attributes because an attribute can only contain data that is known at compile time. So you will need to provide some compile time constant value that you can later use to look up the translated test.
One solution would be to pass the resource name to the attribute. Then when you want to display the translated text you grab the resource name, look up the text in the resources and display the result.
For instance your attribute could look something like:
[Export(Name = "SomeText")]
public class MyExport
{
}
Then when you want to display the string you load the resources from the assembly that defines the export and you extract the actual text from the loaded resources. For instance like this (as borrowed from another answer):
var assembly = typeof(MyExport).Assembly;
// Resource file.. namespace.ClassName
var rm = new ResourceManager("MyAssembly.Strings", assembly);
// exportName contains the text provided to the Name property
// of the Export attribute
var text = rm.GetString(exportName);
The one obvious drawback about this solution is that you lose the type-safety that you get from using the Strings.SomeText property.
--------- EDIT ---------
In order to make it a little easier to get the translated text you could create a derivative of the ExportAttribute which takes enough information to extract the translated text. For example the custom ExportAttribute could look like this
public sealed class NamedExportAttribute : ExportAttribute
{
public NamedExportAttribute()
: base()
{
}
public string ResourceName
{
get;
set;
}
public Type ResourceType
{
get;
set;
}
public string ResourceText()
{
var rm = new ResourceManager(ResourceType);
return rm.GetString(ResourceName);
}
}
Using this attribute you can apply it like this
[NamedExport(
ResourceName = "SomeText",
ResourceType = typeof(MyNamespace.Properties.Resources))]
public sealed class MyClass
{
}
Finally when you need to get the translated text you can do this
var attribute = typeof(MyClass).GetCustomAttribute<NamedExportAttribute>();
var text = attribute.ResourceText();
Another option is to use the DisplayAttribute

c# returning arrays via properties

Id like to firstly apologise for what may appear to be a stupid question but im confused regarding the following.
Im writting a class library which will not be running on the UI thread. Inside the CL i need an array which im going populate with data received from a stored procedure call. I then need to pass this data back to the UI thread via an event.
Originally i was going to write the following.
public class ColumnInformation
{
public string[] columnHeaderNames;
public string[] columnDataTypes;
}
but im pretty sure that would be frowned upon and i instead should be using properties.
public class ColumnInformation
{
public string[] columnHeaderNames {get; set;}
public string[] columnDataTypes {get; set;}
}
but then i came across the following.
MSDN
so am i correct in assuming that i should actually declare this as follows:
public class ColumnInformation
{
private string[] _columnHeaderNames;
public Names(string[] headerNames)
{
_columnHeaderNames = headerNames;
}
public string[] GetNames()
{
// Need to return a clone of the array so that consumers
// of this library cannot change its contents
return (string[])_columnHeaderNames.Clone();
}
}
Thanks for your time.
If your concern is the guideline CA1819: Properties should not return arrays,
It will be same whether you are exposing Array as a Public Field, or Property (making readonly does not matter here). Once your original Array is exposed, its content can be modified.
To avoid this, as the link suggest, make Field private, and return Clone from the Getter.
However major concern is that there may be multiple copies of your array if retrieved many times. It is not good for performance and synchronization.
Better solution is ReadOnlyCollection.
Using ReadOnlyCollection, you can expose the collection as read only which cannot be modified. Also any changes to underlying collection will be reflected.

Ninject does not resolve dependency correctly in silverlight project

I have a silverlight 4 project with mvvmlight and ninject 3.x.
I've setup the container like this
kernel = new StandardKernel(new ViewModelModule(), new ClientSessionModule());
And the modules like this
public class ViewModelModule : NinjectModule
{
public override void Load()
{
((StandardKernel)Kernel)
.Bind(scanner => scanner.FromThisAssembly()
.Select(x => x.IsSubclassOf(typeof(ViewModelBase)))
.BindDefaultInterface());
}
}
and
public class ClientSessionModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IClientContext>().To<ClientContext>().InSingletonScope();
}
}
Now the problem is the latter one. At one point in the application this dependency is resolved explictly and updated like this:
var context = App.Ioc.Get<IClientContext>();
context.Username = "just a sample name";
Now when a ViewModel is loaded it get the IClientContext injected like
public MainViewModel(IClientContext clientContext)
The problem is that the instance does not have the name set earlier.
But if I inside the same ViewModel resolves explictly again I get the expected instance with the name set.
What am I missing since the sigleton does not get injected as I expected it to be automatically?
Just found a duplicate kernel in my solution. And that explains why I was not able so resolve as expected as I had 2 kernels running

WPF/Prism : Views return System.Object

I am new to WPF and Prism, but I already learned that you have to register a View in Unity as an object:
Container.RegisterType<Object,MyView>("My.Assembly.MyView");
Still, when I use
var RelativeUriToMyView = new Uri("My.Assembly.MyView",UriKind.Relative);
RegionManager.RequestNavigate(RelativeUriToMyView, RegionName, CallbackResult);
the MyView displays as System.Object, and the CallbackResult contains no Error.
What am I missing? I'm happy to provide more information if needed.
You would want to look at the RegionNavigationContentLoader.cs in the PRISM source code; Here is the code that is loading the view for you.
protected virtual object CreateNewRegionItem(string candidateTargetContract)
{
object newRegionItem;
try
{
newRegionItem = this.serviceLocator.GetInstance<object>(candidateTargetContract);
}
catch (ActivationException e)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateNavigationTarget, candidateTargetContract),
e);
}
return newRegionItem;
}
There are several helper methods that take the URI, extract the query string, and create the 'name' used to lookup your view and cast it as an object.
Essentially, the name you are using to associate your concrete class as an object with Unity is the same one you'll need to use when you try to resolve the object with Unity. Here is some pesudocode to explain,
Container.RegisterType<object, ConcreteClass>(typeof(ConcreteClass).FullName);
Locator.GetInstance<object>(UriWithFullName)
If none of this helps, post the RelativeUriToMyView so I can see the contents.
Good luck.
The issue seemed to be caused by registering the view with its FullName (My.Assembly.MyView) instead of its Name (MyView).
Edit:
Changed the question to more accurately reflect the issue.

Can someone explain the magic going on in Prism's resolve<> method?

I've got a CustomersModule.cs with the following Initialize() method:
public void Initialize()
{
container.RegisterType<ICustomersRepository, CustomersRepository>(new ContainerControlledLifetimeManager());
CustomersPresenter customersPresenter = this.container.Resolve<CustomersPresenter>();
}
The class I resolve from the container looks like this:
class CustomersPresenter
{
private CustomersView view;
private ICustomersRepository customersRespository;
public CustomersPresenter(CustomersView view,
ICustomersRepository customersRepository,
TestWhatever testWhatever)
{
this.view = view;
this.customersRespository = customersRepository;
}
}
The TestWhatever class is just a dummy class I created:
public class TestWhatever
{
public string Title { get; set; }
public TestWhatever()
{
Title = "this is the title";
}
}
Yet the container happily resolves CustomersPresenter even though I never registered it, and also the container somehow finds TestWhatever, instantiates it, and injects it into CustomersPresenter.
I was quite surprised to realize this since I couldn't find anywhere in the Prism documentation which explicitly stated that the container was so automatic.
So this is great, but it what else is the container doing that I don't know about i.e. what else can it do that I don't know about? For example, can I inject classes from other modules and if the modules happen to be loaded the container will inject them, and if not, it will inject a null?
There is nothing magical going on. You are specifying concrete types, so naturally they are resolvable, because if we have the Type object, we can call a constructor on it.
class Fred { };
Fred f1 = new Fred();
Type t = typeof(Fred);
Fred f2 = (Fred)t.GetConstructor(Type.EmptyTypes).Invoke(null);
The last line above is effectively what happens, the type t having been found by using typeof on the type parameter you give to Resolve.
If the type cannot be constructed by new (because it's in some unknown separate codebase) then you wouldn't be able to give it as a type parameter to Resolve.
In the second case, it is constructor injection, but it's still a known concrete constructable type. Via reflection, the Unity framework can get an array of all the Types of the parameters to the constructor. The type TestWhatever is constructable, so there is no ambiguity or difficulty over what to construct.
As to your concern about separate modules (assemblies), if you move TestWhatever to another assembly, that will not change the lines of code you've written; it will just mean that you have to add a reference to the other assembly to get this one to build. And then TestWhatever is still an unambiguously refeferenced constructable type, so it can be constructed by Unity.
In other words, if you can refer to the type in code, you can get a Type object, and so at runtime it will be directly constructable.
Response to comment:
If you delete the class TestWhatever, you will get a compile-time error, because you refer to that type in your code. So it won't be possible to get a runtime by doing that.
The decoupling is still in effect in this arrangement, because you could register a specific instance of TestWhatever, so every call to Resolve<TestWhatever>() will get the same instance, rather than constructing a new one.
The reason this works is because Unity is designed for it. When you Resolve with a concrete type, Unity looks to see if it can resolve from the container. If it cannot, then it just goes and instantiates the type resolving it's dependencies. It's really quite simple.

Resources