Sorting UK Postcodes with C#

19 11 2012

Ok, before you say anything, yes I know. It has been a long time since I posted anything remotely useful here. Well in my last job I ended up doing less development and more team management so the useful bits I came across were few and far between. In my new job I am back to development, so I should have more to post here in the future.

One of the requirements I had recently was to sort UK postcodes in ascending order. The postcodes were being stored in a list of type IEnumerable and were all strings. As you are probably aware if you are searching for this, UK postcodes are alphanumeric (NP10, NP11 etc). This means that if you try and sort the following list of postcodes: NP1, NP23, NP35, NP3, NP2, NP45, NP11

You would get the outcome: NP1, NP11, NP2, NP23, NP3, NP35, NP45

However the outcome required is: NP1, NP2, NP3, NP11, NP23, NP35, NP45

I found this brilliant blog post which provides some code under the MIT license which does the job perfectly – Natural Sorting in C#

I included his EnumerableComparer class as a Utility class in my Framework and then used the code in a similar way to this:

IEnumerable<PostcodeAllocation> allocations = GetAllAllocations();
// Declare convert string as per IanG's blog post
Func<string, object> convert = str =>
{
try
{
return int.Parse(str);
}
catch
{
return str;
}
};
allocations.OrderBy(str => Regex.Split(str.Postcode.Replace(" ", ""), "([0-9]+)").Select(convert), new EnumerableComparer<object>());

This then sorts my data as follows: NP1, NP2, NP3, NP11, NP23, NP35, NP45.

Perfect! I hope this helps someone else and a huge thanks to IanG on his blog for this great snippet of code.





It’s been a while…

17 02 2011

So here I am, apologising again for a lack of updates to this blog! I started a new job in November and moved house at the same time so it’s all been a bit manic really. I hadn’t done any admin with the site since late November so I came back to over 500 comments to moderate! There was a large amount of spam so if I accidentally trashed someone’s genuine comment then I am very sorry. Please post it again and I will approve it.

On the subject of comments, my general rule when moderating is to look at the name provided and the e-mail address provided and see if they match in some way. For example if the name provided is Sarah then the e-mail address is martin@someemailprovider.com then chances are it will get trashed. I also look at the URL’s provided. If there is one there, I look to see if it looks genuine and if it is, I check it out. I wish I could remove the comment moderation but there really are so many spammers out there!

Anyway, what I plan to do from here is to get back into posting regular content. I’m planning to do a little stats summary like I did at the end of 2009 (for my benefit to look back on really). I’ve also been looking into some SEO techniques at work recently so might start posting a little about SEO bits and also trying some things out on the site.

Another thing I’ve been considering is maybe getting a guest writer on to write some posts for the site. A similar sort of thing to what I do, general hints and tips for programming etc. If you’re interested please leave me a comment and I’ll get in touch with you.

So sorry again for the lack of new articles. I plan to spend much more time on it from now on when time allows!





How to ‘Publish’ a Web Application in Visual Studio 2003

3 08 2010

If you’ve used later versions of Visual Studio for creating web applications, you will know that there is an option to ‘Publish’ your application which allows you to compile your application into only files needed to run the application (a good practice to use when putting your application online).

When it comes to Visual Studio 2003, there isn’t such an option but the functionality is still there, just masquerading under a different menu option!

When you have your project open, build it in ‘Release’ mode (it is not essential that it is built in ‘Release’ mode but I find there are performance improvements over building it in ‘Debug’ mode). Now select ‘Copy Project’ from the ‘Project’ menu along the top.

CopyProjectMenu

You will then be presented with the following pop-up dialog:

CopyProjectDialog

Here you give it a destination project folder (in my case, the same as the source project folder, but to a folder called ‘Published’), and a web access method. I choose to publish it to my local file system, and then upload it myself. You then choose to copy ‘Only files needed to run this application’ and click ‘OK’. If you now go to the folder which you chose in the ‘File Share’ path, you will have all the files you need to upload to put your web application online, the same as if you had ‘Published’ a web application in a later version of Visual Studio.





How To Do A Printer Friendly Pop Up That Has Information From The Original Web Page

8 07 2010

Well that’s a bit of a lengthy title isn’t it! I wasn’t really sure what to call it. I’m sure this could be used in other ways too, but in my case I wanted to create a printer friendly pop up page, that took information from my ASP.net page to present in the pop up. I’ll show the C# code first but then will also show you just the javascript without all the added double quotes and various other symbols that may cause confusion. Also apologies for the somewhat messy code listing for the C’# part, I may need to consider a change of theme soon!

IMPORTANT NOTE: The web site I was doing this in is in .NET 1.1 so I am using the RegisterClientScriptBlock from the C#. This method is obsolete from 2.0 upwards so you should look to replace it with it’s correct newer method.

RegisterClientScriptBlock("PrintWindow", "<script language=\"javascript">\" + @"
var content = '" + infoLabel.Text + @"';
var printFriendly=window.open('','PrinterFriendly','toolbar=no,menubar=no,width=1000,height=600');
printFriendly.document.open();
printFriendly.document.write('<html><head><title>Printer Friendly Pop Up Page</title></head>');" +
"printFriendly.document.write('<img src="\"Images/ProgressPrintHeader.png\"" /><h1>');" + @"
printFriendly.document.write(content);
printFriendly.document.write('</h1>');
printFriendly.document.write('<h5>Printed on ');
printFriendly.document.write('" + DateTime.Now.ToString("dd MMMM yyyy") + @"');
printFriendly.document.write('</h5></body></html>');
printFriendly.document.close();
printFriendly.focus();
</script>");

Now for just the javascript code on it’s own, without all the squiffy formatting and confusing symbols!

var content = 'Text from original page';
var printFriendly=window.open('','PrinterFriendly','toolbar=no,menubar=no,width=1000,height=600');
printFriendly.document.open();
printFriendly.document.write('<html><head><title>Printer Friendly Pop Up Page</title></head>');
printFriendly.document.write('<body onLoad="self.print()"><img src="Images/ProgressPrintHeader.png"></br></br><h1>');
printFriendly.document.write(content);
printFriendly.document.write('</h1></br></br>');
printFriendly.document.write('<h5>Printed on ');
printFriendly.document.write('Today's date');
printFriendly.document.write('</h5></body></html>');
printFriendly.document.close();
printFriendly.focus();

It’s important to use the document.close() method, otherwise your print dialog will never pop up because as far as your browser is concerned, the document is still being written.

So as you can see, in order to take the text from my original ASP.net page into my pop up, I am referencing the label that the required text is in. It is also possible to do it using javascript if you are not using ASP.net or anything similar.

If I had the text I wanted to print within div tags for example:

<div id=”print”>All text to be printed</div>

then I could then retrieve that text using:

document.getElementById(‘print’).innerHTML;

I hope that all makes sense! Feel free to comment if I have well and truly confused you 🙂





Adding Text to an Image

23 06 2010

I had a blank calendar icon that I needed to draw a date on to depending on the user that was signed in to my website. It took some fiddling, but eventually after a few errors and some searching, I have the solution. On my ASP.net page, I have 2 images: calenderIcon and blankCalenderIcon. Both of these have their ‘Visible’ attribute set to false. blankCalenderIcon is the image I always start with and that is never changed, and calenderIcon is the image that has been modified to include a date. The code snippets are originally broken up to allow me to explain easier what is going on and provide some relevant links. However there is a full code snippet at the end of the post without any explanations.

Firstly, as there is a crossover here between System.Drawing.Image and System.Web.UI.WebControls.Image, I had to save the image I had placed on my page as a System.Drawing.Image.

System.Drawing.Image img = null;
img = System.Drawing.Image.FromFile(Server.MapPath(blankCalenderIcon.ImageUrl));

Then in order to edit the image, and save it back to it’s original ‘ImageUrl’ path, you need to create 2 Bitmap objects. If you try and do all of this with one Bitmap object, you will get the following error, "A generic error occurred in GDI+". This is because the file is locked. For a more in depth explanation, click here.

Bitmap originalCalender = new Bitmap(img);
Bitmap newCalender = new Bitmap(originalCalender.Width, originalCalender.Height);
Graphics newG = Graphics.FromImage(newCalender);
newG.DrawImage(originalCalender,0,0);

Now that you have your Graphics object that contains the blank image, you can add the text to it. I personally set the Anti Aliasing for smoothness, that’s obviously not a necessity. I then use the DrawString method to place my text on the image. For some further info on how to do this and how it works, click here.

newG.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
newG.DrawString("July 2011", new Font("Arial", 12), Brushes.White, new RectangleF(12,5,newCalender.Width, 30));

Now that your new image is ready, you need to dispose of your graphics object, your originalBitmap and in this case the Image object created to allow us to create the original Bitmap object (I say in this case because in a Windows Forms application, that step wouldn’t have been necessary).

newG.Dispose();
originalCalender.Dispose();
img.Dispose();

Now that everything has been disposed, you can save your new Bitmap object back to your original icons ‘ImageUrl’ and then in my case, make the icon visible.

newCalender.Save(Server.MapPath(calenderIcon.ImageUrl));
calenderIcon.Visible = true;

And now you will see your original Image, but with your text added. Magical!

System.Drawing.Image img = null;
img = System.Drawing.Image.FromFile(Server.MapPath(blankCalenderIcon.ImageUrl));
Bitmap originalCalender = new Bitmap(img);
Bitmap newCalender = new Bitmap(originalCalender.Width, originalCalender.Height);
Graphics newG = Graphics.FromImage(newCalender);
newG.DrawImage(originalCalender,0,0);
newG.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
newG.DrawString("July 2011", new Font("Arial", 12), Brushes.White, new RectangleF(12,5,newCalender.Width, 30));
newG.Dispose();
originalCalender.Dispose();
img.Dispose();
newCalender.Save(Server.MapPath(calenderIcon.ImageUrl));
calenderIcon.Visible = true;





How to retrieve Connection Strings from a Web App config file

12 05 2010

A friend of mine who’s just starting out with a bit of C# and asp.NET asked me about this yesterday. He had spent the evening before doing lots of searching and hadn’t found anything that actually helped him get his connection string from his web.config file into the C#. So I thought I’d write a little post about it.

The common practice with connection strings in asp.NET is to put them in your web.config file. By doing this, when you need to change your connection string, for example when you put it on your web server, you can change it in one place in the config file and your web application doesn’t need to be changed or rebuilt in any way. As mentioned above, the problem my friend had was getting the connection string from the config file into the C# so here’s some code example to show how it’s done.

1. Put your connection string in your config file (www.connectionstrings.com is a great resource to help with formatting of connection strings and different types of connection strings for different servers). Please excuse the formatting of the XML below, it wouldn’t allow me to use the <> tag’s in the code box so this was a better way!

<connectionStrings>

<add name=”UsefulAppConnString” connectionString=”Data Source=myServerAddress;Initial Catalog=myDataBase;IntegratedSecurity=SSPI;”

</connectionStrings>

2. Add a reference to System.Configuration (right click ‘References > Add Reference’, select the .NET tab and find System.Configuration. Double click it or highlight it and click ‘OK’).

addref

3. Add a using statement to your C# class where you will be pulling in the connection string.

using System.Configuration;

4. Now you have everything you need to get the connection string! In this example I’m just going to put it in a string variable. You could assign it to a string variable when your web app loads that could then be accessed throughout your web application or you could just retrieve it from the config file every time you wanted to use it. That’s up to you.

string connString = ConfigurationManager.ConnectionStrings["UsefulAppConnString"].ToString();

You can also store the connection string in the appSettings part of a config file. If you do, you will need to use ConfigurationManager.AppSettings instead of ConfigurationManager.ConnectionStrings.

So the ConfigurationManager is effectively your config file. Using ConfigurationManager.ConnectionStrings is looking at the data within the ConnectionStrings tags in your config file. The name in the square brackets as you’ve probably noticed is the name attribute I assigned to my connection string in step 1.

So there it is. How to retrieve your connection string from your web.config file.





Date Manipulation in C#

30 03 2010

DateTime to String

When you have a DateTime object that you want to store or present as a string, I find the easiest way to format the date is as follows:

DateTime today = DateTime.Now;
string stDate = today.ToString("dd MMMM yyyy");

This code will return "30 March 2010". You can format it as you like using the ToString method, using the key string combinations for different ways of displaying days, months, year, minutes and seconds. I have linked to a useful site in a previous post that will give you the string combinations you can use, here’s the link again http://blog.stevex.net/string-formatting-in-csharp/ . The ones you will probably use most are under Custom Date Formatting on that site.

If you wanted to add the “th” after the date you could do the following:

DateTime today = DateTime.Now;
string stDate = String.Format("{0}th {1}", today.ToString("dd"), today.ToString("MMMM yyyy"));

This code will return “30th March 2010”.

Adding & Subtracting Days / Months / Years / Hours / Minutes / Seconds

There are methods available to add days, months and years to a DateTime object. AddDays(), AddMonths() etc. So if I wanted to show 6 months time, I would use the following code:

DateTime sixMonthsTime = DateTime.Now.AddMonths(6);
string stDate = sixMonthsTime.ToString("MMMM yyyy");

This code will return “September 2010”.

To subtract days, months, years etc, we use the same method. If I wanted to show 6 months ago, I would use the following code:

DateTime sixMonthsTime = DateTime.Now.AddMonths(-6);
string stDate = sixMonthsTime.ToString("MMMM yyyy");

This code will return “September 2009”.

 

This is all I have chance to write on this subject at the moment but I will add to this post whenever I get chance or come across something new.