Monday 20 July 2015

Allow Datetime null in scaffolding model

When you are trying to do scaffolding with a model which has datetime filed , the common code is as follows.
    
        [Display(Name = "End Date")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        public DateTime EndDate { get; set; }


But this makes this filed mandatory by default. So in-order to make it nullable , we need to alter the code as following.
    
        [Display(Name = "End Date")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        Public Nullable<DateTime>  EndDate { get; set; }


Thursday 16 July 2015

Add Migrations to existing code first Model

Following steps guides you how to generate migration code for the existing code first dbContext model.

1. Create your model class
 public class NewsSlider
    {
        [Key]
        [HiddenInput(DisplayValue = false)]
        public int NewsSliderId { get; set; }

        [Display(Name = "News Item")]
        [StringLength(500)]
        public string NewsItem { get; set; }
    }


2. Update your dbContext class as follows
 
   public System.Data.Entity.DbSet<myapp .models.newsslider=""> NewsSliders { get; set; }

3. Execute Add-Migration NewsSlider in the Package Manager console

4. This would generate the migration code using scaffolding.
  public partial class NewsSlider : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.NewsSliders",
                c => new
                    {
                        NewsSliderId = c.Int(nullable: false, identity: true),
                        NewsItem = c.String(maxLength: 500),
                    })
                .PrimaryKey(t => t.NewsSliderId);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.NewsSliders");
        }
    }

Thursday 9 July 2015

Avoiding pluralization in the Data Context class

When we are designing the Data Access as code first, the Data Context is looking for pluralized tables in the DB.

Eg :

public DbSet<Student> StudentSet{ get; set; } 

This is looking for the table Students in the database.

If we want to use the same table name, we need to remove the PluralizingTableNameConvention attribute from the lmodelBuilder. The full example is as follows

 public class SchoolContext : DbContext
    {
        public SchoolContext ()
            : base("name=SchoolCon")
        {
            Database.SetInitializer<SchoolContext>(null);
        }

        public DbSet<Student> StudentSet { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<Student>().HasKey<int<(e => e.StudentId);
        }
    }


Wednesday 8 July 2015

Using FluentValidation in .Net Projects

FluentValidation is a very easy to use simple validation framework which we can use in .Net projects. This is been developed by Jeremy Skinner. It uses  fluent interface and lambda expressions for building validation rules for your business objects.
Following is a simple example of how to use this validation framework in a simple class. 
 class StudentValidator : AbstractValidator
        {
            public StudentValidator ()
            {
                RuleFor(obj => obj.Id).NotEmpty();
                RuleFor(obj => obj.Name).NotEmpty();
                RuleFor(obj => obj.Age).GreaterThan(5).LessThanOrEqualTo(20);
            }
        }

        protected override IValidator GetValidator()
        {
            return new StudentValidator ();
        }

AbstractValidator is fluent class which accepts the class that needs to be validated.


Friday 3 July 2015

Match data contract namespaces in two entities

When we need to do any data contract mapping between two layers or entities ( eg : client and server sides ) the name spaces should match. Otherwise the mismatch error would occur when we tying to do the data contact mapping in between two layers or entities.

Following are the two example data contract classes that resides in two layers.

The Business Entity data contract class

namespace TestApp.Business.Entities
{
    [DataContract]
    public class Student : EntityBase, IIdentifiableEntity
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age{ get; set; }
   }
}
The Business Client entity data contract class
namespace TestApp.Client.Entities
{
    [DataContract]
    public class Student : EntityBase, IIdentifiableEntity
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age{ get; set; }
   }
}


This would give the m=contract mismatch error because the name spaces are different. The simplest solution for this is having the namespace tag in the contract attribute.
namespace TestApp.Business.Entities
{
     [DataContract(Namespace = "http://www.priyaltech.com/appname/servicename")]
    public class Student : EntityBase, IIdentifiableEntity
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age{ get; set; }
   }
}

namespace TestApp.Client.Entities
{
    [DataContract(Namespace = "http://www.priyaltech.com/appname/servicename")]
    public class Student : EntityBase, IIdentifiableEntity
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age{ get; set; }
   }
}

But most of the time in the client side, we tend to not to have simple public attributes with data contracts. This is mainly due to the validation and and other client side processing we need to do. Typical client side data entity class would looks like following.
namespace CarRental.Client.Entities
{
    public class Student: ObjectBase
    {
        int _StudentId;
        string _Name ; 
        int _Age;

        public int StudentId
        {
            get { return _StudentId; }
            set
            {
                if (_StudentId != value)
                {
                    _StudentId = value;
                    OnPropertyChanged(() => StudentId);
                }
            }
        }

        public string Name
        {
            get { return _Name; }
            set
            {
                if (_Name != value)
                {
                    _Name = value;
                    OnPropertyChanged(() => Name);
                }
            }
        }

      public int Age
        {
            get { return _Age; }
            set
            {
                if (_Age != value)
                {
                    _Age = value;
                    OnPropertyChanged(() => Age);
                }
            }
        }
   }
}

As you can see, we do not have the DataContract and DataMember attributes in this client class. So how we can do the contract mapping. The best way is to use the AssemblyInfo class of the project and do the data contract mapping there as follows.
[assembly: ContractNamespace("http://www.priyaltech.com/appname/servicename",
                              ClrNamespace = "TestApp.Business.Entities")]
Do the same to the client project's AssemblyInfo class as well.
[assembly: ContractNamespace("http://www.priyaltech.com/appname/servicename",
                              ClrNamespace = "TestApp.Client.Entities")]