find a location for property in a new city

Monday, 22 November 2010

Adding service reference gives the system cannot find the path specified error

I got an "The system cannot find the path specified." error box pop up when I tried to add a WCF web service reference to my web project. Problem with Service References?

Every time I tried to add the service reference to another WCF service I had set up in another web project I kept getting "The system cannot find the path specified." pop up in an alert box in Visual Studio 2010.

Solution

Somewhere along the line I had deleted the "Service References" folder from the project folder I was trying to add the reference to. It is simply solved by creating an new folder (in Windows Explorer) in the correct location called "Service References". Problem solved

Follow britishdev on Twitter

Thursday, 18 November 2010

How to host multiple secure sites in IIS

I have two sites: www.site1.com and www.site2.com. Both have pages that are served securely and so need a binding for https on port 443.

The problem is that only one site can be bound to the https protocol and if I disobey that rule I get strange behaviour such as requests for site1 actually serving the page from site1.

How to host multiple secure sites on your local IIS

First, you should know that sites resolve which site to bind to based on:
  • Host header e.g. local.www.site1.com
  • Port e.g. 443
  • IP adress

In this scenario I really just want to change the host headers of the two https bindings for the different sites but IIS won't let me. But I have ways of persuading it...

Step 1:
Navigate your way to C:\Windows\System32\inetsrv\config where you may or may not see applicationHost.config. This is a very mysterious file, it's there but not, sort of. I've found that it can be edited in NotePad (but nothing else(?))

Step 2:
Ctrl+F your way to "443:" and you should find your attempted 443 http bindings. In my case there are two and they both look like <binding protocol="https" bindingInformation="*:443:" /> (Oh yeah they are exactly the same, lets change that.

Step 3:
Change them to <binding protocol="https" bindingInformation="*:443:local.www.site1.com" /> and <binding protocol="https" bindingInformation="*:443:local.www.site2.com" /> respectively.

Job done

If you check in your IIS UI you will notice that you host headers have indeed been set and your sites should now be able to discriminate between the two.

Follow britishdev on Twitter

Static Membership helper class causing problems with MembershipProvider

I was having a problem where after a user changes their password using my custom MembershipProvider it was being updated in the database but didn't seem to be propagating to my application. So if they tried to log in they would be expected to provide their old password even though there was a new password in the database.

It is almost as if Membership didn't particularly care what has changed in the database and it kept on just doing its own thing.

Almost as if Membership is a static class... oh right it is

I thought the Membership was acting as if it was a singleton or something and never going through its constructor which sets a new UserService() to the UserService property (the service which ultimately gets the users' data). Maybe it is something to do with the fact that MEMBERSHIP IS A STATIC CLASS! Of course.

Membership was using my MembershipProvider but only ever instantiating it once due to its static nature so the UserService was keeping the old version even if the data had been edited. My fix was to make sure that the MembershipService property returned a new MembershipService() each time it is called.

So for context I changed this code in MyMembershipProvider:
public MyMembershipProvider()
{
    UserService = new UserService();
}

public UserService UserService { get; set; }

To this:
public MyMembershipProvider() {}

public UserService UserService
{
    get { return new UserService(); }
}

Follow britishdev on Twitter

Wednesday, 3 November 2010

Allow self closing tags in TinyMCE

I needed to make a tag self-close when using TinyMCE. It wouldn't allow it though, it kept opening them up again for me even after I edited them in HTML. How difficult can it be to add a tag to this allow self-closing tags list.

Answer: Not very. Even still though it took me a ridiculous amount of time to find out how to allow a new self closing tag. So I thought I'd share my discovery in case anyone else is struggling to find the answer.

I was trying to type in <source src="myVideo.m4v" /> but TinyMCE kept changing it to <source src="myVideo.m4v" ></source>.

Closed setting allows new self-closing tags

Turns out there is a little know closed setting you can set on tinyMCEs init method. I added my source tag to the list like so:
closed: /^(br|hr|input|meta|img|link|param|area|source)$/

Now any source tags are automatically self closing.

Notice I added a load more like img. The others are there by default in the core TinyMCE code so if I were to just put in source, the others (like img) would stop being self-closing. Not cool.

Follow britishdev on Twitter

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:
DBCC CHECKIDENT('myTable', RESEED, 10)

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 lovemoney.com. 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))
.RegisterInstance(typeof(ContentService));

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 lovemoney.com 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 www.example.com?x-requested-with=XMLHttpRequest (case sensitive). This will also make IsAjaxRequest() return true.

Follow britishdev on Twitter

Thursday, 23 September 2010

Get all month names from DateTime in C# programatically

I needed to have a drop down list of all the months but I don't want to be writing all of that out. So is there a way to list all the months programmatically in C#. Hell yeah there is

I knew there would be a way to do it and I knew it would be something to do with the CultureInfo of the session.

Here is a method I wrote to return a set of key values for each month:
public IEnumerable<KeyValuePair<int, string>> GetAllMonths()
{
 for (int i = 1; i <= 12; i++)
 {
  yield return new KeyValuePair<int, string>(i, DateTimeFormatInfo.CurrentInfo.GetMonthName(i));
 }
}

Just to demonstrate, I used it in my ASP.NET MVC app:
<%: Html.DropDownListFor(model => model.DobMonth, new SelectList(Model.GetAllMonths(), "Key", "Value", Model.DobMonth)) %>

Which outputs the following HTML:
<select id="DobMonth" name="DobMonth">
<option selected="selected" value="1">January</option> 
<option value="2">February</option> 
<option value="3">March</option> 
<option value="4">April</option> 
<option value="5">May</option> 
<option value="6">June</option> 
<option value="7">July</option> 
<option value="8">August</option> 
<option value="9">September</option> 
<option value="10">October</option> 
<option value="11">November</option> 
<option value="12">December</option> 
</select>

Follow britishdev on Twitter