Currently, I have very successfully archived my applications as follows:
Data Model (Entity Framework 4.1)
Validation using Enterprise Application 5.0 Application Application Block.
An object context managed by a reusable class library.
So, the user interface is pretty easy to use code, but I know that is not yet complete.
If I wanted to set up my projects so that I could implement Web Forms, MVC, WPF Desktop or Silverlight โ even Windows Phone 7, what additional steps might be required?
Here's some code intentionally simplified to illustrate my current state of the game (I skipped Code Contracts and class libraries):
(Currently EF4 Model First and ASP.NET Web Forms)
Partial class for an automatically generated object
namespace MyNamespace.Database { using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; [HasSelfValidation] public partial class MyEntity : IMyEntity { [SelfValidation] public void Validate(ValidationResults validationResults) {
Validation
namespace MyNamespace.Database { using System.ComponentModel.DataAnnotations; using System.Diagnostics.Contracts; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; [ContractClass(typeof(MyEntityContract))] public interface IMyEntity { int Id { get; set; } [Required] [NotNullValidator] [StringLengthValidator(0, RangeBoundaryType.Ignore, 50, RangeBoundaryType.Inclusive, MessageTemplate = "MyEntity Name must be 50 characters or less.")] string Name { get; set; } void Validate(ValidationResults validationResults); } }
Facade of data access
namespace MyNamespace.Facade { using System.Collections.Generic; using System.Linq; using Common.ObjectContextManagement; using Database; public sealed class MyEntityFacade : FacadeBase<MyEntities, MyEntity> { public IEnumerable<MyEntity> GetAll() { return this.ObjectContext.MyEntitys .Distinct() .ToList(); } } }
Web application web interface
using (new UnitOfWorkScope(false)) { this.MyEntityList.DataSource = new MyEntityFacade().GetAll(); this.MyEntityList.DataBind(); } // Or... using (var scope = new UnitOfWorkScope(false)) { var myEntityFacade = new MyEntityFacade(); var myEntity = new MyEntity(); PopulateEntity(myEntity); // Validation errors are automatically presented // to the user from the Validate method if (Validate(myEntity)) { try { myEntityFacade.Add(myEntity); scope.SaveAllChanges(); } catch (Exception exception) { Logging.Write("Error", LoggingLevel.Error, exception.Message); } } }
How close am I?