castle: register interface proxies by convention - castle

I want to register multiple components implementing the dictionary adapter, but the AllTypes.From.. only picks class-types. I want to do something like this:
container.Register(AllTypes.FromAssemblyContaining<IFooSettings>()
.Where(type => type.IsInterface)
.Configure(component =>
component.UsingFactoryMethod((kernel, model, creationContext) => new DictionaryAdapterFactory().GetAdapter(creationContext.RequestedType, ConfigurationManager.AppSettings))));
Now I can't seem to be able to create my own version of "AllTypes" since the FromTypesDescriptor ctor is internal. Any ideas how I can accomplish this?

This now works in Castle 3.3.0:
var dictionaryAdapterFactory = new DictionaryAdapterFactory();
container.Register(
Types.FromThisAssembly().Where(t => t.Name.EndsWith("Settings") && t.IsInterface)
.Configure(component => component.UsingFactoryMethod((kernel, model, creationContext) => dictionaryAdapterFactory.GetAdapter(creationContext.RequestedType, ConfigurationManager.AppSettings))));
You have to use "Types" which also picks up interfaces

I do something like this
container.Register(
AllTypes
.FromThisAssembly()
.Pick()
.WithService.DefaultInterface()
.Configure(r => r.LifeStyle.Transient));
This registers components based on a matching interface and class name.
So if I ask Castle for an interface called IFooSettings then Castle will by default return the class FooSettings.
There are a series of rules you can use for registration and you can see them here. It's does not recommend using the Factory method you are using in your example.

Related

ReactiveUI and binding data objects from backend system

Currently, we are investigating possibilities with ReactiveUI how to visualize content of data objects coming from a backend system.
In the ReactiveUI documentation it is mentioned, the recommended approach is using type-safe bindings.
Therefore,
the code behind consists of all bindings between view and view model
the view model is enriched with read-write properties or read-only properties necessary for the binding
the view model has to take the data object's content to make it accessible via the read-write or read-only properties
View:
this.Bind(ViewModel,
viewModel => viewModel.DiameterInInch,
view => view.MaterialDiameterInInch.Text)
.DisposeWith(disposableRegistration);
View Model:
constructor
{
// reading data object in constructor
this.WhenAnyValue(x => x.Material.MutableDataObject.DiameterInInch)
.Subscribe(diameter => DiameterInInch = diameter);
// writing to data object in constructor
this.WhenAnyValue(x => x.DiameterInInch)
.Subscribe(diameter =>
Material.MutableDataObject.DiameterInInch = diameter);
}
[Reactive]
public double DiameterInInch { get; set; }
With this approach, we see that we are facing a certain effort when we have to implement the complete binding chain in code behind and the view model for each content field / property of a data object.
What further approaches can you recommend to minimize or avoid such an implementation effort / code duplication?
Why not just bind directly to DiameterInInch?
The way I see it, Material is a property of your ViewModel and its property - MutableDataObject - has to be a ReactiveObject (or some other implementation of INPC; otherwise you wouldn't be able to use this.WhenAnyValue on it). Maybe try doing it this way:
View:
this.Bind(ViewModel,
vm => vm.Material.MutableDataObject.DiameterInInch,
v => v.MaterialDiameterInInch.Text)
.DisposeWith(disposableRegistration);
Please note that I'm not an expert user of ReactiveUI so I may be missing something important here.

AutoMapper mapping fails randomly when defining mappings locally

We are configuring automapper for my asp.net MVC/Web API project in the method definition as follows.
public HttpResponseMessage GetDetails(int assignmentId)
{
var valuation = _valuationRepository.GetOneById(assignmentId);
Mapper.CreateMap<UserLicenses, UserLicenseResponseModel>()
.ForMember(dest => dest.State, opt => opt.MapFrom(src => src.States.StateCode))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId))
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => (src.UserProfile != null) ? (src.UserProfile.FirstName + ' ' + src.UserProfile.LastName) : " "));
Mapper.CreateMap<AdditionalExpenses, AdditionalExpensesResponseModel>();
Mapper.CreateMap<ValuationAssignment, ValuationAssignmentResponseModel>();
var model = Mapper.Map<ValuationAssignmentResponseModel>(valuationAssignment);
return Request.CreateResponse(HttpStatusCode.OK, new { Assignment = model });
}
We are noticing that api is randomly not mapping values and response json is returning null values for the mapped fields.
When this happens I'm recycling the app pool and it seems to work for a period of time and we run into the issue again.
Documentation refers to storing all the mappings in Application_Start in Global.asax. However, we are setting them in the method definition - Is that why we are seeing this issue?
The problem is that Web applications are threaded, and Automapper is not fully thread safe. i.e. there are methods and classes that are thread safe, and others that are not. If you use the static class Mapper, it can happen that while one thread is trying to map an object the other is trying to redefine the mapping, and that's why you get those random errors.
As Jasen tells in his comment, and you yourself say in your question, one solution is to define all the mappings in a central location, only once, and before the first requests are executed, usually in Application_Start.
Another option is to use non static classes from AutoMapper. I.e. instead of using Mapper use other non static classes. In this way each thread has its own instances and thread safety is not a concenr. For more information on the problem, and this alternative solution, please see also this Q&A: Is Mapper.Map in AutoMapper thread-safe?.
By the way, from the performace point of view it's much better to define the mappings only once and reuse them, instead of redefining them all the time. Most probably AutoMapper uses Reflection, and, if so, caching the types and properties informations is very advisable not to degrade performance.

TDD with Laravel 4, Factory Muff, Ardent, Faker - I'm doing it wrong

I want to write tests for my data models that make sense and work
I've been playing trying to test models like a boss in Laravel (right now I'd say I'm struggling to hold down a position in middle management). I'm using Ardent for my data models. The article referenced above makes it look like Factory Muff is super awesome and would be really handy in facilitating the creation of mock objects.
However, as I dig deeper, I find that Factory Muff is very limited in the data it can provide. It's basically just random words and email addresses. Anything beyond that, it seems I have to write a static method into my data model to generate valid data for the mock object. That doesn't seem very useful, but I'm guessing I'm probably doing it wrong, with a complete misunderstanding of what Factory Muff is all about.
In the data model
Consider this data validation ruleset:
public static $rules = [
'property' => 'required|address',
'name' => 'required|name',
'email' => 'required|email',
'phone' => 'required|phone',
'dob' => 'required|date',
];
Factory Muff seems to be completely ill-suited to generate any of this data beyond the name and email address, unless I want to write a static method that generates data formatted in the correct fashion. This is what I think I have to do with Factory Muff to be able to create a mock object without getting validation errors:
public static $factory = [
'property' => 'call|makeStreetAddress',
'name' => 'string',
'email' => 'email',
'phone' => 'call|makePhone',
'dob' => 'date|makeDate',
];
public static function makeStreetAddress()
{
$faker = \Faker\Factory::create();
return $faker->streetAddress;
}
public static function makePhone()
{
$faker = \Faker\Factory::create();
return $faker->phoneNumber;
}
public static function makeDate()
{
$faker = \Faker\Factory::create();
return $faker->date;
}
This seems pretty verbose, particularly with 10 to 20 fields on a table. I also don't like calling \Faker\Factory::create() in every single static method call (I don't really have a concrete reason, I just don't like it; if you know of a workaround, or if my fear is unfounded, please let me know.)
In the database seeder
I've got database seeding scripts setup that use Faker to generate a bunch of garbage in the database for use in development and testing. It's super intuitive and easy-to-use. For example, this is the seeding script for the above data set.
$faker = \Faker\Factory::create();
$application = Application::create([
'property' => $faker->streetAddress,
'name' => $faker->name,
'email' => $faker->email,
'phone' => $faker->phoneNumber,
'dob' => $faker->dateTimeBetween('-60 years', '-18 years'),
]);
The more I think about what it is I'm doing here, the more I feel like I'm being redundant.
Questions
If I'm seeding the database with garbage data generated by Faker before running my tests, do I even need Factory Muff to create mock objects? Shouldn't I be able to adequately test the codebase using the seed data from the database? Why would I need to mock?
Am I missing the whole point of Faker Muff? Does it have any advantages? It seems to me like little more than a random word generator.
What am I doing wrong? I'm extremely interested in TDD, but it's so daunting. If you noticed any bad practices, or the lack of best practices in my code, please let me know.
I think you are mixing up two different concepts here.
First, the purpose of the data that you create with Faker (in your case, database seeding) is to simulate real life scenarios in your application. For example, if you are developing a blogging platform, you can use it to have some blog posts with tags, user comments and author comments.
When it comes to testing, you can use this in your functional or acceptance tests. For example, if you want to test something like test tag page shows posts tagged with X tag or test user can only delete his own comments, then you could take advantage of Faker data to have some previous posts, tags and comments to work with.
On the other hand, FactoryMuff allows you to quickly create an instance of any given model. Consider the scenario when you are unit testing the validation method for your Post model, so you would have to:
// 1. create new Post
// 2. fill it with data
// 3. try to validate
Having your database seeded is not going to be useful here, since you are going to be creating a new model, and FactoryMuff will do steps 1 and 2 for you. Also, keep in mind that when you are unit testing, you want to do it in isolation, so you shouldn't need to touch your database at all. Instead, you could mock your database object and return fake models and its possible relationships (FactoryMuff to the rescue again).
Finally, I think that maybe you are not seeing the advantages of FactoryMuff functionality because your application may be still small, but you will and won't mind writing a few static methods as your codebase –and your tests– grows.

Ninject and MVCContrib GridModels

I am sure there has to be an easy way to do this, but I just cant seem to get my head around it.
I am using the MVCContrib Grid control to display a number of grids in a 3 tier application I am working on (ASP.NET MVC3 PL -> BLL -> DAL). I also am using Ninject to automatically inject all my dependencies.
The problem I am having is that I am using a grid model to display grids in my Views like this:
#Html.Grid(Model).WithModel(new UserGridModel(Html)).Attributes(id => tableName)
and have the corresponding grid model defined:
public class UserGridModel : GridModel<User> {
public UserGridModel(HtmlHelper html)
{
Dictionary<int, string> userStatuses = /*TODO: GET ALL USER STATUSES*/;
Column.For(user => user.ID);
Column.For(user => html.ActionLink(user.Email, "Edit", new {id = user.ID})).Named(DtoResources.UserDto_Email);
Column.For(user => user.FirstName);
Column.For(user => user.LastName);
Column.For(user => userStatuses[user.StatusID]);
}
}
Now I need to inject a service into this model so it can pull in all of the applicable statuses from the service (BLL) level. Currently just to make sure this would work, I exposed the IKernel in the Bootstrapping code and just IKernel.Get() but I don't think that is the cleanest way to get it. I would use constructor injection, but if I put the IUserStatusService as a parameter in the constructor, I can't figure out how I would get Ninject to inject the correct parameter when I call new UserGridModel(Html) in the view without explicitly using the IKernel there.
I am either missing something or wiring this up all wrong. Either way I'm stuck ... any help? What is the proper way to get an instance of my service through Ninject
In my opinion the cleanest solution to your problem is to change your controller so that it creates a model that already contains the user status as string so that no convertions is required in the view. I would do as littel as possible in the view and grid model.
Another possibility is to property inject the service to your view an pass it to the grid model. But as I mentioned this way you are introducing logic to your view.

Zend Framework Model

is it posible to have a true Model Layer in PHP like in Ruby on Rails? With Zend Framework you can create a Model but this is a class. As I know you have to write all the logic by myself.
Solutions?
True, in Zend Framework you need to declare classes for the database tables you'd like to access. But the rest can be done implicitly, if the default behavious is sufficient. The following is a valid and functional model class (compare to http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.introduction):
class bugs extends Zend_Db_Table_Abstract
{
// table name matches class name
}
This should let you access the table named "bugs", e.g.:
$table = new bugs();
$data = array(
'created_on' => '2007-03-22',
'bug_description' => 'Something wrong',
'bug_status' => 'NEW'
);
$table->insert($data);
Again, the example was taken directly from the documentation mentioned above.
Or since 1.8.x there is a DataMapper pattern used for models (see quickstart in manual)
i wrote a script that might suite your needs.
http://code.google.com/p/zend-db-model-generator/

Resources