Chris Risner . Com

Veritas – Site Configuration – Part 7

Posted on: 7/22/2010 11:42:00 PM by

Veritas To continue with the scheme of the last entry, we’re going to again depart from our originally planned series.  Today we’re going to talk about our Blog Configuration.  As we discussed in the initial database design entry, our blog config database table primarily consists of an XML column.  Instead of creating a column for each setting we might want, we’ll store it all dynamically as XML.  Furthermore, there is no way I’m going to think of all the config settings we’ll want while I’m writing this.  Rather then trying to update this entry every time I think of something new, we’ll just outline what we’re going to do in our BlogConfig object so when we decide to add something else down the road, you’ll understand.  First we’ll add a BlogConfig class to the Models folder in our DataLayer.  This will be a partial class and will expand on our already created BlogConfig object (it was created as part of our Entity Framework EDMX):

   1:  namespace Veritas.DataLayer.Models
   2:  {
   3:      public partial class BlogConfig
   4:      {
   5:          
   6:      }
   7:  }

We’re probably going to end up with dozens of settings (at least) but we’re only going to handle three of them for now.  We’ll add a boolean that will control if comments are allowed on the site, a string to contain the “about” information of the blog, and an int to store the number of posts:

   1:  namespace Veritas.DataLayer.Models
   2:  {
   3:      public partial class BlogConfig
   4:      {
   5:          public bool AllowComments { get; set; }
   6:          public string BlogAbout { get; set; }        
   7:          public int PostCount { get; set; }
   8:      }
   9:  }

Now, since we’re not making columns for any of these, we’re going to need to load them from the xml column whenever we load our BlogConfig object and pull them into the xml when we save it.  Lastly we’ll add methods to load our xml from the properties and to load the properties from the xml:

   1:  public void LoadConfigFromXml()
   2:  {
   3:      XmlDocument doc = new XmlDocument();
   4:      doc.LoadXml(this.ConfigXml);            
   5:      if (doc.DocumentElement["AllowComments"] != null)
   6:          this.AllowComments = Convert.ToBoolean(doc.DocumentElement["AllowComments"].InnerText);
   7:      if (doc.DocumentElement["BlogAbout"] != null)
   8:          this.BlogAbout = doc.DocumentElement["BlogAbout"].InnerText;
   9:      if (doc.DocumentElement["PostCount"] != null)
  10:          this.PostCount = Convert.ToInt32(doc.DocumentElement["PostCount"].InnerText);
  11:  }
  12:   
  13:  public void BuildXmlFromConfig()
  14:  {
  15:      XElement blogConfigXml = 
  16:          new XElement("BlogConfig",
  17:              new XElement("AllowComments", this.AllowComments),
  18:              new XElement("BlogAbout", this.BlogAbout),
  19:              new XElement("PostCount", this.PostCount)
  20:              );            
  21:      this.ConfigXml = blogConfigXml.ToString().Replace("\r\n  ", "").Replace("\r\n", "");            
  22:  }

As we add (many) more config settings, we’ll have to alter these methods but you get the basic idea of how we’re storing and reading our configuration xml.  I added in unit tests for both of these methods as well.  You can get the latest here.

 
Categories: .Net, MVC, Programming, Veritas, Web
Bookmark and Share
First Article

Veritas – Data Access with Entity Framework 4.0 – Part 6

Posted on: 7/12/2010 10:51:00 PM by

Veritas If you were paying attention, you know that part 6 in our Veritas Blog Engine series was supposed to be about Error Logging.  Well, we’re going to go a bit out of order and do Data Access first.  The reason for this is that we’re going to use a lot of our data access methods in the sections I originally thought we’d write first.  I ran into quite a bit of trouble the last time I played with Entity Framework when it was 3.5.  Thankfully, they made quite a few improvements with 4.0 so we’re going to give it another try.

Veritas EDMX First things first, if you haven’t already done so, add a Models folder to your DataLayer project.  All of our database objects and any extensions will sit in this folder and namespace.  After that, we’ll add a “ADO .Net Entity Data Model” which is the Entity Framework file that we generate all of our database classes and connections in.  Like every past version of Microsoft’s “This is the way to do database access”, we get to generate the majority of our code straight from the database.  Included in this is the same functionality we had with the Linq2Sql generator for pluralizing / singularizing object names (though now it’s optional) as well as including foreign key columns in the models (which will hopefully fix the FK problems that plagued 3.5 (seriously it was like they designed it to be hard to have foreign key constraints).  Once we’ve selected all of our tables and tell it to generate we’re given an EDMX file and presented with a fantastic database diagram view.  Now, technically, we’ve generated our database access.  We could call it a day.  However, since we’re using the repository pattern and we want all of our data access methods to be in one place, we’ll go ahead and create all of those methods in the repository class we made in the last entry.

Before we can add any data access methods we need to add a instance of our Entities object (EDMX) to our repository like so:

private VeritasBlogDBV3Entities db = new VeritasBlogDBV3Entities();

So inside of our repository class we’ll use db. to do all our database interaction.  The first method we’ll create is our Save method.  This method handles saving any inserts, updates, and deletes after they’re done:

   1:  /// <summary>
   2:  /// Saves all DB changes and then accepts the changes.
   3:  /// </summary>
   4:  public void Save()
   5:  {
   6:      db.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
   7:  }

We’ll call this method after doing any DB changes (or after any group of DB changes if we’re not doing them individually).  After this, we’ll add entries (separated out into regions) for each of our objects for adding and deleting.  So for example, here are the methods for the BlogConfig object:

   1:  #region BlogConfig
   2:   
   3:  public void Add(BlogConfig blogConfig)
   4:  {
   5:      db.BlogConfigs.AddObject(blogConfig);
   6:  }
   7:   
   8:  public void Delete(BlogConfig blogConfig)
   9:  {
  10:      db.BlogConfigs.DeleteObject(blogConfig);
  11:  }
  12:   
  13:  #endregion

These are pretty simple methods and just handle telling our entity object that we want to insert or delete something.  The Save method still has to be called after each of these.  A quick note on the delete methods:  we may or may not end up ever using them.  Typically I don’t like deleting data as much as “marking it inactive” for historical purposes.  We’re going to write some unit tests in a second so we’re going to write a method to pull all our BlogConfigs from the DB.  We won’t end up using this anywhere but in our unit test.

   1:  public IEnumerable<BlogConfig> GetAllBlogConfigs()
   2:  {
   3:       return db.BlogConfigs;
   4:  }

Now, before we can actually write some unit tests, we need to implement the StartTransaction and RollbackTransaction methods we made in the last entry.  These methods will be called before and after any unit tests so we’re not actually putting anything in the database. 

   1:  public DbTransaction Transaction { get; set; }
   2:  /// <summary>
   3:  /// Will create a new transation.  
   4:  /// </summary>
   5:  public void StartTransaction()
   6:  {
   7:      db.Connection.Open();
   8:      DbTransaction trans = db.Connection.BeginTransaction();
   9:      this.Transaction = trans;
  10:  }
  11:   
  12:  /// <summary>
  13:  /// Rolls back a transation. 
  14:  /// </summary>
  15:  public void RollbackTransaction()
  16:  {
  17:      this.Transaction.Rollback();
  18:  }

Now that these methods are implemented, we just need to make a base test class to handle calling these.

   1:  [TestClass()]
   2:  public class TestBase
   3:  {
   4:      public VeritasRepository repo = VeritasRepository.GetInstance();
   5:   
   6:      //Use TestInitialize to run code before running each test
   7:      [TestInitialize()]
   8:      public void MyTestInitialize()
   9:      {
  10:          repo.StartTransaction();
  11:          repo.Save();
  12:      }
  13:   
  14:      //Use TestCleanup to run code after each test has run
  15:      [TestCleanup()]
  16:      public void MyTestCleanup()
  17:      {
  18:          repo.RollbackTransaction();
  19:      }
  20:  }

Now we have everything we need to actually write a unit test to test adding a new BlogConfig:

   1:  /// <summary>
   2:  ///A test for Add BlogConfig
   3:  ///</summary>
   4:  [TestMethod()]
   5:  public void AddBlogConfigTest()
   6:  {
   7:      BlogConfig blogConfig = new BlogConfig()
   8:      {
   9:          Host = "test.com",
  10:          LastUpdateDate = DateTime.Now,
  11:          CreateDate = DateTime.Now,
  12:          ConfigXml = "<BlogConfig></BlogConfig>"
  13:      };
  14:      repo.Add(blogConfig);
  15:      repo.Save();
  16:      //Check the db for changes
  17:      var configs = repo.GetAllBlogConfigs().ToArray();
  18:      var testConfig = configs.Where(p => p.Host == "test.com").SingleOrDefault();
  19:      Assert.IsNotNull(testConfig);            
  20:  }

Since this class implements our TestBase class, before this unit test is called, we’re getting a new instance of VeritasRepository and calling StartTransaction on it.  When the test is done, it will call the RollbackTransaction method on the repo.  If everything goes well, it will create a new config object, insert it into the database, save that change, pull it back, and make sure it comes back from the DB.  Since most of our tests (such as our DeleteConfig test) will rely on having a BlogConfig and a BlogUser (if not many more things) to already be in the DB, we’ll eventually insert all of these in the test initialize but for now, we can add all of our Add / Delete methods and create tests for them.  Since we need to be able to pull records back from the database to make sure our tests are working, we’ll need to add more methods like the GetAllBlogConfigs seen above.  There are a lot of methods that we’ll in our repository that we’re not going to list here so if you want to see them all, download the files and check out the repo.  As of now, we’ve got what should be all the data access methods we’ll need as well as the unit tests for all of them.  As always, you can download the latest here.

Categories: .Net, MVC, Programming, SQL, Veritas, Web
Bookmark and Share
First Article