MSTest and the error Method should be marked static

If you came from the world of NUnit you may stomped into the error “Method should be marked static” without any other indication of which method it’s about.

With NUnit, you were using TestFixtureSetUp as attribute to a class’ method to get it executed before all test once. With MSTest you have to use the attribute ClassInitialize.

So, if you are used to write :

        public void Init()
            //Some code executed once

You cannot simply use :

        public void Init()
            //Some code executed once

In fact, the Microsoft Unit Testing framework require to have this method public with a parameter of TestContext.

        public static void Init(TestContext ctx)
            //Some code executed once

Once this is set as it should, with the statis method and the TestContext attribute, the error “Method should be marked static” will be removed and you will be all fine.

Unit testing System.UnauthorizedAccessException: [InvalidCrossThreadAccess]

When unit testing you can get this kind of error if you try to use a class that use different thread of the main one.

At first, I haven’t realized that I were using another thread because I was testing my Shape class. After some minutes, I realized that I were using the System.Windows.Shape and not mine… once the reference set correctly I were able to remove this error and have my test working.

Test method UT.ShapeTest.CreateNewShape threw exception: System.UnauthorizedAccessException: [InvalidCrossThreadAccess]
Arguments: …

Access to modified closure when having a Linq inside a loop

If you have Resharper, you can see sometime a warning saying that you “Access to modified closure”. If you do not have it, you can still have odd behavior something with the values. In both case, this mean that Linq is accessing a value that might (or not) be modified.

Linq execute delegate functions. If you try :

var  listInteger = new List<int>() { 1, 2, 3, 4, 5 }; //Values

var funcs = new List<Func<int>>(); //Delegate function that take a Integer as parameter

foreach(var v in listInteger)  // Add in the list of delegate's functions a function that return the integer value
	funcs.Add( ()=>v );
foreach(var f in funcs)  //Execute functions which should just return the value.
	Console.WriteLine(f()); // We expect here to have 1,2,3,4,5

You wull not see 1,2,3,4,5 but 5,5,5,5,5. The reason is that is access a modified variable. The function is not adding the value of v but the pointer to it. This is why it remains on the last value of the loop. But, by using a variable inside the loop, the pointer is to this variable and directly to the good value.

var  listInteger = new List<int>() { 1, 2, 3, 4, 5 }; //Values

var funcs = new List<Func<int>>(); //Delegate function that take a Integer as parameter

foreach(var v in listInteger)  // Add in the list of delegate's functions a function that return the integer value
	var vv = v;
	funcs.Add( ()=>vv );
foreach(var f in funcs)  //Execute functions which should just return the value.
	Console.WriteLine(f()); // We expect here to have 1,2,3,4,5

Most of the time, no body will feel this problem because most of the time the Linq won’t execute delegate function defined somewhere else but an anonymous function that call directly the value of the variable. But, as a good practice, it’s always better when accessing variable that may be changed to create a temporary variable to remove the undesired effect.

How to backup table’s data with Sql Server 2008?

Some time it can be useful to dump all data of a table in the format of SQL insert statement.

This can be done easily with Microsoft SQL Management Studio. The first step is to right click on the database and select the option Task>Generate Script. This will popup a wizard window.

Microsoft Sql Management Studio Generate scripts

The last step is to select that we desire only the data.

Select data to get all information of the table without creating the schema

This will produce all SQL’s insert statement with your data.

Localized Silverlight with Resource File

Let say that you want to have your application in multiple language. In Asp.Net, the choice is obvious to go with resource file. Since I am coming from the web side, I did the same thing with Silverlight.

Visual Studio Resource Editor

In Silverlight, you can still use Resource File. They are available in the New Item dialog.

How to add a Resource file to Silverlight

In my project I added two resources file : MyRes1.resx and This way, I can have English and French words translated.

The next logical step is to handle the language selection. In my case, the language came from the Asp.Net page. It was passed as a parameter. In App.xaml.cs, in the Application_Startup() event, I added a call to SetCultureInformation() which I have defined like this:

private void SetCultureInformation(StartupEventArgs e)
	var languageInfo = new CultureInfo("en");
	if (e.InitParams.ContainsKey("language"))
		if (e.InitParams["language"] == "fr")
			languageInfo = new CultureInfo("fr");
	Thread.CurrentThread.CurrentCulture = languageInfo;
	Thread.CurrentThread.CurrentUICulture = languageInfo;            

I were ready to execute to test but I had the problem that Silverlight didn’t want to switch to French.

After few hours, I realized that Silverlight’s project can have specific variable to be set to be able to tell Silverlight which language is supported.

To do, open your Silverlight project with Notepad and search for “SupportedCultures”


You need to set all language you want, but no need to add the default one. In my case, I added only the French one, so “fr”.

After that, everything worked.

How to compare element from the same collection with Linq?

Lets imagine that you have a collection with a class containing Images. All images are identified by an unique key and a caption that the user enter. You want to verify that the caption entered by the user is unique to the collection. How to do it?

This can be done with Linq to Object pretty easily by using 2 from statement.

var hasDouble =  
         (from s1 in this.Images
          from s2 in this.Images
          where s1.Key != s2.Key
                && s1.Caption == s2.Caption
         select new { Image1 = s1, Image2 = s2 }).Any();

This will loop through all the images and will compare the caption of all shape but not compare node with itself.
I have created an anonymous object because in fact, I may want to get those 2 elements that have the same caption. In that case I just need to call the same code and remove the .Any().

This can be translated to Lambda expression.

(this.Shapes.SelectMany(s1 => this.Images, (s1, s2) => new{s1, s2})
             .Where(tt => tt.s1.Key != tt.s2.Key
              && tt.s1.Caption == tt.s2.Caption)
             .Select(tt => new { Image1 = tt.s1, Image2 = tt.s2}

But for this kind of task, Lambda is more confusing from my point of view.

How to add animated effect to UIElement.Effect

If you want to make glowing a shape with Silverlight without having to use Xaml it’s possible. At first, I thought it was impossible because I were using a third-party object that use their own type of Shape. After reading the property I figured out that the Effect property was exposed. This let us use System.Windows.Media.Effects.

To make it looks glowing, I decided to use the DropShadowEffect which can have a blurry shadow.

    var errorEffect = new DropShadowEffect { BlurRadius = 50, Color = Color.FromArgb(255, 255, 0, 0), Direction = 0, ShadowDepth = 0, Opacity=1};

This create the blurry effect because the ShadowDepth is at 0 and the BlurRadius somehow high.

The problem is that I wanted it to fade it and fade out which wasn’t possible without using StoryBoard. I also thought that it was impossible cause the shape didn’t have any story board or animation property. I was wrong.

It’s possible to use the static method of the StoryBoard class to set an animation or many animation to an object.

Here is two ways to make the shape going on and off.

 var shadowOpacityAnimation = new DoubleAnimationUsingKeyFrames
                                             Duration = new Duration(TimeSpan.FromMilliseconds(10000)),
                                             RepeatBehavior = RepeatBehavior.Forever,
                                             AutoReverse = true
            shadowOpacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = new TimeSpan(0,0,0,0), Value = 0 });
            shadowOpacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = new TimeSpan(0,0,0,1), Value = 1 });
            shadowOpacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = new TimeSpan(0,0,0,7), Value = 1 });
            shadowOpacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = new TimeSpan(0,0,0,10), Value = 0 });
            Storyboard.SetTarget(shadowOpacityAnimation, myShape);
            Storyboard.SetTargetProperty(shadowOpacityAnimation, new PropertyPath("(UIElement.Effect).(DropShadowEffect.Opacity)"));

This way let you use key frame which are some time mark where you can set value. In the above example, I set the total animation time to 1000 milliseconds and make it repeat forever. I also specify that I want the animation to go on to off, and off to on with the AutoReverse to True. I after that add 4 time marks which set the opacity to 0 and will fade in for 1 second to the maximum opacity value : 1. Then, I wait from 1 second to the 7th second with full opacity before going down to 0.

The last two line tell to set the animation target to my shape. In that case, I were setting the shadowOpacityAnimation to myShape. The last one specify which property of myShape I will change. This can be a little bit more tricky. If you have blend, it’s a good time to fire it up and check the generated Xaml. Otherwise, do not worry, it’s logic.

You need to create a PropertyPath which will tell what property to change.

...  new PropertyPath("(UIElement.Effect).(DropShadowEffect.Opacity)") ....

In my case, I want to change the Opacity of the DropShadowEffect which are in the Effect of my objec that inherit this method from UIElement. As you can see, you have to write the sequence in reverse and you are done.

If you want to make it glows without using opacity, you can also do it with the BlurRadius property.

  var blurRadiousAnimation = new DoubleAnimation
                                           From = 50,
                                           To = 0,
                                           Duration = new Duration(TimeSpan.FromMilliseconds(2000)),
                                           RepeatBehavior = RepeatBehavior.Forever,
                                           AutoReverse = true
            Storyboard.SetTarget(blurRadiousAnimation, addFlowShape);
            Storyboard.SetTargetProperty(blurRadiousAnimation, new PropertyPath("(UIElement.Effect).(DropShadowEffect.BlurRadius)"));

In that case, it’s simpler. We do not use key frame but simply a DoubleAnimation that will go from one value to another. This one is changing the BlurRadius every 2 seconds.

In both case, you need after to add the animation to the story board and to start it.

  var stb = new Storyboard();

In that case, I have added both animation. Yes, you can add more than 1 animation per object. Do not forget to use the Begin() method and you will be all set.

The breakpoint will not currently be hit. No symbols have been loaded for this document

Some time Visual Studio can be not a pleasure. You may sometime arrive at a point where you compile and your new code doesn’t seem to load so you decide to add a breakpoint for debugging. But, unfortunately you have a red dot in Visual Studio that is not completely fill up. When you put your mouse cursor hover it you can read the following message :

The breakpoint will not currently be hit. No symbols have been loaded for this document

From there, you can go and confirm that the debug file, the PDB, is not loaded. You can see that in the Symbol Status column of the Module window. The Module window is available only when debugging under Debug>Window>Module.

The Debug Module

If you right click you will be allowed to load symbol from file. If you can go in the Debug folder and select the file do it. If you receive a message saying that the file cannot be loaded than more step is required.

The next step is this one:

  • Close Visual Studio
  • Kill all process of webdev
  • Delete the Bin and Obj folder of your library that doesn’t load
  • Open Visual Studio and compile

You may want to close IIS (net stop w3svc) before doing all those commands if you are using Asp.Net. To restart IIS simply use net start w3svc. You can also do it with the UI with IIS manager tool.
From there, you should be able hook the PDB file (if it’s not done automatically) and debug.


You may also try to :

  • 1- Reboot
  • 2- Delete C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\
  • 3- Delete C:\yourPathTo\bin
  • 4- Delete C:\yourPathTo\obj
  • 5- Change AnyCPU to X86
  • 6- Build
  • 7- Start Debugging