Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

My baby steps to PostSharp 1.0

So... you downloaded PostSharp 1.0 and you installed it and are wondering... "What's next?".

Well my friends, let me walk you through the first steps of PostSharp. What could we do that would be simple enough? Hummm... what about writing to a debug window? That sounds simple enough! Let's start. So I created a new Console Application project and I added the reference to PostSharp.Laos and PostSharp.Public. As a requirement, the class must be tagged with "Serializable" attribute and implement OnMethodBoundaryAspect (not in all case but let's start small here).

Next, I have a few methods I can override. The two that we are interested in right now is "OnEnter" and "OnExit". Inside of it, we'll say which method we are entering and which one we are exiting. Here are my Guinea pig classes:

public class FooBar
        {
        [DebugTracer]
        public void DoFoo()
        {
        Debug.WriteLine("Doing Foo");
        }

        [DebugTracer]
        public void DoBar()
        {
        Debug.WriteLine("Doing Bar");
        }
        }

        [Serializable]
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
        public class DebugTracer : OnMethodBoundaryAspect
        {
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
        Debug.WriteLine(string.Format("Entering {0}", eventArgs.Method.Name));
        }

        public override void OnExit(MethodExecutionEventArgs eventArgs)
        {
        Debug.WriteLine(string.Format("Exiting {0}", eventArgs.Method.Name));
        }
        }

See how simple this is? But... does it work? Let's see the trace of calling each methods:

Entering DoFoo
Doing Foo
Exiting DoFoo
Entering DoBar
Doing Bar
Exiting DoBar

Isn't that wonderful? Compile execute and enjoy. But... what about the community you say? Of course if the tool is not open source there is probably nothing built around it, right? Wrong!

Here is a few resources for PostSharp that include pre-made attributes that are ready to be used:

That was everything I could find. Do you know any others?


Permalink | Comments (0) | Post RSSRSS comment feed

LyricWiki.org - How to retrieve lyrics for your mp3 in C#?

I have an iPhone and I got a lot of songs on it. I don't particularly love to sing but I got a few bands that have tendencies to say their lyrics in a... obscure way. Since I'm really curious, I'm always on Google searching for the lyrics. I wanted to save some time and avoid unnecessary browsing. The iPhone have the capacity of displaying lyrics if they are included inside the mp3 metadata. Updating the lyrics is something but where will I retrieved thousands song lyric?

I recently found out about a website called LyricWiki.org. What is interesting is that they have a web service (for free) available. I then decided to share how I did it. First thing is to start a project. You will then add a service reference like this:

image

Click on Go, change namespace and click on OK. Once  this is done, the easy part is done. Please note that the service URL has been stored under App.config with all the related settings.

Now to retrieve the actual lyrics, no more than a little bit of code:

// create a client to connect to the service
        LyricWikiPortTypeClient client = new LyricWikiPortTypeClient();

        // retrieve a song. Creed is good. Love this band.
        LyricsResult song = client.getSong("Creed", "One");

        // display the artist and the lyrics
        Console.WriteLine(string.Format("Found lyrics for \"{0} - {1}\":\r\n\r\n" +
        "{2}", song.artist, song.song, song.lyrics));

        // let you read it :)
        Console.ReadLine();

That was easy now wasn't it? Next post, how to update your mp3 with iTunes! Keep reading!


Categories: c# | code snippet
Permalink | Comments (0) | Post RSSRSS comment feed

System.Diagnostics.Process and xcopy... why it doesn't work?

We spent 30 minutes on a spiny issue. We execute some commands directly from a C# program but we want to make sure that everything executed. We did unit test on some code and everything seemed to work.

Today, we tried it live with some real case scenario where we execute some XCOPY. And then.... nothing.

We didn't receive any ExitCode that was 0. We didn't catch any exception. And we didn't catch anything in the error stream.

Here is the code that we used:

private void ExecuteProcess()
        {
        // setup the process info
        var startInfo = new ProcessStartInfo(@"cmd.exe", @" /c xcopy c:\file*.txt c:\file*.bck")
        {
        UseShellExecute = false,
        CreateNoWindow = true,
        WorkingDirectory = @"C:\",
        RedirectStandardError = true,
        RedirectStandardOutput = true
        };


        using(Process proc = Process.Start(startInfo))
        {
        proc.OutputDataReceived += ((sender, e) => MessageBox.Show("Data: " + e.Data ?? String.Empty));
        proc.ErrorDataReceived +=
        (sender, e) => MessageBox.Show(string.Format("Error: {0}", e.Data ?? string.Empty));
        proc.BeginErrorReadLine();
        proc.BeginOutputReadLine();

        proc.WaitForExit();
        }

        }

Wow. Nice piece of code isn't it? It will work for everything you have to execute. But if you execute XCOPY it won't work. We found out that it's missing something that should not be needed in our case but that cause XCOPY to just execute with no output and no results.

You want XCOPY to work? Just add this line before starting the process:

startInfo.RedirectStandardInput = true;

That's it! This error will only happen if you have "UseShellExecute" set to false.

Hope it help some clueless programmer that is wondering why the XCOPY won't execute.


Categories: c# | code snippet
Permalink | Comments (3) | Post RSSRSS comment feed

How to add custom build step to a TFS Server Build ?

Most of the time when you are creating a build script (TFSBuild.proj), you need to do some steps after the build. Wether it's creating an MSI for easier deployment, creating a VSI for a Visual Studio Add-in, or whatever if may be... you normally do a post build.

A post build event looks like the following inside the TFSBuild.proj :

<Target Name="AfterDropBuild">
        <CallTarget Targets="PostBuildStep" />
        </Target>

        <Target Name="PostBuildStep">
        <!-- Do something -->
        </Target>

When you only have 1 or 2 tasks and that one fails, it might be easy to find the one that failed. What if you have 8 to 20 tasks? It then becomes incredibly hard to find which one failed. What I've seen the most is normally some "<Message />" tags with some descriptive tasks. This is the equivalent of debugging with Console.WriteLine or Debug.Print.

What if you could know EXACTLY which task failed to run? Here is a way to add a custom build step to your TFS build which will allow you to easily know what crashed.

<Target Name="PostBuildStep">
        <!-- Create the build steps which start in mode "Running" -->
        <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Message="Doing Something on a PostBuild Event" Condition=" '$(IsDesktopBuild)' != 'true' ">
        <!-- Return the ID of the tasks and assigned it to "PropertyName" -->
        <Output TaskParameter="Id" PropertyName="PostBuildStepId" />
        </BuildStep>

        <!-- Do something -->

        <!-- When everything is done, change the status of the task to "Succeeded" -->
        <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(PostBuildStepId)" Status="Succeeded" Condition=" '$(IsDesktopBuild)' != 'true' " />

        <!-- If an error occurs during the process, run the target "PostBuildStepFailed" -->
        <OnError ExecuteTargets="PostBuildStepFailed" />
        </Target>


        <Target Name="PostBuildStepFailed">
        <!-- Change the status of the task to "Failed" -->
        <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(PostBuildStepId)" Status="Failed" Condition=" '$(IsDesktopBuild)' != 'true' " />
        </Target>

With that in place, you will see exactly which task failed. As a bonus, it will also give you the time at which it completed. This will easily allow you to compare with your other task to see which one is taking the most time.

I would like to thank Martin Woodward which is a TeamSystem MVP. The question originated from Stackoverflow and more details are also available on Martin's website.


Categories: build | code snippet | tfs
Permalink | Comments (0) | Post RSSRSS comment feed

Unit testing Internals member of a solution from another project

Here is a little bit of knowledge that lots of people are not aware of. There is an Attribute that is InternalsVisibleToAttribute that allows access to a specific external project (the unit test project).

This attribute, once inserted inside AssemblyInfo.cs, will grant "public" visibility to all internal members of the project to the project specified within the attribute.

Here is how it is shown on MSDN:

[assembly:InternalsVisibleTo("MyAssembly, PublicKey=32ab4ba45e0a69a1")]
        

It is however wrong and will never work. The main reason is that what is there let us believe that it's the PublicKeyToken but it is in fact the PublicKey as clearly typed there.

So... how do we get this PublicKey? By executing the following command:

sn -Tp MyAssembly.dll

The result is going to be something like the following:

Public key is
        0024000004800000940000000602000000240000525341310004000001000100adfedd2329a0f8
        3e057f0b14e47f02ec865e542c2dcca6349177fe3530edd5080276c48c6d02fa0a6f67738cc1a0
        793be3322cf17b8995acc15055c00fa61b67a203c7eb2516922810ff0b17cd2e08492bdcafc4a9
        23e6fff4caba672a4c2d0d0f5cac9aea95c3dce3717bb733d852c387f5f025c42c14ec8d759f7e
        b13689be
Public key token is 96dfc321948ee54c

Here is the end result to make it properly visible:

[assembly: InternalsVisibleTo("AssemblyB, PublicKey="
        + "0024000004800000940000000602000000240000525341310004000001000100adfedd2329a0f8"
        + "3e057f0b14e47f02ec865e542c2dcca6349177fe3530edd5080276c48c6d02fa0a6f67738cc1a0"
        + "793be3322cf17b8995acc15055c00fa61b67a203c7eb2516922810ff0b17cd2e08492bdcafc4a9"
        + "23e6fff4caba672a4c2d0d0f5cac9aea95c3dce3717bb733d852c387f5f025c42c14ec8d759f7e"
        + "b13689be" )]

After this step is done, all reference to internal members are considered "public" for this specific project. This simple trick allows you to complete your tests and don't gives any excuse not to test.


Categories: c# | code snippet | unit test
Permalink | Comments (0) | Post RSSRSS comment feed

Easily enable databindings on a ToolStripButton

I was developping an application lately and I needed to bind the "Enabled" property of a ToolStripButton to my Presenter. I failed to find any "DataSource" or "DataBindings" property. I then decided to make my own button without reinventing the wheel to enable this capability.

Here's this simple class:

using System.Windows.Forms;

namespace TestProject
{
        public class ToolStripBindableButton : ToolStripButton, IBindableComponent
        {
            private ControlBindingsCollection dataBindings;

            private BindingContext bindingContext;

            public ControlBindingsCollection DataBindings
            {
                get
                {
                        if(dataBindings == null) dataBindings = new ControlBindingsCollection(this);
                        return dataBindings;
                }
            }

            public BindingContext BindingContext
            {
                get
                {
                    if(bindingContext == null) bindingContext = new BindingContext();
                    return bindingContext;
                 }
                set { bindingContext = value; }
            }
        }
}
        

Once you include this simple class inside your project/solution... you can easily convert any ToolStripButton into our new ToolStripBindableButton.

And I solved my problem like this:

myBindableButton.DataBindings.Add("Enabled", myPresenter, "CanDoSomething");

Categories: c# | code snippet | controls
Permalink | Comments (0) | Post RSSRSS comment feed

Part 2 - Basic of mocking with Moq

See also:  Part 1 - Part 3

As every mocking framework, except TypeMock which can perform differently, every mocked class can't be sealed and methods that need to be mocked need to be public. If  the class is not inheriting from an interface, the method that are being mocked need to be virtual.

Once this is cleared... let's show a simple example of a Product having it's price calculated with a Tax Calculator.

Here's what we are starting with:

public class Product
{
    public int ID { get; set; }
    public String Name { get; set; }
    public decimal RawPrice { get; set; }
    public decimal GetPriceWithTax(ITaxCalculator calculator)
    {
        return calculator.GetTax(RawPrice) + RawPrice;
    }
}

public interface ITaxCalculator
{
  decimal GetTax(decimal rawPrice);
}

The method we want to test here is Product.GetPriceWithTax(ITaxCalculator). At the same time, we don't want to instantiate a real tax calculator which gets it's data from a configuration or a database. Unit tests should never depend upon your application's configuration or a database. By "application's configuration", I mean "App.config" or "web.config" which are often changed during the life of an application and might inadvertently fail your tests.

So, we are going to simply mock our tax calculator like this:

//Initialize our product
        Product myProduct = new Product {ID = 1, Name = "Simple Product", RawPrice = 25.0M};

        //Create a mock with Moq
        Mock<ITaxCalculator> fakeTaxCalculator = new Mock<ITaxCalculator>();

        // make sure to return 5$ of tax for a 25$ product
        fakeTaxCalculator.Expect(tax => tax.GetTax(25.0M)).Returns(5.0M);

Now It all depends on what you want to  test. Depending if you are a "State" (Classic) or "Behaviour verification" (Mockist), you will want to test different things. If you don't know the difference, don't bother now but you might want to look at this article by Martin Fowler.

So if we want to make sure that "GetTax" from our interface was called:

// Retrived the calculated tax
        decimal calculatedTax = myProduct.GetPriceWithTax(fakeTaxCalculator.Object);

        // Verify that the "GetTax" method was called from  the interface
        fakeTaxCalculator.Verify(tax => tax.GetTax(25.0M));

If you want to make sure that the calculated price equal your product price with your tax added (which confirm that the taxes were calculated):

// Retrived the calculated tax
        decimal calculatedTax = myProduct.GetPriceWithTax(fakeTaxCalculator.Object);

        // Make sure that the taxes were calculated
        Assert.AreEqual(calculatedTax, 30.0M);

What's the difference? The first example verify the behaviour by making sure that "GetTax" was called. It doesn't care about the value returned. It could return 100$ and it would care. All that mattered in this example was that GetTax was called. Once this is done, we can assume that the expected behaviour was confirmed.

The second example is a state verification. We throw 25$ inside the tax calculator and we expect the tax calculator to return 5$ for a total price of 30$. It wouldn't call GetTax and it wouldn't care. As long as the proper value is returned, it's valid.

Some people will argue that behaviour is better than state (or vice versa). Personally, I'm a fan of both. A good example is that I might want to verify that an invalid invoice will not be persisted to the database and a behaviour verification approach is perfect for this case. But if I'm verifying (like in this case) that the tax were properly calculated, state behaviour is more often than not quicker and more easier to understand.

Nothing prevent your from doing both and making sure that everything works. I'm still not a full fledged TDD developer but I'm trying as much as possible to make tests for my classes as often as possible.

If you found this article helpful, please leave a comment! They will be mostly helpful for my presentation on February 25th 2009 at www.dotnetmontreal.com.


Categories: c# | code snippet | mock | moq | tdd
Permalink | Comments (0) | Post RSSRSS comment feed

Code Snippet - Quickly changing the host in an URL in C#

Quick code snippet today. Let's say you have some URLs that you want to change the hostname/port on it without having to do string manipulation.

//multiple constructor are available
        UriBuilder builder = new UriBuilder("http://localhost:1712")
        {
        Host = Environment.MachineName,
        Port = 80
        };
        Uri myNewUri = builder.Uri; 

There you go! It's as easy as this. This will avoid countless hour of parsing a URL for the hostname, port number or whatever else you are searching.

The bonus with that is that the path of the URL won't be touched at all.

Have fun!


Categories: c# | code snippet
Permalink | Comments (0) | Post RSSRSS comment feed

Code Snippet: Filtering a list using Lambda without a loop

This is not the latest news of the day... but if you are doing filtering with loops, you are doing it wrong.

Here's a sample code that will replace a loop easily:

List<String> myList = new List<string> {"Maxim", "Joe", "Obama"};
        myList = myList.Where(item => item.Equals("Obama")).ToList();

While this might sound too easy, it's easily done and works fine. Just make sure that the objects that you are using inside this kind of filtering are not ActiveRecord DAL object or you might be sorry for the performance.


Categories: c# | code snippet
Permalink | Comments (0) | Post RSSRSS comment feed

Creating a StreamProxy with Delegate/Lambda to read/write to a file

I saw a question the last time on Stackoverflow. The accepted answer was from Jon Skeet which was:

  • Event handlers (for GUI and more)
  • Starting threads
  • Callbacks (e.g. for async APIs)
  • LINQ and similar (List.Find etc)
  • Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)

I was once asked "What is the use of a delegate?". The main answer that I found was "to delay the call". Most people see delegate as events most of the time. However, they can be put to much greater use. Here is an example that I'll gladly share with you all:

 

public class StreamProxy<T>
        where T : Stream
        {
        private Func<T> constructorFunction;

        private StreamProxy(Func<T> constructor)
        {
        constructorFunction = constructor;
        }

        public void Write(Action<StreamWriter> func)
        {
        using(T stream = constructorFunction())
        {
        StreamWriter streamWriter = new StreamWriter(stream);
        func(streamWriter);
        streamWriter.Flush();
        }
        }

        public String Read(Func<StreamReader, String> func)
        {
        using (T stream = constructorFunction())
        {
        string result = func(new StreamReader(stream));
        return result;
        }
        }

        public static StreamProxy<T> Create(Func<T> func)
        {
        return new StreamProxy<T>(func);
        }
        }

To summarize what it does... it accept a delegate that returns a class that derives from "Stream" that will be used as a Constructor. It will return you a StreamProxy object that you can then use to read or write String out of that stream. What is interesting is that when it's first created... nothing is done on the file. You are just giving instruction to the class on how to access it. When you then read/write from the file, the class knows how to manage a stream and make sure that no locks are left on the files. Here is a sample usage of that class:

 

// Here I use a FileStream but it can also be a MemoryStream or anything that derives from Stream
        StreamProxy<FileStream> proxy = StreamProxy<FileStream>.Create(() => new FileStream(@"C:\MyTest.txt", FileMode.OpenOrCreate));

        // Writing to a file
        proxy.Write(stream => stream.WriteLine("I am using the Stream Proxy!"));

        // Reading to a file
        string contentOfFile = proxy.Read(stream => stream.ReadToEnd());

That's all folks! As long as you can give a Stream to this proxy, you won't need to do any "using" in your code and everything will stay clean!

See you all next time!


Categories: c# | code snippet
Permalink | Comments (0) | Post RSSRSS comment feed