Struct, optional parameters and overload resolution

A note what i have seen today. (I made up this sample to emphasize the important part). Assume this type definition:

struct MyValueType
{
    public MyValueType(int number = 1)
    {
       this.number = number;
    }
    private int number;
    public int Number
    {
        get { return number; }
        set { number = value; }
    }
}

And the usage of the type later:

var myValueType = new MyValueType();
// code follows assuming that myValueType.Number == 1

The author of this code did not know that value types get a default contructor (or did not consider that), and incorrectly assumed that the newly created value type “instance” will be created by the explicitly defined contructor (having an optional parameter). However this default constructor has changed everything, since overload resolution prefers the overload with fewer arguments.
Nice little gotcha of c#.

Posted in Uncategorized | Leave a comment

Moles and .Net 4.5

Recently i had to make a solution still targeting version 4.0 of the .Net framework to compile and run on a machine with .Net 4.5 . This was the first step of migrating that solution to 4.5.
First i have created a test environment (VS2010 + .Net 4.0) where i made sure that the everythig is fine (solution compiles and all tests pass) before attempting to install .net 4.5. After installing 4.5 almost all projects compiled, except the unit test projects using moles. It seems moles generated source for .Net 4.5 types, however the unit test projects were set to target version 4.0. (One example of this is the SqlCredential class)
After seraching on the web i found the suggested workaround for this, namely to exclude the problematic types using the .moles file, however this did not work for me.
I needed more information from moles so i tried to turn on logging to verbose level, however setting that from the .moles file did not gave any usable results. When checking the build output i found out that the moles msbuild task generates an options file and runs moles.exe using that file as settings file. This settings file can be found in obj\moles\moles.args. I modified this file by adding /d for enabling diagnostic mode and /v:Noisy for detailed logging. Then i ran moles.exe and passed the modified @moles.args as parameter. From the logs it was clear that moles is trying to load the 4.0 reference assembly from the reference assemblies directory, however the assembly with the same version is loaded from the GAC (which is in place updated to 4.5). Checking the code with ILSpy, it turned out that moles loads assemblies in two separate ways depending on the ReflectionOnly attribute. If this is set to true, the correct reference assembly gets loaded into the reflection only load context, otherwise the GAC 4.5 assembly gets loaded. After modifying all the moles files to use ReflectionOnly=”true”, all the moles assemblies got generated successfully (using 4.0 code) and all the tests passed (except one, that found an incompatible change in .Net 4.5).

As it turned out setting the ReflectionOnly property to true can solve moles compilation errors in projects targeting .Net 4.0 on a machine having 4.5 installed.

Posted in Uncategorized | Leave a comment

WPF databinding to properties with long running getter

I have just seen a WPF application what was showing some list of items coming from a web service call. To avoid blocking the UI thread the viewmodel was using the threadpool to do the web request and when the response arrived it used the PropertyChanged event to notify the ui to “refresh” the binding. This all seems reasonable, but wpf has built-in support for this scenarios, namely the IsAsync property of the Binding class. Using this property is fairly simple and helps to avoid that bunch of code that one needs to write to achieve the same results. Here is a simple example, first the code behind simulating a long running task.

 1: using System.Collections.Generic; 
 2: using System.ComponentModel; 
 3: using System.Threading; 
 4: using System.Windows; 
 5: 
 6: namespace AsyncBinding 
 7: { 
 8: public partial class MainWindow : Window 
 9: { 
 10: public MainWindow() 
 11: { 
 12: InitializeComponent(); 
 13: this.DataContext = this; 
 14: } 
 15: 
 16: private List<Element> elements; 
 17: 
 18: public IEnumerable<Element> Elements 
 19: { 
 20: get 
 21: { 
 22: if (elements == null) 
 23: { 
 24: elements = new List<Element>(); 
 25: Thread.Sleep(5000); 
 26: for (int i = 0; i < 10; i++) 
 27: { 
 28: elements.Add(new Element() { Value = "Value" + i }); 
 29: } 
 30: } 
 31: return elements; 
 32: } 
 33: } 
 34: } 
 35: 
 36: public class Element 
 37: { 
 38: public string Value { get; set; } 
 39: } 
 40: } 
 41:

For this simple example the DataContext is the window itself and it has the Elements property which does take long time to read for the first time. The xaml of the window:

 1: <Window x:Class="AsyncBinding.MainWindow" 
 2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
 3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
 4: Title="MainWindow" Height="350" Width="525"> 
 5: <Grid> 
 6: <ListBox ItemsSource="{Binding Elements, IsAsync=True}"> 
 7: <ListBox.ItemTemplate> 
 8: <DataTemplate> 
 9: <TextBlock Text="{Binding Value}" /> 
 10: </DataTemplate> 
 11: </ListBox.ItemTemplate> 
 12: <ListBox.Style> 
 13: <Style TargetType="ListBox"> 
 14: <Style.Triggers> 
 15: <Trigger Property="HasItems" Value="false"> 
 16: <Setter Property="Template"> 
 17: <Setter.Value> 
 18: <ControlTemplate> 
 19: <Border BorderBrush="Aqua" BorderThickness="5"> 
 20: <TextBlock Text="Please wait.." HorizontalAlignment="Center" VerticalAlignment="Center"/> 
 21: </Border> 
 22: </ControlTemplate> 
 23: </Setter.Value> 
 24: </Setter> 
 25: </Trigger> 
 26: </Style.Triggers> 
 27: </Style> 
 28: </ListBox.Style> 
 29: </ListBox> 
 30: </Grid> 
 31: </Window> 
 32: 

At line six the IsAsync property is set to true for the Binding doing the binding for the ItemsSource of the ListBox. Also from line twelve to twenty-eight there is some added style to provide some information for the user while waiting for the list items.

In my opinion this feature is really usefull in these common situations.

Posted in Uncategorized | Leave a comment

Using config transformations in non web applications

I have recently faced a problem where i needed to use separate configuration settings in an application depending the build configuration. The well known web.config transformations came to my mind however this application is not a web one. I have tried to add app.Debug.config and app.Release.config to the project hoping that it will pick up the transformations but it didn’t. Knowing this i thought that there must be some web related build task that is responsible for the transformations so the next step was to check the msbuild target files. With a bit of searching i came to Microsoft.Web.Publishing.targets file which has a task called TransformXml what seemed doing what i need. What left was to call this task in my project, and for that BeforeBuild target looked a good candidate for me. This build target sits in the project file. To edit the project file i right-clicked it and selected unload project, then right-clicked it again and selected edit. At the end of the file i made the following modifications:

  1:  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  2:   <!-- Import targets file for transformations -->
  3:   <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
  4:   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
  5:        Other similar extension points exist, see Microsoft.Common.targets. -->
  6:   <Target Name="BeforeBuild">
  7:     <TransformXml 
  8:       Source="$(ProjectDir)app.config" 
  9:       Transform="$(ProjectDir)\app.$(ConfigurationName).config" 
 10:       Destination="$(TargetDir)\$(TargetName)$(TargetExt).config" 
 11:       Condition="Exists('$(ProjectDir)app.config') AND Exists('$(ProjectDir)\app.$(ConfigurationName).config')" />
 12:   </Target>
 13:   <!--<Target Name="AfterBuild">
 14:   </Target>
 15:   -->

First things first i have imported the required targets file (i haven’t checked but it seems coming with VS installation, even with the express one), then i added the new TransformXml task to the BeforeBuild task i have uncommented. Here i simply set that the config transformation output will be created in the build output folder. After this all i had to do is to make sure that i have added the config transformation files to the project and after building i got the expected config file in my output folder.

Using web config transformations is a very useful tool in my opinion, however for non web applications it is not available by default. By using this method i hope one can use this really cool feature in desktop (or whatever) applications as well.

Posted in Uncategorized | Leave a comment

Asp.Net MVC inline editing

Today I got a feature request to have inline editing available on an mvc list view (like what traditional asp.net data controls have). The main reason for this that the business entity is really simple in this case (actually only a user name). My first idea was to do it with partial views and ajax.

Lets start going backward, so create some standard edit controller actions first. (GetEntityForEdit and SaveEntity are helper methods allowing to avoid non necessary code)

   1: public ActionResult Edit(int id)
   2: {
   3:   return View(GetEntityForEdit(id));
   4: }
   5:  
   6: [AcceptVerbs(HttpVerbs.Post)]
   7: public ActionResult Edit(int id, Entity entity)
   8: {
   9:   SaveEntity(id, entity);
  10:   return RedirectToAction("Index");
  11: }

Now create a partial view for editing. Since we are editing a simple text value, we can omit validation.

   1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<InlineEditing.Models.Entity>" %>
   2: <% using (Html.BeginForm()) {%>
   3:     <%= Html.Hidden("ID", Model.ID) %>
   4:     <label for="Text">Text:</label>
   5:     <%= Html.TextBox("Text", Model.Text) %>
   6:     <input type="submit" value="Save" />
   7: <% } %>

Now create the action that will present a list.

   1: public ActionResult Index()
   2: {
   3:     return View(GetEntityList());
   4: }

In the corresponding view every item needs an own div, so we can access it from javascript, and overwrite it with the result from edit action call. The ajax call can be made with the mvc ajax library, using an ajax actionlink. (don’t forget to reference the MicrosoftAjax and the MicrosoftMvcAjax script libraries).

   1: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<InlineEditing.Models.Entity>>" %>
   2: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
   3:     Index
   4: </asp:Content>
   5: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   6:     <h2>Index</h2>
   7:     <% foreach (var item in Model) { %>
   8:     <div id='<%= string.Format("div_{0}", item.ID)%>' >
   9:         Text : <%= Html.Encode(item.Text) %>
  10:         <%= Ajax.ActionLink("Edit", "Edit", new { id = item.ID }, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = string.Format("div_{0}", item.ID) })%>
  11:     </div>
  12:     <% } %>
  13: </asp:Content>

This will create a very basic inline editing experience, that can be improved a lot of ways.

Posted in Uncategorized | Leave a comment