Using DataAnnotations yaaay!

Posted: June 30, 2012 in Educational
Advertisements

Validation of data

Posted: June 29, 2012 in A fresh start...

ValidationAttribute is common use in check data validation.

 


public abstract class ValidationViewModelBase : ViewModelBase, IDataErrorInfo
  {
    private readonly TypesContent _typesContent;

    private readonly Type _thisType;

    protected ValidationViewModelBase()
    {
      this._thisType = GetType();
      this._typesContent = new TypesContent(this._thisType);
    }

    #region Implementation of IDataErrorInfo

    public string this[string columnName]
    {
      get
      {
        PropertyInfo info = this._typesContent.GetPropertyInfo(
          this._thisType, columnName);

        var validationAttributes =
          this._typesContent.GetValidationAttribute(this._thisType, columnName);

        var value = info.GetValue(this, null);

        var errors = new List<string>();

        foreach (var validationAttribute in validationAttributes)
        {
          if (!validationAttribute.IsValid(value))
          {
            errors.Add(validationAttribute.ErrorMessage);
          }
        }

        OnPropertyChanged("Error");

        return string.Join(Environment.NewLine, errors.ToArray());
      }
    }

    public string Error
    {
      get
      {
        var propertyInfos = this._typesContent.GetPropertInfos(this._thisType);
        var errorlist = new List<string>();

        foreach (var info in propertyInfos)
        {
          var validationAttributes =
            this._typesContent.GetValidationAttribute(
              this._thisType, info.Name);

          var value = info.GetValue(this, null);

          var errors = validationAttributes.Where(v => !v.IsValid(value))
            .Select(v => v.ErrorMessage).ToArray();
          errorlist.AddRange(errors);
        }

        return string.Join(Environment.NewLine, errorlist.ToArray());
      }
    }

    #endregion

    private class TypePropertyContent
    {
      private readonly Type _type;

      private readonly Dictionary<string, PropertyInfo> _propertyInfos =
        new Dictionary<string, PropertyInfo>();

      private readonly Dictionary<string, ValidationAttribute[]> _validators =
        new Dictionary<string, ValidationAttribute[]>();

      public TypePropertyContent(Type type)
      {
        this._type = type;
        this.LoadData();
      }

      private void LoadData()
      {
        var classType = this._type;
        var properties = classType.GetProperties();
        foreach (var propertyInfo in properties)
        {
          var customAttributes =
            propertyInfo.GetCustomAttributes(
              typeof(ValidationAttribute), true);
          if (customAttributes.Length > 0)
          {
            this._validators.Add(
              propertyInfo.Name, (ValidationAttribute[]) customAttributes);
            this._propertyInfos.Add(propertyInfo.Name, propertyInfo);
          }
        }
      }

      public PropertyInfo GetPropertInfo(string propertyName)
      {
        return this._propertyInfos.ContainsKey(propertyName)
              ? this._propertyInfos[propertyName]
              : null;
      }

      public PropertyInfo[] GetPropertInfos()
      {
        return this._propertyInfos.Values.ToArray();
      }

      public ValidationAttribute[] GetValidationAttribute(string propertyName)
      {
        return this._validators.ContainsKey(propertyName)
              ? this._validators[propertyName]
              : null;
      }
    }

    private class TypesContent
    {
      private static readonly Dictionary<Type, TypePropertyContent> _types =
        new Dictionary<Type, TypePropertyContent>();

      public TypesContent(Type type)
      {
        if (!_types.ContainsKey(type))
        {
          _types.Add(type, new TypePropertyContent(type));
        }
      }

      public PropertyInfo GetPropertyInfo(Type type, string propertyName)
      {
        if (_types.ContainsKey(type))
        {
          var propertyContent = _types[type];
          return propertyContent.GetPropertInfo(propertyName);
        }

        return null;
      }

      public ValidationAttribute[] GetValidationAttribute(
        Type type, string propertyName)
      {
        if (_types.ContainsKey(type))
        {
          var typePropertyContent = _types[type];
          return typePropertyContent.GetValidationAttribute(propertyName);
        }

        return null;
      }

      public PropertyInfo[] GetPropertInfos(Type type)
      {
        return _types.ContainsKey(type) ? _types[type].GetPropertInfos() : null;
      }
    }
  }
  public class ViewModelBase : INotifyPropertyChanged
  {
    #region INotifyPropertyChanged 

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs eventArgs)
    {
      this.PropertyChanged(this, eventArgs);
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
  }
use like this:
ViweModel
 public class PersonViewModel : ValidationViewModelBase
  {
    private string _name;

    [RegularExpression(@"^\w+$", ErrorMessage = "format error")]
    public string Name
    {
      get
      {
        return this._name;
      }

      set
      {
        this._name = value;
        OnPropertyChanged("Name");
      }
    }
  }

View:

<TextBox>
  <TextBox.Text>
    <Binding Path=".Name"
         Mode="TwoWay"
         UpdateSourceTrigger="PropertyChanged"
         ValidatesOnDataErrors="True"
         ValidatesOnExceptions="True"
         NotifyOnValidationError="True">
    </Binding>
  </TextBox.Text>
</TextBox>

Taken from :

 

Entity Framework Code First Data Annotations

Posted on May 6, 2012

 

In the previous post we explored the use of the Entity Framework Code First Fluent API to configure properties and specify how the corresponding database is created. You can do this also by using data annotations. These are a set of configuration attributes found in the System.ComponentModel.DataAnnotations namespace. This post extends on the previous example, so if you haven’t read that one you might want to take a look first.

In this example we recreate the database we used in the previous example. We used the Code First Fluent API for configuring model creation. This time, however, we use data annotations to specify the same custom settings. We have a Bill Of Materials entity with a ProjectName property. We want this to be required, have a maximum length of 24 characters and change the column name in the database to ‘Project’.

using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace CodeFirstPocos { publicclassBillOfMaterials  { publicint Id { get; set; } [MaxLength(24), Required, Column("Project")] publicstring ProjectName { get; set; } publicDateTime CreationDate { get; set; } publicList<AssemblyItem> AssemblyItems { get; set; } } }

That’s all. Our DbContext derived class BomContext still has the two DbSet properties for BillOfMaterials and AssemblyItem without the override of the OnModelCreating method.

using System.Data.Entity; using CodeFirstPocos; namespace CodeFirstData { publicclassBomContext : DbContext  { publicDbSet<BillOfMaterials> BillOfMaterialsSet { get; set; } publicDbSet<AssemblyItem> AssemblyItems { get; set; } } }

Lets create a test to verify this configuration with data annotations. We create a new Bill Of Materials with a ProjectName larger than the allowed 24 characters. We expect a DbEntityValidationException to be thrown, so we set the ExpectedException attribute of the testmethod accordingly.

using System; using System.Data.Entity.Validation; using CodeFirstData; using CodeFirstPocos; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CodeFirstTests { [TestClass] publicclassBomTests  { [TestMethod] [ExpectedException(typeof (DbEntityValidationException))] publicvoid ProjectNameWithMoreThan24CharsShouldThrowException() { var bom = newBillOfMaterials  { CreationDate = newDateTime(2012, 6, 29), ProjectName = "The Data Annotation Project", AssemblyItems = null, }; var context = newBomContext(); context.BillOfMaterialsSet.Add(bom); context.SaveChanges(); } } } 

If we run the test it passes so the DbEntityValidationException is thrown as we expected. The exception is thrown on the context.SaveChanges() method.

Entity Framework Code First Data Annotations Test

Finally lets see if the database got created the way we configured it with data annotations.

Entity Framework Code First Bom Context

And so it did… :-)

 

this article is taken from Remondo.net

 

The original link is: http://www.remondo.net/entity-framework-code-first-data-annotations/

 

(This article is taken from Romando.net)

the original link is:   http://www.remondo.net/code-first-fluent-api-entity-framework-model-creation/

 

Code First Fluent API Entity Framework Model Creation

 

Since Entity Framework 4.1 we can use the Code First Fluent API to specify how our database gets created, effectively overriding the default settings. This is also possible with data annotations, but the Fluent API gives us a way to keep this out of our POCO classes and into the data layer.

In this example we have two POCO’s; first a Bill of Materials (BOM)…

using System; using System.Collections.Generic; namespace CodeFirstPocos { publicclassBillOfMaterials  { publicint Id { get; set; } publicstring ProjectName { get; set; } publicDateTime CreationDate { get; set; } publicList<AssemblyItem> AssemblyItems { get; set; } } }

… which can contain a list of assembly items.

namespace CodeFirstPocos { publicclassAssemblyItem  { publicint Id { get; set; } publicint BillOfMaterialsId { get; set; } publicstring PartNumber { get; set; } publicstring Description { get; set; } publicdouble Quantity { get; set; } publicdecimal Price { get; set; } } }

If we let Entity Framework create our database, we get default creation behavior which is not always what we want. For instance the string type gets translated to the database as a nullable varchar(max) column by default. Maybe we want to restrict the length of that property. Or maybe we use lengthy names for properties in our POCO classes, but we want shorter equivalents in the table. That’s where the Code First Fluent API comes into play.

With Code First we create a descendant of the DbContext class with a DbSet property for each POCO entity. The first time this DbContext gets instantiated it will create the database for us (if it’s not already there). During that process the OnModelCreating method gets called and that is the spot where we may provide different configuration using the Code First Fluent API.

In the BomContext class below we override the OnModelCreating method and specify the maximum length of the ProjectName property of the BillOfMaterials entity. We also tell Entity Framework to make it required and rename this property to ‘Project’ in the database.

using System.Data.Entity; using CodeFirstPocos; namespace CodeFirstData { publicclassBomContext : DbContext  { publicDbSet<BillOfMaterials> BillOfMaterialsSet { get; set; } publicDbSet<AssemblyItem> AssemblyItems { get; set; } protectedoverridevoid OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<BillOfMaterials>() .Property(p => p.ProjectName) .HasMaxLength(24) .IsRequired() .HasColumnName("Project"); } } }

We create a simple test against SQL Express to see how Entity Framework creates our tables. We create one fictive Bill of Materials with three assembly items.

using System; using System.Collections.Generic; using CodeFirstData; using CodeFirstPocos; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CodeFirstTests { [TestClass] publicclassBomTests  { [TestMethod] publicvoid FirstCallToBomContextShouldCreateDatabase() { var bom = newBillOfMaterials  { CreationDate = newDateTime(2012, 5, 18), ProjectName = "The Code Project", AssemblyItems = newList<AssemblyItem> { newAssemblyItem  { PartNumber = "A1284-e", Description = "Case", Price = 199m, Quantity = 1, }, newAssemblyItem  { PartNumber = "124-448", Description = "Motherboard", Price = 398m, Quantity = 1, }, newAssemblyItem  { PartNumber = "i7-2600K", Description = "Intel i7 CPU", Price = 720m, Quantity = 1, }, } }; var context = newBomContext(); context.BillOfMaterialsSet.Add(bom); context.SaveChanges(); } } }

We take a look at the database after we run the test method. Entity Framework created the database for us called CodeFirstData.BomContext. In the BillOfMaterials table we now have the required column ‘Project’ allowing a maximum length of 24 characters.

Entity Framework Code First Bom Context

This guy in the video explains how to do a cheating engine for PC games really good. I recommend you to take a look at it;)

Hello world!

Posted: April 14, 2012 in A fresh start...

Hi everyone. Welcome to my new blog. I thought that HelloWorld is an appropriate title for a Computer Engineering student so here I am.  I’m gonna be sharing about educational stuff, my experiences, and ofcourse about music news because music is an essential thing for life right? 🙂