Living in the Tech Avalanche Generation A practitioners introspective on technology 2009-01-07T10:01:37Z WordPress http://www.simonsegal.net/blog/feed/atom/ Simon Segal http://www.simonsegal.net <![CDATA[Fetching Strategies for the Entity Framework - a waste of time for now?]]> http://www.simonsegal.net/blog/2009/01/07/fetching-strategies-for-the-entity-framework-a-waste-of-time-for-now/ 2009-01-07T10:01:37Z 2009-01-07T10:01:37Z I really want Fetching Strategies for the Entity Framework however my efforts in making this happen have been exhausted for now. Implementing Fetching Strategies (eager loading only) was possible in LINQ To SQL and I expect that abstracting the .Includes extension method on ObjectQuery<T> is just as feasible, however what’s questionable right now is whether it’s worth implementing a half baked solution that only helps in eager fetching. Building calls to .Includes() in non generic methods implemented by a Repository, would probably be the best place to do this for Repositories implemented on top of Entity Framework V 1.0.

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.

Share/Save/Bookmark

]]>
0
Simon Segal http://www.simonsegal.net <![CDATA[Silverlight and Model View Presenter (is it a realistic option?)]]> http://www.simonsegal.net/blog/2009/01/06/silverlight-and-model-view-presenter-is-it-a-realistic-option/ 2009-01-06T13:16:45Z 2009-01-06T13:01:00Z I am currently working on ‘Case In Point‘, a Silverlight application which is available online and if you want to know more about it and why I chose to build it, please check out this previous post. In more recent times I have moved beyond the layout / UI Design stage (the main point in building this app) and have just now moved into preparing the ground for structuring my approach to the Business Logic and Data Access and how I was going to affect loosely coupled layers.

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.

Setting up the Model View Presenter.

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);
    }
}

The Presenter.

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();
    }
}

And finally the Model

[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.

Share/Save/Bookmark

]]>
0
Simon Segal http://www.simonsegal.net <![CDATA[Are Designers or even Devigner’s a requirement for XAML UI’s?]]> http://www.simonsegal.net/blog/2009/01/04/are-designers-or-even-devigners-a-requirement-for-xaml-uis/ 2009-01-04T12:03:35Z 2009-01-04T12:00:08Z stick figure Based on some of my experimental / learning project work with Silverlight and what I have seen on line I think that there is enough in the XAML UI frameworks to offer the plain old graphically challenged business developer. Sure the designer / devigner might add huge value but I don’t see a lot of organisations simply taking that role on board because there is a new UI framework in town; no matter how powerful. Certainly my own effort to date I find a little drab but I don’t think my past Winform or ASP.Net applications were not graphical feats of brilliance either, yet I like so many others have produced many business applications that have served their user bases faithfully nonetheless. My first Silverlight application (currently underway) was indeed designed for this reason, to get as comfortable as possible with laying out a typical data driven LOB application window.

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!

Share/Save/Bookmark

]]>
0
Simon Segal http://www.simonsegal.net <![CDATA[Why I want Silverlight to succeed in a huge way - [A new year wish].]]> http://www.simonsegal.net/blog/2009/01/02/why-i-want-silverlight-to-succeed-in-a-huge-way-a-new-year-wish/ 2009-01-02T06:06:01Z 2009-01-02T06:00:33Z Ok I’m just going to come out and say it - I don’t want to know two UI frameworks equally as well or perhaps I should say one ‘less well’ than the other. It’s a fact of life that a great deal of we .NET developers  (the majority I would think) work for an SME and also that the great majority of work we do is not public facing web sites. These SME’s form a significant portion of Microsoft’s Market and the main two UI frameworks used by this customer segment, have up until recent times been developing their application using Windows Forms or ASP.Net. More recently, Microsoft have invested heavily in UI frameworks grounded in the XAML which offers perhaps the first real opportunity we have seen for a unification of a single set of skills to be employed both across the web and desktop. Historically of course we have witnessed the relative failure of the Java Applet and the ActiveX control but we shouldn’t let those failures deter us from exploring success with WPF and Silverlight.

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  winner 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.

Share/Save/Bookmark

]]>
4
Simon Segal http://www.simonsegal.net <![CDATA[Post Christmas and Pre New Year Question?]]> http://www.simonsegal.net/blog/2008/12/30/post-christmas-and-pre-new-year-question/ 2008-12-29T23:18:57Z 2008-12-29T23:18:57Z As we approach the new year and many of us reflect on the one that just passed, I find myself compelled to ask the question - are we as human being’s becoming spiritually (not in a religious sense) lost in the after glow of technological advance? Certainly technology has changed my life in a most profound way. I was once a musician and recording engineer and to execute my job required some technological expertise coupled with some artistic flair (I hope). After changing careers and moving into software development, I find that my creative desires are to some extent still fulfilled however my sense of shared experience and the actual amount of time I spend developing my skills ‘with others’ is not comparable at all. No more rehearsals, recording sessions, writing groups, all of which required much human interaction and debate, a lot of which took place in social settings. These days I do most of my learning in isolation, sitting in front of the very computer screen that I see now as I type this post. It is clear that even in my constant education and expression via this blog that I am communicating, however it is still seems to lack some of the interpersonal aspects that traditional face to face interaction can bring.

The Question:

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.

Share/Save/Bookmark

]]>
0
Simon Segal http://www.simonsegal.net <![CDATA[Entity Framework Learning Materials (continued)]]> http://www.simonsegal.net/blog/2008/12/28/entity-framework-learning-materials-continued/ 2008-12-28T00:44:23Z 2008-12-28T00:41:32Z I first posted about some learning materials just recently and during the time between then and now I discovered some more good introductory material that can be found on Stefan Cruysbergh’s personal web site. Stefan has produced a three part series to introducing the basics in the Entity Framework and then some more detailed investigation in the final instalment of his series of posts. Stefan also has a blog separate to his web site.

Part 1

Part 2

Part 3

Part 4

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.

Share/Save/Bookmark

]]>
1
Simon Segal http://www.simonsegal.net <![CDATA[Entity Framework - Specification Pattern Code Update]]> http://www.simonsegal.net/blog/2008/12/23/entity-framework-specification-pattern-code-update/ 2008-12-23T06:29:54Z 2008-12-23T06:15:09Z I thought it might be useful to include the entire code base from this previous post with the change to the Specification Pattern alone at this stage, in case anyone wanted to see the changes incrementally as I refactor the entire library. Time to version this code as it may be production bound before too long! The code is in the usual place here.

Share/Save/Bookmark

]]>
0
Simon Segal http://www.simonsegal.net <![CDATA[Entity Framework and the Specification Pattern]]> http://www.simonsegal.net/blog/2008/12/22/entity-framework-and-the-specification-pattern/ 2008-12-22T12:16:28Z 2008-12-22T12:12:09Z A while back I posted a small framework for working with LINQ To SQL. This small set of libraries included a Repository pattern, coupled with the Specification Pattern and Fetching Strategies. In more recent times I decided that LINQ To SQL and the Entity Framework were just too close to warrant the investment in learning, understanding and using both, so to that end I decided to work those previous libraries into shape and refactor them for support of both OR/M products.

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.

Share/Save/Bookmark

]]>
2
Simon Segal http://www.simonsegal.net <![CDATA[Good practice skills vs. Technology skills - which should I choose.]]> http://www.simonsegal.net/blog/2008/12/21/good-practice-skills-vs-technology-skills-which-should-i-choose/ 2008-12-21T09:56:20Z 2008-12-21T09:53:26Z Something that intrigues me is the very nature of the way software development skills are rated. It’s not altogether unheard of that the more technology specific stuff you put into your resume the better understood or rather perceived you might be and the more design and practice oriented stuff you put in that resume, may find you perceived all the more esoteric.

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 perplexedsupport_structure 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!

Share/Save/Bookmark

]]>
0
Simon Segal http://www.simonsegal.net <![CDATA[Narrowing ORM options for the sake of sanity]]> http://www.simonsegal.net/blog/2008/12/17/narrowing-orm-options-for-the-sake-of-sanity/ 2008-12-17T09:33:23Z 2008-12-17T09:30:38Z "The right tool for the job" or so the saying goes which I don’t believe can be applied to a choice between LINQ to SQL and the Entity Framework.  Currently I am evaluating the virtues of Entity Framework over LINQ Tochoices SQL; why not use both I hear you say? Well I have already reached the point in the evaluation to know that there is not enough separating them to make me consider maintaining skills in both and considering that all Microsoft’s serious investment is going into the Entity Framework then the choice is made that much easier.

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.

Share/Save/Bookmark

]]>
4
Simon Segal http://www.simonsegal.net <![CDATA[Habits of the career minded programmer.]]> http://www.simonsegal.net/blog/2008/12/15/habits-of-the-career-minded-programmer/ 2008-12-15T11:46:13Z 2008-12-15T11:35:20Z headphones One thing I often remark is my preference for developers who exhibit habits that identify them as being ‘invested in their careers’. One such habit (in my humble opinion) is regular listening to pod casts however I should say that if a developer doesn’t listen to pod casts does not mean that they are not invested, perhaps they have other such ‘invested’ habits. Anyway, this post wasn’t meant to be a discussion of what are and aren’t the habits but rather a list of pod casts that I listen to and think are worth checking out if you weren’t aware of them previously.

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.

Share/Save/Bookmark

]]>
2
Simon Segal http://www.simonsegal.net <![CDATA[More Entity Framework frustration [I want my Specification Pattern].]]> http://www.simonsegal.net/blog/2008/12/15/more-entity-framework-frustration-i-want-my-specification-pattern/ 2008-12-14T14:44:26Z 2008-12-14T14:22:20Z A while back I posted about LINQ To SQL and how to implement the specification pattern and fetching strategies with a IRepository. Since then you may have heard the announcements and followed the ensuing debate about the future of LINQ To SQL. On reflection I have since decided to explore EF as fully as possible and prepare for knowing it deeply, particularly as it promises to embody values such as support of POCO and Lazy Loading which are some of things I am not prepared to live without.

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:

ef_spec_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);
    }
}
The problem with the Specification as it is now, is that it fails when we combine Specifications into an OrSpecification or AndSpecification. You might notice that I added the _evalFunc member, this was an attempt to to use the overload of IQueryable<T>.Where that takes a Func<T> as the argument rather than the Expression<Func<T>> ; this approach work’s to a degree but you lose the ability to cast IQueryable<T> to ObjectQuery<T>. The other thing that I find enormously frustrating is that LINQ To Entity queries return’s a WhereSelectEnumerableIterator if I use the overloaded version of the Where extension method that takes the Func<T> as it’s argument and this means I am unable to cast it to ObjectQuery<T> which constricts our options in moving that strategy forward.
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:

ef_specpattern_error_enumerable

which is as already stated, related to the issue created by using the .Where extension method that accepts a Func<T> as opposed to the Expression<Func<T, bool>>.
As I said it’s late and so far I have a big headache but I will persist.

Share/Save/Bookmark

]]>