Ninject bind by convention using BindToFactory to a factory interface with class T - ninject

I want to replace this code:
Kernel.Bind<ITaskFactory<AlertTask>>().ToFactory();
Kernel.Bind<ITaskFactory<PopupTask>>().ToFactory();
with something like this:
Kernel.Bind(scanner => scanner.FromThisAssembly().SelectAllClasses()
.EndingWith("Task").MAGICGOESHERE().BindToFactory()
I tried to create a IBindingGenerator, but stranded when trying to get ITaskFactory<T> from T.

Use this instead:
kernel.Bind(scanner => scanner
.FromThisAssembly()
.SelectAllInterfaces()
.EndingWith("Factory")
.BindToFactory());
kernel.Bind(scanner => scanner
.FromThisAssembly()
.SelectAllClasses()
.EndingWith("Task"));
var f = kernel.Get<ITaskFactory>();
var task1 = f.CreateTask<AlertTask>();
var task2 = f.CreateTask<PopupTask>();
public class AlertTask {}
public class PopupTask { }
public interface ITaskFactory
{
T CreateTask<T>();
}

Related

Wrong currency format

I've done this...
[HttpGet("method")]
public IEnumerable<object> GetStuff() =>
repos.FetchStuff()
.Select(c => new
{
val = string.Format("{0:C}", c.Rate)
});
And it's formatted the currency as ¤8.00.
Well, I wonder what currency that is?!
How do I make it show a £ symbol?
You may try this one:
[HttpGet("method")]
public IEnumerable<object> GetStuff() =>
repos.FetchStuff()
.Select(c => new
{
val = c.Rate.ToString("c" , new CultureInfo("en-GB").NumberFormat)
});
As commented above, you'll have to set CultureInfo:
Example:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
var total = 10.99;
var numFormat = new CultureInfo("en-GB").NumberFormat;
Console.WriteLine(total.ToString("c", numFormat));
}
}
Result: £10.99

typemock test not working

public class GetDatasourceDependencies : BaseProcessor
{
/// <summary>
/// The process.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
public override void Process(GetDependenciesArgs context)
{
Assert.IsNotNull(context.IndexedItem, "indexed item");
Assert.IsNotNull(context.Dependencies, "dependencies");
Item item = (context.IndexedItem as SitecoreIndexableItem);
if (item != null)
{
var layoutLinks = Globals.LinkDatabase.GetReferrers(item, FieldIDs.LayoutField);
var sourceUris = layoutLinks.Select(l => l.GetSourceItem().Uri).Where(uri => uri != null && uri != item.Uri).Distinct();
context.Dependencies.AddRange(sourceUris.Select(x => (SitecoreItemUniqueId)x));
}
}
}
How do I write a test with typock for this. I am very new to typemock and have written something like this. I understand that i need to mock the args and context but as the method is returning nothing back, how do i test it.
My test should be success only if the context.dependents have some values.
[Test]
public void GetIndexingDependencies_Calls()
{
var indexable = Isolate.Fake.Instance<IIndexable>();
var fake = Isolate.Fake.Instance<GetDependenciesArgs>();
var context = Isolate.Fake.Instance<GetDatasourceDependencies>();
var obj = new GetDatasourceDependencies();
Isolate.Verify.WasCalledWithAnyArguments(() => context.Process(fake));
Isolate.WhenCalled(() => fake.IndexedItem).WillReturn(indexable);
//Isolate.WhenCalled(() => fake.Dependencies.Count).WillReturn(2);
}
Disclaimer, I work at Typemock.
You can use a real collection for context.Dependencies and assert that some items are actually added.
To achieve this you should replace the collection that Globals returns and make sure that linq can process it as you expect (I just returned the same collection from the linq query for the sake of the example).
Your test should look something like this:
public void GetIndexingDependencies_Calls()
{
//Arrange
var fakeContext = Isolate.Fake.Instance<GetDependenciesArgs>();
fakeContext.Dependencies = new List<SitecoreItemUniqueId>();
var itemList = new List<SomeItem> { new SomeItem(), new SomeItem() };
Isolate.WhenCalled(() => Globals.LinkDatabase.GetReferrers(null, null)).WillReturn(itemList);
Isolate.WhenCalled(() => itemList.Select(l => l.GetSourceItem().Uri).Where(uri => true).Distinct()).WillReturn(itemList);
//ACT
var underTest = new GetDatasourceDependencies();
underTest.Process(fakeContext);
//ASSERT
Assert.AreEqual(2, fakeContext.Dependencies.Count);
}
Some more points:
Don't fake whatever you're testing, in this case it's GetDatasourceDependencies. If it's faked it will not really be called and not be tested.
Don't write asserts\verify before the executing the code that you're trying to test, in this case context.Process(fake) wasn't called before verify.

Ninject Get<T> WhenTargetHas<T>

So I'm using Ninject, specifically the contextual binding as follows :
Bind<IBlah>().ToMethod(x => FirstBlahProvider.Instance.GiveMeOne()).WhenTargetHas<FirstAttribute>().InRequestScope();
Bind<IBlah>().ToMethod(x => SecondBlahProvider.Instance.GiveMeOne()).WhenTargetHas<SecondAttribute>().InRequestScope();
I need to use the Kernel to get a given instance and would like to do it based on the Condition WhenTargetHas<T>. Something like the following would be great.
var myblah = Kernal.Get<IBlah>(x => x.HasWithTarget<FirstAttribute>)
How can you retrieve an instance based on the condition?
Worked out the answer :
Best to avoid using WhenTargetHas<T> instead use WithMetaData(key, value)
So
Bind<IBlah>().ToMethod(x => FirstBlahProvider.Instance.GiveMeOne()).WhenTargetHas<FirstAttribute>().InRequestScope();
Bind<IBlah>().ToMethod(x => SecondBlahProvider.Instance.GiveMeOne()).WhenTargetHas<SecondAttribute>().InRequestScope();
Becomes :
Bind<IBlah>().ToMethod(x => FirstBlahProvider.Instance.GiveMeOne()).WithMetaData("Provider", "First);
Bind<IBlah>().ToMethod(x => SecondBlahProvider.Instance.GiveMeOne()).WithMetaData("Provider", "Second");
You then need to create an Attribute which inherits the Ninject ConstraintAttribute and use that attribute in your constructor arguement.
As :
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class FirstProviderConstraint : ConstraintAttribute
{
public override bool Matches(IBindingMetadata metadata)
{
return metadata.Has("Provider") && metadata.Get<string>("Provider") == "First";
}
}
You then use it in a constructor arg as :
public class Consumer([FirstProviderConstraint] IBlah)
{
...
}
Or resolving from the Kernel
Get<ISession>(metaData => metaData.Get<string>(BindingKeys.Database) == BindingValues.OperationsDatabase)
I need to resolve scoping but that's how you satisfy both Constructor injection and explicit resolution from the Kernel when you have more than one binding.

Fluent NHibernate: testing collection mapping with CheckList

I've used Fluent NH in some projects but I'm having some problems with using the PersistenceSpecification class for testing a collection mapping. Here's the code for my classes (I'm just putting here the collection definition):
public class Ocorrencia : EntityWithAction, IHasAssignedId<Int32> {
private IList<Intervencao> _intervencoes = new List<Intervencao>();
public IEnumerable<Intervencao> Intervencoes {
get{
return new ReadOnlyCollection<Intervencao>( _intervencoes );
}
set {
_intervencoes = new List<Intervencao>( value );
Contract.Assume(_intervencoes != null);
}
}
public void ModificaEstado(Intervencao intervencao ){
//some checks removed
intervencao.Ocorrencia = this;
_intervencoes.Add(intervencao);
}
//more code removed
}
public class Intervencao : EntityWithAction, IHasAssignedDomainAction {
//other code remove
internal Ocorrencia Ocorrencia { get; set; }
}
And here's the mappings (only the important things):
public class IntervencaoMapping: ClassMap<Intervencao> {
public IntervencaoMapping()
{
WithTable("Intervencoes");
Not.LazyLoad();
Id(intervencao => intervencao.Id)
.ColumnName("IdIntervencoes")
.WithUnsavedValue(0)
.SetGeneratorClass("identity");
Map(intervencao => intervencao.Guid, "Guid")
.Not.Nullable();
Version(ent => ent.Version)
.ColumnName("Version");
References(ent => ent.Action, "IdAccao")
.Cascade
.SaveUpdate();
Map(intervencao => intervencao.TipoEstado, "TipoEstado")
.CustomTypeIs(typeof (TipoEstado))
.CustomSqlTypeIs("integer");
Map(intervencao => intervencao.Observacoes, "Observacoes");
References(intervencao => intervencao.Ocorrencia, "IdOcorrencias")
.Not.LazyLoad();
}
}
public class OcorrenciaMapping: ClassMap<Sra.Ocorrencias.Ocorrencia> {
public OcorrenciaMapping()
{
WithTable("Ocorrencias");
Not.LazyLoad();
Id(ocorrencia => ocorrencia.Id)
.ColumnName("IdOcorrencias")
.WithUnsavedValue(0)
.SetGeneratorClass("identity");
Map(ocorrencia => ocorrencia.Guid, "Guid")
.Not.Nullable();
Version(ocorrencia => ocorrencia.Version)
.ColumnName("Version");
Map(ocorrencia => ocorrencia.Descricao)
.ColumnName("Descricao");
Map(ocorrencia => ocorrencia.Nif, "Nif")
.Not.Nullable();
Map(ocorrencia => ocorrencia.TipoOcorrencia, "TipoOcorrencia")
.CustomTypeIs(typeof(TipoOcorrencia))
.CustomSqlTypeIs("integer");
Map(ocorrencia => ocorrencia.BalcaoEntrada, "Balcao")
.CustomTypeIs(typeof(TipoBalcao))
.CustomSqlTypeIs("integer")
.Not.Nullable();
References(ocorrencia => ocorrencia.Organismo, "IdOrganismos")
.Cascade.None()
.Not.Nullable();
HasMany(ocorrencia => ocorrencia.Intervencoes)
.Access.AsCamelCaseField(Prefix.Underscore)
.AsBag()
.Cascade
.All()
.KeyColumnNames.Add("IdOcorrencias")
.Not.LazyLoad();
}
}
As you can see, Interncao objects are added through the ModificaEstado method which ensures that Ocorrencia reference on Intervencao "points" to a reference of Ocorrencia. Now, how do I test this relationship with the PersistenceSpecification object? I've ended up with the following code:
[Test]
public void Test() {
using (var session = _factory.GetSession()) {
using (var tran = session.BeginTransaction()) {
var accao = CreateAction();
session.Save(accao);
var organismo = CreateOrganismo();
session.Save(organismo);
var intervencao = CreateIntervencao();
((IHasAssignedDomainAction)intervencao).SetActionTo(accao);
var intervencoes = new List<Intervencao> {intervencao};
new PersistenceSpecification<Ocorrencia>(session)
.CheckProperty(e => e.Nif, _nif)
.CheckProperty( e =>e.Organismo, organismo)
.CheckProperty( e => e.Descricao, _descricao)
.CheckProperty( e => e.TipoOcorrencia, TipoOcorrencia.Processo)
.CheckList( e => e.Intervencoes, intervencoes)
.VerifyTheMappings());
tran.Rollback();
}
}
}
Since IdOcorrencia is defined as an external key in table Intervencoes, the previous code fails because it tries to insert the intervencoes list with IdOcorrencia set to null. If I remove the external key, then the test works fine, but I believe that I shouldn't be doing that.
I'm probably doing something wrong but I'm not sure on what that is. So, can anyone be kind enough and give me a hint on how to solve this?
thanks guys.
Luis
The problem was that I was using an old version of the fluent nhibernate. recente versions have overrides which let you solve this kind of problem:
http://www.mail-archive.com/fluent-nhibernate#googlegroups.com/msg06121.html

Rhino Mocks: How do I mock a method call within a method call?

I have a really simple class with two methods; One that will be called and the other that it will call. The idea is to call the OuterMockMethod method BUT mock the InnerMockMethod. Right now I can only seem to mock the OuterMockMethod method.
public class MockClass : IMockInterface
{
public virtual MockClass InnerMockMethod()
{
MockClass returnValue;
returnValue = new MockClass();
returnValue.SomeMessage = "Not mocked";
return returnValue;
}
public virtual MockClass OuterMockMethod()
{
MockClass mock;
mock = new MockClass();
return mock.MockedMethod();
}
}
Now this works, but it isn't the method I want to mock:
public void MockTest_Internal()
{
MockClass returnedClass;
MockClass mockProvider;
mockProvider = repository.StrictMock<MockClass>();
mockProvider.Expect(item => item.OuterMockMethod())
.Return(new MockClass { SomeMessage = "Mocked" });
repository.Replay(mockProvider);
returnedClass = mockProvider.OuterMockMethod();
Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
}
As you can see, it calls the OuterMockMethod which it likes but I don't want that. I want to mock the InnerMockMethod so that when it's called by the OuterMockMethod it will return what I want it to.
public void MockTest_Internal()
{
MockClass returnedClass;
MockClass mockProvider;
mockProvider = repository.StrictMock<MockClass>();
mockProvider.Expect(item => item.InnerMockMethod())
.Return(new MockClass { SomeMessage = "Mocked" });
repository.Replay(mockProvider);
returnedClass = mockProvider.OuterMockMethod(); //Boom angry Rhino
Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
}
In this case you need to put the mock on the returned object:
MockClass returnedMock = MockRepository.GenerateMock<MockClass>();
returnedMock.Expect( rm => rm.InnerMockMethod() )
.Return( new MockClass { SomeMessage = "Mocked" } );
mockProvider.Expect( mp => mp.OuterMockMethod() ).Return (returnedMock );
returnedClass = mockProvider.OuterMockMethod();
...
Note that StrictMock has been deprecated. The preferred pattern is now AAA (Arrange, Act, Assert). You can find more info here.