Go to content Go to navigation Go to search

Brokenwire.NET::M

Quick Tip: VirtualBox sound on Windows Server 2008R2 x64
· 2010-12-10 19:02 by Thijs Kroesbergen for Brokenwire.NET

To enable audio for a Windows Server 2008 (and most probably also on windows 7) guest in VirtualBox you can get the generic AC'97 Audio Codecs from the realtek website:

http://www.realtek.com/downloads/downloadsCheck.aspx?Langid=1&PNid=23&PFid=23&Level=4&Conn=3&DownTypeID=3&GetDown=false

The zip file is about 30 mb, seems like a lot of bytes for just a sound driver… but hey, it works.

Just download and extract the zip file to a folder, then point the device manager to that folder and let it install the driver.

Update:

If you want to play sounds using the WPF MediaPlayer class then you also need to have Media Player (at least version 10) installed. To do that on Windows Server you need to install the “Desktop Experience” feature.

Permalink -

How to unittest internals
· 2010-12-08 16:13 by Thijs Kroesbergen for Brokenwire.NET

This how-to is written by Mark Groot, and published on here on Brokenwire.net with his permission.

Normally when you try to unit test a method from an internal class, u will receive a message saying something like ‘… is inaccessible due to its protectionlevel’. The typical response in these kind of situations is either ‘ah, f.. it. I’ll just skip this test’ or ‘I’ll just make the class public. Who cares.’.

What you actually want to do is to make the internal method accessible to your unit test project. As it turns out, that this isn’t really all that difficult. Visual Studio will do most work for you. There are however a few things u have to keep in mind. In this article I will stretch out on those things.

First, let’s make a little console app which contains an internal class. (The entire solution can be downloaded here).

public interface ICoinFlip
{
  bool YouWon(bool choiceIsHead);
}


internal class CoinFlip : ICoinFlip
{
  public CoinFlip()
  {
  }

  bool ICoinFlip.YouWon(bool choiceIsHead)
  {
      // You can only win if you pick head
      // This is stupid, but that is not the point here
      return choiceIsHead;
  }
}

static void Main(string[] args)
{
  ICoinFlip flip = new CoinFlip();
            
  bool coinSideIsHead = (new Random()).Next(0, 2) == 1;

  if (flip.YouWon(true) == coinSideIsHead)
    Console.WriteLine("You win!");
  else
    Console.WriteLine("You lose!");
}

When you run this code you will get a nice little console window telling u whether or not you won.

Now how to test this? There are a few steps you have to take.

Let Visual Studio create a unittest and a unit test project for you.

You can create a unit test for the YouWon method by right-clicking the method and selecting ‘Create Unit Tests…’ from the contextmenu.

Clicking the menu option will popup the following window.

In the treeview you can select additional methods for which you want to create unit tests. You have to select a project from the listview in which the test has to be created.

Now Visual Studio will create a test class for the selected method in your selected unit test project including all the necessary references.

Visual Studio will also add the assembly:InternalsVisibleTo attribute to the AssemblyInfo file of your console application.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("coinflipTest")]

By using this attribute the unit test assembly will become a “friend assembly ” of the main assembly, and therefore the main assembly will allow the test assembly access to its internals.

Edit the test method

Visual Studio will generate a TestMethod in the new test class looking like this:

After some clean up the code looks like this:

[TestMethod()]
[DeploymentItem("coinflip.exe")]
public void YouWonTest()
{
  ICoinFlip target = new CoinFlip();
  bool choiceIsHead = false;
  bool expected = false;
  bool actual;
  actual = target.YouWon(choiceIsHead);
  Assert.AreEqual(expected, actual);
}

We enter the value false into the method and we expect to receive a value false back. If that is true, then the test passed.

The following steps are only necessary when you have a strongly signed project:

Find the public key of your unit test project

There was a time where finding the public key token using sn –T was enough. Now however, the InternalsVisibleTo  attribute uses the public key.
We can retrieve that key in two steps by using the sn.exe tool.
First create a file with the public key from the assembly key file using the following command (inside a Visual Studio command prompt)

sn –p NameOfYourKeyFile.snk NameOfYourOutputFile.PublicKey.

Use the output file to retrieve the public key with the –tp option of sn.exe:

sn –tp NameOfYourOutputFile.PublicKey.

The result is some text and a large key looking like this:

Microsoft (R) .NET Framework Strong Name Utility  Version 4.0.30319.1
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key is
00240000048000009400000006020000002400005253413100040000010001003b825be7fe7e93
f782f0ff49cb2c86845698b15301834dc63cf9b9c62ea95aa02151a069cafb82f1902dfec1e2be
16b7f05d99e84a5796060d044ab62a1bcc6ffc7d12ab03827c22b4a70a67797bc82aea51a6c9b9
c31fee99410dbbc54b32dd9b18f202e97912b967120d4655a8575a2568738e7a08b662a0004440
91d500cf

Public key token is de3fc1b9aa83af40

Then add the key into the AssemblyInfo of the console application.

As we saw before, when we created the unit test the following entry was created in the AssemblyInfo file:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("coinflipTest")]

You have to change this into:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("coinflipTest, PublicKey=PASTE-YOUR-PUBLIC-KEY-HERE")]

Here you copy-paste the public key from the previous step into the marked section. You will have to remove the linebreaks, but that should be rather obvious. Don’t copy the key shown here, you have to use your own key…

To see if this works: build the project, and run the test.

Enjoy!

Permalink -

Equals is not Differs
· 2010-10-12 12:43 by Thijs Kroesbergen for Brokenwire.NET

Just a small code snippet I wanted to share with you… (it made me laugh and cry at the same time)

public bool Equals(Adres a2)
{
    return !Differs(a2);
}

public bool Differs(Adres a2)
{
    return (a2 == null)
    || (this.Straat != a2.Straat)
    || (this.Huisnummer != a2.Huisnummer)
    || (this.Postcode != a2.Postcode)
    || (this.Plaats != a2.Plaats)
    || (this.DatumIngang != a2.DatumIngang)
    || (!this.DatumEinde.HasValue && a2.DatumEinde.HasValue)
    || (this.DatumEinde.HasValue && !a2.DatumEinde.HasValue)
    || (this.DatumEinde.HasValue && a2.DatumEinde.HasValue && (this.DatumEinde.Value != a2.DatumEinde.Value))
    ;
}

Watch, learn, don’t repeat. Share the pain in the comments.

Permalink -

Bill Gates in Outlook 2010
· 2010-10-04 12:53 by Thijs Kroesbergen for Brokenwire.NET

If you have used outlook 2010 you must have seen the new ‘People pane’ which feature the contact information of all people involved in the current item. Last week a colleague pointed out that the gray “Generic User” is supposed to be an image of Bill Gates himself. So lets see…

The avatar in outlook:

The Bill Gates Mugshot:

This mugshot is said to be made when Bill was caught speeding, back in the seventies.

Now lets combine the two images:

And because i’m not very good with Paint.Net you may like this one better (it’s been spreading all over the web since the last few days)

Well how about that! These folks at Microsoft sure have a good sense of humor.

Next question: who is the shadow person used in Google contacts & Gmail?

Permalink -

The madness of “exclusive” row locks
· 2009-06-24 15:19 by Thijs Kroesbergen for Brokenwire.NET

Yesterday I discovered some really weird behavior of SQL Server. I had a case where I could read a record that was exclusively locked by someone else. Considering the word “exclusive” you would expect that when one transaction has an exclusive rowlock an other transaction would be unable to read that same row. But there is one specific case where this isn’t true. In that case it is possible to read a record that is locked exclusively by someone else.

It took me (together with a colleague) a lot of time to finally find out what was happening.

To reproduce this behavior you need a test-table with some random data in it.

CREATE TABLE [MyTable]
 ([Col1] bigint PRIMARY KEY CLUSTERED, [Col2] bigint)
INSERT INTO [MyTable] ([Col1], [Col2]) VALUES (1,10)
INSERT INTO [MyTable] ([Col1], [Col2]) VALUES (2,20)
INSERT INTO [MyTable] ([Col1], [Col2]) VALUES (3,30)
INSERT INTO [MyTable] ([Col1], [Col2]) VALUES (4,40)
INSERT INTO [MyTable] ([Col1], [Col2]) VALUES (5,50)

You can put this table in any database, as long as it doesn’t have snapshot isolation turned on. The recovery model for your database doesn’t matter.

Now let’s run some queries and see what happens. To be able to test this properly you should run two different session against this table. To be able to hold (and see) the locks that used you need to start a transaction and run some statements, but don’t complete the transaction (yet).

First in the first window of the Query Analyzer (which I’ll refer to as session 1) select one row from the table and request an exclusive rowlock on it with the XLOCK and ROWLOCK table hints.

session 1:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN
SELECT Col1 FROM [MyTable] WITH (XLOCK, ROWLOCK) WHERE [Col1] = 3

To verify the locks that where put into place you can run sp_locks to check the locks that are granted to the connection (spid) that you used to perform the actions for session 1.

spid   dbid   ObjId       IndId  Type Resource                         Mode     Status
------ ------ ----------- ------ ---- -------------------------------- -------- ------
56     21     69575286    1      PAG  1:41                             IX       GRANT
56     21     69575286    1      KEY  (030075275214)                   X        GRANT
56     21     69575286    0      TAB                                   IX       GRANT

As you can see there is an “X” (exclusive) lock on the first key of this table. (The other locks are “IX” (intentional)). Now let’s move to session 2 and see if we can we retrieve that record.

session 2:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRAN
SELECT Col1 FROM [MyTable] WHERE [Col1] = 3

I did expected this statement to just “hang” while waiting for the record to come available. But I was surprised to see that the record could be retrieved without a problem. Also, sp_locks doesn’t show any additional locks for this statement, not even a shared lock!

If you rollback session 2 (to clear everything that might have happened) and retry it with the HOLDLOCK table hint you do get the expected behavior, because the select in session 2 now will wait for the transaction in session 1 to complete.

To understand what is happening here you should remember one of the rules of read committed data access. This rule says that you can read any row as long as it’s in a committed state. The row we’re trying to read here is in a “clean” state (it’s not marked “dirty” by the system). In this case the optimizer decides that it doesn’t hurt to retrieve it via the index without checking for locks. So your table doesn’t even need a primary key, a long as you have an index containing the requested data the rowlocks may be skipped at will.

So if the locked record has not changed and the data for requested columns is stored in an index and you are working from an READ COMMITTED isolation level then the exclusive lock is possibly not honored.

One possible workaround is to add a “HOLDLOCK” table hint to the select in session 2. Alternatively you can actually update the record to have it exclusively locked (and marked “dirty”) in session 1. The last possibility is to lock an entire page instead of just one row by using the PAGLOCK hint. Exclusive page locks do prevent all other readers for the rows in that page.

There’s a thread on http://social.msdn.microsoft.com/ posted by someone who has observed the same weird locking behavior. A Microsoft employee responded with:

Using XLOCK in SELECT statements will not prevent reads from happening. This is because SQL Server has a special optimization under read committed isolation level that checks if the row is dirty or not and ignores the xlock if the row has not changed. Since this is acceptable under the read committed isolation level semantics it is by design.

Perhaps the worst thing about all this is that this behavior cannot be found easily in the Books Online. A small note somewhere in the section about table hints would have be nice. There are some hints in KB324417 (which applies to Sql Server 2000). Combine all that with the fact that the optimizer may choose to do this at will, you’ll have a very hard to find bug in your sql code.

Conclusion:

It took me a lot of time to find out what was going on here. So remember kids: a SELECT with XLOCK and ROWLOCK hints doesn’t mean that you are the only one who can read those rows!

Permalink -

New feature: Webslice
· 2009-04-20 14:31 by Thijs Kroesbergen for Brokenwire.NET

Brokenwire.NET now has it’s own webslice. You may wonder what a webslice is. Remember 1997 ? That’s when we had snippets of web pages on our active desktop! Well a web slice is just that, it’s a piece of information from a site inside a small window in your browser. Internet Explorer 8 is the only browser that supports these things right now.

When you have installed the slice on you browser’s favorites bar it will look like this:

So if you have IE8 you can click on the small link in the right sidebar on this site to add the Brokenwire.NET webslice to your own browser.

Creating such a slice is very easy, with some help of this blogpost about webslices I was able to do this in 10 minutes.

The basic HTML structure:

<html><head>
<title>Page Title</title>
</head><body>
<div class="hslice" id="techologynews">
<h2 class="entry-title">IE 8 web slice</h2>
<div class="entry-content">
<p><a href='#'>Link 1</a></p>
<p><a href='#'>Link 2</a></p>
<p><a href='#'>Link 3</a></p>
</div></div>
</body></html>

The basic rules:

    1. The WebSlice must use the class name hslice in the container.
    2. Each WebSlice must contain an ID in the container. This is how the WebSlice will be differentiated from others on the page.
    3. The WebSlice must have at least one entry-title element defined. This will be displayed both in the page and in the feed button that appear in the Favorites Bar when a user subscribes to the WebSlice.
    4. While not required, each WebSlice should contain at least one entry-content element. This is the information that will appear when the user selects the WebSlice from their Favorites Bar.

There is also an official Microsoft whitepaper about webslices.

I wonder if anybody is actually going to use this, but it was a nice thing to play with for a bit.

Enjoy!

Permalink -

Previous