Look up the default web in IIS
Default as defined by port 80, no host headers and is running on the local machine:
private string GetDefaultWebPath()
{
string result = null;
using (var de = new DirectoryEntry("IIS://Localhost/W3SVC"))
{
foreach (DirectoryEntry child in de.Children
.Cast<DirectoryEntry>()
.Where(d => d.SchemaClassName == "IIsWebServer" &&
d.Properties["ServerState"]
.Value.ToString() == "2" /* Started*/))
{
var bindings = child.Properties
.Cast<PropertyValueCollection>()
.Where(i => i.PropertyName == "ServerBindings")
.ToList().Cast<PropertyValueCollection>();
if (bindings.Count() == 1 && bindings
.First().Value.ToString() == ":80:")
{
var root = child.Children
.Cast<DirectoryEntry>()
.FirstOrDefault(d => d.SchemaClassName == "IIsWebVirtualDir");
if (root != null)
{
result = root.Properties["Path"].Value.ToString();
}
}
}
}
if (string.IsNullOrEmpty(result))
{
throw new Exception("Could not determine the default web.");
}
return result;
}
Ever wish JavaScriptSerializer had a non-generic Deserialize method (like DataContractJSONSerializer)?
Well, Rex informed me of the handy MethodInfo.MakeGenericMethod which creates a constructed generic method, allowing us to avoid having to declare the generic types at design time. So, now we can bolt on a Deserialize method (note, we cache the constructed generic methods) (formatted to appease wordpress)
public static class JavaScriptSerializerExtensions
{
private static object _lock = new object();
private static IDictionary<Type, MethodInfo> _deserializers
= new Dictionary<Type, MethodInfo>();
private static MethodInfo GetDeserializeMethod(Type type)
{
lock (_lock)
{
if (_deserializers.ContainsKey(type)==false)
{
var mi = typeof(JavaScriptSerializer)
.GetMethod("Deserialize");
_deserializers[type] = mi.MakeGenericMethod(type);
}
}
return _deserializers[type];
}
public static object Deserialize(
this JavaScriptSerializer serializer, Type type, string json)
{
return GetDeserializeMethod(type).Invoke(
serializer, new object[] { json });
}
}
Get inspiration from .net’s LINQ in Javascript
When you think about working with enumerable stuff client-side, you can get great inspiration from .net’s awesome LINQ goodness. For example, if you need a trivial way to sum up items in an array, you can bolt on a “sum” routine onto Arrays. For example, here’s a small one, which has a default implementation to deal with strings or numbers:
Array.prototype.sum = function (predicate) {
predicate = predicate || function (match) {
if (typeof match == "string") {
return match.length;
}
return match;
};
var result = 0;
for (var i = 0; i < this.length; i++) {
result += predicate(this[i]);
}
return result;
};
Here are a couple usage examples:
// Baked-in sum for strings
var array1 = ["hello","world"];
var length = array1.sum());
// Baked-in sum for numbers
var array2 = [10,20,30];
length = array2.sum();
// Custom for custom objects.
var array3 = [{yearsOfExperience:3},{yearsOfExperience:5}];
length = array3.sum(function(match){return match.yearsOfExperience;});
Here’s a Fiddle that demonstrates this (hit F12 in FF, Chrome, IE*+ and look at the console when running): http://jsfiddle.net/harperj1029/Zeaqa/
Think Linq!
Use Powershell and Slickrun to display w3wp info
If you have multiple pools running within IIS locally, you’ll see corresponding w3wp.exe processes in visual studio when you try to attach for debugging purposes. One quick way to figure out *which* one is the w3wp that you need to attach to is to display the process id and application pool for all the w3wp processes on your machine. There’s plenty of old-school way to do that, or you can use a powershell script such as this:
gwmi win32_process -filter “name=’w3wp.exe’” | format-table -autosize name,processId,commandLine
So, you could pop that into a powershell file and call that either via an old-school batch file – or….. you could use a command line utility such as SlickRun and in-line the command into a “MagicWord” (Slickrun-speak for a named command) like this:
magic.
Of course, this is pretty simple too: http://www.ervinter.com/2009/04/23/get-process-id-from-multiple-application-pool-iisapp/
Couple great tools for JavaScript and regex…
If you are whipping up some JavaScript and want a great place to build/run and perhaps share with other, then you need to check out JSFiddle. This tool is fantastic, and a great way to collaboratively work on JavaScript. For debugging and/or writing out to a console, consider using Firefox’s [awesome] firebug addin (IE Developer tools works pretty well too).
For times when you need to use regular expressions – and you’re either not strong at them, or have been away from them for more than 2 minutes (the time it takes to forget most of the syntax), then check out RegExPal. This little utility is handy, and give great real-time visual indications of matches.
Mocking with Moq and Moles
I had the pleasure recently to do some unit testing work for some foundational classes (not, not TDD, but still…) and decided to quit stubbing and start Mocking. One of our colleagues recommended Moq, and that’s the one we went with. Moq is great, and I totally dig the mocking approach and am astonished yet again at how little I’ve actually known about real unit testing. One little problem I ran into with Moq, however, led me to another little gem (Hint: Moles). See, I was unit testing already-existing classes, and the idea of refactoring to make them more unit test friendly was not part of the plan. Luckily nearly all the classes either directly supported dependency injection, so getting around dependencies in most cases was quite straight forward. However, there were a few scenarios where I needed to mock out non-virtual methods, or, gasp, static routines. Turns out Moq does not excel in this department, so I stumbled upon the awesomeness of Microsoft Moles. Moles fit right into my scenario allowing me to swap out non-virtual and/or static routines that were inherent dependencies in the execution path of the routines I was unit testing. For example, if you are writing a unit test for the routine “Foo” and within that routine, there is a call to a static method that actually *does* something outside the scope of the unit test (ie, *it* has dependencies on something), then you can use Moles to basically swap out that routine (essentially hijack it and force that code to use whatever you tell it to use – perhaps replacing the static method with a do-nothing routine).
So, if you are unit testing, or perhaps even new to unit testing, I encourage you to consider looking at both of these tools. Perhaps start out with Moq, but if you encounter the same limitation, check out Moles.
J
Feels like Windows Live is stepping it up
Yeah, I love Google like everyone else, but it does appear that Microsoft has some pretty snazzy stuff going on in the Windows Live space, perhaps taking a jab back at Google [docs | apps]. The deep integration of various office products and of course, SharePoint, provides numerous compelling options for collaboration.
oData, LinqPad and NetFlix
Playing with Linqpad and writing a couple oData queries against the Netflix odata api. Pretty nifty. Guess I need to get up to speed on this stuff.
jQuery plugin – “backgroundColorizer” – declarative approach
OK, so I’m taking the cheesy backgroundColorizer plugin to a different place because of this guy’s super clever trick. Couple things had to happen. First, I made my <body> tag look like this:
<body xmlns:sys="javascript:Sys"sys:activate="*">
Then I added this 1-time-only registration line below (this essentially tells the sweet little $.declare function to burn my “backgroundColorizer” plugin as a registered behavior for each element this its attached to , activated by that global sys:activate=”*” piece we added to the <body> tag) (did that make any sense?):
$(function () { $.declare("backgroundColorizer"); });
Now, some html elements can simply look like this with no additional javascript needed:
<ul sys:attach="backgroundcolorizer">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
<tablesys:attach="backgroundcolorizer"backgroundcolorizer:oddColor=’lightGreen’ backgroundcolorizer:evenColor=’Green’>
<tr><td>Jane </td><td>Smith</td></tr>
<tr><td>Joe </td><td>Smith</td></tr>
<tr><td>John </td><td>Doe</td></tr>
<tr><td>Jane Q. </td><td>Public</td></tr>
</table>
OK, here’s the worst and hackish part, where i took my plugin and put in embarrassingly cheesy code to get around the various “children” semantics. I’m sure this would break down immediately, but for this trivial sample it works ok:
// The "backgroundColorizer" pluggin allows you to essentially color alternative odd/even rows' background // (thrilling, eh?) (function ($) { $.fn.extend( { backgroundColorizer: function (options) { var defaults = { oddColor: 'red', evenColor: 'blue' }; var options = $.extend(defaults, options); var selector = this; if (this[0].tagName == "TABLE") { selector = $('tr'); } else { selector = this.children(); } return $(selector).each(function (index) { var obj = $(this); if (index % 2 > 0) { obj.css("background-color", options.oddColor); } else { obj.css("background-color", options.evenColor); } }); } }); })(jQuery);
OK. So, there you have it. We’re using the declarative behavior approach of Microsoft’s ajax library to wrap around our JQuery plugin. Check out that link at the beginning of this post and after your brain stops curdling (as mine did) from that dude’s solution, then soak it up and savor.
Leave a Comment
