C# – Calculating the Absolute path of an HTML Redirect

I’ve been writing a little program that has to get some information from a diagnostic page on an embedded device. There is no password configured, but you still have to go through the login page to get a session. The device uses the rather antiquated “HTML refresh” method of redirecting from the login page to the page you originally requested.

The redirection is in the form of a relative url, ie “../../diagnostics/streams.cgi“. I needed to convert this into an absolute path to make the next request.

This is not ASP.NET, just a plain old windows forms app, so I’m using HttpWebRequest and can’t use the normal ASP.NET tools for dealing with the paths. I could just hard code it in this situation, but I hate doing that. I knew that had to be a “correct” way of dealing with it. Eventually I found out about the System.Web.VirtualPathUtility class and I thought I was home and dry. It appeared that the VirtualPathUtility.toAbsolute(VirtualPath, ApplicationPath) was what I needed. However, that doesn’t seem accept relative paths that take you back to the root. I kept getting the error “The relative virtual path ../../diagnostics/streams.cgi is not allowed here”. No indication of why – just that it’s not allowed.

Finally I spotted the VirtualPathUtility.Combine(absolutePath, relativePath) method. This was what actually worked for me:

(request is the original HttpRequest that returned the redirect)

String url = VirtualPathUtility.Combine(request.RequestUri.AbsolutePath, redirectUrl);

I hope this will help someone as my Googling revealed that a lot of people had given up looking for this and had hand-crafted their own solutions to the problem.

Generating PDF documents From C# Code

I recently had a requirement to convert an outlook calendar file into a printable diary. It was fairly easy to export the calendar into a format readable by C# code, but I didn’t expect it to be so easy to dynamically generate a PDF booklet from this data.

I looked at a few PDF toolkits based on suggestions on this page but by far the best in my opinion was PDFSharp. It simply allows you to dynamically create a PDF document, add pages to it and to draw or write whatever you want at any position on the page.

I managed to write a program that looped over my dataset and outputted separate odd and even pages (one per week) in a one (admittedly long) evening.

It would be a really good tool for any problem where you have to generate non-standard reports or documents from a data set, where you need complete control of what goes on the page. I must admit that I’m quite keen do do more with it.