Archive

Archive for the ‘Tip’ Category

Repository and Unit Of Work Design Pattern– ASP.NET MVC

October 21, 2012 1 comment

Hello! There are two design patterns that I’m going to speak about today, which have been covered loads online and in various books, but I’m going to cover them quickly here:

 

Repository Pattern

 

Quite simply this is a pattern to separate all the data access logic from your application into separate container classes. It is good practise to create Repositories for each Domain area of your application and separate data access concerns, like CRUD operations within these. For e.g. I have the following Domains within my application Accountable (A personal Accounts App):

 

  • LedgerUser – User details
  • LedgerPeriod – Date from/to for each Accounting period defined by the LedgerUser
  • LedgerTransaction – Ledger Transactions that occur each Ledger Period.
  • Many more….

‘I’m not going to go into massive detail, but each Repository of each domain would have the following methods which are generally found in data access:

 

  • Create – Create new records
  • Update – Update existing records
  • Delete – Delete existing records
  • Find – Find records

Do design your Data Source correctly then apply the Repository classes to these. So this should make you think There is a lot of duplicate code here…..”  What do we do in these cases? We write some generic Interfaces to impose some rules on how our Repositories should behave. Please raise your classes (get it…?!) to IRepository:

 

public interface IRepository<TEntity> 
{
    void Create(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
    IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
    IQueryable<TEntity> FindAll();
    TEntity FindById(Guid id);
    

}

 

 

See we have used IQueryable so that we can use other awesome chained LINQ methods (like OrderBy).

 

So this all lovely, but now onto the nitty gritty, taking that interface and applying it to a concrete example. Because I’m using EF a lot at the moment, i have written a EntityFrameworkRepository example using DbContext and Dbset:

 

    public class EntityFrameworkRepository<T> : IRepository<T> 
        where T : class, IRepositoryEntity
    {
        internal DbContext context;
        internal DbSet<T> dbSet;

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="context"></param>
        public EntityFrameworkRepository(DbContext context)
        {
            this.context = context;
            this.dbSet = context.Set<T>();
        }

        public void Create(T entity)
        {
            dbSet.Add(entity);
        }

        public void Update(T entity)
        {
            dbSet.Attach(entity);
            context.Entry(entity).State = EntityState.Modified;
        }

        public void Delete (T entity)
        {
            if (context.Entry(entity).State == EntityState.Detached)
            {
                dbSet.Attach(entity);
            }
            dbSet.Remove(entity);

        }

        public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
        {
           
            return dbSet.Where(predicate);
        
        }

        public T FindById(Guid id)
        {
            
            return dbSet.Single(o => o.id == id);
        }

        public IQueryable<T> FindAll()
        {
            return dbSet;
        }


        
    }
}

 

As you can see this class also implements IRepositoryEntity, which is an idea I stole off the Pluralsight video I watched, whereby in our IRepository interface where have a FindById method. This is presuming that the Entity in question using id within its design, which all my Entities do, so I’m safe to enforce this:

 

 

public interface IRepositoryEntity
{

    Guid id { get; }

}

 

 

 

Unit of Work

 

 

This is all nice and lovely but where is the data persistence? If you look closely and without just copy & pasting these examples, you will see in the Repository interfaces and concrete implementations, there are “commit” or “save” methods. Why? Well we can abstract this further into a Unit Of Work pattern which will:

  • Handle persistence
  • Share the context within Repositories

This will allow one context to be used without the Repositories having to know about each other or their respective Dbcontext’s. Now because we are good programmers we should first design the interface, IUnitOfWork:

public interface IUnitOfWork : IDisposable
{


    void Save();


}

 

Is that it?! Well yes. What i would like to do in the future is have a GenericCollectionRepository within the Unit Of Work concrete implementations, but i will refactor that in at a later date. So following the pattern of EF, this is the EntityFrameworkUnitOfWork:

 

public class EntityFrameworkUnitOfWork : IUnitOfWork
    {
        private AccountsContext context = new AccountsContext();
        internal IRepository<LedgerAccount> account;
        internal IRepository<LedgerUser> user;
        internal IRepository<UserType> userType;
        internal IRepository<Image> image;
        internal IRepository<SystemReference> systemReference;
        internal IRepository<LedgerService> ledgerService;

       


        public IRepository<LedgerAccount> Account
        {
            get
            {
                if (account == null)
                {
                    account = new 
EntityFrameworkRepository<LedgerAccount>(context); } return account; } } public IRepository<LedgerUser> User { get { if (user == null) { user = new EntityFrameworkRepository<LedgerUser>(context); } return user; } } public IRepository<UserType> UserType { get { if (userType == null) { userType = new EntityFrameworkRepository<UserType>(context); } return userType; } } public IRepository<Image> Image { get { if (image == null) { image = new EntityFrameworkRepository<Image>(context); } return image; } } public IRepository<SystemReference> SystemReference { get { if (systemReference == null) { systemReference = new
EntityFrameworkRepository<SystemReference>(context); } return systemReference; } } public IRepository<LedgerService> LedgerService { get { if (ledgerService == null) { ledgerService = new
EntityFrameworkRepository<LedgerService>(context); } return ledgerService; } } public void Save() { context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } }

The beautify of this approach is the reduction in business logic within your Controller of your MVC Application and reducing "controller bloat”.

 

Here is an example of the both patterns working in harmony:

 

 

public class LedgerUserController : Controller
   {
             
       private EntityFrameworkUnitOfWork unitOfWork = 
new EntityFrameworkUnitOfWork(); // // GET: /LedgerUser/Details/5 public ActionResult Details(Guid id) { LedgerUserViewModel viewModel = new LedgerUserViewModel(); UserType userType = new UserType(); try { viewModel.LedgerUser = unitOfWork.User.FindById(id); viewModel.UserType = unitOfWork.UserType.FindAll() .SingleOrDefault
(u => u.id == viewModel.LedgerUser.UserTypeId) .Description; viewModel.UniqueKey = viewModel.LedgerUser.id.ToString(); return View(viewModel); } catch (ArgumentNullException ex) { Console.WriteLine("ArgumentNullException " + ex.ToString()); } catch (InvalidOperationException ex) { Console.WriteLine("InvalidOperationException " + ex.ToString()); } return RedirectToAction("Index", "Home"); } }

 

All my controller is doing is what is was designed to, setting up the views data ready for rendering.

 

I know the code on these sites isnt the best, but i want to create a github repo of it soon. Watch this space! Smile

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Enhanced by Zemanta

[AJAX] IE and its stupidity–Part 100255454577 – Ajax Caching

April 3, 2012 2 comments

This is a note to anyone who uses Ajax and Http GET requests – turn off cache for each request otherwise IE wont refresh and display the latest response. Good example is in JQuery:

$.ajax({
  type: 'get',
  url: url,
  cache: false,
  success: function(result) {
 $(targetDiv).html(result);
  }

This nice little method allows you to pass a parameter called cache which you need to set to false.

Another method in JScript is to provide dummy URL parameter to fool the old dog into refreshing:

var url = '/accountstest/SiteAdmin/Dashboard' + "?dummy=" + new Date().getTime();

Chrome and Firefox do not have this problem.

Reading AJAX For Dummies

Reading AJAX For Dummies (Photo credit: daveynin)

Enhanced by Zemanta
Categories: Tip Tags: , ,

[MVC3] ViewModel Binding To Controller–POST Methods

March 8, 2012 4 comments

Now we should be writing strongly typed Views based on our Models. Now in some cases you may want to use the ViewModel pattern, which allows you to create a View based on:

 

a) One Model and some additional properties

b) Two or more combined Models

c) Two or more combined Models plus some additional properties.

These ViewModel classes would sit in a folder structure, you guessed it, ViewModels in your Visual Studio Project.An example would be my RegisterViewModel i have created:

 

 

public class RegisterViewModel {
    public RegisterModel RegisterModel { get; set; }
    public string UniqueKey { get; set; }
    public bool Thumbnail { get; set; }

}

 

 

So this is quite straight forward really. I have a RegisterModel which is the MVC default Membership model for handling when a new user Registers. I have a property called UniqueKey which will hold the of a created user, and a Boolean field Thumbnail which will be set to true if he want thumbnail images or false if we don’t.

So this is nice a simple then. So what this means that in our GET Action controller for register we can setup the required values. In this instance we only set the Thumbnail property:

 

// GET: /Account/Register public ActionResult Register()
{
    var viewModel = new RegisterViewModel {
        Thumbnail = true };

    return View(viewModel);
}

 

 

Then in our Review View, we need to declare our ViewModel instead of our RegisterModel, plus all our Model fields and the additional properties are parsed:

 

@model MvcImage.ViewModels.RegisterViewModel @using MvcImage.Models
@using Bradaz.OpenSource.MVC
@using Bradaz.OpenSource.MVC.HTMLHelpers

@{     ViewBag.Title = "Register";
} @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
    <div> <fieldset> <legend>Account Information</legend> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.UserName)
            </div> <div class="editor-field"> @Html.TextBoxFor(model => model.RegisterModel.UserName)
                @Html.ValidationMessageFor(model => model.RegisterModel.UserName)
            </div> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.Email)
            </div> <div class="editor-field"> @Html.TextBoxFor(model => model.RegisterModel.Email)
                @Html.ValidationMessageFor(model => model.RegisterModel.Email)
            </div> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.Password)
            </div> <div class="editor-field"> @Html.PasswordFor(model => model.RegisterModel.Password)
                @Html.ValidationMessageFor(model => model.RegisterModel.Password)
            </div> <div class="editor-label"> @Html.LabelFor(model => model.RegisterModel.ConfirmPassword)
            </div> <div class="editor-field"> @Html.PasswordFor(model => model.RegisterModel.ConfirmPassword)
                @Html.ValidationMessageFor(model => model.RegisterModel.ConfirmPassword)
            </div> <div class="editor-label"> @Html.Label("Avatar")
            </div> <div class="editor-field"> @Html.UploadImageFor(model => model.UniqueKey,thumbnail:true)
            </div> <div class="editor-field"> @Html.HiddenFor(model => model.Thumbnail)
            </div> <p> <input type="submit" value="Register" /> </p> </fieldset> </div> }

 

NB: I have changed my UploadImageFor HTML Helper to include Thumbnail support. This will be documented separately and released under my Open Source MvcImage Project.

So this all sounds simple right? Well you may get into a bit of a pickle (like me) when handling the POST Register ActionMethod. This would be peoples first attempts, which are both wrong:

Attempt 1

[HttpPost]
public ActionResult Register(RegisterModel registermodel,
    HttpPostedFileBase imageLoad2)
{
    ///---Code something }

Attempt 2

[HttpPost]
public ActionResult Register(RegisterViewModel registerviewmodel,
    HttpPostedFileBase imageLoad2)
{
    ///---Code something }

 

These are wrong if you wish to access the additional properties and the ResgiterModel within the RegisterViewModel. Let me explain:

 

Attempt 1 – You would be able to access the RegisterModel properties but not the Thumbnail property.

 

Attempt 2 – Your RegisterModel would be null and you wont be able to access the Thumbnail.

 

After these attempts most people scratch their head, curse, then head over to ASP.NET/FORUMS or stackoverflow for an answer. Well it took me a lot of scratching, googling and forum posting (plus nagging my poor friend Shawson!) to find the answers. The answer lies in how MVC binds the Models. The best place to start is in Fiddler, which is a free application for debugging HTTP and is very useful. Here is a glimpse of the form POST when i hit the Register button on my view:

 

 

Capture_Blog

 

As you can see our RegisterModel properties are prefixed with “RegisterModel” and our Thumbnail is just Thumbnail. So if you apply the MVC Binding on this, in the two attempts above, in the first attempt, MVC recognises RegisterModel as these have been binded from the HTTP post data, so are available. Thumbnail though isn’t available in the RegisterModel declaration in the class so this is ignored. In the 2nd attempt there is no RegisterViewModel in the POST so the binding will fail, thus nothing is available and you will get null fields.

 

The answer is the following:

[HttpPost]
public ActionResult Register(bool Thumbnail, 
[Bind(Prefix = "RegisterModel")]RegisterModel registermodel,
    HttpPostedFileBase imageLoad2)
{
    ///-Code something }

 

So here we declare Thumbnail as its own separate parameter and Bind the RegisterModel with a Prefix “RegisterModel” using the BindAttribute.  This allows us toaccess our RegisterViewModel properties AND Models within our controller quite happily.

I hope this helps you when using ViewModels.

Enhanced by Zemanta
Categories: Tip Tags: , , ,

[CSS] inner Container – float issue

October 7, 2011 Leave a comment

An age old problem apparently where a inner div is attached to a outer div element in the DOM tree. Now usually when the inner div grows in size (i.e. content is added), the outer div will size accordingly. The issue is when a float is applied to the inner div. This causes the container div to ignore what is happening to the inner div element, thus it will not resize based on the inner div.

 

Right, confused? Too many div’s to!  Here is an example of a page with float:left applied to the list elements (li):

 

 

 

 

As you can see, the list elements are floating left, BUT the outer div container (white block), hasn’t resized. Now removing float:left shows you how i want the container div (outer) to behave:

 

 

 

 

 

Unfortunately my lists are not behaving correctly. Now because im new to HTML/CSS i added a forum post to asp.net forums, where a kind chappy told me about the clearfix resolution.

http://forums.asp.net/t/1727780.aspx/1?float+left+issues+lists+

 

On Googling this fix to locate what it is doing, i found the following post which mentions an even cleaner fix adding overflow:auto to my outer container div:

http://www.sitepoint.com/simple-clearing-of-floats/

And like magic, this has worked! And here is the proof:

 

 

 

 

 

 

 

Enhanced by Zemanta

[MVC 3] ObjectSet Extension Method–CountAll

September 16, 2011 Leave a comment

I find myself when using Entity Framework, before accessing any of Objects i have various try/catch methods, due to the amount of exceptions that “bubble” up.

 

Now before i try and access my ObjectSet’s within my ObjectContext i usually make sure there are objects there to begin with. I usually do something like:

 

 

if ((db.RoomTypes.Count(i => i.Type_Code == room.Type)) > 0)
{
    roomType = db.RoomTypes.SingleOrDefault(i => i.Type_Code == room.Type);
    r.RoomType = roomType.Type_Name;

}

 

 

Now this is fine for when I’m trying to select against say, an id. This doesn’t work when i want to return all records from my ObjectSet. So i have come up with an extension method to the said ObjectSet:

        #region CountAll
        public static int CountAll<TEntity>(this ObjectSet<TEntity> objectSet) 
where TEntity : class { int _count = 0; foreach (var ObjectSet in objectSet) { if (objectSet != null) { _count++; } } return _count; } #endregion

 

 

Take note of the TEntity class constraint. Some little background. When you create your EF classes based on your database, there are various classes that are created.

Here is another example, db.Rooms being my ObjectContext:

 

Room room = db.Rooms.SingleOrDefault(r => r.Unique_Key == id);

 

If you look at the definition of Rooms (ObjectSet – a table), this is the collection of Room:

 

public ObjectSet<Room> Rooms
 {
     get
     {
         if ((_Rooms == null))
         {
             _Rooms = base.CreateObjectSet<Room>("Rooms");
         }
         return _Rooms;
     }
 }

 

If you look at the definition of Room generic parameter, represents a row in the table Room:

public partial class Room : EntityObject

 

So we know in essence the ObjectSet is the table and EntityObject is a row. So now we know this you can interrogate the definition of ObjectSet:

public class ObjectSet<TEntity> : ObjectQuery<TEntity>, IObjectSet<TEntity>,
IQueryable<TEntity>,IEnumerable<TEntity>, IQueryable, IEnumerable
where TEntity : class { }


So there’s your TEntity you need for your extension method constraint. Now you know why we have done what we have done for the Extension Method, here is how to use it:

try
{
  if ((db.Properties.CountAll()) > 0)
  {
     //--code here
      
  }
}

So we can CountAll the ObjectsSets (Rows) within Properties, if there are more than 0, the do something (Like query the data).

Anyway, i hope this helps.

 

 

 

Enhanced by Zemanta

[MVC 3]– HiddenFor Helper –Remember to Use!–TIP

September 11, 2011 Leave a comment

I was skyping a MVC problem with my friend Shaw Young the other day, and it turned out the problem i was experiencing was a nOOb error of not passing a my from the view to the Model, and i kept getting the following SQL Foreign Key exception:

 


The INSERT statement conflicted with the FOREIGN KEY constraint FK_source_destination

 

 

This turned out to be a red herring. The issue was that my View hadn’t had my Guid  field Unique_Key declared to be bound, ready for POST Action Method. Now because i don’t want the user to see the keys (It would be ugly!) on the view, you can use the following HTML Helper method:

 

@Html.HiddenFor(model => model.Unique_Key)

 

This will mean my Guid is not rendered to the user BUT is passed to my POST method to be used without throwing any nasty exceptions. A nOOb mistake but easy to miss and even harder to find! I spent along time checking my SQL DB Design.

Enhanced by Zemanta
Categories: Tip Tags: , , ,

[MVC 3] ModelState ModelErrorCollection Debug–Extension Method

September 6, 2011 2 comments

In the last i described a way of using a static method to obtain which model field is causing your ModelState to be invalid. My good friend Shaw Young said that a Extension Method would be another way of doing this. And thinking of it, it makes more sense and a better and cleaner implementation.

So here is that piece of code again:

if (ModelState.IsValid)
{

  //—Your code here
}
else {
    Debug.ModelStateErrors( ModelState);
    ModelState.ModelStateErrors();
}

So now instead of a Debug.ModelStateErrors, there is a Extension Method ModelStateErrors referenced by the object itself.

And here is the code:

public static void ModelStateErrors (this ModelStateDictionary modelState)
{
    var errors = modelState.Where(a => a.Value.Errors.Count > 0)
        .Select(b => new { b.Key, b.Value.Errors })
        .ToArray();

    foreach (var modelStateErrors in errors)
    {
        int count = modelStateErrors.Errors.Count();
        System.Diagnostics.Debug.WriteLine("...Errored When Binding.",        
        modelStateErrors.Key.ToString());

    }

}

There you are! The only difference is the implementation of the static method itself. The actual code is the same.

Enhanced by Zemanta
Categories: Tip Tags: , ,

[MVC 3] ModelState ModelErrorCollection Debug

September 5, 2011 2 comments

UPDATE: Dan Kendall kindly done a gist of the code which can be found here if you need it which is related to this post:

https://gist.github.com/3699804

We all use the ModelState.IsValid before we commit any changes to our Entity Framework ObjectContext to update our data source. But what is ModelState.IsValid? Well basically ModelState says…

“Yes, all models have binded successfully from the view”

But what happens when we the ModelState is NOT valid. Well, I  have a little static method So you can write to the Output window to see what the property name is, so you can fix it quickly.

if (ModelState.IsValid)
{
   ///—- Your code.
}
else {
    Debug.ModelStateErrors( ModelState);

}

Now my method, Debug.ModelStateErrors consists of an Anon Type which i use a LINQ to abstract the ModelErrorCollection from the ModelState. I then print out the Key from the Dictionary to the Output window.  Example on the 2nd image which is property.PropertyType is the model field.

#if DEBUG
       /// <summary> 
 /// Output the properties which are causing the issues when 
 /// the model is binding. 
 /// </summary> public static void ModelStateErrors (ModelStateDictionary modelState)
        {
            var errors = modelState.Where(a => a.Value.Errors.Count > 0)
                .Select(b => new { b.Key, b.Value.Errors })
                .ToArray();

            foreach (var modelStateErrors in errors)
            {
                 System.Diagnostics.Debug.WriteLine("...Errored When Binding.",                                  modelStateErrors.Key.ToString());

            }

        }
#endif #endregion 

Capture

Enhanced by Zemanta
Categories: Tip Tags: , ,

[MVC 3] Entity Framework 4–Disposing ObjectContext–TIP

August 30, 2011 1 comment

ADO.NET Entity Framework stack

Image via Wikipedia

The Entity Framework can throw a lot of Exceptions depending on what you are trying to achieve. We are lucky that the default CRUD controller template includes how to use EF during a Create/Delete/Edit scenario, but sometimes (a lot of the time in my case), when you first begin using EF, the exceptions keep on coming.

 

A lot of people use either try/finally or using statements when using their ObjectContext. You will find a lot of people will have something like (db being the ObjectContext):

 

    finally {
        if (db != null)
 db.Dispose();
    }

}

 

 

Now this is fine, but you need to handle this correctly, because if you saves changes after this, you could throw an InvalidOperationException, with the following text:

 

The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.

OR

 

 

ObjectDisposedException

 

In Entity Framework, entities are attached to the EF context and changes are “tracked” within the framework. So you need to make sure you are not trying to Attach or Detach your entities incorrectly. Remember:

 

AddObjectUsed solely to add new entities only (Does not deal with EntityState.Modified items) to the context to be added to the data source.

AttachUsed to update an object that already exists in the context.

 

Now if we Dispose the object context incorrectly, then this could cause the above exceptions to be thrown later on when trying to update the data sources after the finally statement which includes the Dispose.

 

Now the way i get around this is use partial to extend my EF ObjectContext class (in my case EduEntities), and override the Dispose method so i only Detach the Unchanged Entities.

 

public partial class EduEntities {
    protected override void Dispose(bool disposing)
    {

        foreach (var entry in ObjectStateManager.GetObjectStateEntries       (EntityState.Unchanged))
        {

            Detach(entry.Entity);
        }

        base.Dispose(disposing);

    }

}

 

This means that the tracking on my changed objects are not lost.

Enhanced by Zemanta
Follow

Get every new post delivered to your Inbox.

Join 269 other followers

%d bloggers like this: