A generic implementation of the Repository Pattern for LINQ to SQL
Back in 2008 I started working on a project at home which never really went anywhere. It’s still lingering around in the back of my mind but I just gotta find the time to work on it. At the time I figured I could use the project as a learning experience.
It was going to be an ASP.NET site using .NET 3.5 and SQL Server 2008, all tools which I use everyday and know pretty well. To get something more out of it, I chose to use LINQ to SQL as an ‘ORM’, something I hadn’t used before. Then one of my work colleagues recommended that I read up on Domain Driven Design and pointed me in the direction of the ‘Repository Pattern’, so off I went!
The Repository Pattern
According to Microsoft, a repository should be used to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. In essence, the repository acts as a mediator between the data source layer and the business layers of the application. It serves several purposes – it retrieves data from data source, maps it to business entities and persists any changes back to the data source. Sounds pretty useful, doesn’t it?
My generic repository class
After setting up the basics and creating a few tables in my database, I started off on my quest to use the Repository Pattern. I started implementing strongly-typed Repository classes for each table in my database and quickly came to the conclusion that this didn’t feel right… I already had half a dozen tables in my database and all my Repository classes were almost identical. It seemed what I actually needed was a generic repository class!
I used my mega-searching-skills on the Google but couldn’t find anyone who had written a generic repository class for LINQ to SQL that returned interfaces of entities at the time. So I got my hands dirty and wrote my own…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | using System; using System.Collections.Generic; using System.Linq; using MyProject.DataContexts; namespace MyProject.Repositories { public class Repository<T, K> : IRepository<T> where T : IEntity where K : class, T { protected MyProjectDataContext DataContext; public Repository() { DataContext = new MyProjectDataContext(); } public List<T> All() { return GetTable.Cast<T>().ToList(); } public virtual T CreateInstance() { return Activator.CreateInstance<K>(); } public void Save() { try { DataContext.SubmitChanges(); } catch (Exception ex) { throw ex; } } public virtual T Save(T entity) { try { if (entity.Id == 0) DataContext.GetTable<K>().InsertOnSubmit((K)entity); DataContext.SubmitChanges(); } catch (Exception ex) { throw ex; } return entity; } public virtual T Retrieve(int id) { return GetTable.Cast<T>().Single(e => e.Id == id); } public virtual T Single(Func<T, bool> exp) { return GetTable.Cast<T>().Single(exp); } public T First(Func<T, bool> exp) { return GetTable.Cast<T>().First(exp); } public virtual void Delete(T entity) { try { GetTable.DeleteOnSubmit((K)entity); } catch (Exception ex) { throw ex; } } public virtual List<T> Find(Func<T, bool> exp) { return GetTable.Cast<T>().Where(exp).ToList(); } public virtual List<T> Find(Func<T, bool> exp, Func<T, IComparable> order, bool desc) { if (desc) return GetTable.Cast<T>().Where(exp).OrderByDescending(order).ToList(); else return GetTable.Cast<T>().Where(exp).OrderBy(order).ToList(); } private System.Data.Linq.Table<K> GetTable { get { return DataContext.GetTable<K>(); } } } } |
That’s all! One generic repository class for all my tables… I love it!
Using the repository
As it’s supposed to, the repository pattern makes it really easy to access your data in a standardized way. Below is a snippet out of my UserService class…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | namespace MyProject.Services { public class UserService { Repository<IUser, User> userRepo; public UserService() { userRepo = new Repository<IUser, User>(); } public IUser CreateUserInstance() { return userRepo.CreateInstance(); } public IUser InsertNewUser(IUser user) { try { user = userRepo.Save(user); } catch (Exception ex) { // Logging } return user; } ... } |
And so on and so forth…
Conclusion
I’m not saying that LINQ to SQL is awesome, nor am I saying that the Repository Pattern is the way to go. This was just a cool piece of code I wrote a long time ago which I thought I might blog about :)
Read MoreCLR Versioning and Side-by-Side Execution – .NET 2.0 to .NET 3.5 and .NET 3.5 to .NET 4.0
The other day at work I spent some time investigating an OutOfMemoryException being thrown by third-party component being used in a .NET 3.5 application. After a closer look and weighing up some options on how to fix it, we realized that the problem went away if the application was recompiled in .NET 4. This ended up causing some discussion among the team – how could simply recompiling the application that the .NET 3.5 third-party library was being used in fix the problem in the library itself?
One of our team members was convinced that if the third-party library had been built using .NET 3.5 and it was then used in an application that targeted .NET 4, that the third-party library would continue to run under the context of .NET 3.5. To that end, he was sure that recompiling the application in .NET 4 couldn’t have actually solved the problem.
Of course this triggered a Google search frenzy which lead us to this article on msdn:
Excerpt #1:
Add-in Problems:To give all add-ins the best chance of working, we always choose the latest runtime for managed COM activation. Even if you only have older add-ins installed, there is no way for us to know that when that add-in gets activated, so the latest runtime still gets loaded.
An unfortunate side effect of this activation policy is that when a user installs a new application with a new version of the runtime, completely unrelated applications that use managed COM add-ins, built against older versions, suddenly start running on a newer runtime and can fail.
For the .NET Framework 3.0 and 3.5, we solved this problem through an extremely strict policy: each release was additive and only added new assemblies to the prior version with the same runtime underneath. This prevented any compatibility issues when installing them on a machine running the .NET Framework 2.0.
This means that when you are running an app on the .NET Framework 3.5, you are really running it on the 2.0 runtime, with a few extra assemblies on top of it.
What the above implies is that the update from .NET 2.0 to .NET 3.5 was only ‘additive’, that is, Microsoft added some new functionality (dlls) but kept existing functionality the same for backwards compatibility. Actually, if you take a look in the v3.5 folder under Microsoft.NET in the Windows directory, you’ll see that there are a handful of new dlls but no new core libraries to replace the .NET 2.0 versions.
Therefore, if the application we were dealing with had been using a .NET 2.0 third-party component and we were rebuilding the whole application in .NET 3.5, all core types would still be exactly the same under the covers and our colleague would have indeed been correct in his conclusion that rebuilding the application couldn’t have solved the problem.
However, this doesn’t seem to be the case from .NET 3.5 to .NET 4… if one reads on:
Excerpt #2:
Add-in Problems:This means that when you are running an app on the .NET Framework 3.5, you are really running it on the 2.0 runtime, with a few extra assemblies on top of it. However, it also means that we couldn’t innovate in the .NET 2.0 assemblies, which include key functionalities, such as the garbage collector, just in time (JIT) and base class libraries.
With the .NET Framework 4 we have implemented an approach that allows high compatibility, including never breaking existing add-ins, and also lets us innovate in the core. We can now run both .NET 2.0 and .NET 4 add-ins in the same process, at the same time. We call this approach In-Process Side-by-Side, or In-Proc SxS.
So the .NET Framework 4 allowed Microsoft to ‘innovate in the core’ – in other words, there are new versions of the core libraries. Fair enough, Microsoft do need to be able to make improvements to existing code after all, otherwise we’d still be using .NET 1.0 at the core! But hang on, doesn’t this mean that if you re-build your application in .NET 4.0 that you’ll have to regression test the whole lot because who knows what core type implementations may have changed under the covers? Well no, not really, because of this new approach that Microsoft have adopted called In-Process Side-by-Side execution!
This all sounds great, until you read…
What Does In-Process Side-by-Side Mean to You? > Library Developers and Consumers:In-Proc SxS does not solve the compatibility problems faced by library developers. Any libraries directly loaded by an application—either via a direct reference or an Assembly.Load*—will continue to load directly into the runtime and AppDomain of the application loading it. This means that if an application is recompiled to run against the .NET Framework 4 runtime and still has dependent assemblies built against .NET 2.0, those dependents will load on the .NET 4 runtime as well. Therefore, we still recommend testing your libraries against all version of the framework you wish to support.
Yup, that’s right. If you’re either developing or consuming a library (and really, what developer isn’t doing at least one of those two?) and you decide to upgrade your application to .NET 4, Microsoft actually recommend that you test, test, test!
This tweaked my interest – how different could these new core libraries really be?. I installed dotPeek and opened up both the .NET 2.0 and .NET 4.0 mscorlib.dll assemblies. I drilled down to the Dictionary class and found that there were in fact quite a few, albeit minor, differences between the two implementations!

Anyway, the moral of the story is – upgrading from .NET 2.0 to .NET 3.5 really isn’t a big deal – it’s always wise to do some regression testing, just in case, but you really shouldn’t find many issues with this migration. Upgrading from .NET 2.0 or .NET 3.5 to .NET 4.0 is a different story though. If you’re lucky, In-Proc SxS will help you with backwards compatibility, but if you’re developing or consuming libraries then you’d better have some regression test plans up your sleeve for this migration.
So at the end of the day, it seems like our third-party component bug could well be resolved by rebuilding the whole application in .NET 4 – who would’ve thought!
Read MoreHow to make a text string fit your labels in .NET
In my chosen career, I solve problems everyday. Sometimes the problems I’m given are small and simple to solve, and sometimes they are most definitely not. That, I can deal with. What annoys me is when a problem seems like it should only take five or so minutes to solve and yet somehow, it takes you all day. It’s not that you’re bad at what you do, it’s just that the thing you’re trying to do wasn’t quite as simple as you or anyone else had thought it would be. Or perhaps the framework you’re working with has some nasty little quirks that you weren’t aware of. Or perhaps the thing you’re trying to do just hasn’t been done before, or at least hasn’t been well documented. Whatever the reason, spending all day on a “simple problem” isn’t good for your sanity and makes you feel like you ought to be doing COMP101 all over again.
One such problem that I’ve come across more than once in the last few weeks is how to make a text string fit inside a label or other similar control. If the string is too long to fit, the end should be truncated and replaced by an ellipsis. Sounds pretty straightforward eh? Nope, think again.
After coming up with a few complicated solutions including but not limited to iterating through every character in the string and measuring the length of the string (yes, highly inefficient, I know!), I finally found a solution which seems to do the trick. I feel this amazing solution needs to be shared with everyone so here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | private string textToDraw = "Hello, how are you? Why does this string not fit in the label that I have drawn? Maybe it is because it is too long?"; public Form1() { InitializeComponent(); label1.Text = ShortenString(textToDraw, this.Width - 10, label1.Font); } public string ShortenString(string myString, int width, Font font) { string result = string.Copy(myString); TextRenderer.MeasureText(result, font, new Size(width, 0), TextFormatFlags.EndEllipsis | TextFormatFlags.ModifyString); return result; } private void Form1_ResizeEnd(object sender, EventArgs e) { // Set the width to something - I've just set it to the width of the form - 10 to allow for the ellipsis but // I guess this would need to depend on which control the label is to be displayed inside of int width = this.Width - 10; label1.Text = ShortenString(textToDraw, width, label1.Font); } |
The trick to solving this problem was to use the TextRenderer class and calling its MeasureText function. MeasureText doesn’t seem like the most obvious function to use but it seems to work.
Note that this example is for a C# winforms application. The same could be done for a web application although you’d have to use JavaScript to re-calculate the string when the browser or element is resized.
Has anyone else ever had to solve this particular problem? If so, I’m interested to hear how you did it!
Read MoreHow to populate a drop down list from an XML file in .NET
I know this is not rocket science but it’s actually something I’d never had to do until recently. Normally I populate my drop down lists (and repeaters, etc etc) using data from databases, not XML.
However, fear not. Using XML as a datasource in .NET is super easy. Here is one way to do it:
1 2 3 4 5 6 7 8 | XmlDataSource source = new XmlDataSource(); source.DataFile = Server.MapPath("Values.xml"); source.XPath = "ParentElement/ValueList/ValueItem"; myDropDownList.DataSource = source; myDropDownList.DataTextField = "Text"; myDropDownList.DataValueField = "Value"; myDropDownList.DataBind(); |
And your xml file, Values.xml, may look something like:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <ParentElement> <ValueList> <ValueItem Text="Item 1" Value="1" /> <ValueItem Text="Item 2" Value="2" /> </ValueList> </ParentElement> |
Happy coding!
Read MoreHow to develop secure .NET applications using Server SSL Certificates and Client Certificates – PART 4
The following article is part 4 and therefore the last in a 4 part series of articles about developing .NET applications using SSL. Part 1 in this series can be found here, part 2 can be found here and part 3 can be found here.
How to set up a web application to automatically redirect to HTTPS if accessed via HTTP when SSL is required
SSL can be “required” at the site level, folder level or even file level.
If any file that has SSL set to “required” is requested via HTTP, HTTP Error 403;4 “Forbidden” will be returned automatically by IIS. As far as I can tell, there is no simply way to tell IIS to re-direct to the same page via HTTPS. This effect can be achieved in two different ways and if “defence in depth” is the preferred approach then both solutions can be implemented together. Note that both solutions require custom code to be written however.
Redirect with IIS and code:
- Create a new Web Form (aspx) in your Web Application called RedirectToSSL (or similar).
- In the Page_Load event handler, insert the following code:
1 2 3 4 5 6 7 8
string redirectUrl = HttpContext.Current.Request.Url.Query; redirectUrl = redirectUrl.Substring((redirectUrl.LastIndexOf(';')+1) , redirectUrl.Length - (redirectUrl.LastIndexOf(';')+1)); System.UriBuilder secureUrlBuilder = new System.UriBuilder(redirectUrl); secureUrlBuilder.Scheme = System.Uri.UriSchemeHttps; secureUrlBuilder.Port = -1; // Use default port HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString(), true);
- The aspx needs to be at least 512 bytes, otherwise IIS won’t redirect to it. So make sure you don’t delete everything out of it, it should never get displayed anyway.
- In IIS, right-click your Web Site and go to Properties > Custom Errors.
- Select the “403;4” HTTP error in the list HTTP errors and click the Edit Properties button.
- Select “URL” from the Message type drop-down list and enter “/RedirectToSSL.aspx” into the URL textbox, as shown below.
- Press OK twice to close the dialogs down.
- Restart the website and/or reset IIS to ensure all settings have been applied.
- Open Internet Explorer and go to:
https://<servername>/<securedpage>and verify that you are automatically redirected to the https version of the same page.
Redirect with code alone:
- Insert the following code at the beginning of the Page_Load event handler of every page that needs to be secured:
1 2 3 4 5 6 7 8 9
// Make sure the request has come through SSL (ie that HTTPS has been used) if (!HttpContext.Current.Request.IsSecureConnection) { System.Uri currentUrl = HttpContext.Current.Request.Url; System.UriBuilder secureUrlBuilder = new System.UriBuilder(currentUrl); secureUrlBuilder.Scheme = System.Uri.UriSchemeHttps; secureUrlBuilder.Port = -1; HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString(), true); }





















