Setting MaxValue for Migrations

12 03 2013

I’ve just been using the MigratorDotNet framework for the first time. I was creating a migration that would create a new table with various new fields. One of the fields I wanted to create was to store files so therefore I wanted a varbinary(max) field. If you leave the size undeclared, it will create a varbinary(8000). The way I got around this was to create my column as follows:

Column file = new Column("BinaryFile", System.Data.DbType.Binary, int.MaxValue, ColumnProperty.NotNull);

Using the int.MaxValue gives the same result as varbinary(max). However, this doesn’t create a varbinary(max) field (at least not in SQL Server 2008 R2 which is what I am using). It creates an image field instead. This isn’t necessarily a problem, it still gives me the space I require. Importantly though, Microsoft are now advising you do not use this type in new development as it will be removed in a future version of SQL Server (see MSDN article here). We’ve weighed this up and have decided that this is not a problem for us at this time because we are developing improvements to a current system with no plans for any SQL upgrade in the future. There are also uses of the image type in other parts of the database. We have instead logged it in our technical backlog to go through and change all uses of this type at a later date. Personally, in a new project, I would not use it, just in case!

I did some searching in the hope I would find a more elegant solution (something akin to the EF Code First data annotations would have been nice) but I didn’t find anything. If anybody comes across this post, and you’ve found a nicer way to do this, please comment on here to let me know!





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.





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 Enable Integrated Windows Authentication in IIS 7

16 06 2010

I’m currently working on a website that was created in .NET 1.1 and Visual Studio 2003 and I had nothing but nightmares getting it to work on my Vista machine which is running IIS7! My final hurdle was getting it to run in Debug from Visual Studio 2003. To do this I needed to enable integrated Windows authentication for the website. So here is how I did it:

1 – Open IIS Manager

2 – Highlight your website that you want to enable integrated Windows authentication for

iis7

3 – Double-click the Authentication tab

4 – Where it says “Windows Authentication” in the Name column, the status column should read “Enabled”. If it reads disabled, right click and select “Enable”.

iis72

This did it for me and I was then able to go back into my Visual Studio 2003 environment and successfully run the website in debug mode. REMEMBER!!! Visual Studio 2003 might need to be run as an administrator to allow debugging (Right Click — Run as administrator) so if you are still having problems give that a go!





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.