ASP.NET MVC Model Mixins? - asp.net-mvc

I have a set of fields that I intend to share between multiple models. I want all the fields to be included in each entity's table (not just one table for the fields). I'm more familiar with languages such as Python, where this type of pattern is called a "mixin", essentially a class that doesn't exist on its own (it doesn't get instantiated/doesn't have a table in the case of a model class). Instead, the derived class simply inherits the fields and its table looks as if the fields were simply included right on the model class.
The concept of a "Complex Type" in Entity Framework seems like a close proxy to what I'm looking for, but the inability to include navigation properties is a bit of killer. Is there any other way to do this, or if Complex Types are the answer, then what should I do about the navigation properties?

I've read this note in a book:
An interesting possibility beyond base classes and interfaces are mixins, but they are an OOP feature not supported by .NET languages. A mixin is a class that provides a certain functionality that other classes can inherit, but it is not meant to be a standalone class. Put another way, a mixin is like an interface where some of the members might contain a predefined implementation. Mixins are supported in some dynamic languages, including Python and Ruby. No .NET languages currently support mixins, but mixins can be simulated using ad hoc frameworks such as Castle. DynamicProxy. With this framework, you first define a class that contains all the methods you want to inject in an existing class—the mixin. Next, you use the framework to create a proxy for a given class that contains the injected methods. Castle.DynamicProxy uses Reflection.Emit internally to do the trick.

You can do this using inheritance. If you've already considered that, I apologize. Code follows.
public abstract class WidgetBase
{
public string Name { get; set; }
}
public class SweetWidget : WidgetBase
{
public int SweetnessFactor { get; set; }
}
public class SourWidget : WidgetBase
{
public int Sourness { get; set; }
}
Then in your model configuration, you do:
const string discriminator = "WidgetType";
Map<SweetWidget>(mc => mc.Requires(discriminator).HasValue("Sweet"));
Map<SourWidget>(mc => mc.Requires(discriminator).HasValue("Sour"));
You will need to add a column, "WidgetType", to your table. EF will then populate it as specified in the mapping.
Note that the base class MUST be abstract. As long as your table contains all of the fields for all of the derived classes, this is how you do Table Per Hierarchy in EF Code First.

Actually had a chance to discuss this with one of the developers on Entity Framework. It's not technically possible at this time. It's apparently being kicked around, but no one is working on it at this point. Complex Types are a sort-of version, but they of course don't support navigation properties. Thanks to everyone who took at stab at it for me.

Related

What is the difference between ComponentModel.DataAnnotation and decorator pattern.?

I was implementing repository decorator pattern on my project as:
[Auditable]
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
}
I got this idea from the following link.
https://efpatterns.codeplex.com/discussions/282699
But couldn't successfully implemented. Then I start learning about decorator pattern and DataAnnotation because the way Auditable attribute on Product entity is somewhat similar in DataAnnotation and decorator pattern. So my question is are they same thing.? If they are the same then how would I implement Auditable repository pattern (more on link) on my project.
That's not the decorator pattern as originally described by the Gang Of Four.
The decorator pattern is an inheritance technique to add functionality to existing classes. The pattern works by creating a set of subclasses which each provide a specific type of functionality on top of the base class.
Then you compose a combination by passing the existing instance as inner object to a subclass instance:
public class SecurityToken
public class ExpiringToken : SecurityToken;
public class RpcSecurityToken : SecurityToken;
So if you would like to have a token which is remote and will expire after an amount of time:
var token = new RpcSecurityToken(new ExpiringToken(new SecurityToken("sds")));
What you do is to just decorate a class with an attribute, which not is the same thing.
The decorator pattern is a mechanism of taking a base implementation of a given interface as extending its behavior without modification of original implementation.
Its similar to inheriting from a base class, however it has more flexibility. For example, a decorator class can be applied to any other class that implements the same interface, there is no restriction to only extending a single base class. They can also be chained together etc...
e.g
public interface IThing
{
void AMethod()
}
public abstract class ThingDecorator : IThing
{
private IThing inner;
public ThingDecorator(IThing inner)
{
this.inner = inner;
}
public virtual void AMethod()
{
this.inner.AMethod();
}
}
Inheriting from ThingDecorator and applying your own extension to the virtual AMethod will add behavior (decorate) the inner instance that is passed in. As the inner instance is coupled to an interface it can be any implementation of that interface.
In your example, you could inherit ThingDecorator as AuditThingDecorator, and override AMethod and include Audit features before you call the base.AMethod()
This is different to just applying an attribute to a class. I think you are trying to apply behavior with an attribute. Attributes can only apply behavior to the class if there is a container, or some other part of the system that can read them and actually apply given behavior. With DataAnnotations, there are other classes that read these attributes and apply behavior (for example, within ASP.NET MVC, the DefaultModelBinder use some of the attributes to provide validation when binding the model).
This is a AOP (apsect orientated programming) approach. One way to apply this (and a way I tend to use) is to use Castle.Core and create interceptors that can automatically implement interface methods or extend virtual methods and read attributes from the Methods/properties that are intercepting, and then apply behavior:
http://docs.castleproject.org/Tools.DynamicProxy-Introduction.ashx
They are both essentially proxies of a given type, however the Decorator pattern above is not dynamic, they are created within code, and the AOP approach can apply behavior at runtime.

where to keep frequently used methods in MVC

I need to implement MVC architecture in my company, So can anyone suggest where to keep frequently used methods to call on all pages. Like:
states ddl, departments ddl also roles list and etc...
Please give me suggestions where to keep them in architecture.
Thanks
There are different solutions depending on the scale of your application. For small projects, you can simply create a set of classes in MVC application itself. Just create a Utils folder and a DropDownLists class and away you go. For simple stuff like this, I find it's acceptable to have static methods that return the data, lists, or enumerations you require.
Another option is to create an abstract MyControllerBase class that descends from Controller and put your cross-cutting concerns in there, perhaps as virtual methods or properties. Then all your actual controllers can descend from MyControllerBase.
For larger applications, or in situations where you might share these classes with other MVC applications, create a shared library such as MySolution.Utils and reference the library from all projects as required.
Yet another possibility for larger solutions is to use Dependency Injection to inject the requirements in at runtime. You might consider using something like Unity or Ninject for this task.
Example, as per your request (also in GitHub Gist)
// declare these in a shared library
public interface ILookupDataProvider
{
IEnumerable<string> States { get; }
}
public class LookupDataProvider: ILookupDataProvider
{
public IEnumerable<string> States
{
get
{
return new string[] { "A", "B", "C" };
}
}
}
// then inject the requirement in to your controller
// in this example, the [Dependency] attribute comes from Unity (other DI containers are available!)
public class MyController : Controller
{
[Dependency]
public ILookupDataProvider LookupDataProvider { get; set; }
public ActionResult Index()
{
var myModel = new MyModel
{
States = LookupDataProvider.States
};
return View(myModel);
}
}
In the code above, you'll need to configure your Dependency Injection technology but this is definitely outside the scope of the answer (check SO for help here). Once configured correctly, the concrete implementation of ILookupDataProvider will be injected in at runtime to provide the data.
One final solution I would suggest, albeit this would be very much overkill for small projects would be to host shared services in a WCF service layer. This allows parts of your application to be separated out in to highly-scalable services, should the need arise in the future.

How do I validate a Modelbound item without violating DRY in ASP.NET MVC?

I'm using the ASP.NET MVC DefaultModelBinder to bind a request to a model class, but only using two of its properties:
namespace MVCApp.Models
{
public class Ticker
{
public string Symbol {get; set;
public string Exchange {get; set;}
}
}
namespace Domain //in another assembly
{
public class Quote
{
public string Symbol {get; set; }
public string Exchange {get; set; }
//lots of other properties we need for output
}
}
public ActionResult ShowQuote(Ticker ticker)
{
var quote = quoteRespository.GetQuoteBy(ticker);
return View(quote);
}
In the view, they can specify the Ticker and Exchange; and that's ModelBound using the DefaultModelBinder. However, each time we need to actually use this Ticker object for something, we need to go to the QuoteRespository and get all of the properties populated for that Ticker.
Question
Should I get rid of the Ticker Object and just create a custom modelbinder to Model-bind to the Quote object; and in the Modelbinder make the respository calls to actually fill out the Quote object? Or should I violate DRY and make the call to that respository in every place we need a quote? Is there a built-in framework way of doing this that I'm missing?
It appears there is a school of thought that says not to make service-layer calls in the Modelbinder.
Update
I created the Ticker class just because we had these two properties in (almost) every single action:
public ActionResult ShowQuote(string symbol, string exchange)
Since they always belong together, I created a small Model class in the UI layer to push them around together (the aforementioned Ticker class). Ticker is not a view model class, and it isn't meant to be.
"Or should I violate DRY and make the call to that respository in every place we need a quote? Is there a built-in framework way of doing this that I'm missing?"
You could always retrieve the quote as part of a Quote controllers OnActionExecuting function.
I wouldn't consider this a DRY violation. Just the cost of doing business. Chances are the way you retrieve quotes won't change and you'll probably have < 10 places were you need this functionality. Depends on how many times you'll need to include that line.
Better to have short and concise action methods than getting all mangled up in base controller and onactionexecuting stuff.
Don't get into model binding against your repository. Did it in a previous project and its the worst and most brittle piece of the application.
I would use AutoMapper to map between view models and domain models.
For me it would be important to see what does Quote contains ? You mention it has other properties for output but does it have other properties and methods which are only relevant to the Domain namespace? If yes then I would like to keep an abstraction between the types used for views and the types in your domain namespace.
So you could end up having a TicketViewModel which contains everything required by your views and as Darin mentioned, use AutoMapper to map TicketViewModel to Quote.
EDIT:
If you really want to ensure DRY, then you can create your own ModelBinder (it's easy, tons of tutorials on Google) and bind your viewmodel from repository in it.

Should I place POCO classes under Helpers or Models namespace?

I usually create POCO classes and place them under the Helpers namespace -they are not in my database model. Now I wonder if I should really place them under the Models namespace. How should I decide? Thank you for your help.
Generally speaking, POCO's refer to persistence-ignorant objects, usually directly representing models in your data tier. In other words, you might have a table called tblProducts, and a POCO called Product:
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
Which represents that table (but not dependant on it). Your ORM (Nhibernate, Entity Framework) can then map the table to this POCO.
With that in mind, i believe it's good practice to put your POCO's in an entirely seperate assembly, not even the same assembly as your data repository.
This way, they are kept isolated from other concerns (persistence, presentation), should not have dependencies on anything else, and are therefore truly persistent-ignorant.
If you want a bit more info on POCO's in .NET, i answered a question a few months back here.
HTH
If you're referring to your domain objects (e.g. Customer, Order) then it's actually better to put them in a separate class library project so you can reuse them from outside of your MVC app too if need be.
If those are view model or model classes then they could go in the Models namespace. You could use the Helpers namespace to define static classes containing extension methods for the HtmlHelper and UrlHelper classes.

In TDD and DDD, how do you handle read-only properties in fakes?

Question
How do you handle read-only fields when creating fakes?
Background
I'm in the beginner stages of using ASP.Net MVC and am using Steven Sanderson's Sports Store and Scott Gu's Nerd Dinner as examples. One small problem that I've just hit is how to work with read-only properties when doing fakes. I'm using LINQToSQL.
My interface is:
public interface IPersonRespository
{
Person GetPerson(int id);
}
and my fake becomes
public class FakePersonRepository
{
public Person GetPerson(int id)
{
return new Person {id="EMP12345", name="John Doe", age=47, ssn=123-45-6789, totalDrWhoEpisodesWatched=42};
}
}
Here's my problem. The fields id, ssn and totalDrWhoEpisodesWatched are read-only, so the above code won't actually work. However, I don't recognize how to create a fake new person and set a read-only property. I'm sure there is a solution, but I haven't come across it yet in my searches.
Update: Inheritance + Property Hiding as a Potential Solution?
I haven't yet decided upon a firm solution to the problem. I dislike the notion of modifying my Domain classes for the purposes of creating fakes. To me, adding markup to the domain classes in order to do testing is a form of added coupling -- coupling to the implementation of your test. I'm now investigating another possibility, which is to create a FakePerson class, which inherits from Person, but hides the properties with new read-write properties.
public class FakePerson: Person
{
public new int age { get; set; }
public new string ssn { get; set; }
public new int totalDrWhoEpisodesWatched { get; set; }
}
So far, this solution is how I am leaning. It does break the Liskov Substitution Principle, however that doesn't bug me as much in a test project. I'd be glad to hear any criticism and/or feedback on this as a solution.
Winner: Mock Frameworks
Moq appears to do the job. My last solution of hiding the property through inheritance does, in fact, work, however by using Moq, I get a standardized set of functionality that is more maintainable. I assume that other mock frameworks have this functionality, but I haven't checked. Moq is said to be more straightforward for the beginning mock writing, which I definitely am right now.
Consider mocking the Person type in your test. Example using Moq:
var mock = new Mock<Person>();
mock.SetupGet(p => p.id).Returns("EMP12345");
mock.SetupGet(p => p.ssn).Returns("123-45-6789");
mock.SetupGet(p => p.totalDrWhoEpisodesWatched).Returns(42);
return mock.Object;
Otherwise, try finding out how LINQ to SQL sets those read only properties.
EDIT: If you attempt the above and Moq throws an ArgumentException in the SetupGet call with the message "Invalid setup on a non-overridable member: p => p.id", then you need to mark the property as virtual. This will need to be done for each property whose getter you wish to override.
In LINQ to SQL, this can be done in the OR designer by selecting the property, then in the Properties window set Inheritance Modifier to virtual.
You can only set readonly properties in the constructor of the class. The Person object should have a constructor that accepts id, ssn, and totalDrWhoEpisodesWatched. Of course, if this is a linqtosql generated object, you might have issues modifying that as the code is auto-generated.
You could consider using a mapped object to expose in your repository ... so you'd never actually have to use your linqtosql object as your model.
In .NET, you could mark your setters as "internal" and use the InternalsVisibleTo assembly attribute to make internals visible to your test assembly. That way your setters won't be public, but you can still access them.
note: even though the question isn't tagged .NET, I assumed it was based on your usage of object initializer syntax. If my assumption was wrong, this suggestion does not apply (unless the language you're using has an equivalent feature, of course).
If it's for tests - consider using reflection. That wouldn't involve messing around your domain model.
For example - i got FactoryBase class, which uses reflection to set needed prop by lambda expression through parameters (like this). Works like a charm - creating new factory is simple as defining repository type and default entity data.
I also use Moq. I love it and it works great. But, before I started using Moq, I wrote many fakes. Here's how I would have solved the problem using fakes.
Since a fake can have additional methods that the "production" implementation doesn't have, I would add a few extra methods to my fake implementation to handle setting the read-only portion.
Like this:
public class FakePersonRepository : IPersonRespository
{
private IDictionary<int, Person> _people = new Dictionary<int, Person>();
public Person GetPerson(int id) // Interface Implementation
{
return _people(id);
}
public void SetPerson(int id, Person person) // Not part of interface
{
_people.Add(id, person);
}
}

Resources