Category Archives: 8431

Is Your ASP.NET Development Server Not Working?

Since Visual Studio 2005, Visual Studio comes with a development web server: the ASP.NET Development Server.

I’ve been using this web server for simple test projects since than with Visual Studio 2005 and Visual Studio 2008 in Windows XP Professional on my work laptop and Windows XP Professional, Windows Vista 64bit Ultimate and Windows 7 64bit Ultimate at my home desktop without any problems (apart the known custom identity problem, that is).

When I received my new work laptop, I installed Windows Vista 64bit Enterprise and Visual Studio 2008 and, for my surprise, the ASP.NET Development Server wasn’t working.

I started looking for differences between the laptop environment and the desktop environment and the most notorious differences were:

System

Laptop

Desktop

SKU

Windows Vista 64bit Enterprise

Windows Vista 64bit Ultimate

Joined to a Domain

Yes

No

Anti-Virus

McAffe

ESET

After asserting that no domain policies were being applied to my laptop and domain user and nothing was being logged by the ant-virus, my suspicions turned to the fact that the laptop was running an Enterprise SKU and the desktop was running an Ultimate SKU. After having problems with other applications I was sure that problem was the Enterprise SKU, but never found a solution to the problem. Because I wasn’t doing any web development at the time, I left it alone.

After upgrading to Windows 7, the problem persisted but, because I wasn’t doing any web development at the time, once again, I left it alone.

Now that I installed Visual Studio 2010 I had to solve this. After searching around forums and blogs that either didn’t offer an answer or offered very complicated workarounds that, sometimes, involved messing with the registry, I came to the conclusion that the solution is, in fact, very simple.

When Windows Vista is installed, hosts file, according to this contains this definition:

127.0.0.1       localhost
::1             localhost


This was not what I had on my laptop hosts file. What I had was this:



#127.0.0.1       localhost
#::1             localhost


I might have changed it myself, but from the amount of people that I found complaining about this problem on Windows Vista, this was probably the way it was.



The installation of Windows 7 leaves the hosts file like this:



#127.0.0.1       localhost
#::1             localhost


And although the ASP.NET Development Server works fine on Windows 7 64bit Ultimate, on Windows 7 64bit Enterprise it needs to be change to this:



127.0.0.1       localhost
::1             localhost


And I suspect it’s the same with Windows Vista 64bit Enterprise.

A TraceListener For Tests

In my code, I make extensive use of debug assertions (see System.Diagnostics.Debug.Assert). These assertions are very helpful while debugging because you don’t need to step into every line of code to see if all pre-conditions are met. As soon as a pre-condition fails, an assertion failed window will pop up and will allow us to either abort, ignore or go to the assertion instruction (retry).


Imagine you have this code:

private void IKnowForSureThatANullStringWillNeverBePassed(string text)
{
    System.Diagnostics.Debug.Assert(string != null, “text is null.”);

    // …
}

Because this method is private, I have full control of what is passed to the text parameter, therefore I’m asserting that it will never be null. Because it might not be obvious that text will never be null, the assertion also acts as documentation.


I usually run my unit tests and integration test on debug compilations and these assertions would be helpful by making the test fail on an assertion fail instead of running through the method and failing with an NullReferenceException. That’s why I (and more people out there) wrote this simple TraceListener:

public class TraceListener : global::System.Diagnostics.TraceListener
{
    public static readonly TraceListener Default = new TraceListener();

    protected TraceListener()
    {
        this.Name = “Testing Trace Listener”;    
    }

    protected TraceListener(string name)
        : base(name)
    {
    }

    public override void Write(string message)
    {
    }

    public override void WriteLine(string message)
    {
    }

    public override void Fail(string message, string detailMessage)
    {
        var builder = new global::System.Text.StringBuilder();

        builder.Append(message);

        if (detailMessage != null)
        {
            builder.Append(” “);
            builder.Append(detailMessage);
        }

        throw new global::Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException(builder.ToString());

    }
}

This trace listener won’t write anything to anywhere. It will just throw an AssertFailedException if the Fail method is called, which is what happens when an assertion fails.


Because an assertion window is not desired when running the tests (specially if they are automated tests ran as part of a build process) it’s better to disable the assert UI on the configuration file of the test project.

<?xml version=1.0encoding=utf-8?>
<configuration>
    <system.diagnostics>
        <assert assertuienabled=false/>
        <trace>
            <listeners>
                <add name=TestTraceListenertype=PauloMorgado.TestTools.VisualStudio.UnitTesting.Diagnostics.TraceListener, PauloMorgado.TestTools.VisualStudio/>
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>
You can find this and other tools on the PauloMorgado.TestTools on CodePlex.

How To Set Elements Of An Array Of A Private Type Using Visual Studio Shadows

Visual Studio uses Publicize to create accessors public for private members and types of a type.


But when you try to set elements of a private array of elements of a private type, things get complicated.


Imagine this hypothetic class to test:

public static class MyClass
{
    private static readonly MyInnerClass[] myArray = new MyInnerClass[10];

    public static bool IsEmpty()
    {
        foreach (var item in myArray)
        {
            if ((item != null) && (!string.IsNullOrEmpty(item.Field)))
            {
                return false;
            }
        }

        return true;
    }

    private class MyInnerClass
    {
        public string Field;
    }
}

If I want to write a test for the case when the array has “non empty” entries, I need to setup the array first.


Using the accessors generated by Visual Studio, I would write something like this:

[TestClass()]
public class MyClassTest
{
    [TestMethod()]
    public void IsEmpty_NotEmpty_ReturnsFalse()
    {
        for (int i = 0; i < 10; i++)
        {
            MyClass_Accessor.myArray[i] = new MyClass_Accessor.MyInnerClass { Field = i.ToString() };
        }

        bool expected = false;
        bool actual;

        actual = MyClass.IsEmpty();

        Assert.AreEqual(expected, actual);
    }
}

But the test will fail because, although the elements of the private array myArray can be read as MyClass_Accessor.MyInnerClass instances, they can’t be written as such.


To do so, the test would have to be written like this:

[TestClass()]
public class MyClassTest
{
    [TestMethod()]
    public void IsEmpty_NotEmpty_ReturnsFalse()
    {
        for (int i = 0; i < 10; i++)
        {
            MyClass_Accessor.ShadowedType.SetStaticArrayElement(“myArray”, new MyClass_Accessor.MyInnerClass { Field = i.ToString() }.Target, i);
        }

        bool expected = false;
        bool actual;

        actual = MyClass.IsEmpty();

        Assert.AreEqual(expected, actual);
    }
}

But, this way, we loose all the strong typing of the accessors because we need to write the name of the array field.


Because the accessor for the field is a property, we could write a set of extension methods that take care of getting the field name for us. Something like this:

public static class PrivateypeExtensions
{
    public static void SetStaticArrayElement<T>(this PrivateType self, Expression<Func<T[]>> expression, T value, params int[] indices)
    {
        object elementValue = (value is BaseShadow) ? (value as BaseShadow).Target : value;

        self.SetStaticArrayElement(
            ((PropertyInfo)((MemberExpression)(expression.Body)).Member).Name,
            elementValue,
            indices);
    }

    public static void SetStaticArrayElement<T>(this PrivateType self, Expression<Func<T[]>> expression, BindingFlags invokeAttr, T value, params int[] indices)
    {
        object elementValue = (value is BaseShadow) ? (value as BaseShadow).Target : value;

        self.SetStaticArrayElement(
            ((PropertyInfo)((MemberExpression)(expression.Body)).Member).Name,
            invokeAttr,
            elementValue,
            indices);
    }
}

Now, we can write the test like this:

[TestClass()]
public class MyClassTest
{
    [TestMethod()]
    public void IsEmpty_NotEmpty_ReturnsFalse()
    {
        for (int i = 0; i < 10; i++)
        {
            MyClass_Accessor.ShadowedType.SetStaticArrayElement(() => MyClass_Accessor.myArray, new MyClass_Accessor.MyInnerClass { Field = i.ToString() }, i);
        }

        bool expected = false;
        bool actual;

        actual = MyClass.IsEmpty();

        Assert.AreEqual(expected, actual);
    }
}

It’s not the same as the first form, but it’s strongly typed and we’ll get a compiler error instead of a test run error if we change the name of the myArray field.


You can find this and other tools on the PauloMorgado.TestTools on CodePlex.

Compiling .NET 1.1 Projects In Visual Studio 2008

After having put my .NET 1.1 application running on the .NET 2.0 runtime (^), I’m planning on migrating it to .NET 2.0, but not all at once.

Because I don’t want to have 2 solutions (one on Visual Studio 2003 for the .NET 1.1 assemblies and another on Visual Studio 2008 for the .NET 2.0 assemblies) I decide to try using MSBee and have only one Visual Studio 2008 solution.

MSBee has a CodePlex project. You can download it from there or from Microsoft Downloads. Because the build on Microsoft Downloads seemed to be the most stable one, that was the one I downloaded and installed. The package comes with a Word document that explains all that needs to be done.

Before you can install and use MSBee you’ll need to install the .NET 1.1 SDK.

Having everything installed, I just opened the Visual Studio 2003 solution in Visual Studio 2008 and let it convert the solution and projects (near 30).

After the conversion, for building the projects with the .NET 1.1 C# compiler, the project files need to be edited to add the override the default targets with the MSBee ones by adding the MSBee imports after the default imports for the language:

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath)\MSBee\MSBuildExtras.FX1_1.CSharp.targets" />



Another change needed (for Visual Studio 2008 – I don’t know if it was needed for Visual Studio 2005) is the tools version. MSBee needs version 2.0. To change that you’ll have to change the ToolsVersion attribute of the project’s root element:



<Project DefaultTargets="Build" ToolsVersion="2.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">



MSBee likes has own idea about output paths and I had set up custom output paths on my project. There’s information about this on the documentation but I decided to simply comment that out of the $(MSBuildExtensionsPath)\MSBee\MSBuildExtras.FX1_1.Common.targets file:



<!-- Paulo
<Choose>
  <When Condition=" '$(BaseFX1_1OutputPath)' == '' ">
    <PropertyGroup>
      <OutputPath>bin\FX1_1\</OutputPath>
    </PropertyGroup>
  </When>
  <Otherwise>
    <PropertyGroup>
      <OutputPath>$(BaseFX1_1OutputPath)</OutputPath>
      <OutputPath Condition=" !HasTrailingSlash('$(OutputPath)') ">$(OutputPath)\</OutputPath>
    </PropertyGroup>
  </Otherwise>
</Choose>
-->

<!-- Paulo
<PropertyGroup>
  <BaseIntermediateOutputPath>obj\FX1_1\</BaseIntermediateOutputPath>
  <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU' ">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
  <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU' ">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>

  <OutputPath Condition=" '$(PlatformName)' == 'AnyCPU' ">$(OutputPath)$(Configuration)\</OutputPath>
  <OutputPath Condition=" '$(PlatformName)' != 'AnyCPU' ">$(OutputPath)$(PlatformName)\$(Configuration)\</OutputPath>
  
  <- Once OutputPath is determined, set OutDir to its value. ->
  <OutDir>$(OutputPath)</OutDir>
</PropertyGroup>
-->



This all seemed to work fine on my old Windows XP machine without any third party Visual Studio plug-ins, but when I tried it on my Windows Vista X64 machine, I came across some problems:



  • License Compiler

    Because I’m using Infragistics‘ controls, there’s a licences.licx file and the build will compile it. And that proved to be a problem.

    MSBee copies all the files it needs to the build process to a temporary folder, builds it in there and then copies the result to the output path.

    LC.exe seemed to never be able to find all the assemblies it needed. Searching seemed to me to be an old issue (even from the .NET 1.1 times) and the solution always pointed to not compile the license file. So, I commented that part out of the $(MSBuildExtensionsPath)\MSBee\MSBuildExtras.FX1_1.Common.targets file:

    <Target
        Name="CompileLicxFilesCondition="'@(_LicxFile)'!=''"
        DependsOnTargets="$(CompileLicxFilesDependsOn)"
        Inputs="$(MSBuildAllProjects);@(_LicxFile);@(ReferencePath);@(ReferenceDependencyPaths)"
        Outputs="$(IntermediateOutputPath)$(TargetFileName).licenses">
    
      <!--
      <LC
          Sources="@(_LicxFile)"
          LicenseTarget="$(TargetFileName)"
          OutputDirectory="$(IntermediateOutputPath)"
          OutputLicense="$(IntermediateOutputPath)$(TargetFileName).licenses"
          ReferencedAssemblies="@(ReferencePath);@(ReferenceDependencyPaths)"
          ToolPath="$(TargetFrameworkSDKDirectory)bin\">
    
        <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
        <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
    
      </LC>
      -->
    </Target>
  • Resource Generator

    Although this worked fine on the command line, inside Visual Studio ResGen.exe would throw some error and needed to be closed.

    Looking at the Windows Application Log I found out this:

    Faulting application Resgen.exe, version 1.1.4322.573, time stamp 0x3e559b5f, faulting module MockWeaver.dll, version 0.0.0.0, time stamp 0x4adb072e, exception code 0xc0000005, fault offset 0x00018fac, process id 0x4a50, application start time 0x01ca53c14488a2fb.

    MockWeaver.dll belongs to Isolator and I just disable it when building inside Visual Studio. I was hoping to start using Isolator on this project, but, for now, I can’t.



I hope this can be of some help and, if you need more, you’ll probably find it at the MSBee’s CodePlex forum.



The bottom line is: You don’t need Visual Studio 2003!

MSDN Ramp Up Program

MSDN Ramp Up Program

I just came across this: www.MyRampUp

Ramp Up is a free, online, community-based program that can help users save time in learning Microsoft technology.

The easy-to-access content (provided by subject-matter gurus) is specifically tailored to the Ramp Up program, and offered in a variety of forms (whitepaper, v-lab, codecast and slidecast).

Program Guide

The currently available routes are:

SharePoint for Developers track - learn more

Visual Studio 2008 track - learn more

Aspiring Developer - learn more

Success with Java and C# - learn more

Next Level Visual Basic - learn more

Next Level Microsoft.NET - learn more

Currently, there are no assessments in the program, so it’s quicker than ever to graduate and receive the reward (25% off on certification and 50% off on e-Learning – only for graduates of Ramp Up).