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!

Advertisements




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.





Combining 2 PDF Documents into 1 with PDFSharp

4 03 2010

After looking at the example of how to do this on the PDF sharp website, I wrote the following code to combine 2 existing PDF documents into one & send the new document back to the user to download. Both PDF documents existed as byte arrays (which I had retrieved from my database, reportPdfContents & certsPdfContents) so if you’re retrieving them from your file system, you will need to slightly alter the code.

MemoryStream msReport = new MemoryStream(reportPdfContents); //reportPdfContents is a byte array
MemoryStream msCerts = new MemoryStream(certsPdfContents); //certsPdfContents is a byte array
PdfDocument reports = PdfReader.Open(msReport, PdfDocumentOpenMode.Import);
PdfDocument certificates = PdfReader.Open(msCerts, PdfDocumentOpenMode.Import);
PdfDocument combinedOutput = new PdfDocument();
int repPageCount = reports.PageCount;
for (int i = 0; i < repPageCount; i++)
{
PdfPage page = reports.Pages[i];
page = combinedOutput.AddPage(page);
}
int certPageCount = certificates.PageCount;
for (int i = 0; i < certPageCount; i++)
{
PdfPage page = certificates.Pages[i];
page = combinedOutput.AddPage(page);
}
byte[] combinedContents = null;
using(MemoryStream stream = new MemoryStream())
{
combinedOutput.Save(stream, true);
combinedContents = stream.ToArray();
}
Response.ContentType = "application/pdf"; //set the MIME type here
Response.AddHeader("content-disposition", "attachment; filename=ReportAndCertificates.pdf");
Response.BinaryWrite(combinedContents);
Response.End();

If you are familiar with PDF Sharp and have already looked at the examples, I think this code is probably pretty self explanatory. If you want some more information though, on the PDF’s, saving to/reading from byte arrays or opening a file on the client side just leave a comment. I do check them quite often so I’ll probably reply fairly quickly!





Casting SqlParameter/Object as a Byte array

2 03 2010

I’ve just spent ages working this out, and all the time I was just making a silly mistake! So hopefully this may save someone else the pain! For anyone that doesn’t want to read the rest of the post, the code to do it is:

byte[] fileContents = (byte[])sqlParameters[3].Value;

I was saving a PDF file as a byte array and then inserting that to my database as a varbinary. I needed to be able to then get that varbinary back out of the database as a byte array, and open it without corrupting the information.

So casting is the obvious candidate. But I made a silly mistake and had the following:

byte[] fileContents = (byte)sqlParamters[3].Value;

Which caused a problem as I was trying to cast a single byte to a byte array. I then got all caught up in using the ToString() method on the parameter value and then converting it from a string to a byte array. It just kept getting corrupted!

When I actually sat back and thought about it, a SqlParameter is just an object. So a simple cast is all that’s required. When I took a step back, I realised my code should have been:

byte[] fileContents = (byte[])sqlParameters[3].Value;

See what I mean about it being a stupid mistake?! All I needed was the square brackets in the casting and now it works perfectly, giving me back my lovely PDF, uncorrupted!

Sometime problems aren’t as complicated as you first think and the easy solution is the right one 🙂