Living in the Tech Avalanche Generation

A practitioner’s introspective on technology

ADSD Course with Udi Dahan in Sydney Australia for November 2010

image Hot on the heels of Udi’s visit to Melbourne this year (in January), comes another chance to make good if you missed out. Plans are underway for Udi to visit us yet again, this time in Sydney. If your interested check out Udi’s post and register your interest using the link for the proposed Sydney event. If you want to know more about the course you can see the course outline here and read my review which contains links to some further reviews from other attendees in Melbourne earlier this year.

Share/Save/Bookmark

No comments

Helping Entity Framework v4.0 play it’s <ROLE> – Part 3.0

In part 1.0 we laid the foundation and part 2.0 unravelled some of the internal details of how NFetchSpec (the libraries that are subject of this discussion) goes about enlisting the benefits that can be derived by using explicit roles in your system by collapsing a swathe of Entity Framework functionality into a somewhat compact approach to dealing with a Domain Model. First a quick recap of the underpinnings.

Figure 1.0

ef_roles_part3_nfetch_in_action_usage_quadrant

Code from Figure 1.0

public void resolves_everything_from_container()
{
    IList<IRunOutDiscountForProducts> products = null;

    var compParams = new Dictionary<string, string>();
    compParams.Add(_conParamName, _connectionStringOnly);

    var repo = FetchSpec.Configure
                            .With(new IoC())
                            .AndBuildSession<IRunOutDiscountForProducts>
                                (compParams)
                            .ForRepository();

    using (var scope = new TransactionScope(TransactionScopeOption.Required,
        new TransactionOptions()
        {
            IsolationLevel =
                SessionBuilder<IRunOutDiscountForProducts>.ScopeIsolation()
        }))
    {
        products = repo.Get<IRunOutDiscountForProducts>();
        foreach (var product in products)
        {
            product.DiscountProductForRunOut();
        }

        scope.Complete();
    }
}

Figure 1.0 demonstrates how all the moving parts in the developer experience are put to use when using the NFetchSpec libraries to query and make changes to a persisted Domain Model. Let’s now examine in detail all the steps that make up the entire developer experience of composing all the discrete pieces needed in addressing the role of IRunOutDiscountForProducts (in our fictitious system).

The Development Scenario

image The first outlined section in figure 1.0 demonstrates the building of an appropriate ObjectContext for the Repository that is instantiated by the fluent interface. From the developer experience perspective, nothing special needs to be done outside of specifying the role to the fluent interface in this manner.

image The second outlined section in figure 1.0 highlights how the role is leveraged to dynamically have NFetchSpec chose the ‘right’ isolation level. Being explicit in this way we can achieve a high degree of separation of concerns with respect to transaction isolation and thus exercise our control over the concurrency and throughput in the database on a role by role basis. In the example, we are discounting products earmarked for a run out sale, consequently changing their unit price, therefore we might like to choose a higher isolation level for that particular operation, depending on the volatility of the data that your dealing with and the normalization or lack thereof in your database schema. For the developer this means creating a concrete implementation of the interface IProvideIsolationLevelFor<T>, to support this automagic behaviour.

public interface IProvideIsolationLevelFor<TRole>
{
    IsolationLevel GetScopeIsolationForRole { get;}
}

public class RunoutDiscountIsolation :
             IProvideIsolationLevelFor<IRunOutDiscountForProducts>
{
    public IsolationLevel GetScopeIsolationForRole
    {
        get { return IsolationLevel.ReadCommitted; }
    }
}

That’s it as far as getting your transaction set for the right Isolation Level within the scope of work for a given role. If we decide at some point that this Isolation Level is not the best fit, we can replace it with a new implementation.

image The Third outlined section in figure 1.0 highlights the use of the Repository to retrieve the Entities that we are interested in. This is where the NFetchSpec machinery goes to work to resolve all the purpose built artefacts that have been implemented for the given role, such as any applicative Fetching Strategy, Specification, Entity and Mapping.

The Loaded Fetching Strategy

public class ProductRunOutFetchingStrategy :
             FetchingStrategy<IRunOutDiscountForProducts>
{
    public ProductRunOutFetchingStrategy()
        : base(false)
    {
        var production_intentions =
            EagerFetchingIntention
            .CreateInstance<IRunOutDiscountForProducts,
                            ISupplier>(p => p.Supplier);

        this.AddIntentions(new IEagerFetchingIntention[]
        {
            production_intentions
        });
    }
}

The intent of the developer in building this Fetching Strategy is to load Products eagerly with their reference Supplier.

The Loaded Specification

public class RunOutProductDiscountSpecification :
             Specification<IRunOutDiscountForProducts>
{
    public RunOutProductDiscountSpecification()
        : base(p => p.UnitPrice > 5M && p.Supplier.Region == "London") { }
}

The Specification is really quite simple and self evident – setting up the applicative Expression that will ultimately be translated into a ‘where’ predicate.

The Loaded Mapping

First up we need to map our Entities and that requires a Mapping<T>.

public class ProductMapping : Mapping<Product>
{
    public ProductMapping(string objectSetName) : base(objectSetName)
    {
        Property(p => p.ProductID).IsIdentity();
        Property(p => p.ProductName).HasMaxLength(50).IsRequired();
        Property(p => p.UnitPrice).Precision = 19;
        Property(p => p.UnitPrice).Scale = 4;
        Relationship(p => p.Supplier).IsOptional();
        Relationship(p => p.Supplier).IsOptional().FromProperty(s => s.Products);
    }
}

And because our example has a reference Entity in the root we require the following Supplier Entity Mapping also.

public class SupplierMapping : Mapping<Supplier>
{
    public SupplierMapping(string objectSetName)
        : base(objectSetName)
    {
        Property(s =>  s.SupplierID).IsIdentity();
        Property(s => s.CompanyName).HasMaxLength(40).IsRequired();
        Property(s => s.Region).HasMaxLength(15);
        Relationship(s => s.Products).IsOptional().FromProperty(p => p.Supplier);
    }
}

The last requirement of the developer with respect to mapping is to create a MappingRole<T>, the purpose of which is to indicate to the infrastructure which mappings are applicable to the Role.

public class RunOutDiscountMappingRole :
             IMappingRole<IRunOutDiscountForProducts>
{
    private IMapping[] _mappings;

    public RunOutDiscountMappingRole()
    {
        _mappings = new IMapping[]
                    {
                        new ProductMapping("Products"),
                        new SupplierMapping("Suppliers")
                    };
    }

    public IMapping[] Mappings
    {
        get { return _mappings; }
    }
}

image The fourth and final outlined section in figure 1.0 is really the essence of what is going on here, it is entirely the reason this code is being invoked – it is the purpose (discounting products) of the system for this role. When developing in this way we need to specify the behaviour of the Role through the stable abstraction of it’s interface, and implement that behaviour in a concrete Entity.

public interface IRunOutDiscountForProducts : IProductData
{
    void DiscountProductForRunOut();
}

The Bang and Crash

So with all that done, we need to deploy our “Role inspired” artefacts to the executing processes assemblies folder and when it’s all said and done the code from Figure 1.0 executes, enlisting the service of NFetchSpec in applying the combined intent and customised behaviours described in all of the deployed pieces.

From the database perspective, SQL Profiler tells us that our intent for this ROLE has been met and the system has behaved precisely as expected.

SELECT
    [Extent1].[ProductID] AS [ProductID],
    [Extent1].[ProductName] AS [ProductName],
    [Extent1].[UnitPrice] AS [UnitPrice],
    [Extent1].[SupplierID] AS [SupplierID]
FROM
    [dbo].[Products] AS [Extent1]
INNER JOIN
    [dbo].[Suppliers] AS [Extent2]
ON
    [Extent1].[SupplierID] = [Extent2].[SupplierID]
WHERE
    ([Extent1].[UnitPrice] < cast(20 as decimal(18)))
AND
    (N‘London’ = [Extent2].[Region])

We can see that Fetching Strategy and Specification have been successful in shaping the TSQL sent to the server to retrieve the data. Below we can also see the effect of applying the business rules through our Domain Model.

exec sp_executesql N‘update [dbo].[Products]
set [UnitPrice] = @0
where ([ProductID] = @1)
‘,N‘@0 decimal(19,4),@1 int’,@0=3.2960,@1=1

Just one more thing

Part 4.0 will be the final part in the series and will focus on how this approach blends into a service layer in a Service Oriented Architecture and also make the code for NFetchSpec available for download.

Share/Save/Bookmark

7 comments

Doing .NET Days March 6th Fully Booked.

20pc_black Doing .Net Days for March 6th 2010 is now fully booked. Thanks to all those who have registered. It’s becoming apparent that the current venue may not be large enough to accommodate the interest moving forward so we are exploring alternative venues and will keep you up date as news comes to hand.

We are also in the throws of putting together the web site for the event which will be announce shortly.

Share/Save/Bookmark

No comments

Next Page »

Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia