Disabling File-System-Redirection on 64bit

The following call disables File-System-Redirection on 64bit Windows in WOW mode (e.g. Accessing Program Files and ending up in Program Files (x86)): // Minimum client Windows XP Professional x64 Edition or higher // Minimum server Windows Server 2003 with SP1 or higher NativeMethods.Kernel32.Wow64DisableWow64FsRedirection(pt1);

Visual Studio Intellisense support for parameters in JavaScript

From the perspective of a .NET developer JavaScript lacks of intellisense. Of course, Visual Studio is capable of showing intellisense for defined objects and their members, but when it comes to parameters we face the untyped world. Last year I did a project with a few developers who had to leave their beloved C# world and enter the JavaScript area. Their motivation declined from day to day. So I thought of how to provide them with what they were missing like water in the desert. My approach is based on the facade pattern. It allows to instanciate objects of a type with an instance of the same type, to acts as a wrapper to restore intellisense a JSON object, to be able to load data from a server request into a domain object Here is the code: function Person(data) { /// <summary>Instantiates a new instance of a Person. /// <para> 1. An JSON object containing data.</para> /// <para> 2. A Person object.</para> /// </summary> /// <param name="data" type="object"> /// An object. /// <para>containing data to initialize a person.</para> /// <para>- or -</para> /// <para>of type Person beeing returned by the facade /// to activate intellisense.</para> /// </param> var args, arg, member, lcMember, memberValue; this.firstName = ''; this.lastName = ''; this.fullName = function () { /// <summary> /// Returns the full name of the person. /// </summary> return this.firstName + ' ' + this.lastName; }; //#region Facade pattern to keep intellisense alive... if (arguments !== null || arguments.length === 1) { args = arguments; arg = args[0]; if (arg instanceof Person) { return arg; } else if (arg instanceof Object) { for (member in arg) { lcMember = member.substring(0,1).toLowerCase() + member.substring(1); if (this.hasOwnProperty(lcMember)) { memberValue = arg[lcMember]; if (arg.hasOwnProperty(lcMember)) { memberValue = arg[lcMember]; } else if (arg.hasOwnProperty(member)) { memberValue = arg[member]; } if (typeof(memberValue) === 'string' && memberValue.indexOf('/Date(') === 0) { memberValue = new Date( parseInt( memberValue.substr(6))); } this[lcMember] = memberValue; } } } } //#endregion return this; } The only thing I don’t like about is the fact that I need to name the type when comparing by instanceOf… Wrapped in an Visual Studio snippet eases up the pain… And here is an example of the usage: $(document).ready( function () { // After an object is instantiated intellisense works... var person = new Person({ firstName: 'daniel', lastName: 'fisher' }); // ... but when passed as a parameter it gets lost ... printFullName(person); }); function printFullName(person) { // ... using the facade pattern we let intellisense // know what *type* it is. var thePerson = new Person(person); console.log(thePerson.fullName()); } I hope this helps!

MsBuild finding directories if not given as parameter

I’m a lazy developer. Being lazy does not mean I avoid to work. It means that I like to reflect things I am doing and optimize and atomize stuff to get more time on the valuable tasks. Code generation is a tool I tend to use quite regularly and T4 is at most my generator of choice. Generated files can cause a lot of merging conflicts. So they are not to be checked into my source control system (currently my choice is HG/Mercurial). For the build server this means the files do not exist when the repository is freshly checked out – they need to be generated during the build right before the compile happens. With code generation I usually tend to use a pattern that is for example also used by ASP.NET MVC Views/Controller generation: If there is a local directory containing code generation templates, use it. Otherwise utilize the system wide templates. MsBuild version 4.0 comes with a feature called property functions. This allows to place for instance a “find directories” inside a property group. I use them to: Allow to set a system wide template directory using the command line/the MsBuild API. If no directory is set use a local directory. If non of the above is applied set a fallback default. Here is the XML snippet that shows how to use the pattern: <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Generate" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <RootFolder>..\src</RootFolder> <CodeGeneratorDir Condition=" '$(CodeGeneratorDir)' == '' " /> <LocalCodeGeneratorDir> CodeGenerationTemplates </LocalCodeGeneratorDir> <CodeGeneratorDirFallback> C:\CodeGenerationTemplates </CodeGeneratorDirFallback> </PropertyGroup> <ItemGroup> <ModelFiles Include="..\src\**\*.xdml" /> <TemplateDirectory Include="$(CodeGeneratorDir);" /> <TemplateDirectory Condition=" '$(CodeGeneratorDir)' == '' " Include="$([System.IO.Directory]::GetDirectories( &quot;$(RootFolder)&quot;, &quot;$(LocalCodeGeneratorDir)&quot;, System.IO.SearchOption.AllDirectories))" /> <TemplateDirectory Condition=" '@(TemplateDirectory)' == '' " Include="$(CodeGeneratorDirFallback)" /> </ItemGroup> <Target Name="Generate"> <Message Text="@(TemplateDirectory)" /> <Message Text="@(ModelFiles)" /> </Target> </Project>

Setting up a local SSL development environment for multiple sites

The environment should also work on a notebook while working at a coffee shop. The need for a NIC that is always connected. 1. Add a loopback adapter... [WIN] + [R] | hdwwiz.exe 2. Open the “Network and Sharing Center” … 3. Click “Change adapter settings” and identify the loopback adapter… 4. Rename the loopback adapter… 5. Open loopback adapter’s properties… 6. Disable IP v6… 7. Edit IP v4 settings and assign an IP Address… 8. Click advanced an add another IP address for each SSL-Site to be hosted… 9. Open “IIS Manager” and click “Server Certificates”… 10. Click “Create self signed certificate” for each SSL site to be hosted and choose the host name as friendly name… 11. Assign each site to be hosted a dedicated IP address plus certificate… 12. Associated IP addresses with host names in the hosts file (or install DNS Services when on Server 2008)… Done!

Regions are like knives

Most people state that regions are bad. I prefer a more fine grained definition: Regions in code are like knives. They can cause serious injury. But a surgeon can use one to do good. What are region intended for? Regions provide you the ability to expand and collapse code. You can do this with members, classes and namespaces without a region. The difference is that the region keeps the collapsed state when opening a file. The ugly There are a few problems with regions like merging in source control or the growth of classes but these are not my main pain points. Most times I stumble across region they are used in a bad manor. On a code review today this is what showed up in the editor: What is so bad about it? Well I like to read code and believe that reading code is really important. Therefor readability of code is important to me. It increases the maintainability. Lowers the times to understand and extend or refactor code. In short: Things that make me happy. The regions showed force me to do unnecessary stuff, before I can read the code – I need to expand the regions, otherwise: I can’t see what members are contained in the class. I can’t read the names of the members that tell me what they do/the code does (Yes, I know – I assume that developers read the C# coding guidelines and name their stuff by using their brain). You could argument that VS has this nice little thing that shows all members in a drop down list on the upper right corner of the editor. But I don’t want to read code in a drop down list, sorry. I use regions Despite of the many things on the negative side, I like regions and I use them. I believe that regions can even give you a plus on the pain point I described. I create regions to decrease the time somebody needs to read or understand code. For me a region is an abstraction. And as we all know also abstraction can be good as well as bad is used wrong. Abstracting code by wrapping member types together is contra-productive because I don’t care for instance what members are in the class. That’s only a technical perspective. On the opposite an increased productivity can be achieved by providing a layer that shows the skeleton or structure of the class. This way I can see what’s in the class from a functional perspective. If I now want to drill down into the code (after I already know what’s there) I’m forced to react. That is o.k. and my intention because the regions give me an overview and do not hide almost everything.  

Enable editing of enumerable data in ASP.NET MVC

I’m currently working on an ASP.NET MVC project. Today I stumbled across a requirement that involved enabling the editing of data that is displayed (on a lets call it master page). The specialty of the data is it’s an enumerable. I had a few Ideas how to solve the problem. 1. Ajaxification Pro: I like jQuery. I like that you can directly edit stuff Con: I like to have a low-level fallback 2. The UeberEditorTemplate.ascx  Pro: On first sight an easy way out Con: Yakk! all that logic in one editor template. Both did not really satisfy me. So I started playing around a bit. The first thing I figured out is that editor templates can be used with c# currying: Next I created my action that handles the post to inspect the forms collection the templates would create. This is the time where a custom model binder can be a really be a helpful friend. I switched to a view model that contains the enumerable to enable the model binder through the class attribute: 1 [ModelBinder(typeof(UserContactDataBinder))] 2 public class Xyz 3 { 4 public List<MyDataItem> Data { get; set; } 5 } And finally created the model binder: 1 public object BindModel( 2 ControllerContext controllerContext, 3 ModelBindingContext bindingContext) 4 { 5 var model = new Xyz(); 6 model.Data = new List<MYDataItem>(); 7 var context = 8 controllerContext.HttpContext; 9 var formValues = 10 context.Request.Form; 11 12 var values = 13 formValues["data.Value"].Split(','); 14 15 for (int i = 0; i < values.Length; i++) 16 { 17 var ucd = 18 new MyDataItem 19 { 20 Value = values[i], 21 }; 22 model.Data.Add(ucd); 23 } 24 25 return model; 26 } 27 } That’s it! ASP.NET MVC really rocks!

Do not debug on daylight saving time switch

  WTF? Solution: Unmark the auto adjustment EDIT: While I blogged this I had the same issue on my blog. Here is the snapshot of the event log Event code: 3005 Event message: An unhandled exception has occurred. Event time: 10/31/2010 2:11:48 AM Event time (UTC): 10/31/2010 12:11:48 AM Event ID: 2da507c58aa84c7b8ed29e8fbf3908bc Event sequence: 496 Event occurrence: 9 Event detail code: 0  Application information:     Application domain: /LM/W3SVC/4/ROOT-1-XXXXXXXXXXX     Trust level: Full     Application Virtual Path: /     Application Path: X:\xxxxxxx\lennybacon.com\www\     Machine name: DEVPLEXHQ  Process information:     Process ID: 4212     Process name: w3wp.exe     Account name: NT AUTHORITY\NETWORK SERVICE  Exception information:     Exception type: ArgumentOutOfRangeException     Exception message: Specified argument was out of the range of valid values.Parameter name: utcDate  Request information:     Request URL: http://lennybacon.com/FormatPage.aspx?path=SiteConfig/pageerror.format.html     Request path: /FormatPage.aspx     User host address: XX.XX.XX.XX    User:      Is authenticated: False     Authentication Type:      Thread account name: NT AUTHORITY\NETWORK SERVICE  Thread information:     Thread ID: 18     Thread account name: NT AUTHORITY\NETWORK SERVICE     Is impersonating: False     Stack trace:    at System.Web.HttpCachePolicy.UtcSetLastModified(DateTime utcDate)   at System.Web.HttpCachePolicy.SetLastModified(DateTime date)   at newtelligence.DasBlog.Web.Core.SiteUtilities.GetStatusNotModified(DateTime latest)   at newtelligence.DasBlog.Web.Core.SharedBasePage.NotModified(EntryCollection entryCollection)   at newtelligence.DasBlog.Web.Core.SharedBasePage.Page_Load(Object sender, EventArgs e)   at System.Web.UI.Control.OnLoad(EventArgs e)   at System.Web.UI.Control.LoadRecursive()   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

More comfort reading values from lines in CSV-files

Today I had to read values from multiple CVS-files. I wanted to build a testable and reusable solution instead of the ugly sequential spaghetti that easily happens. So here is a sample of a line: 1 var lineReadFromCsv = 2 "42;Daniel;Fisher;1980-03-25;{79704C0D-1A4F-4DDD-80F6-CA79E81BF7CD}"; To increase the readability I created enumerations that point to the index of the position of the values in each line that I wanted to read: 1 public enum DataFormatField 2 { 3 Id = 0, 4 GivenName = 1, 5 Surname = 2, 6 DateOfBirth = 3, 7 UniqueId = 4, 8 } I created a class called ParserParameter that contains enums that 1 public class ParserParameter 2 { 3 prop Enum FirstName { get; set; } 4 //... 5 } 6 Last but not least an extension class the provides a generic method TryGetValueOrDefault<T>(). It takes an enum member as parameter. It can convert int, long, float, decimal, double, guid, datetime as well as string and can easily be extended. 1 int id; 2 if (fields.TryGetValueOrDefault( 3 DataFormatField.Id, 4 out id)) 5 { 6 Console.WriteLine(id); 7 } 8 9 string givenName; 10 if (fields.TryGetValueOrDefault( 11 DataFormatField.GivenName, 12 out givenName)) 13 { 14 Console.WriteLine(givenName); 15 } 16 The complete code can be downloaded at forkcan.