Friday, August 26, 2011

iCarMode - available on the appStore !!

Today my post is not another .net/sql/programming post.

Today I am happy to present my new iPhone app 1st release.

The application is called - iCarMode and it's a joined effort of Mark Mishaev & myself.

Small quote from the appStore description:

"iCarMode presents a new user interface speacilly designed to allow safer use of your iPhone while driving.

The large buttons give you a quick and comfortable access to your favorite contacts, iPod playlists, navigation and other useful features."

If you ever tried to play music, make a phone call or find your favorite GPS app from your (hopefully) docked iPhone you probably noticed how uncomfortable it is, if not to say - dangerous.

iCarMode is meant to expose a simpler UI to allow you to perform those actions in a safer mode.

Here's the main screenshot:



For more details, goto the product's new website: http://www.iCarMode.com
And don't forget to download, rate and spread the word at the appStore.





Best Regards,
Diego

Tuesday, May 31, 2011

Web Application Automatic Deployment using MsBuild with Microsoft SDC Task Library

Introduction
Projects commonly have a web application component, be it a front end or in the form of WebServices. This article will demonstrate how the web applications can be automatically deployed and configured under IIS using the Microsoft SDC Task Library extensions for MsBuild.
The SDC Task Library is free and available at http://codeplex.com/sdctasks Over 300 tasks included in this library including tasks for: creating websites, creating application pools, creating ActiveDirectory users, running FxCop, configuring virtual servers, creating zip files, configuring COM+, creating folder shares, installing into the GAC, configuring SQL Server, configuring BizTalk 2004 and BizTalk 2006 etc.

Step 1
Create project xml file and import SDC tasks
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="Microsoft.Sdc.Common.tasks"/>

</Project>
Step 2
Create deployment Work Plan
<Target Name="Deploy_Webapp">
<CallTarget Targets="CopyFolders" />
<CallTarget Targets="SetPermissions" />
<CallTarget Targets="CleanIIS" />
<CallTarget Targets="CreateWebSite" />
</Target>
Step 3
Implement every Target in Work Plan, let's focus on CreateWebSite. First of all I will create a WebSite and then I will create a VirtualDirectory.
<Target Name="CreateWebSite" DependsOnTargets="CleanIIS">
<Web.WebSite.Create
Description="testWebSite"
Path="C:\Server"
MachineName="localhost"/>
<Web.WebSite.CreateVirtualDirectory
VirtualDirectoryName="testVD"
Path="C:\Server"
MachineName="localhost"
AppPoolID="DefaultAppPool"
AppCreate="True"
WebSiteName="testWebSite"
AuthFlags="NTLM"/>
</Target>
CreateVirtualDirectory attributes:
  • virtualDirectoryName - name of the virtual driectory to create
  • path - Path to map the virtual directory to.
  • machineName - Machine to add the virtual directory on.
  • appPoolID - Application pool to run the virtual directory under
  • appCreate - Set to "true" to create an application for this virtual directory.
  • webSiteName - Web site to attach the virtual directory onto.
  • authFlags - Authentication flags to apply to the directory.

Step 4
Create batch file to make all this easier to run
@ECHO OFF

IF EXIST %windir%\Microsoft.NET\Framework64\v2.0.50727\ (
%windir%\Microsoft.NET\Framework64\v2.0.50727\msbuild configServer.xml
) ELSE (
%windir%\Microsoft.NET\Framework\v2.0.50727\msbuild configServer.xml
)
Finally
Microsoft SDC Task Library extensions for MsBuild provides us much more options, You can read a manual that comes with it in order to learn more.

Complite Example: here

Sunday, May 8, 2011

Using DataAnnotations to validate entities

In every sample on the internet regarding MVC and Entity Framework 4.0, we can find the use of DataAnnotations.

DataAnnotations allows us to add to our entities some Meta data including simple rules of validation (as well as hiding column, defining display name etc.).
By simple validation rules I mean we can define:
- Required fields
- String Length
- Range

Adding DataAnnotations is quite simple, after adding a reference to System.ComponentModel.DataAnnotations, we can add a partial class extending the relevant entity from our Entity Framework edmx and defining a metadatatype class with the rules.
For example:

    [MetadataType(typeof(TrackMetaData))]
    public partial class Track
    {
        public class TrackMetaData
        {
            [ScaffoldColumn(false)]
            [DisplayName("Track Id")]
            public int Id { get; set; }

            [StringLength(50)]
            public string Name{ get; set; }

            [Range(typeof(DateTime), "1/1/1753", "31/12/9999",
               ErrorMessage = "Value for {0} must be between {1} and {2}")]
            [DisplayName("Play Date")]
            public Nullable PlayDate { get; set; }
        }
    }
}

In this example we can see the use of ScaffoldColumn, StringLegth, DisplayName & Range...for those who work on multi language system or just prefer - you can retrieve the error message from a resource file as well.

Adding this class will work for MVC, MVC's plumbing will use this class to show error messages when relevant...but what if we have another type of client and we want to make sure data is validated before saving it to database?

Add this simple helper class to your project (or even better to your framework/core/library):
   public class ValidationHelper
    {
        /// 
        /// Check if specified object is valid
        /// 
        /// The object to validate        /// 
        public static bool IsValid(object obj)
        {
            return (!Validate(obj).Any());
        }

        /// 
        /// Validate an object against Data Annotations meta data defined against the object 
        /// 
        /// The object to validate        /// A List of  
        public static List Validate(object obj)
        {
            Type instanceType = obj.GetType();
            Type metaData = null;
            MetadataTypeAttribute[] metaAttr = (MetadataTypeAttribute[])instanceType.GetCustomAttributes(typeof(MetadataTypeAttribute), true);

            if (metaAttr.Count() > 0)
            {
                metaData = metaAttr[0].MetadataClassType;
            }
            else
            {
                throw new InvalidOperationException("Cannot validate object, no metadata assoicated with the specified type");
            }

            TypeDescriptor.AddProviderTransparent(
            new AssociatedMetadataTypeTypeDescriptionProvider(instanceType, metaData), instanceType);

            List results = new List();
            ValidationContext ctx = new ValidationContext(obj, null, null);

            bool valid = Validator.TryValidateObject(obj, ctx, results, true);
            return results;
        }

        /// 
        /// Get Validation errors as string
        /// 
        /// The object to validate        /// 
        public static string GetValidationErrors(object obj)
        {
            List errors = Validate(obj);

            var errorText = new StringBuilder();
            foreach (var error in errors)
            {
                errorText.Append(error.ErrorMessage + Environment.NewLine);
            }
            return errorText.ToString();
        }
    }

Than..add a few lines of code to your UnitOfWork (see my previous post for details: EF4 Self Tracking Entities & Repository design pattern)

    public class UnitOfWork:IUnitOfWork, IDisposable
    {

        public void ApplyChanges(string entityName, object entity)
        {
            if (entity == null)
                return;

            if (entity is IObjectWithChangeTracker)
            {
                bool ok = ValidationHelper.IsValid(entity);

                if (!ok)
                {
                    string message = string.Format("Can not apply changes to the '{0}' entity due to validation errors", entity.ToString());
                    LogUtil.LogInfo(string.Format("{0} ({1})", message, ValidationHelper.GetValidationErrors(entity)));

                    throw new ValidationException(message);
                }

                _context.ApplyChanges(entityName, (IObjectWithChangeTracker)entity);
            }
            else
            {
                throw new ArgumentException("entity must implement IObjectWithChangeTracker to use applyChanges");
            }
        }
    }

That's it..before the save of every entity (you implemented a MetadataType class for), it will validate the object and refuse to applyChanges or any other policy you decide is suitable to your project.

Happy validation,
Diego

Thursday, April 7, 2011

EF4 Self Tracking Entities & Repository design pattern

Today I'm going to talk about a new sample project I was building these days just to get to know Entity Framework 4.0 better.

After reading Mark Mishaev's post here (Building N-Tier Applications with Entity Framework 4) & a few of his references I decided to explore the self tracking entities.

As I see it, Self tracking entities is one of the most basic features the previous version of EF was missing.

Self tracking entities as the name implies is the ability of our entities to contain their state, if you're familiar with datasets & their diffgram capability than you probably used the RowState property to detect which rows are new, which are updated, deleted or unchanged - that is what tracking means.

With STE (self tracking entities) you can send your entities to your client & when receiving it back, detect easily all the changes your client made and save it to your database (of course after choosing the right concurrency strategy for your application), without it - you'll find yourself comparing the returned entity with your database to decide which changes were made & setting their state one by one before you can actually save.

So STE is the ultimate solution? Not for sure....one of the big disadvantages of STE is the fact that your client must know the actual entity - meaning:
1. It will work only if you code both the server & client (it's not always the case), proxies passing the entity's datamembers won't do the tracking stuff...
2. Your client must be .net client.
3. Any changes to entity structure/logic will require client publishing (a big minus architecturally speaking).

If you're absolutely sure you can ignore these disadvantages in your specific application - you will gain a simple & great way to track changes out of the box.

Searching for the best way to implement the use of EF I encounter many discussions about a few related patterns, the two that repeatedly stood out were Repository & UnitOfWork.

To make a long reading short..

Repository will help us separating our business logic layer from knowing anything about entity framework - potentially can allow us to control our dataAccess layer behavior (cache, trace, security etc) better and change the implementation without changing the whole application, it will also allow us to replace the repository with an in-memory repository which can be a great way to unit test our application without a database.

namespace Dieg.Framework.DataAccess
{
    public interface IRepository
    { 
        T GetById(int id);
        IEnumerable GetAll();
        IEnumerable Query(Expression<Func<T, bool>> filter);
        void Add(T entity);
        void Remove(T entity);

        void ApplyChanges(T entity);
    }
}

Implementation:

namespace Dieg.Framework.DataAccess
{
    public abstract class Repository : IRepository where T : class
    {
        protected IObjectSet _objectSet;
        protected IUnitOfWork _uow;

        public Repository(IUnitOfWork uow) 
        {
            _uow = uow;
            _objectSet = _uow.CreateObjectSet();
        }

        public abstract T GetById(int id);

        public IEnumerable GetAll()
        {
            return _objectSet;
        }

        public IEnumerable Query(System.Linq.Expressions.Expression<Func<T, bool>> filter)
        {
            return _objectSet.Where(filter);
        }

        public void Add(T entity)
        {
            _objectSet.AddObject(entity);
        }

        public void Remove(T entity)
        {
            _objectSet.DeleteObject(entity);
        }

        public abstract string Name
        {
            get;
        }

        public abstract void ApplyChanges(T entity);
    }
}

Implementing a specific repository, I prefer implementing a separate repository for each entity this way we can choose a unique behavior for each entity (for example: not all entities allow all CRUD operations, maybe there are different authorization rules for some entities etc).

namespace Dieg.MusicLibrary.DataAccess
{
    public class ArtistRepository:Repository
    {
        public const string ENTITY_NAME = "Artist"; 

        public ArtistRepository(UnitOfWork uow):base(uow)
        { }

        public override Artist GetById(int id)
        {
            return _objectSet.SingleOrDefault(a => a.Id == id);
        }

        public override string Name
        {
            get { return ENTITY_NAME; }
        }


        public override void ApplyChanges(Artist entity)
        {
            _uow.ApplyChanges(Name, entity);
        }
    }
}

UnitOfWork - according to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." (The Unit Of Work Pattern And Persistence Ignorance).

namespace Dieg.Framework.DataAccess
{
    public interface IUnitOfWork
    {
        IObjectSet CreateObjectSet() where T : class;

        void SaveChanges();

        void ApplyChanges(string entityName, object entity);
    }
}

ApplyChanges method will contain the STE implementation of updating our entities state, since ApplyChanges is per entity, we can control in our BL which entities should be influenced by the specific BL method and avoid saving irrelevant changes.

Notice the implementation will have to be in the dataAcess layer project & not part of the 'framework/core/lib', since we want it to use the STE specific context extensions.

namespace Dieg.MusicLibrary.DataAccess
{
    public class UnitOfWork:IUnitOfWork, IDisposable
    {
        private readonly DiegMusicLibraryContainer _context;

        public UnitOfWork()
        {
            _context = new DiegMusicLibraryContainer();
        }
        
        public void SaveChanges()
        {
            _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }

        public IObjectSet CreateObjectSet() where E : class
        {
            return _context.CreateObjectSet();
        }

        public void ApplyChanges(string entityName, object entity)
        {
            if (entity is IObjectWithChangeTracker)
            {
                _context.ApplyChanges(entityName, (IObjectWithChangeTracker)entity);
            }
            else
            {
                throw new ArgumentException("entity must implement IObjectWithChangeTracker to use applyChanges");
            }
        }
    }
}


As I mentioned earlier, when using STE the client must have a reference to the entities, so we'll have to separate the entities from the EF context & edmx code, this can easily done using T4 templates (see :How to Separate Self-Tracking Entities to Their Own Class Library (by Gil Fink)).

Let's code a simple test to see the basic concept:

static void Main(string[] args)
        {
            Artist artist;
            
            using (UnitOfWork uow = new UnitOfWork())
            {
                ArtistRepository Artists = new ArtistRepository(uow);

                foreach (var Artist in Artists.GetAll())
                {
                    Console.WriteLine(Artist.Name);
                }
                
                artist = Artists.GetById(1);

            }

            /*unitOfWork (which holds the objectContext) is disposed here
            this will happen also when sending objects through a
              WCF (or similar) service
            */

            //change something...
            artist.ChangeTracker.ChangeTrackingEnabled = true;
            artist.Name = string.Concat(artist.Name,"AAA");


            using (UnitOfWork uow2 = new UnitOfWork())
            {
                ArtistRepository Artists = new ArtistRepository(uow2);

                //calling ApplyChanges will update the state of the artist
                //using behind the scense the STE Changetracker
                //without this the save won't recognize any changes -
                // comment the following line & try it out!!
                Artists.ApplyChanges(artist);

                uow2.SaveChanges();

                Artist b = Artists.GetById(1);
                Console.WriteLine(b.Name);
            }

            Console.ReadLine();
        }

Good luck!
Diego

Saturday, January 29, 2011

Grid view in MVC using mvcContrib

Last post I showed a simple way to display images in your html using an MVC controller Displaying images from a database - MVC style.

But then it got me thinking...what if I have a lot of records ? what if I want to allow the users to search for a specific record?
So the answer is of course - adding some sort of page/sort/filter control/s
in ASP.NET we just needed to pick one from millions..what about MVC?

Googling through this topic I found all sort of HTML helpers some free & some commercial, the 1st one to catch my eye and later on proven to be a good catch was mvcContrib.

I will show you a small sample I built based on Raj Kaimal blog using mvcContrib.

Lets start from a few semi-new concepts when developing in MVC:

1. ViewModels:
The architectural hype these days is definitely ORM tools like EntityFramework, NHibernate etc - These frameworks and others were invented to decouple the database structure from the logical entities defined in our application and map between them to allow transferring data back and forward.
The thing is that before these tools came we were working with smaller sets of data, retrieving only the data we needed for display and sometimes modeling it for smoother work in a specific view.
For this type of work we will use ViewModel, view-model is a portion of our model built specific for a single view (or more if same that is display in more than one way), it decouple the view from the model, allows us to work with a smaller set of data in a structure adjusted to the view but still keep it strongly typed.

2. Controllers
Controllers as their name suggests - control, they are the main MVC concept, Controllers are the gateway of the view to the application & data - building a wall between them - a real wall - not an imaginary one as in webform ASP.NET - this "wall" will allow us to serve the same services for different types of views (web applications, webservices, smart phones etc).

Let's see an implementation of these concepts.

In every grid view there are 3 different views:
1. The filter view.
2. The main view.
3. The paging view.



Every view has its own viewModel.
The filter will need a viewModel which describes the filter, a list of items for a combo filter, a datetime for a datepicker etc
The main view will probably need columns from all sorts of entities, some of them could be "translated" using some sort of lookup table, some maybe formatted differently for this view etc.
The paging view will need a viewModel that describes the paging ruler, in the case of mvcContrib - implementation of IPagination.
The main view will also need to implement GridSortOptions to allow sorting.

Sounds kinda complicated, but actually it couldn't be easier...

Filter's view model will contain a list that will be represented as a dropdown in the view:
public class AlbumFilterViewModel
    {
        public AlbumFilterViewModel()
        {
            SelectedArtistId = -1;
        }

        public int SelectedArtistId { get; set; }

        public List Artists { get; set; }
    }

The main view view-model, this will contain the columns we want to display in the gridview, notice that we can change the way the columns are displayed using simple attributes, this could be implemented for a specific view or at the entity level exploiting the fact that EF entities are define as partial classes (using DataAnnotations: [MetadataType(typeof(AlbumMetaData))]):

public class AlbumListViewModel
    {
        [ScaffoldColumn(false)]  //this columns won't be shown in view
        public int ArtistId { get; set; }

        [ScaffoldColumn(false)]
        public int AlbumId { get; set; }

        [DisplayName("Artist Name")] //change the display name of the column
        public string ArtistName { get; set; }

        [DisplayName("Album Name")]
        public string Name { get; set; }

        [DisplayName("Cover")]
        public byte[] Picture { get; set; }

        [DisplayName("Last Updated Date")]
        [DisplayFormat(DataFormatString = "{0:g}")] //format the date
        public DateTime LastUpdatedDate { get; set; }

    }

As I mentioned before the main view implements the acutal grid and also the paging and sorting, the viewModel will contain the previous one plus the paging and sort definition. it will look like this:
public class AlbumListContainerViewModel
    {
        //paging
        public IPagination AlbumPageList { get; set; }
        //main view
        public AlbumFilterViewModel AlbumFilterViewModel { get; set; }
        //sort
        public GridSortOptions GridSortOptions { get; set; }
    }

Now lets go to the view.
We'll have 3 different partial views (ascx):
1. The filter.
2. The main view.
3. The paging ruler that we'll had before and after the main view.

The container will look something like this:
<% Html.RenderPartial("SearchFilter", Model.AlbumFilterViewModel); %>
    <% Html.RenderPartial("Pager", Model.AlbumPageList); %>
    <% Html.RenderPartial("SearchResult", Model); %>
    <% Html.RenderPartial("Pager", Model.AlbumPageList); %>

The filter view html is quite simple, notice that the view is strongly typed:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
.
.
            
<%:Html.DropDownList("ArtistId", Model.Artists, "-- All --", htmlAttributes)%>
. .

The search result view code, you will see the mvcContrib's html helpers does everything, the only two place I wrote my own code was to specify a different behavior for two columns, one is the "More.." column which is linked to a detail view of the chosen row and a the image column which is linked to the controller that retrieve the image from the database:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="MvcContrib.UI.Grid" %>
<%@ Import Namespace="DiegJukeboxRemote.Models" %>
<%@ Import Namespace="DiegJukeboxRemote.HtmlHelpers" %>
<%= Html.Grid(Model.AlbumPageList).AutoGenerateColumns()
    .Columns(column => {
        column.For(a => Html.ActionLink("More..", "ThumbChooserEdit", new { id = a.AlbumId })).InsertAt(4).Encode(false);
    })
    .Columns(column=> {
        column.For(a => Html.Image(a.AlbumId, "RetrieveImage", "MusicInfo", 
            new Dictionary() { 
                                                { "Height", "100" }, { "Width", "100" },
                                                {"onerror", "onImgErrorSmall(this)"}
            })).InsertAt(3).Encode(false);
    })
    .Sort(Model.GridSortOptions)
    .Attributes(@class => "table-list")
%>

The pager couldn't be simpler:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="MvcContrib.UI.Pager" %>

<%= Html.Pager(Model) .First("First") .Last("Last") .Next("Next") .Previous("Previous") %>


Finally the controller, using LINQ we retrieve the data we need from artist/album repositories, you will see here two special points:
1. Using System.Web.Mvc.SelectListItem for the dropdownlist.
2. Using MvcContrib.UI.Grid.GridSortOptions & MvcContrib.Pagination.PaginationHelper so mvcContrib helpers can do the rest :-)
public ActionResult ThumbChooser(int? artistId, GridSortOptions gridSortOptions, int? page, bool? MissingCoverOnly)
        {
            IQueryable albumList = null;

            if (!MissingCoverOnly.HasValue || !MissingCoverOnly.Value)
            {
                albumList = _BL.GetAlbumListView();
            }
            else
            {
                albumList = _BL.GetAlbumListViewMissingCover();
            }

            if (string.IsNullOrWhiteSpace(gridSortOptions.Column))
            {
                gridSortOptions.Column = "ArtistId";
            }

            if (artistId.HasValue)
            {
                albumList = albumList.Where(a => a.ArtistId == artistId.Value);
            }

            var albumFilter = new AlbumFilterViewModel();
            albumFilter.SelectedArtistId = artistId ?? -1;

            albumFilter.Artists = _BL.GetArtistList().OrderBy(art=>art.Name)
                                    .Select(a => new { a.ArtistId, a.Name })
                                    .ToList().Select(a =>
                                        new SelectListItem
                                        {
                                            Text = a.Name.Length > 20 ? string.Concat(a.Name.Substring(0,20),"...") : a.Name,
                                            Value = a.ArtistId.ToString(),
                                            Selected = a.ArtistId == albumFilter.SelectedArtistId
                                        }).ToList();

            var albumPageList = albumList
                                .OrderBy(gridSortOptions.Column, gridSortOptions.Direction)
                                .AsPagination(page ?? 1, 10);

            var albumListContainer = new AlbumListContainerViewModel
            {
                AlbumFilterViewModel = albumFilter,
                AlbumPageList = albumPageList,
                GridSortOptions = gridSortOptions
            };

            return View(albumListContainer);
        }

That's it!

Till next time...
Diego

Saturday, January 8, 2011

Building N-Tier Applications with Entity Framework 4

Introduction

This post describes using of EF4 for building N-Tier applications. I've decided to write about this topic, after reading an excellent series of articles about N-Tier applications by Daniel Simmons:

1. N-Tier Application Patterns
2. Anti-Patterns to Avoid in N-Tier Applications
3. Building N-Tier Apps with EF 4

Those articles provide in-depth explanation about different issues and considerations we need to take into account, while building N-Tier applications.

Self-Tracking Entities

Self-tracking entities are smart objects with an ability to keep track on their own changes. The key difference between them and regular datasets is that self-tracking entities are plain-old CLR objects (POCO) and consequently are not tied to any specific persistance technology. They are relatively simple objects that represent the entities and information about changes that they went through.

T4 Templates

T4 templates are text templates that contain text blocks and control logic mixed together and can generate a text file, similar to Velocity Template Engine used in Java.

In our example we will use T4-based code generator to create our self-tracking entities.
You need to download and install it before you start.

Building N-Tier Application

The application we're going to build is based on the example from Daniel Simmons third article and uses Northwind database as a back-end.

Let's start with building our data access layer project:

New Project--->Class Library Project, name it Northwind.DAL
Add--->New Item--->ADO.NET Entity Data Model



We will generate our model from the database:



Our model will look like this:



Right-click on the model designer--->Add Code Generation Item--->ADO Self-Tracking Entity Generator



This action will add T4 template to our project. You can also notice that it will disable the default code generation for our EF model



Now we're going to move our newly generated self-tracking entities to separate project in order to decouple the DAL project from the entities.

Right-click on the solution item--->Add New Project--->Class Library project, name it Northwind.Entities.
Afterwards, you simply cut the Northwind.tt item and paste it into Northwind.Entities project.
Don't forget to reference System.Runtime.Serialization assembly in the Northwind.Entities project and add a reference to Northwind.Entities project in Northwind.DAL project.



We're ready to add WCF service layer to our application.
Right-click on the solution item--->Add New Project--->WCF Service Application project, name it Northwind.Service.
Rename the created service definition interface to INorthwindService and move it to the entities project.

Add following methods to the INorthwindService:
[ServiceContract]
public interface INorthwindService
{
[OperationContract]
IEnumerable<products> GetProducts();

[OperationContract]
Customers GetCustomer(string id);

[OperationContract]
bool SubmitOrder(Orders order);    
}


I know that in a real application we would add additional layers like Business Logic layer and Service Interface layer, but for the sake of simplicity we will leave it out.

Let's add an implementation to our service:
public class NorthwindService : INorthwindService
{
public IEnumerable<products> GetProducts()
{
using (var ctx = new NorthwindEntities())
{
return ctx.Products.ToList();
}
}

public Customers GetCustomer(string id)
{
using (var ctx = new NorthwindEntities())
{
return ctx.Customers.Include("Orders")
.Where(c => c.CustomerID == id)
.SingleOrDefault();
}
}

public bool SubmitOrder(Orders newOrder)
{
using (var ctx = new NorthwindEntities())
{
ctx.Orders.ApplyChanges(newOrder);
return ctx.SaveChanges() > 0;
}
}
}


Please note the Include method used in GetCustomer method. This method allows so-called eager loading of Orders table to reduce the number of round-trips to the database.
The detailed information about different loading data options in EF may be found here.

Instead of building some "state of art" client to test our service, let's add a real test project to our solution:

Right-click on the solution item--->Add New Project--->Test Project, name it Northwind.Test



You have to add a reference to Northwind.Service and Northwind.Entities. Don't forget to clean up all the proxies automatically generated for the entities.

Add following test methods to the test class:
[TestClass]
public class NorthwindTest
{
public NorthwindTest()
{
}

private TestContext testContextInstance;

/// 
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}



[TestMethod]
public void TestGetProducts()
{
using (NorthwindServiceClient client = new NorthwindServiceClient())
{
List<Products> products = client.GetProducts();

Assert.IsTrue(products.Count > 0);
}
}

[TestMethod]
public void TestGetCustomer()
{
using (NorthwindServiceClient client = new NorthwindServiceClient())
{
Customers customer = client.GetCustomer("ALFKI");
Assert.IsNotNull(customer);
}
}

[TestMethod]
public void TestSubmitOrder()
{
using (NorthwindServiceClient client = new NorthwindServiceClient())
{
var products = new List<Products>(client.GetProducts());
Assert.IsTrue(products.Count > 0);

var customer = client.GetCustomer("ALFKI");
Assert.IsNotNull(customer);               

try
{
// add a new order
var newOrder = new Orders();
newOrder.OrderDate = DateTime.Now;
newOrder.RequiredDate = DateTime.Now;

var orderedProduct = 
products.Where(p => p.ProductName ==  "Chang")
.Single();
Order_Details orderDetails = new Order_Details()
{
ProductID = orderedProduct.ProductID,
Quantity = 1

};
newOrder.Order_Details.Add(orderDetails);                                       
customer.Orders.Add(newOrder);

var submitSuccess = client.SubmitOrder(newOrder);
Assert.IsTrue(submitSuccess);
}
catch (Exception ex)
{
TestContext.WriteLine(ex.StackTrace);
Assert.Fail();
}
}
}
}


I think we're done.

To see your application in action just run all test methods from the "Test" menu.

The complete code could be downloaded here.

This is it,

Mark.