Friday, 4 November 2011

Using reflection to map values to properties that could be nullable in C# 4

I encountered an issue with a piece of reflection code that someone had written before I joined the project.  They were mapping to fields on a class that matched the column names on a database.  The only problem was that when the field was a nullable datetime any combination of Convert and SetValue I tried resulted in an error due to the absence of a Convert function for DateTime.  The solution I came up with was to use the dynamic keyword to declare an initialised Nullable generic so that assignment of null to the object acted exactly as if it was being assigned to an actual Nullable object.


/// <summary>
        /// Maps a field name value pair to the matching property on the target object
        /// </summary>
        /// <param name="targetObj">The object to assign a parameter value to</param>
        /// <param name="fieldName">The name of the parameter</param>
        /// <param name="fieldValue">The value to be assigned</param>
        public static void GenericMapField(object targetObj, string fieldName, object fieldValue)
        {
            PropertyInfo prop = targetObj.GetType().GetProperty(fieldName);
            if (prop != null)
            {
                if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    dynamic objValue = System.Activator.CreateInstance(prop.PropertyType);
                    objValue = fieldValue;
                    prop.SetValue(targetObj, (object)objValue, null);
                }
                else
                {
                    prop.SetValue(targetObj, fieldValue, null);
                }
            }
        }

Monday, 18 July 2011

MSDeploy "Could not find Default Web Site" issue

I was having a pretty strange issue where one of our sites was failing to deploy over MSDeploy.  We were deploying about 3 other sites to the same server, all of which were deploying fine to Default Web Site but just this one site was throwing a deployment error: Error: Site 'Default Web Sitedoes not exist..  After some googling, with no luck finding a sensible cause I tried modifying the .csproj file to clean it up so that it matched one of the successfully deploying sites.
I made the following changes that wound up sorting the issue:
1. Added a "ProductVersion" to the project file
2. Removed the empty TargetFrameworkProfile tag
3. Moved assembly signing details from Project config property groups into global propertygroup.
4. Removed DeployIisAppPhysicalPath and DeployIisAppPath tags from config propertygroups into global propertygroup.

I also then deployed the project using Visual studio before I then used our full build process.  All of this seemed to solve our issue with the "'Default Web Site' does not exist" issue for that site.

Friday, 24 June 2011

Javascript code seperation

When I arrived at my current role, the first and most obvious problem that made maintenance next to impossible was the intertwining of javascript with the C# code behind.  It was one of my pet peeves before I arrived to see C# strings used to inject javascript into a page but the codebase here was almost unbelievable - javascript that called a setTimeout with javascript inside it that had multi-escaped double quotes inside the string.
Now, sometimes there's just no avoiding it - if you want to get that truely fantastic maps integration to work really slickly with the data in your working context you might have to inject some dynmically  generated javascript.  Now, most of the time it would be better to do it by using json, parameterising properly but sometimes it's difficult to avoid.  The prime example would be when you're trying to write a server control that outputs javascript appropriate to its environment based on some control parameters.
So, how do we solve the problem?  Well, javascript lives in javascript files for a reason.  Code seperation is there for a reason too but there just wasn't a mechanism for creating the kind of dynamic javascript we wanted.  The solution I came up with was to have the server read in from a series of javascript file resources that contained some placeholder symbols to put variables in to.  I did the same for HTML injection where we needed to dynamically output html, which was also pretty useful.
Of course, since we finally managed to convince the boss that jQuery was a good thing the need for all of that has dropped significantly but it's still a nice thing to be able to do.  I'll post a link to the javascript reader class and html reader class soon so that anyone that wants to can use it.

Making more of this blog

Well, the decision is made and it's coming up to crunch time.  I've been working my way up to becoming a contractor for a long time and now I've got a fixed time frame to do it.  Come mid-August the notice is going in and I'll be looking for a contract as soon as I can get one.  So I've decided to put more posts out on this blog to give myself a bit more of a proffessional presence on the internet.  I'll look at migrating any posts I make out to my own website as soon if I ever get the time (I imagine that will be priority one if I find myself in need of a project to do whie I'm looking for work - if I get work straight away though then I won't have such a need for the blog ;-) ).  Anyway, I hope the stuff I put out there is useful to somebody

Friday, 21 January 2011

Dynamically resizing fancy box according to window height

For version 1.3.4 of fancy box I was trying to resize it dynamically so that as the window was resized my nice full screen modal dialog was also resized.  Here's how I did it:


function resizeFancyBox()
{
var newheight = $(window).height() - 30;
var newHeightStr = newheight + 'px';
$("#fancybox-content").css({ 'height': newHeightStr });
}

function closeCallback() {
$(window).unbind('resize', resizeFancyBox);
}

function startCallback(){
$(window).bind('resize', resizeFancyBox);
}

function showEformFancyBox() {
$('#hdnFancyBoxLink').fancybox({
width: 800,
height: $(window).height() - 20,
onStarted : startCallback,
onClosed : closeCallback,
showCloseButton: true
});
$('#hdnFancyBoxLink').click();
}

Thursday, 20 January 2011

Cancel a fancy box close

A quick one since I couldn't actually find this anywhere in the api or documentation. If you want to cancel a user request to close a fancybox then all you have to do is return false from the callback assigned to onCleanup in the fancybox options. Annoyingly I worked this out by looking at the fancybox code but still managed to struggle with it for a while because the callback I inherited had another evaluated function that was causing a close. Oh well - got there in the end!