Amending a SQL table without getting “Saving changes is not permitted”

When I come to amend a table in SQL Server all is fine until you come to save the new structure you end up getting the following message:

“Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.”

This is happening because ““Prevent saving changes that require table re-creation” option is enabled.  You can disable this by going into Tools -> Options -> Designers-> Uncheck “Prevent saving changes that require table re-creation”, this is either in Visual Studio or SQL Management Studio.

Now you can apply your new changes to the table

ILinqRepository at last

LINQ to SQL is a very easy to use and very powerful tool for many things when dealing with SQL.  But the time has come that I need to wrap it all up and use an iRepository pattern.  I’ve Googled for the IRepository and found a few useful references but none that will complete my picture.  How ever I did get some good ideas when looking around othe rimplementation of the IRepository pattern that others had implmented.

So why whould I use the iRepository when Linq to Sql and so good?

There are a few time, and this keeps happening that when you come to save an object you forget to use the SubmitChanges(), and what happens if there is a conflict.  You can handle conflicts in Linq to Sql but you need to add extra code for each time you SubmitChanges().  The iRepository I am going to use will wrap all this up and sort it out for us in to one place.  There are a number of reasons, but mainly the iRepository will provide a layer that I can use to hold all these methods in one place.

First the pattern will use Generics.  So this means that you can passing in any Linq to Sql object and it will perform a task.

So here is the Interface I’ll be using:

public interface IRepository<T> where T : class
    {
        /// <summary>
        /// Return all instances of type T.
        /// </summary>
        /// <returns></returns>
        IEnumerable<T> All();

        /// <summary>
        /// Return all instances of type T that match the expression exp.
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        IEnumerable<T> FindAll(Func<T, bool> exp);

        /// <summary>Returns the single entity matching the expression. Throws an exception if there is not exactly one such entity.</summary>
        /// <param name="exp"></param><returns></returns>
        T Single(Func<T, bool> exp);

        /// <summary>Returns the first element satisfying the condition.</summary>
        /// <param name="exp"></param><returns></returns>
        T First(Func<T, bool> exp);

        /// <summary>
        /// Mark an entity to be deleted when the context is saved.
        /// </summary>
        /// <param name="entity"></param>
        void MarkForDeletion(T entity);

        /// <summary>
        /// Create a new instance of type T.
        /// </summary>
        /// <returns></returns>
        T CreateInstance();

        /// <summary>Persist the data context.</summary>
        void SaveAll();

        long Count(Expression<Func<T, bool>> criteria);

        void Save(T entity);
    }

So that is the easy part, next is the concreate implementation of the interface

public class Repository<T> : IRepository<T>
        where T : class
    {
        protected DataContext DataContext;

        /// <summary>
        /// Return all instances of type T.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> All()
        {
            return GetTable;
        }

        /// <summary>
        /// Return all instances of type T that match the expression exp.
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public IEnumerable<T> FindAll(Func<T, bool> exp)
        {
            return GetTable.Where(exp);
        }

        /// <summary>See _vertexRepository.</summary>
        /// <param name="exp"></param><returns></returns>
        public T Single(Func<T, bool> exp)
        {
            return GetTable.SingleOrDefault(exp);
        }

        /// <summary>See _vertexRepository.</summary>
        /// <param name="exp"></param><returns></returns>
        public T First(Func<T, bool> exp)
        {
            return GetTable.First(exp);
        }

        /// <summary>See _vertexRepository.</summary>
        /// <param name="entity"></param>
        public virtual void MarkForDeletion(T entity)
        {
            DataContext.GetTable<T>().DeleteOnSubmit(entity);
        }

        /// <summary>
        /// Create a new instance of type T.
        /// </summary>
        /// <returns></returns>
        public virtual T CreateInstance()
        {
            var entity = Activator.CreateInstance<T>();
            GetTable.InsertOnSubmit(entity);
            return entity;
        }

        /// <summary>See _vertexRepository.</summary>
        public void SaveAll()
        {
            DataContext.SubmitChanges();
        }

        public long Count(Expression<Func<T, bool>> exp)
        {
            return GetTable.Where(exp).Count();
        }

        public void Save(T entity)
        {
            Save(new List<T> { entity });
            return;
        }

        public void Save(IEnumerable<T> entities)
        {
            var table = DataContext.GetTable<T>();

            foreach (var entity in entities)
            {
                var entity1 = entity;
                var dbEntity = (from p in table
                                where p == entity1
                                select p).FirstOrDefault();

                if (dbEntity == null)
                    table.InsertOnSubmit(entity);

                try
                {
                    //  Save the changes.
                    DataContext.SubmitChanges();
                }

                //  Detect concurrency conflicts.
                catch (ChangeConflictException)
                {
                    //  Resolve conflicts.
                    DataContext.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                }
            }
        }


        public Repository(DataContext dataContext)
        {
            DataContext = dataContext;
        }

        #region Properties

        private Table<T> GetTable
        {
            get { return DataContext.GetTable<T>(); }
        }

        #endregion
    }

That is it, job done.

You’ll notice that in the Save method it handles quite a lot from inserting a new record, updating an exisiting record if one is found with the addition of an object copier to make life easier and then will save the changes to the database and if there happens to be any conflicts it deals with them.

The Save() will accept either single objects or and IEnumerable of an object making things easier and simpler.

I would love any feed back on what I have produced

To compliment the IRepository concreate class I’ve built a set of tests using MS Test that create and use a test database:

IRepository.zip (4.11 kb)

IRepository.Tests.zip (47.25 kb)

Transaction scoping within Linq to Sql

If you are like me and us are using an IRepository for Linq to SQL you’ll probably at some point need to be able to generate a Transaction.

As the IRepository saves records as it goes and not on a SubmitChanges() we’re going to have to use the Microsoft TransactionScope Class, from the System.Transactions (in System.Transactions.dll), which makes a code block transactional.

Here it is:

using (var transaction = new TransactionScope())
{
    try
    {
	//Do something here

        transaction.Complete();
    }
    catch (Exception ex)
    {
        return;
    }
}

It is also worth having a look at Implementing an Implicit Transaction using Transaction Scoping for further information on what you can do.

After playing with this for a while I found that you some times get a MSDTC error, to fixes this take a look at:

Fix MSDTC (Microsoft Distributed transaction coordinator) by Pongsathon Keng

Google Mail not searching everywhere

Ever used Google Mail and the search when trying to find something and it can’t find it.  This is most probably because it is somewhere where the default search does not look in, like the BIN

To search everywhere you use in:anywhere

 

To see all the the possibilities of search in Google Mail check out:

http://support.google.com/mail/bin/answer.py?hl=en&answer=7190

Debugging and developing using Firefox

So I need to trap and look at the traffic going over HTTP and knowing that Firefox is the browser to use with all it different plugins it makes sense to download the latest version of Firefox and see what I can plug in to it.

What I like about Firefox is it is so easy to install plugins, just click restart Firefox and you’re done.

So what I need to do is trap, monitor and post HTTP requests using XML, so what plug in am I going to use?

First one is FireBug every good developer and bad developer, even hackers will be using FireBug.

Next I need to monitor what is happening and I found Tamper Data which monitors ongoing requests, and more importantly monitors and posts and gets in the back ground.

Okay now the more tricky issue of being about to POST or GET using HTTP, I settled for Poster a great plug in for all the REST requests and perfect for what I am looking for.

So to summerise here is a list of what I have downloaded:

So I’m off, if I get any problems with them I’mm report them directly on this blog with comments so if you see no comments all is good.

Back and working

So I’m back and ready to go, with just getting back from my travelling I’m back at work with only two days of my own time….!  Oh well I was looking at taking December off and start fully working in the new year.  Not that I took the first job that came along, far from it.  While on the beaches of Goa I made up a list of what work I will only accept it included working near where I live, work I have done before so as to make it easier to get back in to the working mode, something to do with the Olympics, and a small team on a new project.  And you guessed it this role fits all the criteria so a result 

Laughing

So time to keep my blog up to date and running again……!

 

Using MEF to provide PlugIns

MEF has now been released, a Plug-In Framework, for .Net 4.0

After reading up on CodePlex, I have generated a small application that provides a plug-in framework, see attached below.

http://mef.codeplex.com/wikipage?title=Guide&referringTitle=Overview

MEF.zip (70.88 kb)

I’ve also produced a .NET 3.5 version too:

MEF in 3.5.zip (427.41 kb)

Few MEF links:

Glenn Block

Nicholas Blumhardt

MEF on CodePlex

Channel 9 Silverlight 4 MEF Screencasts

MEF 101

XSD to Objects

I’ve been dealing with REST services within WCF, and one thing that has come to my attention is that the calling service or third party only has access to the REST interface and the XSD’s.

The XSD’s holds all the contract information, therefore if you need to generate a concreteclass you are going to have to translate the XSD to an object. 

I’ve have come across the XSD Object Generator frm Microsoft which appears to do the job.

XSDObjectGen.msi (667.00 kb)

Lifestyles of the Castle Windsor IoC Containers

It’s worth knowing how the Castle Windsor IoC work, by default it uses Singletons, where this will work for the most of the time, there are a lot more options available to you depending on your needs.  These lifestyles that are available in Castle Windsor are:

  • Singleton: components are instantiated once, and shared between all clients
  • Transient: components are created on demand
  • PerWebRequest: components are created once per Http Request
  • Thread: components have a unique instance per thread
  • Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them
  • Custom: allows you to specify a custom lifestyle… you’d have to specify a type that implements the ILifeStyleManager interface

For further information on this take a look at Castle Windsors Lifestyles or  Windsor and component instance lifetimes