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")]


Wednesday, 22 April 2015

Generic Repository to do transactions with Azure Document DB

Following is a generic repository we can use in order to do data manipulations in Azure document DB. This can be used to save and retrieve POCO objects and generic streamed objects in Azure Document DB.

I have used MEF to do the dependency injections. This repository is used only to deal with one collection. More generic implementation is on its way and will update soon.

 public interface IDocumentDb
        {
            dynamic GetRecord(string id);

            IEnumerable<object> GetRecords();
            
             Task Add(object entity);

            Task Update(object entity,string id);

            Task Delete(string id);

            void Dispose();
        }
The implementation class is as follows.
   [Export(typeof(IDocumentDb))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
   public class DocumentDb : IDocumentDb
    {
        private static DocumentClient _client;
        private Database _database;
        private DocumentCollection _collection;

        private static readonly string DadatabaseId = ConfigurationManager.AppSettings["DatabaseId"];


        private static readonly string EndpointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
        private static readonly string AuthorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
        private static readonly string CollectionId = ConfigurationManager.AppSettings["CollectionId"];

    
        public DocumentDb()
        {
            
           Init();
        }

        private async Task Init()
        {
            _client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);
            try
            {
                this._database = _client.CreateDatabaseQuery().Where(db => db.Id == DadatabaseId).ToArray().FirstOrDefault();
                if (_database == null)
                {
                    this._database = await _client.CreateDatabaseAsync(new Database { Id = DadatabaseId });
                }

                this._collection = _client.CreateDocumentCollectionQuery(_database.SelfLink).Where(c => c.Id == CollectionId).ToArray().FirstOrDefault();
                if (_collection == null)
                {
                    _collection = await _client.CreateDocumentCollectionAsync(_database.SelfLink, new DocumentCollection { Id = CollectionId });
                }
            }
            catch (Exception ex)
            {
                
                throw;
            }
          

          
        }

        public async Task Add(object entity)
        {
            try
            {
                await _client.CreateDocumentAsync(_collection.SelfLink, entity);
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        public async Task Update(object entity,string id)
        {
            try
            {
                var doc =
                   _client.CreateDocumentQuery(_collection.SelfLink).Where(d => d.Id == id).AsEnumerable().FirstOrDefault();

                if (doc != null)
                    await _client.ReplaceDocumentAsync(doc.SelfLink, entity);

            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        public dynamic GetRecord(string id)
        {
            try
            {
                dynamic doc =
                    _client.CreateDocumentQuery(_collection.SelfLink).Where(d => d.Id == id).AsEnumerable().FirstOrDefault();
                return doc;
            }
            catch (Exception ex)
            {
                throw;
            }
           
        }

        public IEnumerable<object> GetRecords()
        {
            try
            {
                var obj = _client.CreateDocumentQuery(_collection.SelfLink, "SELECT * FROM " + CollectionId).AsEnumerable().ToList();
                return obj;
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async Task  Delete(string id)
        {
            try
            {

                var doc =
                    _client.CreateDocumentQuery(_collection.SelfLink)
                        .Where(d => d.Id == id)
                        .AsEnumerable()
                        .FirstOrDefault();

                if (doc != null)
                {
                    var resourceResponse = await _client.DeleteDocumentAsync(doc.SelfLink);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void Dispose()
        {
            if (_client == null)
            {
                return;
            }

           _client.Dispose();
        }

    }
Following is the consumer class.
public class Consumer
{
      [Import(typeof(IDocumentDb))]
      public IDocumentDb DocumentDb { get; set; }

      public Consumer()
      {
      }

      public void TempAdd()
      {
                  DocDbCustomFieldViewModel docDbEntity = new DocDbCustomFieldViewModel();
                  docDbEntity.Id = model.ID;
                  docDbEntity.ClientId = CurrentClientID;
                  docDbEntity.ProjectId = CurrentProjectID;

                List lCusFields = new List();
                foreach (var cusField in cusFields)
                {
                    CustomFieldViewModel newCusField = CustomFieldProvider.Get(cusField.CustomFieldID);
                    CustomFieldViewViewModel tmpModel = new CustomFieldViewViewModel();
                    tmpModel.DisplayName = newCusField.DisplayName;
                    tmpModel.FieldName = newCusField.FieldName;
                    tmpModel.Value = string.Empty;
                    lCusFields.Add(tmpModel);

                }
                docDbEntity.CustomFields = lCusFields;     

                 DocumentDb.Add(docDbEntity);
       }

       public void TempSearch(string id)

}

Tuesday, 7 April 2015

Dynamically Importing multiple functionality using MEF (Managed Extensibility Framework)

Using Managed Extensibility Framework (MEF) we can create lightweight, extensible applications without much of a fuzz.  It is a pretty good tools for IoC and can be easily use as a good DI component as well.

Following is a very simple example of using MEF create simple message service which include many variations.

First of all you need to import the assembly System.ComponentModel. This is the assembly that contains all the beauty of MEF.

We would be creating a very simple console application just to demonstrate the  principle.

The Program class is looks as follows.

    class Program
    {
        static void Main(string[] args)
        {
           DynamicLoad();
        }

        private static void DynamicLoad()
        {
            var testDynamicMessaging = new DynamicMessaging();
            testDynamicMessaging.Run();

            Console.ReadLine();
        }
      
    }

This class is very simple. Just invoking the method Run in the DynamicMessaging class.
DynamicMessaging looks as follows.
 internal class DynamicMessaging
    {
        [ImportMany]
        public IEnumerable Messages { get; set; }
        public void Run()
        {
          Compose();
          foreach (var messenger in Messages)
          {
              messenger.Send("Hi");
          }

        }
        
        private void Compose()
        {
          var assemblyCatalog = new AssemblyCatalog(GetType().Assembly);
          var container = new CompositionContainer(assemblyCatalog);

          container.ComposeParts(this);

        }
    }
There are few important points in this class as follows. 1. ImportMany attribute enables importing many interfaces to the enumerable property Messages. 2. We are creating an assembly catalog and using that when creating the CompositionContainer. 3. When composing parts, we are just passing the current object only. (this) . But if we are not going to load multiple interfaces , the code would looks as follows. ie: only the object type we need.
 var container = new CompositionContainer();
 container.ComposeParts(this, new SpecificMessenger());
Finally the implemented messenger classes are looks like follows.
[Export(typeof(IMessenger))]
    class EMailMessenger : IMessenger
    {
        public void Send(string message)
        {
            Console.WriteLine("This is from the email Messenger " + message  );
        }
    }

 [Export(typeof(IMessenger))]
    class TextMessenger : IMessenger
    {
        public void Send(string message )
        {
            Console.WriteLine("This is from the text messenger " +  message);
        }
    }

Re sharper r - Re-factoring failed - Files still read-only' error message - Issue Fixed


Just got this error in Re sharper re-factoring.



I am using GIT as my source control and this is caused by that. So in VS2013 , Just Select the plugin as None in Source Control as follows. 

Bingo ! This solves the issue.