find a location for property in a new city

Wednesday 27 October 2010

Set an identity seed back after delete in SQL

When deleting from a table in SQL the seed of the identity column or primary key will not be forgotten. It would be nice to truncate the selected rows(?). This is a little annoying but there is a way around it.

If you want to quickly remove all rows from a table and begin the table from scratch TRUNCATE is the best approach. It is quicker too since it logs nothing (so beware).

TRUNCATE is only for destroying all data in a table though. What if you want to remove only the last few rows and then begin the seeding off from the last primary key?

Use CHECKIDENT to reseed

You can delete the rows you want and after you can reset the SEED of the table to what you desire using the following line:

Note: the 10 is a seed so you would set this to be the current maximum identity. So if you reseed with 10 the next insert will yield 11 as the primary key.

Follow britishdev on Twitter

Thursday 14 October 2010

How to set up the Repository pattern using Unity

Recently moved from Spring.NET to Unity 2.0 over here in the London based We were already using the Repository pattern and Unit of Work pattern with Entity Framework. Now all there is to do is scrap Spring.NET and bring in Unity. Easy right?

I actually found it very difficult to plagiarise this work off some documentation so I thought I'd help the cause by spilling how I managed it. I'm not going to talk about how to set up the Repository pattern, Unit of Work pattern, or Unity in general. Just how to make a delicious combination of all three.

In my inventory of classes to wire up I have:
  • ContentEntities - this is my ObjectContext
  • UnitOfWork - this is my implementation of IUnitOfWork (Google that for guidance)
  • EntityRepostory<T> - this is my implementation of IRepository<T> where T:class (again for guidance on this pattern Google it)
  • ContentService - This has a dependency property for the ContentRepository of type IRepository<Content>

To wire these all up for the RepositoryPattern to be correctly implemented so that the UnitOfWork is reused correctly I used the following code in my Application_Start() method:
//new container
var container = new UnityContainer();

//set up the unit of works to use the singleton pattern (AKA ContainerControlledLifetimeManager)
container.RegisterType<IUnitOfWork, UnitOfWork>("contentUow", new ContainerControlledLifetimeManager(), new InjectionConstructor(new SocialEntities()));
//get the instance (i have named it to disambiguate in the event of having multiple UOWs (quite likely))
var contentUow = container.Resolve<IUnitOfWork>("contentUow");

//now we have the reference start up a new container
container = new UnityContainer()
//content repository (any other repositories within the model can use this same contentUow instance)
.RegisterType<IRepository<Content>, EntityRepository<Content>>(new InjectionConstructor(contentUow))

Note I used the ContainerControlledLifetimeManager for the UnitOfWork. There are more for you to choose from, I decided from the description that this is the best for me. Check here for a full list of LifetimeManagers.

This is interesting reading if you are interested in what happens when you ignore the UnitOfWork part of the Repository pattern. Bad things!

Follow britishdev on Twitter

Don't fuck with the repository or unit of work pattern

I am one for not taking patterns as gospel so I have a tendency to use the bits I want and discard the bits I don't. Today I discovered I don't necessarily know best.

At I have just started using Unity 2.0 to replace Spring.NET as our dependency container. This has meant that I have had to reimplement some of the wiring of the dependencies. This includes our implementation of the Repository pattern for use with Entity Framework.

Now, my problem with the Repository pattern is that I have always struggled to see the point in the UnitOfWork part of the pattern. Just extra typing for me with no/little benefit. I decided that (as with most things I don't understand) they should prove their worth. Reading didn't help their cause so I went for the more drastic way of not using and see what goes wrong. Well, nothing did! So there it is I will never use the Unit of Work pattern again.

Until today that is.

Here is a snippet from my EntityRepository:
public ObjectContext Context { get; private set; }
//in an orthodox implementation this would accept a UnitOfWork instead of an ObjectContext
public EntityRepository(ObjectContext context)
    Context = new UnitOfWork(context).Context;

And here is the wiring in my Unity configuration:
var container = new UnityContainer();

//content repositories
container.RegisterType<IRepository<LoveContent>, EntityRepository<LoveContent>>(new InjectionConstructor(new ContentEntities()))

Something just wasn't right. I first noticed it when I created a new item and added it to the repository and then tried to delete it. Well deleting the item wasn't the problem, it was the repository knowing what had happened. I deleted the item and it was gone, gone from the database, gone from the data returned from the database but not gone from the Repository when it came to display the results on the page.

So, I figured this was something to do with my bastardisation of the Repository and Unit of Work pattern. I configured Unity correctly to implement this pattern and lo it worked as expected.

So I won!

Well, sort of. I know I thought best, it turned out I didn't, then I came crawling back to convention. But I think I am better off for it. If I had just done what all of the blogs had told me I wouldn't have understood why I was doing it.

Being a curious chap I like to understand everything I use and this has helped me. Hopefully it will help you too if you are scratching your head at the Unit of Work pattern.

But seriously, how do you solve it?

If you are/were struggling with this I have written another blog post that will tell you how to set up the repository pattern with Unit of Work using Unity 2.0.

Follow britishdev on Twitter

Wednesday 6 October 2010

ASP.NET Authentication cookie not persisting across servers and subdomains

Recently some internal users have started complaining about being sporadically logged out and having to log in again when accessing a different server or different sub domain. It seems like the ASP.NET security cookie is not being persisted between live production servers and development servers.

I noticed a pattern to the seemingly spurious logging out and having to log in again:

  • Log in on live or if you are already logged in. Fine.
  • Log in on your development machine. (Oh that's weird, I thought I was logged in... but okay maybe I wasn't). Fine.
  • Refresh your page on the live site and I need to login again.

Why won't my cookie persist?! Why am I being logged out?

This has started happening since the recent ASP.NET security fix was put on our servers. Apparently it is something to do with changing the necessary authentication cookie. I guess in case you were already exploited before the security fix went out. Anyway, if you are swapping between non-patched development servers and patched production servers you're cookie will NOT persist and you will be asked to log in again if authentication or authorization is demanded by your page.

So either:
  1. Install the patch on all servers as per the ASP.NET team's advice
  2. OR be content with the fact that your customers won't have the problem. (Unless you have both patched and non-patched servers in your web farm)

Follow britishdev on Twitter

Friday 1 October 2010

ASP.NET MVC IsAjaxRequest() not recognising request from jQuery $.ajax()

If you are finding that an AJAX request from, say, a piece of jQuery AJAX code such as $.ajax() $.get() or $.post() or you own custom AJAX code (you legend) is not registering as an AJAX request when using the IsAjaxRequest() then the problem is probably to do with X-Requested-With.

I used .NET Reflector to have a look at how IsAjaxRequest() works and it is something like this:
return ((request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest")));

So that means you need to have a header of "X-Requested-With" set to "XMLHttpRequest" which is usually the case when you are using AJAX libraries like ASP.NET's or jQuery's. You can see if this is the case using Fiddler.

However, interestingly you can also set this as either part of your form POST or even a GET querystring! Such as (case sensitive). This will also make IsAjaxRequest() return true.

Follow britishdev on Twitter