kdmurray.blog

The crossroads of life and tech

Accessing HttpContext objects from other classes

I could swear I wrote about this at some point in the distant past, but I couldn’t find the article this week when I needed it to help troubleshoot an issue with another developer. The issue he was having was how to access objects from the executing web page’s HttpContext object from a class other than the CodeBehind of the executing web-forms page. Essentially he was looking for a way to map a web-path to a physical folder path without needing to hard-code it or know where the application was deployed on the server in question.

If done correctly, an application can reside anywhere in the file system and be deployed to a virtual directory at any depth without causing a problem with URL resolution. In the code-behind of a web-forms page, the code is simple:

string physicalPath = Server.MapPath("~/somefolder/myfile.xml");

However doing this from another page involves just a little bit more work:

Using System.Web;
string physicalPath = HttpContext.Current.Server.MapPath("~/somefilder/myfile.xml");

It’s really quite straightforward when you see it, and I can’t believe that I forget how to do it. This method will also provide you access to lots of other useful objects which makeup the “state” of the application from an HTTP perspective.

Back to Basics

Over the past year my personal life as undergone some fairly major changes. I started a new job a little over a year back and there were the obvious changes that go along with that. But more importantly my wife and I welcomed our first child into the world and that was a life changing moment. Now, most of you know that I don’t talk about my personal life in the blog so suffice to say that we have thoroughly enjoyed our first year as parents. It is a wonderful experience and we eagerly await every new day to see what will happen next.

One of the things that changes when you have a new baby is the amount of time you can spend on yourself and your own hobbies and pursuits. I used to spend upwards of 4-6 hours every day outside of work on the computer blogging, coding, or otherwise toiling in one digital adventure or another. Now I find that the number ranges somewhere in the range of 0-2 hours per day. That is a pretty drastic reduction no matter how you slice it (about 80% for those of you scoring at home).

There are a number of projects that I have started and stopped over the past few years each of them trying to build a better mousetrap, or re-make something from scratch just to see if I could do it. With the limited time available to me now, I have become more focused on wanting to actually do more with the time I have — this means not reinventing the wheel every chance I get.

My wife and I have both found that we have become far more effective with our time, getting more done with less time than we ever have before. In the past couple of months I have started to extend that to my digital life as well. Gone are the days when I focused on a writing a to-do list, a backup utility, a blogging engine, a photo manager or a disk-erasing tool. There are lots of great (free) tools out there which can handle those tasks very well, even if they don’t satisfy all my neurotic desires (like how my historic completed work tasks should be handled, cataloged and stored for reporting purposes (you know, for when I will pull metrics on my completed work)).

I have also decided that diving in to learn a new, modern programming language is probably something that would realistically take more time than I’m willing to devote to the enterprise. Python, Ruby, Java, and the ASP.NET MVC framework are all on my list, but are undergoing changes and enhancements so frequently that I’m having trouble keeping up with what’s out there, nevermind trying to actually learn the stuff. But I do want to become a productive programmer in some language outside the rather constrained, and somewhat self-imposed, .NET bubble in which I have spent the majority of my professional career. Ideally I would like to write in something that I can port between operating systems without too much headache. Being able to produce code that will run on anyone’s machine is a great asset — especially when you have Windows, Mac and Linux machines in your own house to start with.

So the question is what can I learn that will allow me to:

  1. write code for multiple platforms
  2. grow as a developer
  3. not have to keep up with constant enhancements

The answer I came to was 42 C. It seems to satisfy all of the criteria above for me in a way that other languages don’t.

C is by nature intended to be a multi-platform system. If you’re able to confine your applications to CGI or the command-line this is made even easier.

C also requires developers to know much more about how computers and compilers work than more contemporary languages like C#, Java or Python. Though it arguably makes programming more difficult, I think it will help me become a better programmer over time as I learn some of the trickier parts of getting a computer to do what I want it to do.

The current ANSI standard specification for C was introduced in 1999. This means that for the past 12 years, the standard for C programming has remained essentially unchanged. This makes C a good choice for someone who doesn’t have a great deal of time to keep up with changes and enhancements in the specification.

For all these reasons, and my own simple curiosity I’m embarking on an adventure to learn and become proficient in C. I make no assertions that I’m trying to master the language as I can’t see myself getting beyond the hobbyist or perhaps open-source contributor stages. I do have some ideas for the first couple of projects I would like to tackle once I get the basics out of the way. Hopefully I’ll be able to release some source code back into the world over the next year or two — after all, I’m in no hurry.

C# IsNumeric implementation

Here’s a quick and dirty implementation of “IsNumeric” in C#. This is one of those methods that just seems to be missing from C# which appears in so many other languages.

UPDATE 12-Apr-2011: After some fantastic discussion elsewhere I’ve modified the code to handle a number of additional scenarios. A point was also raised that a combination of Int64.TryParse() and Decimal.TryParse() would accomplish the same thing. They would, almost, but those methods test for valid 64-bit integers and valid 64-bit decimals — they don’t test whether a string is numeric. Feed them a long enough string of numbers and they’ll return false. It’s a pretty fine distinction, I grant that, but I figured since I was writing the code I might as well make it as robust as possible.

        public static bool IsNumeric(string s)
        {
            return IsNumeric(s, false);
        }

        public static bool IsNumeric(string s, bool allowDecimal)
        {
            bool result = true;
            if (String.IsNullOrEmpty(s))
            {
                return false;
            }

            if (s.StartsWith("-"))
            {
                s = s.Substring(1);
            }

            char[] chars = s.ToCharArray();

            if (allowDecimal)
            {
                bool decimalFound = false;
                foreach (char c in chars)
                {
                    if (c == '.' && !decimalFound)
                    {
                        decimalFound = true;
                    }
                    else
                    {
                        result = result & (char.IsNumber(c));
                    }
                }
            }
            else
            {
                foreach (char c in chars)
                {
                    result = result & char.IsNumber(c);
                }
            }

            return result;
        }

I built 14 39 unit tests for this on the project I built it for throwing all sorts of weird and null data at it, and it seems to run fairly well and reasonably quickly. Any comments/suggestions are welcome.

Announcing EpubSharp

Over the past few days I’ve put some time into working on a library to create EPUB documents in .NET.  When I first did a search for this a few months ago I really didn’t find anything that suited my needs: a library that I could use to create EPUB documents on the fly, in code.

So I said to myself: “Self! You can write code, build the damn thing yourslef!”. So I did.

The initial version of the library has been published up on Google Code and is probably full of holes. If you’re interested, have a look and let me know what you think.  I’ll try to publish some more detailed specs for what the library does in the coming weeks.

For now, it can get got at: http://code.google.com/p/epubsharp/ — and yes, the documentation on that page is as sparse as it is here.  :)

ASP.NET MVC Tutorials

A couple of weeks ago at Mix ’09 the ASP.NET MVC team announced the RTW (release-to-web) version of the MVC framework. I’ve been looking at the framework and playing with pieces of it for a few months now, but due to school & work commitments haven’t really had a chance to give it a good run through, or build anything meaningful with it.

This past week I’ve gone back to the ASP.NET website and discovered that there is now a long list of tutorials which have been put in an order to help make the major features of the MVC framework more learnable, particularly for those of us who haven’t had that MVC-heavy comp-sci education.  The tutorials come in either written or video form (there is some overlap) and do provide some good step-by-step instructions for exploring the new methodology.

Expect me to get into more detail about the ins-and-outs of the MVC framework in upcoming editions of the new podcast (more details soon, I promise!!)

You can, of course, download and use the MVC framework with Visual Studio 2009 without the tutorials, but I would highly recommend giving the first few a once-over.  Have a look at the tutorial site and see what you think.