Posts Tagged ‘.Net’

Equals, ==, and MSTest

April 26th, 2010

  public class SampleClass
    {
        public int X { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (obj.GetType() != typeof(SampleClass)) return false;
            var s = obj as SampleClass;
            return this.X == s.X;
        }
    }

Tests:

        [TestMethod()]
        public void EqualsTest()
        {
            var sc = new SampleClass { X = 1 };
            var sc_copy = sc;
            var sc2 = new SampleClass { X = 1 };

            Assert.IsFalse(sc.Equals(null));
            Assert.IsTrue(sc.Equals(sc));
            Assert.IsTrue(sc == sc_copy);
            Assert.IsFalse(sc == sc2);
            Assert.IsTrue(sc.Equals(sc2));
            Assert.IsTrue(sc2.Equals(sc));
            Assert.IsTrue(sc.Equals(sc_copy));

            Assert.AreEqual(sc, sc2);
            Assert.AreEqual(sc, sc_copy);
            Assert.AreSame(sc, sc_copy);
            Assert.AreNotSame(sc, sc2);
            Assert.AreNotSame(sc_copy, sc2);
        }

External Tools in Visual Studio

April 5th, 2010

If you use subversion or git, bouncing over to source control is something you have to do a lot from Visual Studio. Here’s how to make it easier. In Visual Studio, go to Tools -> External Tools and setup Explorer if you use TortoiseSVN, or GitBash if you use that.

Explorer
GitBash

Passing in “this” in StructureMap

February 26th, 2010

I’ve been working with StructureMap lately, and struggled when I need to pass this in. The following code is an example of resolving that issue…

namespace StateMachine
{
  public class StateRegistry : StructureMap.Configuration.DSL.Registry
  {
    public StateRegistry ()
      {
        For<IState>.Use<StateA>.Named("FirstState");
        For<IState>.Use<StateB>.Named("SecondState");
      }
  }

  public interface IStateMachine
  {
    void ChangeState(IState state);
  }

  public interface IState
  {
    void DoWork();
  }

  public class StateA : IState
  {
    IStateMachine _machine;
    public StateA(IStateMachine machine)
      {
        _machine = machine;
      }
    public void DoWork() { // do stuff }
  }

  public class Machine : IStateMachine
  {
    public IState FirstState {get;set;}
    public IState SecondState {get;set;}
    public IState CurrentState {get; private set;}
    public Machine()
      {
        FirstState = ObjectFactory.With<IStateMachine>(this).GetInstance<IState>("FirstState");
        SecondState = ObjectFactory.With<IStateMachine>(this).GetInstance<IState>("SecondState");
        ChangeState(FirstState);
      }
    public void ChangeState(IState state) { CurrentState = state; }
  }
}

Function Name Instead of Lambda in Linq Functions

February 8th, 2010

I did not realize that functions can fill in for predicates directly without lambda notation. To illustrate, consider the following:

void Main()
{
	var words = new List<string>()
	{
		"therapists",
		"s words",
		"slang",
		"mustache",
		"sean connery"
	};

	var s_words = words.Where(w => w.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase));

	foreach(var word in s_words)
	{
		Console.WriteLine(word);
	}
}

It works, but it’s a rather long lambda, which is why I broke it out of the for loop. Let’s put that logic into a function, getting this:

void Main()
{
	var words = new List<string>()
	{
		"therapists",
		"s words",
		"slang",
		"mustache",
		"sean connery"
	};

	foreach(var word in words.Where(w => SWords(w)))
	{
		Console.WriteLine(word);
	}
}

public bool SWords(string word)
{
	return word.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase);
}

That’s better. And you might find yourself using your test in other places in the code, so it’s useful to have the function. What I found out recently, is that you can go one step further:

void Main()
{
	var words = new List<string>()
	{
		"therapists",
		"s words",
		"slang",
		"mustache",
		"sean connery"
	};

	foreach(var word in words.Where(SWords))
	{
		Console.WriteLine(word);
	}
}

public bool SWords(string word)
{
	return word.StartsWith("s" ,StringComparison.CurrentCultureIgnoreCase);
}

In this example, the savings may not look drastic. But for several chained methods you can gain a lot of brevity and clarity.

MSpec “Hello World” Sample

February 4th, 2010

I’ve been working with MSpec lately. It’s a BDD framework for .Net. Here’s a hello world type example that uses Trace Writing to show a little bit about what it does.

using System;
using Machine.Specifications;
using System.Diagnostics;

namespace UnitedIndustrial.DataImportConcerns
{
    [Subject("Sample")]
    public class SampleConcerns
    {
        static string _myString;
        Establish _context = () =>
        {
            _myString = "value from context";
            LocationValueDump("context");
        };

        Because _of = () =>
         {
             _myString = "value from because";
             LocationValueDump("because");
         };

        It _shouldKnow1And1Equals2 = () =>
         {
             (1 + 1).ShouldEqual(2);
             LocationValueDump("_shouldKnow1And1Equals2");
         };

        It _shouldKnowANewStringIsNotNull = () =>
        {
            "hello".ShouldNotBeNull();
            LocationValueDump("_shouldKnowANewStringIsNotNull");
        };

        private static void LocationValueDump(string location)
        {
            Trace.WriteLine(
                String.Format("in {0} _myString is {1}",
                location, _myString));
        }
    }
}

IEnumerable and Linq

July 7th, 2009

I was helping someone on StackOverFlow.com and ran into an interesting issue. The post is here.

I explained the issue in my response, but I’ll try to sum up. Newer collection types implement IEnumerable(Of T) as opposed to the original IEnumerable interface. For example, System.Generic.List(Of T) implements IEnumerable(Of T), so the following is valid without casting:

Dim names As New Generic.List(Of String)
names.Add("Bob")
names.Add("Bill")
names.Add("Joe")
names.Add("Zeke")
Dim threeLetterNames = From name In names _
                                     Where name.Length = 3 _
                                     Select name
Dim i As Integer = 1
For Each name As String In threeLetterNames.ToList()
    Console.WriteLine("Name {0} of {1}: {2}", i, threeLetterNames.Count, name)
    i += 1
Next
Console.Read()

Because the Generic List returns strings. So “name” in the Where clause is a string.

In the original poster’s question, they were using a DataGridViewRowCollection. It implements IEnumerable. So any Linq code sees each item as an object.

Here’s what’s strange about this. The “as type” clause does not resolve the issue. In a for each loop, it does resolve it. Why does For Each compile to include a cast, and Linq does not? That’s a good question for Microsoft.

SilverLight and Z-Index

July 7th, 2009

When implementing a new SilverLight custom control, it was blocking menu popups (html / javascript) on the page. I set the z-index of the div and object tags that contained SilverLight to no avail. After a lot of googling, I found the following solution.

Set the Windowless property to true. In the case of manually adding SilverLight to the page, that results in the following child tag of the object tag…

<param name="Windowless" value="true" />

Fun With the GAC

June 26th, 2009

The .Net GAC (Global Assembly Cache). It’s where all shared .Net components can live. However, if you have to step through the code of one of these assemblies things can get exciting…

Let’s say that I have a Business Object dll named business.dll and I have it in my GAC. And a project in which I’m referencing that dll is having problems, inside that component. I go to source control and check out the source. Add that project into my solution in Visual Studio. Unreference the GAC version, and reference the local project. I should be able to step through, right?

Wrong. The CLR resolves assemblies in the GAC before anywhere else.

Go into your GAC (C:\Windows\Assembly\GAC_MSIL) and rename the dll with an extension like “.bak”. Don’t forget to rename it after your done debugging :)

tags: , , | categories: Uncategorized | one comment »

Debug NUnit Tests With Visual Studio

November 25th, 2008

1. Set a break point in a unit test
2. Open NUnit
3. In Visual Studio, go the tools Menu and choose Attach to Process (or Ctrl-Alt-P)
4. Choose nunit out of the list
5. Run tests. Make sure you run the test where your breakpoint is if you don’t run all tests.

JScript.Net and C# Interaction

November 19th, 2008

// lib.cs:

using System;

namespace Library {
  public class TestLib {
    public static void speak(){
       Console.WriteLine(“Hello From CSharp Dll”);
    }
  }
}

// hello.js
import System;
import Library;

var a = {name:’JScript Object in Exe’};
a.foo = function (){
  Console.WriteLine(‘Hello From ‘ + this.name);
};

a.foo();

TestLib.speak();

Compiling:

1. Make sure .Net Framework is in your path

2. csc.exe /t:library lib.cs

3. jsc.exe /r:lib.dll hello.js

4. hello.exe