TechQuest: Welcome to TechQuest.
Software Development Secrets: Easing Your Burden – Writing Code that Spits Out Code – Part 2
Bloody AwfulBelow AverageNothing SpecialGoodPretty Damn Good 1 viewers have rated this item.
Sometimes software coding involves repetitive tasks, such as writing the C# Switch-Case code that works through a long list of properties. In one of my current projects, we have a database table that defines properties for various objects—our application reads this database table and uses this information to 1) populate various UI elements, 2) read the values users have set for the various properties, and 3) use those stored property values to read and set the values as the related objects are instantiated. Here is an example:
Uploaded Image

Above is a screenshot from DocAuto’s (IMFO revolutionary, explosively powerful, and surgically accurate) admin tool for SharePoint called SPOrganizer (https://www.docauto.com/products/sporganizer/). What you see is the user interface where you can turn on and off the various Features in a SharePoint Site Collection. This list of features is driven by a database table stored on the customer’s machine. It looks like this:
Uploaded Image

Ultimately, a C# method is submitted a list of properties, works through the list, and performs read/update operations on each property. Here is an example:
Uploaded Image

This Switch-Case block has more than 100 Case statements. That’s a lot of code to write! And if there is a typo in any of the property names, it won’t work correctly. Since we already have this data stored in a database, the solution is to use that data to create the shell of the code we need—automatically. It’s very simple. Here is the SQL code:

SELECT 
'	case "' + Name  + '":
		currentClientContext.Load(siteCollection, s => s.' + Name  + ');
		break;
'
FROM SPProperties
WHERE TypeName='SPSiteCollection'

We tell SQL Management Explorer to display the results in text:
Uploaded Image

And we simply cut the results and paste them into our C# code:
Uploaded Image

And just like that, we have created perfect no-typo code that would have taken a couple of hours to write by hand. Of course there is more work to do in the customizing of code for each individual property, but many won’t need a change at all.

3,127 views.
Bloody AwfulBelow AverageNothing SpecialGoodPretty Damn Good 1 viewers have rated this item.