public class EntitiesRepository<E, C> where E : EntityObject where C : ObjectContext { private readonly C _ctx; //Unit of Work Accessor public C Session { get { return _ctx; } } //Constructor public EntitiesRepository(C session) { _ctx = session; } //Common Unit of Work Methods public void Save() { _ctx.SaveChanges(); } /// <summary> /// A generic method to return ALL the entities /// of type TEntity. This overload will use the /// the parameter entitySetName in the resolution of mapping /// between the CSDL and SSDL. This method is useful /// for Models that DO have their pluralized names /// changed by the developer. For example if Customers /// table from Northwind produces an Entity that by /// default is named Customers but has it’s name changed /// to Customer this method call would fail. In Version /// 2.0 this pluralizing behaviour will change and this /// method overload should be used only if Developers /// change EntitySet names from the default name generated. /// </summary> /// <param name="entitySetName"> /// The EntitySet name of the entity in the model. /// </param> /// <typeparam name="TEntity"> /// The Entity to load from the database. /// </typeparam> /// <returns>Returns a set of TEntity.</returns> public ObjectQuery<E> All(string entitySetName) { return (ObjectQuery<E>)_ctx.CreateQuery<E>("[" + entitySetName + "]"); } /// <summary> /// A generic method to return ALL the entities /// of type TEntity. This overload will use the /// typeof(TEntity).Name in the resolution of mapping /// between the CSDL and SSDL. This method is useful /// for Models that DO NOT have their pluralized names /// changed by the developer. For example if Customers /// table from Northwind produces an Entity that by /// default is EntitySet name is NOT changed. /// </summary> /// <typeparam name="TEntity"> /// The Entity to load from the database. /// </typeparam> /// <returns>Returns a set of TEntity.</returns> public ObjectQuery<E> All() { return (ObjectQuery<E>)_ctx.CreateQuery<E>("[" + typeof(E).Name + "]"); } //…etc etc etc } public class CustomerRepository : EntitiesRepository<Customer, NorthwindEntities> { public IQueryable<Customer> GetCustomerByCountry(string country) { var custs = from c in Session.Customers where c.Country == country select c; return custs; } /// <summary> /// Uses the base constructor /// to inject the Unit of work /// session. (should new up the /// session outside of here if /// it’s being used accross /// repositories. Also change to /// add the context to the constructor /// parameters as well) /// </summary> public CustomerRepository() : base(new NorthwindEntities()) { } }
My fear is that if the changes / upgrades to the Entity Framework for Version 2.0 don’t cut deep enough many will lose faith and patience and may be forced by default into using some other ORM. Personally this is a critical feature for me however for the moment I have decided there is no satisfying solution to this problem and so I am going to leave Fetching Strategies out of my library for now. I will post the entire code soon.
]]>My first instinct was to tackle the task by using the recently devised Model-View View-Model pattern however I chose not to go down that path because this applications primary objective was to provide a learning exercise in UI skills and ultimately I thought that implementing the Model View Presenter pattern in a Silverlight application would provide me a solid foundation to compare when I do finally try out MVVM.
Over the past couple of years I have become accustomed to using a home grown MVP Framework that was fully templated in Visual Studio and offered a lot of benefit in speed of use by cutting out a lot of the repetitive file creational stuff that such an approach requires. Using this templated framework meant that creating a ‘new item’ in Visual Studio would trigger the creation of the Model, View (user control, page, form etc) and Presenter, wiring their dependencies (via injection) together in the process. One of the benefits of this homegrown MVP framework was it’s ability to deal with what effectively handled two way Databinding between the views and the model, something that we now get from Silverlight for free, which gave me a chance to really see how MVP would benefit or from this aspect.
So far my standard MVP approach for Win Forms and Web Forms seems to sit equally as well with Silverlight so I am pleased that I can move forward quickly with completing this learning exercise, which as I have pointed out was completely about getting comfortable with Silverlight in respect to gaining familiarity with the new UI paradigm.
public partial class CaseInPoint : UserControl { //The main UI View (control) that loads all the tabs views) public CaseInPoint() { InitializeComponent(); //new up the model for the tabbed application PointInCaseProject model = new PointInCaseProject(); //new up all the presenters CaseInPointPresenter mainPagePresenter = new CaseInPointPresenter(this, model); ProjectDetailPresenter projDetailsPresenter = new ProjectDetailPresenter(this.AppTabs.ctlProjectCalculator, model); FactorsPresenter factorPresenter = new FactorsPresenter(this.AppTabs.ctlFactorList, model); UserStoryPresenter storyPresenter = new UserStoryPresenter(this.AppTabs.ctlUserStoryView, model); ActorsPresenter actorsPresenter = new ActorsPresenter(this.AppTabs.ctlActorsView, model); } }
internal class ProjectDetailPresenter : IPresenter { private ProjectDetailCalculator _view; private PointInCaseProject _model; private CaseInPoint _viewParentWindow; internal ProjectDetailCalculator View { get { return _view; } set { _view = value; } } internal PointInCaseProject Model { get { return _model; } set { _model = value; } } internal ProjectDetailPresenter(ProjectDetailCalculator view, PointInCaseProject model) { //set the view and model _view = view; _model = model; //wire up the events of the view and its parent window WireUpEventsOnInit(); //do any initial data binding InitialBindUiToEntity(); } }
[XmlRoot()] internal class PointInCaseProject : INotifyPropertyChanged { private ProjectDetails _details; private List<EnvironmentalFactor> _environmentalFactors; private List<TechnicalFactor> _technicalFactors; private List<UserStory> _userStories; private List<Actor> _actors; /// <summary> /// The list of User Stories contained /// within the point case estimate project. /// </summary> [XmlElement()] internal List<UserStory> UserStories { get { return _userStories; } set { NotifyPropertyChanged(“UserStories”); _userStories = value; } } /// <summary> /// The list of Technical Factors /// within the point case estimate project. /// </summary> [XmlElement()] internal List<TechnicalFactor> TechnicalFactors { get { return _technicalFactors; } set { NotifyPropertyChanged(“TechnicalFactors”); _technicalFactors = value; } } /// <summary> /// The list of Environmental Factors /// within the point case estimate project. /// </summary> [XmlElement()] internal List<EnvironmentalFactor> EnvironmentalFactors { get { return _environmentalFactors; } set { NotifyPropertyChanged(“EnvironmentalFactors”); _environmentalFactors = value; } } /// <summary> /// The list of Actors within the /// point case estimate project. /// </summary> [XmlAnyElement()] internal List<Actor> Actors { get { return _actors; } set { NotifyPropertyChanged(“Actors”); _actors = value; } } /// <summary> /// The details of the /// point case estimate project. /// </summary> [XmlElement()] internal ProjectDetails Details { get { return _details; } set { _details = value; NotifyPropertyChanged(“Details”); } } public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public event PropertyChangedEventHandler PropertyChanged; public void Clear() { if (this._details != null) { this._details.Clear(); } if (this._actors != null) { this._actors.Clear(); } if (this._environmentalFactors != null) { this._environmentalFactors.Clear(); } if (this._technicalFactors != null) { this._technicalFactors.Clear(); } if (this._userStories != null) { this._userStories.Clear(); } } }
NOTE: This is not the entire code base and some things above have been left out or assumed, things such as the entities that are contained in generic<> lists in the model and all the subscribing handlers for view events that would be present in the presenters. At the end of the exercise I will follow up by implementing a small application using MVVM framework, putting me in a better position to discuss the differences and merits of both approaches. I have read some opinion that suggests that the Databinding abilities present in Silverlight and WPF are not equally as available to pre-exiting UI development frameworks such as MVC and MVP so I consider this is step one in putting that assertion to the test for my own sanity.
Of course a happy by-product of this exercise is getting a tool to manage my point case estimations for real world projects and in so doing I will be able to remove the dependence on the spreadsheet that currently manages this task for me. As it stands today, the project details tab has it’s data being persisted and I have decided to take a document centric approach to the persistence. Each project will save it’s estimation data in XML format locally in Isolated Storage and each file is saved as a .pce (point case estimate) file. I will post the Visual Studio solution when the project is complete.
]]>I do think that as more and more third party tools (controls) become available I will not be required to work so particularly on my graphical XAML skills and be left to concentrate on the job at hand and surely that’s what we want business developers doing.
So in essence I do think that projects where a high requirement for visual elegance or graphical complexity will benefit greatly from the inclusion of the designer / devigner role, however many projects that need classical data driven forms should be adequately handled by the simple developer who like me is stick figure bound!
]]>I have to say that as a Rich Client kind of guy, I have always been at odds with ASP.Net to a degree. Web Forms was a revelation of sorts when it was introduced and it continues to be a very useful and highly productive framework for web development in the SME IT environments. In pursuit of improving the quality of software the web toolkit exists in a vast nebula of expanding stars which surround ASP.Net Web Forms. Today as Web Developers it’s becoming incumbent on us to have strong skills in CSS, JavaScript, Ajax, JSON, JQuery, DHTML, MVC and the list goes on and on and on and on and…….and this is complicated by the lack of consolidation caused by browser discontinuity - don’t get me started on that. The huge mesh of variation in skill requirement with these technologies is something that never really played well with me and one that I have resisted by and large. I do still from time to time get to develop in ASP.Net, however I still resist these outlying technologies and one might argue that within the context of my business domain that’s perfectly valid (if not required) as a choice.
What I want to be able to do is focus squarely on XAML based UI skills and
leverage this with equal impact on the desktop or the web (or to be precise over HTTP and in the browser) and not feel boxed into my limited abilities with the standard web box of tricks that I named above. Now it’s true that I don’t do a great deal of work on the public facing web however that is not synonymous with my never having to need to build highly scalable applications that exist behind the firewall and even support large user bases outside of that same firewall. If I can affect a streamlining of my team by leveraging XAML via WPF and Silverlight and work richly on the web and desktop and avoid the toolkit soup that comes with browser development, then I will be a happy man - a very happy man.
Certainly these days there is diminishing resistance to the idea of Silverlight becoming more prevalent as an alternative to the prevailing approaches and some of the noise in the blogsphere and opinion in the podcast domain is warming to idea. I would just love to get to the point where my UI technology choice can be more consistent and at best be uniform.
]]>Sometimes it’s not clear whether technology is improving our general quality of life or not. Any thoughts?
Regardless, I hope that 2009 brings an abundance to .NET goodness to one and all. My aim is to be a little more socially inclined next year.
]]>If you read my previous post listing Julie Lerman’s tutorials and the DNR TV episodes with Dan Simmons you should find this series of posts from Stefan a nice accompaniment to those.
I have Julie’s book on order and look forward to reading that when it arrives and a few more are now starting to surface. Joydip Kanjilal has a tutorial and Roger Jennings is working on a book as is Jim Wightman and MS Press have one on the way also.
Also, I have also recently posted about a new version of my implementation of the Specification Pattern for Entity Framework that enables the use of that pattern to build dynamic queries and test Entities for equality. Currently I am working on the Repository Pattern to accompany the Specification Pattern and will also get around to working on NHibernate like Fetching Strategies as per my LINQ To SQL framework that included all three features. Download the code for an early look at the refactor here.
]]>First up in this effort I chose to start with the refactor of the Specification interface and class implementation and that will be the item under discussion in this post.
Recently I remarked that the Entity Framework did not support Expression.Invoke() which made combining Specifications to form .Or and .And Specifications in the current version of the library unusable. After some discussion and comments from that previous post and some further investigation, I discovered an alternative that allowed removing the reliance on Invoking Expressions and enabled rewriting the .Or and .And behaviours of the Expression<T> via the magic of some utility classes with some very handy extension methods. Please take a look at Colin Meek’s post that explains and demonstrates the ‘rewriting’ solution and also recently pointed out that the Entity Framework Extensions library includes a way to resolve this issue, however I chose to utilise the other solution so my library did not form a dependency on the extensions library (for the moment).
the OLD Code:
1: private class OrSpecification : Specification<T>
2: {
3: private readonly ISpecification<T> left;
4: private readonly ISpecification<T> right;
5: public OrSpecification(ISpecification<T> left,ISpecification<T> right)
6: {
7: this.left = left;
8: this.right = right;
9:
10: this._evalFunc =
11: (Func<T, bool>)Func<T, bool>.Combine
12: (left.EvalPredicate.Compile(),
13: right.EvalPredicate.Compile());
14:
15: ParameterExpression parameter =
16: Expression.Parameter(typeof(T), “p”);
17: var invokedExpression =
18: Expression.Invoke(left.EvalPredicate,
19: right.EvalPredicate.Parameters.Cast<Expression>());
20: _evalPredicate =
21: Expression.Lambda<Func<T, bool>>
22: (Expression.Or(right.EvalPredicate.Body,
23: invokedExpression), right.EvalPredicate.Parameters);
24: }
25: public override bool Matches(T entity)
26: {
27: return EvalPredicate.Compile().Invoke(entity);
28: }
29: }
Line 18 is the offending line of code.
My NEW Code:
1: private class OrSpecification : Specification<T>
2: {
3: private readonly ISpecification<T> left;
4: private readonly ISpecification<T> right;
5: public OrSpecification(ISpecification<T> left,ISpecification<T> right)
6: {
7: this.left = left;
8: this.right = right;
9:
10: this._evalFunc =
11: (Func<T, bool>)Func<T, bool>.Combine
12: (left.EvalPredicate.Compile(),
13: right.EvalPredicate.Compile());
14:
15: _evalPredicate = left.EvalPredicate.Or(right.EvalPredicate);
16: }
17: public override bool Matches(T entity)
18: {
19: return EvalPredicate.Compile().Invoke(entity);
20: }
21: }
In short, the extension methods in Colin’s post will kick in and rewrite the behaviour of the .And and .Or method avoiding the need to call Invoke(). This method of composing or ‘rewriting’ as Colin put’s it, also requires a copy of the ExpressionVisitor class which is internal to the Entity Framework. You can find a copy of the ExpressionVisitor here on the wayward blog.
So now I can use my specifications with the Entity Framework! For example if I wish to query my venerable Northwind database and ask for all the products that are now discontinued that are part of existing orders from customers in either Germany and the USA, I can write the following code:
1: [Test()]
2: public void RefineCombinedSpecifications()
3: {
4: Specification<Customer> german_customer_spec =
5: new Specification<Customer>(c => c.Country == “Germany”);
6:
7: Specification<Customer> us_customer_spec =
8: new Specification<Customer>(c => c.Country == “Usa”);
9:
10: Specification<Product> ords_with_discontinued_prods =
11: new Specification<Product>(p => p is DiscontinuedProduct);
12:
13: var comb_country_spec = (german_customer_spec | us_customer_spec);
14:
15: using (var ctx = new NorthwindEntities())
16: {
17: var discontinued_products_on_order =
18: (ObjectQuery<Product>)
19: (from p in ctx.Products
20: .Where(ords_with_discontinued_prods.EvalPredicate)
21: from od in ctx.OrderDetails
22: from o in ctx.Orders
23: from c in ctx.Customers
24: .Where(comb_country_spec.EvalPredicate)
25: where od.ProductID == p.ProductID &&
26: o.OrderID == od.OrderID &&
27: c.CustomerID == o.Customer.CustomerID
28: select p).Distinct();
29:
30: Console.WriteLine(discontinued_products_on_order.ToTraceString());
31:
32: foreach (var product in discontinued_products_on_order)
33: {
34: Console.WriteLine(“The product ID is {0} with a name of {1}”,
35: product.ProductID, product.ProductName);
36: }
37: }
38:
39: Console.ReadLine();
40: }
What’s the benefit you ask? Well the specification class offers me both equality testing (check out the matches method in the download), dynamic querying and and injection as demonstrated in the Repository pattern as here. Next up I will look at flipping open the Repository pattern so it supports LINQ To SQL and the Entity Framework and when the Repository and the Fetching Strategies have been refactored I will post a completely updated version.
]]>I am pretty sure that too much attention in my resume given to practices such as DDD and DI /IoC amongst other things, has been been perceived as fringe and understanding of their value was getting lost in some cases. Typically employers and recruiters are often more interested in how many years of Ajax, ASP.Net, Web Services, ADO.Net etc that you have and I should point out that this is not a criticism of either merely an observation; it comes down to the individual to demonstrate what indeed the value of such knowledge and skills are to any relevant interested party.
So basically I guess my point is this, if your constantly finding yourself perplexed
by what skill you need next, then perhaps you should look at the outlying aspects rather than the obvious and make sure that you give some time to practices or learning new patterns that will help improve the quality of your work regardless of your technology choices. I should point out that whilst many would consider Inversion of Control a technology (I use IoC as an example here), I consider it more a methodology or design practice for the sake of this post and demonstrating the point I am trying to make.
So rather than worry about WCF or WF 4.0 or some other fancy PDC 2008 technology today, perhaps look at Castle Windsor or Spring.Net and begin to get to grips with how DI / IoC can help you write better software or even buy Jimmy Nilsson or Eric Evans books and have a look at Domain Driven Design and see what you can learn from that approach - a wise man once told me "it’s not always about the latest tech!"
PS: I am not saying you should ignore new things as a matter of course (I plan to look at Oslo and M in the coming months myself) but try to balance and give some priority to assigning value to that of the here and now!
]]>I have found to date that I can continue with using the Repository approach along with the Specification Pattern (for dynamic querying) and Fetching Strategies and that was a big criteria for me. There are of course some lingering frustrations with Version 1.0 however at this point I am satisfied that the Entity Framework team will address those in subsequent releases and for the moment I will endure.
]]>THE LIST:
There was a compiled list of pod casts knocking around recently that is more complete (I will post a link when I can find it) but these are the ones I listen too regularly.
]]>In the meantime I thought it was worth taking the same approach as I had with LINQ To SQL and see what was possible with respect to implementing the Specification Pattern in order to provide dynamic querying ability (minus the repository - for the moment only).
Let’s start with a given Entity Model:
I am not going to use much of this model for the purpose of this post but some time soon I will look at how to implement a Fetching Strategies with Entity Framework in a similar manner as that which I demonstrated with LINQ To SQL, but let’s move forward with the specification patterns for now.
So given my model has Orders which aggregate Order_Details and Orders may contain discontinued products I might hypothetically want to sum the total of my unfulfilled problem orders where they contain discontinued products. If I just whip out my specification library (built for LINQ’ish entity / object matching and LINQ To SQL dynamic querying) and I attempt to use it directly with the Entity Framework in this fashion, I get the same behaviour as I expected previously with the other technologies.
static void Main(string[] args) { Specification<Order> order_spec = new Specification<Order>(o => o.Order_Details.All (od => od.Product is DiscontinuedProduct)); using (var ctx = new NorthwindEntities()) { ObjectQuery<Order> orders = (ObjectQuery<Order>) from o in ctx.Orders .Include(“Order_Details”) .Include(“Customer”) .Where(order_spec.EvalPredicate) select o; Console.WriteLine(orders.ToTraceString()); try { foreach (var order in orders) { var sumup = order.Order_Details.Sum (od => od.Quantity * od.UnitPrice); Console.WriteLine(sumup.ToString()); } } catch (ArgumentException argEx) { Console.WriteLine(argEx.Message); } } Console.ReadLine(); }
Ok, that’s great but now I want to try combining specifications which I can do by taking advantage of the operator overloading for OR and AND. Bam, crash it comes tumbling down.
Now its late and I am starting to get annoyed with the Entity Framework. As it turns out (as far as I can tell), LINQ to SQL is far more pliable in managing dynamic queries. Why? Well EF doesn’t play nice with Expression<T>, specifically Expression<Func<T>> etc. Errors arise when you build and invoke Expressions because the Entity Framework doesn’t support Expression.Invoke which is required to combine Expressions.
private class OrSpecification : Specification<T> { private readonly ISpecification<T> left; private readonly ISpecification<T> right; public OrSpecification(ISpecification<T> left, ISpecification<T> right) { this.left = left; this.right = right; this._evalFunc = (Func<T, bool>)Func<T, bool>.Combine (left.EvalPredicate.Compile(), right.EvalPredicate.Compile()); ParameterExpression parameter = Expression.Parameter(typeof(T), “p”); var invokedExpression = Expression.Invoke(left.EvalPredicate, right.EvalPredicate.Parameters.Cast<Expression>()); _evalPredicate = Expression.Lambda<Func<T, bool>> (Expression.Or(right.EvalPredicate.Body, invokedExpression), right.EvalPredicate.Parameters); } public override bool Matches(T entity) { return EvalPredicate.Compile().Invoke(entity); } }
private static void CombinedOrSpecExample() { Specification<Order> order_spec = new Specification<Order>(o => o.Order_Details.All (od => od.Product is DiscontinuedProduct)); Specification<Order> german_customer_spec = new Specification<Order>(c => c.Customer.Country == “Germany”); var orSpec = order_spec | german_customer_spec; using (var ctx = new NorthwindEntities()) { var orders = (ObjectQuery<Order>) from o in ctx.Orders .Include(“Order_Details”) .Include(“Customer”) .Where(orSpec.EvalFunc).AsQueryable<Order>() select o; Console.WriteLine(orders.ToTraceString()); try { foreach (var order in orders) { var sumup = order.Order_Details.Sum (od => od.Quantity * od.UnitPrice); Console.WriteLine(“The sum of orders for order ID: {0} is {1}”, order.OrderID.ToString(), sumup.ToString()); } } catch (ArgumentException argEx) { Console.WriteLine(argEx.Message); } } }
This code produces a casting error: