Archive

Archive for June, 2008

Difference between LINQ to SQL and the Entity Framework

June 30, 2008 9 comments

I was browsing through the usual newsgroups I visit and came up with this post about LINQ to SQL vs EDM and thought I should share it here.

LINQ to SQL and the Entity Framework have a lot in common, but each have features targeting different scenarios.

LINQ to SQL has features targeting "Rapid Development" against a Microsoft SQL Server database. Think of LINQ to SQL as allowing you to have a strongly-typed view of your existing database schema. LINQ to SQL supports a direct, 1:1 mapping of your existing database schema to classes; a single table can be mapped to a single inheritance hierarchy (i.e., a table can contain persons, customers, and employees) and foreign keys can be exposed as strongly-typed relationships.  You can build LINQ queries over tables/views/table valued functions and return results as strongly typed objects, and call stored procedures that return strongly typed results through strongly typed methods.  A key design principle of LINQ to SQL is that it "just work" for the common cases; so, for example, if you access a collection of orders through the Orders property of a customer, and that customer’s orders have not previously been retrieved, LINQ to SQL will automatically get them for you.  LINQ to SQL relies on convention, for example default insert, update, and delete logic through generated DML can be overwritten by exposing appropriately named methods (for example, "InsertCustomer", "UpdateCustomer", "DeleteCustomer").  These methods may invoke stored procedures or perform other logic in order to process changes.

The Entity Framework has features targeting "Enterprise Scenarios".  In an enterprise, the database is typically controlled by a DBA, the schema is generally optimized for storage considerations (performance, consistency, partitioning) rather than exposing a good application model, and may change over time as usage data and usage patterns evolve.  With this in mind, the Entity Framework is designed around exposing an application-oriented data model that is loosely coupled, and may differ significantly, from your existing database schema.  For example, you can map a single class (or "entity") to multiple tables/views, or map multiple classes to the same table/view. You can map an inheritance hierarchy to a single table/view (as in LINQ to SQL) or to multiple tables/views (for example, persons, customers, and employees could each be separate tables, where customers and employees contain only the additional columns not present in persons, or repeat the columns from the persons table).  You can group properties into complex (or “composite”) types (for example, a Customer type may have an “Address” property that is an Address type with Street, City, Region, Country and Postal code properties). The Entity Framework lets you optionally represent many:many relationships directly, without representing the join table as an entity in your data model, and has a new feature called "Defining Query" that lets you expose any native query against the store as a "table" that can be mapped just as any other table (except that updates must be performed through stored procedures).  This flexible mapping, including the option to use stored procedures to process changes, is specified declaratively in order to account for the schema of the database evolving over time without having to recompile the application.

The Entity Framework includes LINQ to Entities which exposes many of the same features as LINQ to SQL over your conceptual application data model; you can build queries in LINQ (or in “Entity SQL”, a canonical version of SQL extended to support concepts like strong typing, polymorphism, relationship navigation and complex types), return results as strongly typed CLR objects, execute stored procedures or table valued functions through strongly-typed methods, and process changes by calling a single save method.

However, the Entity Framework is more than LINQ to Entities; it includes a "storage layer" that lets you use the same conceptual application model through low-level ADO.NET Data Provider interfaces using Entity SQL, and efficiently stream results as possibly hierarchical/polymorphic DataReaders, saving the overhead of materializing objects for read-only scenarios where there is no additional business logic. 

The Entity Framework works with Microsoft SQL Server and 3rd party databases through extended ADO.NET Data Providers, providing a common query language against different relational databases through either LINQ to Entities or Entity SQL.

So while there is a lot of overlap, LINQ to SQL is targeted more toward rapidly developing applications against your existing Microsoft SQL Server schema, while the Entity Framework provides object- and storage-layer access to Microsoft SQL Server and 3rd party databases through a loosely coupled, flexible mapping to existing relational schema.

Technorati Tags: ,

Dependency Injection: Factory vs Container – Unity

June 30, 2008 Leave a comment

As application size and complexity increase it becomes more and more difficult to reuse existing components and integrating these components to form an interconnected architecture because of the dependencies of the components. One way to reduce dependencies is by using Dependency Injection, which allows you to inject objects into a class, rather than relying on the class to create the object itself.

Dependency Injection refers to the process of supplying an external dependency to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency. The basic value Dependency Injection brings to enterprise systems is decoupling. They promote programming to interfaces and isolate you from the creation process of the collaborators, letting you to concentrate on what you need to deliver while improving testing.

The dependency injection approach offers more flexibility because it becomes easier to create alternative implementations of a given service type, and then to specify which implementation is to be used either pragmatically or via a configuration file, without any change to the objects that use the service. This is especially useful in unit testing, because it is easy to inject a mock implementation of a service into the object being tested.

Dependency injection helps in solving the following

  • You want to decouple your classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to your classes source code.
  • You want to be able to write classes that depend on classes whose concrete implementation is not known at compile time.
  • You want to be able to test your classes in isolation, without using the dependencies.
  • You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.

    The factory pattern described as "To construct and instantiate a set of related objects without specifying their concrete objects." is one common way to implement Dependency Injection. When a component creates an instance of another class, it encapsulates the object creation logic within the component. Any other class that requires an instance of the created class must also duplicate the object creation logic as it may not be reusable outside the component.

    Object most often need to be instantiated in a coordinated fashion, usually because of certain dependencies or other requirements. For example, when creating an instance of XmlValidatingReader in client code, an XmlSchemaCollection object is frequently populated with the relevant schemas for use when validating the XmlValidatingReader object. This is an example of needing to not only create an instance of a class, but also to configure it after creation and before it can be used.

    Another example of a factory pattern is to create a static method whose purpose is to return an instance of a class. For example, the Create method of WebRequest takes in either a string or Uri instance, and returns a new instance of a class derived from WebRequest.

    Factories allow for an application to wire together objects and components without exposing too much information about how the components fit together or what dependencies each component might have. Instead of spreading complex creating code around an application, factories allow for that code to be housed in a central location, thereby facilitating reuse throughout the application.

    Client code then calls creating methods on the factory, with the factory returning complete instances of the requested classes. Encapsulation is preserved, and the client is effectively decoupled from any sort of plumbing required to create or configure the object instance.

    Benefits of Factory Pattern

  • Factories allow for an application to wire together objects and components without exposing too much information about how the components fit together or what dependencies each component might have.
  • Instead of spreading complex creating code around an application, factories allow for that code to be housed in a central location, thereby facilitating reuse throughout the application.
  • Client code calls creating methods on the factory, with the factory returning complete instances of the requested classes. Encapsulation is preserved, and the client is effectively decoupled from any sort of plumbing required to create or configure the object instance.

    Drawbacks of factory pattern

  • While a factory implementation can be quite valuable for a certain application, most of the time, it is not reusable across other applications. Frequently all of the available creation options are hardcoded into the factory implementation, making the factory itself non-extensible. Most of the time the class calling the factories’ creation methods must know which subclass of the factory to create.
  • All dependencies for an object that is created using a factory are known to the factory at compile time. At run time there is no way to insert or alter the manner in which objects are created, or which dependencies are populated. This all must happen at design time, or at least require a recompile. For example, if a factory is creating instances of class Foo and instances of class Foo require an instance of class Bar, then the factory must know how to retrieve an instance of the Bar class. The factory could create a new instance, or even make a call to another factory.
  • Since factories are custom to each individual implementation, there can be a significant level of cross-cutting infrastructure that is held captive inside a particular factory. Take my example of a factory dynamically substituting a proxy object for a real object. That is an example of a piece of infrastructure, namely the wrapping of simple objects for deployment over a distributed wire, that is completely encapsulated inside that particular factory. If another object needs to be altered in a similar manner, the logic to do so is hidden inside a factory, and would have to be repeated for the other object. Once this functionality is desired outside of the original application, the problem now becomes how to reuse such functionality while still maintaining the existing factory concept.
  • Factories rely on well-defined interfaces to achieve polymorphism. In order for a factory implementation to be able to dynamically create different concrete subclass instances, there must be a common base class or shared interface implemented by all classes that the factory will create. Interfaces decouple the construction of the object from the specific implementation of the interface. The dilemma that arises now is how you can accomplish this decoupling without being forced to create an interface for everything.

    A container is a compartment that houses some sort of abstraction within its walls. Typically, responsibility for object management is taken over by whatever container is being used to manage those objects. However, containers can also take over instantiations, configuration, as well as the application of container-specific services to objects.

    Containers provide the ability to wrap vanilla objects with a wealth of other services. This allows the objects to remain ignorant about certain infrastructure and plumbing details, like transactionality and role-based security. Oftentimes, the client code does not need to be aware of the container, so there is no real dependency on the container itself. Containers be configured declaratively, meaning they can be configured via some external means, XML files, property files, or .NET-based attributes.

    Dependency Injection is a worthwhile concept to explore for use within applications that you develop. Not only can it reduce coupling between components, but it also saves you from writing boilerplate factory creation code over and over again. Unity is an example of a framework that provides a ready to use Dependency Injection container. Of course all this also means that there is added complexity to the source code; therefore, it is harder to understand.

    Microsoft Patterns and Practices team had been developing Enterprise Library to enable the use of general patterns and practices for .NET platform, which has great pluggable application blocks such as Logging and Validation application blocks. One of them is the Dependency Injection Application Block; but folks thought it should be named differently from the other application blocks, and came with the fancy name Unity.

    Unity exposes Register methods that support configuring the container with mappings and objects (including singleton instances), and Resolve methods to return instances of built objects that contain any dependent objects. Unity sits on top of another framework called ObjectBuilder which has been a part of enterprise library for quite some time. Unity however is based on v2.0 of the object builder which has been tweaked, refactored and optimized for performance. Unity is available as both a standalone download or part of the enterprise library and can be downloaded from http://www.codeplex.com/unity or http://www.codeplex.com/entlib.

    Unity supports the following forms of dependency injection:

  • Constructor injection – parameters of the objects constructor method are used to inject it with its dependencies.
  • Setter injection – object simply provides a property that can hold a reference to that type of service; and when the object is created a reference to an implementation of that type of service will automatically be injected into that property – by an external mechanism.

    David Hayden has done some great screencasts on Enterprise Library and Unity at http://www.pnpguidance.net/ be sure the check them out for furhter readings on dependency injection using Unity Applicaiton Block.

    Technorati Tags: ,

  • ASP.NET Session State and Velocity Provider

    June 10, 2008 1 comment

    ASP.NET session state supports several different storage options for session data. Below is a quick summary of the different modes of session state and their pros and cons

    • InProc
      • Stores session state in memory on the web server.
      • Fastest, but the more session data, the more memory is consumed on the web server, and that can affect performance.
      • Cannot be used with web farms.
      • Session state will be lost if the worker process (aspnet_wp.exe) recycles, or if the AppDomain restarts.
    • StateServer
      • Stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the web application is restarted and also makes session state available to multiple web servers in a web farm.
      • Objects are serialized to an out of process memory store. The cost of serialization/deserialization can affect performance if you’re storing lots of objects.
      • Solve the session state loss problem in InProc mode. Allows a web farm to store session on a central server.
      • Single point of failure at the State Server.
      • For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm.
    • SQLServer
      • Stores session state in a SQL Server database. This ensures that session state is preserved if the web application is restarted and also makes session state available to multiple web servers in a web farm.
      • Solve the session state loss problem in InProc mode. Allows a web farm to store session on a central server.
      • Session state data can survive a SQL server restart, and you can also take advantage of SQL server failover cluster, after you’ve followed instructions in KB 311029.
      • For session state to be maintained across different web servers in the web farm, the Application Path of the website (For example \LM\W3SVC\2) in the IIS Metabase should be identical in all the web servers in the web farm.

    The best scalability is provided by SQLServer session store but it comes with a slight performance cost. The best performance is provided by InProc session store but it cant really be used in any production web app because of scalability issues.

    What if you could have the scalability of SQLServer session store but with the performance of InProc / StateServer session state? "Velocity" is a distributed caching product to provide the .NET application platform support for developing highly performant, scalable, and highly available applications. It allows any type of data CLR object, XML document, or binary data to be cached. Velocity fuses large numbers of cache nodes in a cluster into a single unified cache and provides transparent access to cache items from any client connected to the cluster.

    Velocity provides a session store provider that allows you to store your ASP.Net Session object in Velocity cache – This enables non-sticky routing allowing scaling your application.

    Hooking up Velocity in your ASP.NET web app is easy. All it takes is some web.config entries:

    1. Configure session state provider element in your app’s web.config file:

    <sessionState mode="Custom" customProvider="SessionStoreProvider"> <providers> <add name="SessionStoreProvider" type="System.Data.Caching.SessionStoreProvider, ClientLibrary"/> </providers> </sessionState>

    2. Configure Velocity client configuration elements in web.config:

    <configSections> <section name="dcacheClient" type=" System.Configuration.IgnoreSectionHandler" allowLocation="true" allowDefinition="Everywhere"/> </configSections> <dcacheClient deployment="simple" localCache="false"> <hosts> <!--List of hosts --> <host name="<serviceHostName>" cachePort="22233" cacheHostName="DistributedCacheService"/> </hosts> </dcacheClient>

    Note : “serviceHostName” is the hostname where distributed cache service is running on cache port “22233”(default setting). Configure these 2 parameters appropriately.

    3. Add reference to or copy to \bin folder the following dll’s that the session store provider uses: CacheBaseLibrary.dll, FabricCommon.dll, ClientLibrary.dll, CASBase.dll, CASClient.dll .

    And that’s about it; your web application is ready to run with the Velocity SessionStoreProvider. 

    Note:

    • For Velocity Session State provider to work, Cache cluster should be up and running. To learn about to how to deploy Velocity Distributed Cache Cluster, please refer the product documentation.
    • As the provider stores the session objects in out-of-proc distributed cache service, objects that you put in Session should be serializable.

    For more info please refer to the product documentation or the Velocity blog on MSDN How to Use Session State Provider (Microsoft Project code named Velocity)

    Repository Factory – VisualStudio 2008

    June 8, 2008 Leave a comment

    The Repository Factory is a guidance package that automates creation of entity classes that map to database tables and repository classes to read and write those entity classes. The generated code removes the tedium of writing a persistence-ignorant domain model.

    This package was originally published as the "Data Access Guidance Package" as part of the Web Service Software Factory but was later split out into its own project. Unfortunately this got kinda abandoned with the release of LINQ and therefore there is no support for VisualStudio 2008.

    Here’s the statement from the Repository Factory team

    "Repository Factory is done. There will be no more investment from P&P or Microsoft. Repository Factory was written for ADO.NET 2.0 and VS 2005. .NET 3.5 has many new database access options (with more coming), and a straight port to VS 2008 isn’t good guidance. LINQ, for example, enables newer ways to do queries that don’t fit very well with our repository generation. And right now we’re not convinced that the underlying Enterprise Library Data Access block even makes sense anymore."

    So does that mean this project is dead? What about us poor folks who have been using the service factory with VisualStudio 2005 and now need to upgrade to VisualStudio 2008? Does this mean we cant upgrade to VisualStudio 2008 if we want to continue to use the guidance package?

    Well the P&P team have released the final source code and is available for download. Porting over to VisualStudio 2008 is easy. After you download the source code from the site open the solution file in VisualStudio 2008 and follow the instruction on the convert solution wizard. Try and compile the project as is and it all compiles perfectly (you need to install the Visual J# redistributable for the solution to compile / build). If you try and register the recipe using the Register Guidance from the Guidance Package guidance it works great but the installer is another story. To make the installer work you must add/change arguments in all the custom actions as follow:

    "/Hive=9.0 /Configuration="[TARGETDIR]Data Access Guidance Package.xml"

    Note that changes applies just for the installer. Now rebuild the installer and it should create the setup files for the guidance package.