Customizing MEF - model-view-controller

I have this situation where I want to use MEF in a chess project I'm workin on. Let's say I have a class constructor as in:
public class MoveManager
{
private Piece _piece;
public MoveManager(Piece piece)
{
_piece = piece;
}
Mode code here...
}
In this context I would have several classes that would derive from Piece like, Pawn, Rook, etc. If I put export attributes on all the classes the derive from Piece, the object being passed into the constructor is null. MEF loops through all classes the have the [Export(typeof(Piece))] and if it exceeds 1, it passes in null. So I cannot use MEF in this way. I'm going to use an Abstact Factory for getting the correct piece. Seems like the DI part of MEF can only take a single class that has the [Export(typeof(some base class))].
Can anyone shed some light on this?

I think you might be looking for the [Importing Constructor] arrtibute, which tells MEF how to use an exported class's constructor.
[Export(typeof(IPiece))]
class Pawn : IPiece
{
[ImportingConstructor]
public Pawn(ISomeDependency dep, [ImportMany] IEnumerable<IOtherDependency> depList)
{
//... do stuff with dependencies
}
}
This requires that an ISomeDependency is exported elsewhere (exactly once) and accepts any number of IOtherDependency's that might be exported too.
Supposing you did this with each piece, you could then:
[Export(typeof(IPieceList))]
class PieceList : IPieceList
{
[ImportingConstructor]
public PieceList([ImportMany] IEnumerable<IPiece> pieces)
{
// pieces now contains one of each piece that was exported above
}
}

Related

ExcelDna - Excel can't access function in base class

When Excel tries to call a method in a abstract base class i get a Run-Time error
"Cannot run Marco 'MarcoName'. The macro may not be available"
I can run code from the super class.
The code is similar to this
public abstract class MyBaseClass
{
public static bool MyMethod(string path)
{
if(Valid(path))
{return true;}
return false;
}
}
This code is in a separate assembly imported via a nuget package
The calling code is similar to the below
public class MyClass : MyBaseClass
{
public static bool MyOtherMethod()
{
return true;
}
}
Marking the methods with the "[ExcelFunction]" attribute has no effect.
I am loading the xll file like so,
Application.RegisterXLL (path)
I call the method like so,
Application.Run("MyMethod", path)
Only code in assemblies that are included in the <ExternalLibrary ... /> list in the .dna file are scanned for functions to register. Maybe your external assembly is not mentioned there.
Also, abstract types were not always considered. It looks like this changed at some point, if I look at the code that scans the assemblies here: https://github.com/Excel-DNA/ExcelDna/blob/57c2d0a499a044f6cd1c4ae2c9fbf5b084159dea/Source/ExcelDna.Integration/AssemblyLoader.cs#L93
So it might depend on your Excel-DNA version too.
Easiest might be to have a class with all the functions you want to export, where you can add the Excel-specific attributes (<ExcelFunction .../>) and just forward the calls internally.

Does Processing 3 have class declarations?

Our school project has us make a game using Processing 3. After some studying with the language, our team is pretty confident we can work with the project, though we do have certain reservations of the chosen language.
However, there is one major question we are wondering and could not find an answer. In C++ and many others, when you create a new class in a new file you also create a header file you can include. Does Processing 3 have something similar? I know you can "include" files by adding more tabs, which is still weird but whatever. We would like to have some sort of declarations in advance so we can comment/describe classes and their methods, rather than force each member go through lots of code to find the proper point.
In short, we want to be able to do something like this:
Example.pde
class Example {
//Description
Example();
//Description
void doSomething(int variable);
}
//Other team members don't have to worry past this,
//as they have already seen the public interface
Example::Example()
{
//Constructor
}
void Example::doSomething(int variable)
{
//Function
}
Or do we have to always to like this:
Example.pde
class Example {
//Description
Example()
{
//Constructor
}
//Description
void doSomething(int variable)
{
//Function
}
}
Processing is written in Java, so you can only do things that Java supports. Java does not support header files, so no, you can't use header files in Processing.
However, it sounds like what you're really looking for is an interface.
interface Example {
void doSomething(int variable);
}
class MyExample implements Example{
public MyExample(){
//Constructor
}
void doSomething(int variable){
//Function
}
}
With this, you would only need to show other team members the interface, not the class. As long as they program to the interface, they don't need to ever see the class implementation.
More info on interfaces can be found in the Processing reference.

using resharper to extract a class and introduce a constructor dependency

Is it possible to use Resharper to refactor code such that the below method Eat is extracted into a seperate class, and the newly extracted class is injected in the Dinner class as an external dependency?
Original Code
public class Dinner
{
public Dinner()
{
}
public void Eat()
{
//do the eating
}
}
Refactored Code
public interface IEatService
{
void Eat();
}
public class EatService : IEatService
{
public void Eat()
{
}
}
public class Dinner
{
private readonly IEatService _eatService = null;
public Dinner(IEatService eatService)
{
_eatService = eatService;
}
public void Eat()
{
_eatService.Eat();
}
}
It doesn't have to be exactly as the refactored code - this is shown to give an idea.
You can do it nearly as you want in R# 7 using three-step refactoring:
Place the caret at your Eat method, invoke Extract Class refactoring (Ctrl-Shift-R in VS), name your class EatService.
Place the caret at your EatService class, invoke Extract Interface refactoring.
Place the caret at your EatService class, invoke Use Base type Where Possible refactoring.
All that is left is to fix a constructor in Dinner class so it would get IEatService as a parameter.
Using R# 6, one way to achieve this would be with this sequence of operations. Note that refactorings are available on both ReSharper | Refactor on the menu bar, or (quicker) in context with Ctrl+Shift+R. There's still a bit of typing; I wouldn't be surprised if there were a way that didn't require you to type anything at all.
Start with your Original Code in a file named Dinner.cs
With the cursor on Eat, user the Extract Interface refactoring, naming the interface IEatService
With the cursor on IEatService, Alt+Enter and create a derived type, accepting the offered name of EatService, and Alt+Enter to fill in the method implementation body
Here's where we have to type: In Dinner.Eat(), type _eatService.Eat();. Note that _eatService is red; Alt+Enter on it, choose 'Create field', change the offered type to IEatService
With the cursor on the definition of _eatService, Alt+Enter and choose 'Initialize from ctor paramater, and then Alt+Enter again and accept the readonly suggestion
Note that initialising _eatService to null is redundant; R# would let you know this.
We're now at your target code.
I think R# 7 has some new refactorings (such as Extract Class) which might make this quicker.

modules contract by interface, diagram, logic, general informations

Here is my question, I hope that I'll write it correctly because it is a precise question.
I wonder how to use the interfaces as a contract between two modules. When I draw the module diagrams I never knows which of the modules as the circle and which has the half-open circle. A clear way on how to make the distinction would be very appreciated!
I don't want an example on how to use an interface because I know the properties of the interfaces (behaviors, etc).
Let's say that I got 2 modules, one contains the Bussiness logic, so I'll call it "Model", the other contains the GUI so I'll call it "View".
The view needs a Treeview and a Matrix on each nodes. So we got a tree-like hierarchie that the Model knows about, and for each node we want to fill a matrix of values.
root
- node1
-- leaf1
-- leaf2
- node2
- node3
-- leaf3
-- leaf4
My guts are telling me that I should do something like this:
interface IModelHierarchicMatrix {
void setTreeViewValues(TreeViewModel treeview);
void getMatrixValues();
void setMatrixValues(int[] values);
}
class Model implements IModelHierarchicMatrix {
// the code where I override the interface's function
}
So nice, we can call the needed function for the GUI at the Model. But how can we tell the GUI's class that we need that kind of behaviors (class, etc)...
I find myself often doing this kind of thing:
interface IModelHierarchicMatrixGlue {
void acceptModel(IModelHierarchicMatrix model);
}
class Gui implements IModelHierarchicMatrixGlue {
private IModelHierarchicMatrix model;
...
#Override
public void acceptModel(IModelHierarchicMatrix model) {
if (this.model == null) {
this.model = model;
}
}
}
But I always wonder if it's a good way of creating the contract between the Model and the View.
If I got to create a bi-directional contract between the Modules, how should I do that? Because it might create a cyclic logic between the interfaces...
I hope my question was clear enough, thanks in advance.

Enterprise Library Validation Block - Should validation be placed on class or interface?

I am not sure where the best place to put validation (using the Enterprise Library Validation Block) is? Should it be on the class or on the interface?
Things that may effect it
Validation rules would not be changed in classes which inherit from the interface.
Validation rules would not be changed in classes which inherit from the class.
Inheritance will occur from the class in most cases - I suspect some fringe cases to inherit from the interface (but I would try and avoid it).
The interface main use is for DI which will be done with the Unity block.
The way you are trying to use the Validation Block with DI, I dont think its a problem if you set the attributes at interface level. Also, I dont think it should create problems in the inheritance chain. However, I have mostly seen this block used at class level, with an intent to keep interfaces not over specify things. IMO i dont see a big threat in doing this.
Be very careful here, your test is too simple.
This will not work as you expect for SelfValidation Validators or Class Validators, only for the simple property validators like you have there.
Also, if you are using the PropertyProxyValidator in an ASP.NET page, iI don;t believe it will work either, because it only looks a field validators, not inherited/implemented validators...
Yes big holes in the VAB if you ask me..
For the sake of completeness I decided to write a small test to make sure it would work as expected and it does, I'm just posting it here in case anyone else wants it in future.
using System;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ISpike spike = new Spike();
spike.Name = "A really long name that will fail.";
ValidationResults r = Validation.Validate<ISpike>(spike);
if (!r.IsValid)
{
throw new InvalidOperationException("Validation error found.");
}
}
}
public class Spike : ConsoleApplication1.ISpike
{
public string Name { get; set; }
}
interface ISpike
{
[StringLengthValidator(2, 5)]
string Name { get; set; }
}
}
What version of Enterprise Library are you using for your code example? I tried it using Enterprise Library 5.0, but it didn't work.
I tracked it down to the following section of code w/in the EL5.0 source code:
[namespace Microsoft.Practices.EnterpriseLibrary.Validation]
[public static class Validation]
public static ValidationResults Validate<T>(T target, ValidationSpecificationSource source)
{
Type targetType = target != null ? target.GetType() : typeof(T);
Validator validator = ValidationFactory.CreateValidator(targetType, source);
return validator.Validate(target);
}
If the target object is defined, then target.GetType() will return the most specific class definition, NOT the interface definition.
My workaround is to replace your line:
ValidationResults r = Validation.Validate<ISpike>(spike);
With:
ValidationResults r ValidationFactory.CreateValidator<ISpike>().Validate(spike);
This got it working for me.

Resources