“Quick Find” Feature in the Productivity Power Tool Extension in Visual Studio 2010

May 6, 2011

If you are like me, then you have installed a number of productivity related extensions for Visual Studio 2010, and sometimes it is difficult to know which extensions have each feature.

One feature that is in the Productivity Power Tools (http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/) is Quick Find which replaces the default Find and Replace windows with the following.

image

image

I don’t know about you, but I have a very healthy dislike for this feature – I am constantly clicking the dropdown box to select the Advanced Options to show the normal Visual Studio Find and Replace windows.

You can turn off this feature by going into Tools –> Options –> Productivity Power Tools in Visual Studio and turning off “Quick Find”.

image

Note that after changing this option you will also have to restart Visual Studio for the change to take effect.


Intellisense in Razor for Custom Types and Helpers

May 4, 2011

If you have custom types and custom ASP.NET MVC Helpers, and if you set your Visual Studio Web Project’s Build Output Path folder to something other than the default “bin\” location, then you will be in for a little surprise – you will not see your custom types in the Razor Intelllisense!

It appears that Razor’s Intellisense uses the assembly binding probing path of your Web Project’s root folder and the “bin” sub-folder.

If your Build Output Path is a sub-folder of your Web Project application base folder / root folder (although I don’t understand why you would bother) you could make a change to the web.config file and add a probing privatePath configuration such as:

<configuration>
<runtime>
<assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
<probing privatePath=”myBin” />
</assemblyBinding>
</runtime>
<configuration>

However, in the more likely scenario that you have a common central location for all of your assemblies that is outside of your Web Project application base folder / root folder, then unfortunately by design (for security and side-by-side execution) there is no configuration setting in .NET that is going to help. You cannot load assemblies from outside of your application base folder (via configuration in .NET) – unless they are strong named and in the GAC.

In my scenario, the Build Output Path is outside of the Web Project’s root folder, so configuration is not an option, and my assemblies are not strong named, so the GAC is not an option.

One solution is to create a Visual Studio 2010 Extension or post-build script that copies all the assemblies from my custom Build Output Path into the local “bin” sub-folder. That would work, although it would also slow down my build times and frankly isn’t elegant.

A better solution is to take advantage of the fact that in my scenario the “bin” sub-folder does not actually exist in my Web Projects. I can make it exist in Windows 7 by creating a symbolic link named “bin” which points to my Build Output Path – and then magically Razor Intellisense works!

Note that when you create a symbolic link you need to have Administrator privileges.

The syntax to create the symbolic link is:

mklink /d x:\MyWebProject\bin y:\MyCommonAssembly\Bin


Minimal Configuration Required for Razor Intellisense in ASP.NET MVC 3 RTM

May 4, 2011

Recently I have been creating some custom ASP.NET MVC 3 Helpers and have been working with some customised Visual Studio 2010 Web Projects (we effectively separate our Web Areas into individual Web Projects).

When working in these customised Web Projects for Web Areas, I have faced some issues with the Razor Intellisense. As it turns out, the issues were actually due to a lack of understanding of Razor’s requirements for populating its Intellisense.

And so, here is the absolute minimal configuration needed to get Intellisense working properly in Razor for an ASP.NET MVC 3 Web Project.

(1) A Visual Studio Web Project (sorry, I have not tried Class Library Projects)

(2) A web.config file in the root of the project, with the following contents:

<?xml version="1.0"?>

<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
  </system.web>

</configuration>

This is a cut-down version of the file that is created when you create a brand new, empty MVC 3 Web Project in Visual Studio.

Razor looks to this file in order to determine which assemblies from the GAC to load into its Intellisense. The assemblies listed above are the ASP.NET MVC 3 assemblies that contain the base class for a Razor view (System.Web.Mvc.WebViewPage) and the extension methods for all the standard MVC Helpers – such as HtmlHelper which is accessed through the @Html syntax, etc.).

If you had your own MVC Helpers that were strong named and deployed to the GAC, you could add them to the assemblies element.

All assemblies that are in the Web Project’s private Bin folder are automatically loaded and made available in the Intellisense.

(3) A web.config file in the Views folder, with the following contents:


<?xml version="1.0"?>

<configuration>

  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>

</configuration>

This is exactly the same file that is created when you create a brand new, empty MVC 3 Web Project in Visual Studio.

This web.config file importantly:

(a) Declares the default class that a Razor View/page inherits from (note: System.Web.Mvc.WebViewPage contains the Html and Ajax properties that are referenced by @Html and @Ajax respectively). The class that a specific Razor View inherits from can be overridden in the Razor syntax with the keyword @inherits.

(b) Declares the namespaces that are automatically imported – instead of having to use the @using Razor syntax. This is particularly important because it is the mechanism through which the MVC Helper extension methods are made available.

And that is all you need to get Razor Intellisense working!


Thread-Safe Lazy Singleton Implementation in .NET 4

August 25, 2010

It has been a while since I needed to develop a singleton in .NET, and now that I am working in .NET 4 I thought it was a good time to revisit the implementation and take advantage of new language features.

So without much fanfare, here it is:

Public NotInheritable Class MySingleton

#Region " Thread-Safe Lazy Singleton "

    Private Shared _instance As Lazy(Of MySingleton) = New Lazy(Of MySingleton)(Function() New MySingleton())

    ''' <summary>
    ''' Hide the constructor
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub New()
        ' nothing to do
    End Sub

    ''' <summary>
    ''' Singleton instance
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared ReadOnly Property Instance As MySingleton
        Get
            Return _instance.Value
        End Get
    End Property

#End Region

End Class

The .NET 4 Lazy class by default ensures that the singleton is thread-safe.

If you use the Lazy class and do not pass in any parameters, it will construct the type automatically for you… which means that the class must have a public constructor method with no parameters. By passing a value factory delegate into the constructor of the Lazy class, we can keep our constructor private and thereby force others to use our Instance property and truly make a Singleton.


ASP.NET MVC2 AJAX: Executing Dynamically Loaded JavaScript

June 11, 2010

(or ASP.NET MVC2 AJAX: ASP.NET MVC2 Client Validation in an AJAX Loaded Partial View)

I have been tinkering with ASP.NET MVC2 for a while and I had the problem where the MVC2 Client Validation did not work when I was dynamically loading a partial view through MVC2 AJAX. Upon further investigation, I discovered that the issue was not limited just to MVC2 Client Validation, but to all JavaScript that is dynamically loaded through MVC2 AJAX. The issue has to do with the way that the response is injected into the DOM element – through the InnerHTML property. Any script block injected into that property will not be executed.

Note: when I refer to the ASP.NET MVC2 AJAX, I am specifically referring to the usage of method calls such as “Ajax.ActionLink()” and “Ajax.BeginForm()”.

There are many blogs and tutorials that discuss how to load partial views asynchronously with AJAX in ASP.NET MVC2, and there are even more articles on how do that with jQuery. Unfortunately most of these deal with the simplistic scenario of explaining the basics of partial views.

It is difficult to find any information on how to do MVC2 Client Validation (or use any JavaScript) from within a partial view that is loaded dynamically with ASP.NET MVC2 AJAX. There are however a number of forum posts with people questioning exactly how to do this!

Now, I am not going to go into discussions about how it might be better practice to put all the JavaScript in separate .js files and load those when the page is initially loaded. While I agree, there are times when that is simply not an option… MVC2 Client Validation is one such example, as it emits JavaScript when the partial view is rendered.

Side note: I originally came across this same type of behaviour is ASP.NET Web Forms in 2007, with the AjaxControlToolkit UpdatePanel. A workable solution for ASP.NET Web Forms is described here: http://weblogs.asp.net/infinitiesloop/archive/2007/09/17/inline-script-inside-an-asp-net-ajax-updatepanel.aspx.

Below are some links to various posts by other people who have had similar issues.

In summary, the responses essentially say three things:

1. ASP.NET MVC AJAX will not execute JavaScript that is dynamically loaded into a DOM element;

2. The only workable solution is to not use MVC AJAX and instead write JavaScript and use jQuery to do all the AJAX; and

3. ASP.NET MVC2 Client Validation needs to be reinitialised after a partial view is dynamically loaded and the JavaScript is executed.

I found these responses to be unsatisfactory! Are people seriously suggesting that one does all of that in the AjaxOption.OnSuccess delegate every time? Right now, I want to take advantage of MVC2 Client Validation and I want to use MVC AJAX – because it is simpler than the alternatives. It should ‘just work’, shouldn’t it? Am I asking too much? After all, this is the second version of ASP.NET MVC!

So noting that JavaScript is a dynamic language, I created the following solution which seamlessly extends the ASP.NET MVC2 JavaScript to make the execution of dynamically loaded JavaScript and the reinitialisation of MVC2 Client Validation happen automatically.

Without diving deeply into the code, the approach is to override the MicrosoftMvcAjax.js Sys.Mvc.MvcHelpers._onComplete method so that I can then hook into the ajaxOptions.onSuccess delegate in order to use jQuery.globalEval() to execute the JavaScript dynamically loaded into the target element, and then finally reinitialise the MVC2 Client Validation.

Just by including this script in an application (carefully loaded AFTER the jQuery and MicrosoftMVCValidation scripts!), this will now happen seamlessly on every MVC2 AJAX request.

Yay! Now the dynamically loaded JavaScript executes, and the MVC2 Client Validation works on partial views that are loaded dynamically with MVC AJAX!

AjaxLoadedContentScriptFix.js

////////////////////////////////////////////////////////////////////////////////
//
// Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix
//
// Original Author: Adam M Craven (http://adammcraventech.wordpress.com)
//
// This extension to ASP.NET MVC2 makes any script loaded as part of dynamically loaded content
// be executable and reinitialises the MVC2 client validation to enable that processing to occur
// for an AJAX loaded view.
//
// Warning: This script may not work with future versions of the minimised MicrosoftMvcAjax.js.
//
// When content (e.g. Partial Views) is dynamically loaded into a DOM target element through AJAX
// via the standard ASP.NET MVC2 "Ajax.ActionLink()" or "Ajax.BeginForm()" methods, any script
// (such as javascript or MVC client validation script) that was emitted is not executed because
// the content is assigned to the target element’s "innerHTML" property. This will not cause the
// script to be executed or execuatable.
//
// Must be included after jQuery and the MicrosoftMvcValidation javascript, typically like this:
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/MicrosoftAjax.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/AjaxLoadedContentScriptFix.js") %>"></script>
//

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix() {
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._onComplete = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix$_onComplete(request, ajaxOptions, ajaxContext) {
    /// <param name="request" type="Sys.Net.WebRequest">
    /// </param>
    /// <param name="ajaxOptions" type="Sys.Mvc.AjaxOptions">
    /// </param>
    /// <param name="ajaxContext" type="Sys.Mvc.AjaxContext">
    /// </param>

    // Hook into the ajaxOptions.onSuccess delegate
    ajaxContext._ajaxLoadedContentScriptFixOrigAjaxOptionsOnSuccess = ajaxOptions.onSuccess;
    ajaxOptions.onSuccess = Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._ajaxOptionsOnSuccess;

    // Call the original MVC onComplete method
    Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._origOnComplete(request, ajaxOptions, ajaxContext);
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._ajaxOptionsOnSuccess = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix$_onSuccess(ajaxContext) {
    /// <param name="ajaxContext" type="Sys.Mvc.AjaxContext">
    /// </param>

    // Make any dynamically loaded script execute
    Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._globalEvalScriptInElementId(ajaxContext.get_updateTarget());

    // Reinitialise the MVC validation
    Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._reinitialiseMvcValidation();

    // Call the original success delegate
    if (ajaxContext._ajaxLoadedContentScriptFixOrigAjaxOptionsOnSuccess) {
        ajaxContext._ajaxLoadedContentScriptFixOrigAjaxOptionsOnSuccess(ajaxContext);
    }
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._globalEvalScriptInElementId = function GlobalEvalScriptInElementId(element) {
    if (jQuery) {
        // jQuery.globalEval($("#" + element.id).find("script").text());

        // It seems jQuery 1.4.1 & 1.4.2 has a problem in IE with .text() on script nodes… so do the loop ourselves…
        var scripts = $("#" + element.id).find("script");
        var allScriptText = "";
        for (var i = 0; i < scripts.length; i++) {
            allScriptText += scripts[i].text;
        }
        jQuery.globalEval(allScriptText);

    } else {
        alert("Error: jQuery must be loaded in order to use Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix");
    }
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._reinitialiseMvcValidation = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix$ReinitialiseMvcValidation() {
    if (Sys.Mvc.FormContext) {
        Sys.Application.remove_load(arguments.callee);
        Sys.Mvc.FormContext._Application_Load();
    }
}

// Register this extension
Sys.Application.add_load(function () {

    if (typeof (Sys.Mvc) === 'undefined' || typeof (Sys.Mvc.MvcHelpers) === 'undefined' ||
        (!Sys.Mvc.MvcHelpers._onComplete && !Sys.Mvc.MvcHelpers.$3)) alert("Error: MicrosoftAjax and MicrosoftMvcAjax.js (or their debug versions) must be loaded in order to use Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix");

    var isMicrosoftMvcAjaxDebugJs = Sys.Mvc.MvcHelpers._onComplete;

    if (isMicrosoftMvcAjaxDebugJs) { // if using MicrosoftMvcAjax.Debug.js
        Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._origOnComplete = Sys.Mvc.MvcHelpers._onComplete;
        Sys.Mvc.MvcHelpers._onComplete = Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._onComplete;
    } else { // using MicrosoftMvcAjax.js
        Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._origOnComplete = Sys.Mvc.MvcHelpers.$3;
        Sys.Mvc.MvcHelpers.$3 = Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._onComplete;
    }
});

Note: this same technique could be used to hook into the other AjaxOption delegate methods if there was a standard, application-wide action that should take place on each AJAX operation… oh I don’t know… for instance: error handling… or an animation…

Update 05/07/2010 – fixed an issue where the script only worked when using the MicrosoftMvcAjax.Debug.js and did not work when using MicrosoftMvcAjax.js. Warning: this script may not work with future versions of the minimised MicrosoftMvcAjax.js.

Update 07/07/2010 – slight tweak to make the check for Sys.Mvc.MvcHelpers happen in the load, and not before we actually need to do it. Some older browsers load the js files out of order and the alert was unnecessarily showing.


VMware Virtual Machine Thrashing Hard Disk

April 22, 2010

In a previous post I discussed how I had been having issues with an incompatibility between the VMware “.vmem” file and antivirus software.

It turns out that a similar disk thrashing issue has been occurring while the VM is running… but this time is occurs randomly. For some reason, VMware decides to perform an almost endless number of reads from the “.vmem” file for at least 15 minutes and thus crippling system performance.

I solved this problem by disabling the usage of the “.vmem” file.

Unfortunately VMware Player does not have a UI setting for this, so I opened up my virtual machine’s VMware “.vmx” settings file and appended the following:

mainMem.useNamedFile = "FALSE"

With this setting, VMware no longer creates and uses the “.vmem” file, and instead relies on the Window’s host machine to use its own paging file, only if and when it is actually necessary.

The only time the “.vmem” file is temporarily created is if you save the virtual machine state (similar to hibernation) instead of shutting down the machine.

The virtual machine now has excellent performance characteristics!


Guidance for Using Optional and Named Parameters In C# & .NET 4.0

April 20, 2010

Leading up to the release of Visual Studio 2010 and Microsoft .NET Framework 4.0, there have been a few posts about how C# 4 now has parity with Visual Basic with regards to the ability to use Optional Parameters. Unfortunately, some of the examples that demonstrate this feature are… well… somewhat disturbing to me from a code quality perspective. In addition there is a lot of talk about how ‘cool’ this feature may appear (from 60,000 feet!), but there is little discussion about recommended guidelines for using Optional Parameters and when it is safe to do so.

Let’s start with the code analysis rule CA1026: Default parameters should not be used. Even in Visual Studio 2010, this rule still exists! Previously a large argument against using Optional Parameters was that code in VB.NET could use them but code in C# would not be able to use them. (This was especially annoying with COM interop!) Before C# 4, a C# coder would have to explicitly provide an argument for each Optional Parameter that was defined (annoying). While this is no longer a concern for C# coders, it is however still valid for consideration when creating methods that may be called from other .NET languages that don’t support the usage of Optional Parameters.

Recently this video on Named and Optional Parameters was released. While the author does a reasonable job conveying the essentials, the scenario is simply a code smell. From a clean code perspective, instead of passing a bunch of search criteria parameters to the ‘Search’ method, the SOLID principles should be used and the criteria should extracted into its own class… This would then mitigate the need for optional parameters in the first place.

In ScottGu’s blog post Optional Parameters and Named Arguments in C# 4 (and a cool scenario w/ ASP.NET MVC 2) [respect to ScottGu btw for your many good works :) ], the “cool scenario” replaces a Nullable parameter named ‘page’ with an optional parameter that has a default value, citing that the Optional Parameter and default value on this public method essentially makes the behaviour of the method expressed “more concisely and clearly”.

Now, I agree that the code may appear slightly more ‘concise’, but I think it is quite arguable that it is more ‘clear’.

Side note: is ‘page’ a 1-based number or a 0-based index? Isn’t a page in the real world usually a 1-based number? e.g. “Page 1 of the search results”. In the spirit of the example code, perhaps the parameter really should be renamed to “pageIndex” – I think that would make the method more clear…

Getting back on track though: by inserting a default value into the method signature, a whisper of the internals of the business logic of this method is hard-coded into the public API.   

Read that again… there is subtlety in there that leaves the feature of Optional Parameters open to unwittingly known abuse by the majority of the population! And it is the lack of clarity due to this subtlety that greatly concerns me from a code quality perspective.

 

What are the subtle caveats?

1) As per the CLI specification, the default value must be a compile-time constant value.

2) When compiled, the default value is emitted into a DefaultParameterValue attribute as metadata on the parameter within the method signature.

3) When the compiler is compiling the code that calls the method, the compiler reads this value from the DefaultParameterValue attribute and actually hard-codes that value into the IL at the call-site. In other words, every line of code throughout all applications that call that method have this value hard-coded in their calling assembly.

As an example, if you are using say Version 1.0 of the assembly with the method which specifies a default value of 25 for the parameter, your code will be compiled and have the value of 25 hard-coded into your assembly. If you upgrade to say Version 1.1 of the assembly with the method (which now specifies a default value of 26 instead of 25), and if you do not recompile your code, your code when executed will pass the method a value of 25. The public API has been broken, and almost everyone would be unaware!

(I found that this information is described in much more detail in C# 4.0 FEATURE FOCUS – PART 1 – OPTIONAL PARAMETERS and due to my concern about the age of the post I actually verified it myself with the help of Reflector…)

Anyone else flashing back to why “public [static] readonly” values should be used instead of “const”? It’s the same argument! The const value is treated as a literal and is hard-coded into each assembly that uses the value. (Conveniently, for more information, you can read THE DIFFERENCE BETWEEN READONLY VARIABLES AND CONSTANTS)

4) Alternatively, if you as the caller of the method were to actually name the parameter in your calling code, and if you upgraded to the next version of assembly with the method which has had the parameter renamed, your code will not compile! Why? Because when using Named Parameters, the parameter name itself actually needs to be considered part of your API!

 

What should be the guidelines for using Optional and Named Parameters?

In general, I would suggest that Optional Parameters (just like the usage of the const keyword) should only ever be used with constant values that will never ever change over time – for example, mathematical constants… like the value of PI (although I don’t know why you would make PI an Optional Parameter… but you get the idea nevertheless). Generally and unfortunately however this will typically exclude any ‘constant-like’ values in your business domain. Values in business domains, while seemingly constant for now still can change over time as the business changes!

As always there are going to be a few perspectives on this. I find that it is useful to categorise development into two areas: (a) application development, and (b) reusable library development.

Especially when developing reusable library code, extreme care needs to be taken when creating and maintaining public APIs. I would suggest that Optional Parameters should NOT be used in public APIs of reusable library code… instead revert to the usage of method overloading, or redesigning your API.

However, in application development, where all the code is highly likely to be recompiled (and often), perhaps it isn’t so bad to use the Optional Parameters?… that is, until a team member decides to clean up the code by doing some refactoring and move that method into a reusable library… and then it all begins!

 

Summary

So for safety, clarity, simplicity and consistency across all code-bases (especially with the widely varying technical capabilities of developers), perhaps the best practice guidance for using Optional and Named Parameters should be:

1. Never use Optional Parameters in public methods; and

2. Only use Optional Parameters with default values that are constant in time (like mathematical constants and not apparent business domain constant values).


Best Free Transcoder – XMedia Recode

February 25, 2010

The jury (of just me) is out!

Over the last few years I have tried too many free transcoding tools including: MediaCoder, Handbrake, Super, Format Factory, Any Video Converter, BeSweet and almost every other free tool I could download (thanks especially to Doom9 for their help over the years).

For the last few years, my stable has been MediaCoder, although I have had a love-hate relationship with its stability between versions (introduction of bugs), the annoyingly periodic A/V synchronisation issues that happen for me and other general problems that occur seemingly randomly.

Recently however I discovered XMedia Recode. I am absolutely delighted and I highly recommend this software! It is a German site, but it can be viewed in English through Google Translate.

Of special mention, I had a home DVD that would correctly play on a DVD player but would not correctly play on the 3 different PCs that I tried. From one of those PCs, XMedia Recode actually properly converted this DVD, even though the PC couldn’t properly play it! Go figure!

According to the home page, XMedia Recode can directly convert unprotected DVDs and nearly all popular audio and video formats including 3GP, 3GPP, 3GPP2, AAC, AC3, AMR, ASF, AVI, AVISynth, DVD, FLAC, FLV, H.261, H.263, H.264, M4A , M1V, M2V, M4V, Matroska (MKV), MMF, MPEG-1, MPEG-2, MPEG-4, TS, TRP, MP2, MP3, MP4, MP4V, MOV, QT, OGG, PSP, (S) VCD , SWF, VOB, WAV, WMA and WMV.

Its major features include: batch processing, AVISynth support, a whole swag of video and audio processing options (including cropping, colour correction, aspect ratio selection, zoom, direct stream copy, multi-pass encoding, volume correction and normalisation, and the adjustment of the framerate, bitrate and resolution) and more than 30 profiles/templates for various devices such as Pocket PC, iPod, iPhone, PSP and PS3.

What is it that they say about German engineering?…

This is good, reliable, working software. In fact, it is the best free transcoder I have found – so I take off my hat to you Sebastian Dörfler.


Web Development Links

February 15, 2010

Here are some handy links to web development information.

jQuery

- Download

- Documentation

- Tutorials

        – How jQuery Works

        – Getting Started with jQuery

        – 7 Amazing Presentation Slides

- Variable Types

- APIs

        – Utilities API

        – Manipulation API

        – Attributes API

        – Traversing API

        – Events API

        – AJAX API

        – Effects API

        – CSS API

-jQuery UI

 

ASP.NET

- MSDN ASP.NET root

        – ASP.NET 4 root

                – ASP.NET Walkthroughs by Scenario

                – What’s New in ASP.NET 4

                – ASP.NET Web Pages

                – ASP.NET Web Projects

                – ASP.NET Model View Controller (MVC)

                – ASP.NET Infrastructure

                (HTTP handlers, modules, state and routing)

                – ASP.NET Controls

                – Microsoft Ajax

                – ASP.NET Data Access

                – ASP.NET Web Services

                – ASP.NET Security

                – ASP.NET Migration and Conversion 

                (Migrating to ASP.NET 2, 3.5, and 4)

                – ASP.NET Web Sites for Mobile Devices

        – ASP.NET MVC root

        – HTML and CSS

 

Silverlight

- MSDN Silverlight root

        – Silverlight 4

        – Silverlight 3

 

WCF RIA Services

- MSDN WCF RIA Services root


VMware “.vmem” Files and Antivirus Program Incompatibility

December 16, 2009

I have been using a local virtual machine using WMware products on a Windows 7 host that also runs Microsoft Forefront Client Security (MFCS).

MFCS is configured to schedule a scan of the disk on a nightly basis from 2am. As I have painfully noticed however, if I allow the virtual machine to be in a running state overnight, then even by 10am MFCS is still thrashing the hard disk at 100% and thus making my host machine almost unresponsive.

After an investigation, I discovered that the disk was thrashing on a VMware virtual machine “.vmem” file. This file type is apparently a backup of the virtual machine’s paging file that only exists while the virtual machine is running, or if it has crashed.

So in order to solve the problem I added “*.vmem” to the list of files to exclude when MFCS performs a scan.


Follow

Get every new post delivered to your Inbox.