Running NLog in WPF Browser Application and other partially trusted environments

NLog is a pretty slick logging library, no doubts about that. However if you try to use it from a partially trusted environment you are facing some problems. The solution is to fix two things in the sources and recompile them. Here is the recipe:

1. Open solution NLog.vs2005.sln in Visual Studio. If you have no special needs you’ll need to recompile just the project NLog.vs2005 – you can safely remove others from the solution.

2. Add [assembly: System.Security.AllowPartiallyTrustedCallers] line to AssemblyInfo.cs file. With this change you are allowing partially trusted callers. This might not be enough. See the next paragraph.

3. If you don’t provide explicit configuration then NLog will try to read from environmental variable and thus causing a SecurityException due to EnvironmentPermission request which is not granted by default. To avoid this you’ll have to comment a piece of code in the LogFactory.Configuration property:

if (_config == null)
    if (EnvironmentHelper.GetSafeEnvironmentVariable("NLOG_GLOBAL_CONFIG_FILE") != null)
        string configFile = Environment.GetEnvironmentVariable("NLOG_GLOBAL_CONFIG_FILE");
        if (File.Exists(configFile))
            InternalLogger.Debug("Attempting to load config from {0}", configFile);
            _config = new XmlLoggingConfiguration(configFile);
            InternalLogger.Warn("NLog global config file pointed by NLOG_GLOBAL_CONFIG '{0}' doesn't exist.", configFile);

Since the code is commented no EnvironmentPermission will be thrown even if there is no explicit configuration provided. As a side effect you can’t rely on default configuration settings anymore but this shouldn’t be a big issue since you can’t read them in a default partially trusted environment anyway.

4. Compile in release configuration and there you go.

Don’t forget, most of the default logging targets won’t work due to the security permissions. But the ones your application has access to will.

Happy logging.

.net Parallel programming

Generic Thread.VolatileRead and Thread.VolatileWrite

I am thinking about using a generic version of Thread.VolatileRead and Thread.VolatileWrite. The code is similar to existing one (actually there are plenty of overloads) with the difference of generic type parameter:

public T VolatileRead<T>(ref T address)
    T result = address;
    return result;

public void VolatileWrite<T>(ref T address, T value)
    address = value;

Why would I use generics if there is plenty of overloads already there? Because you have to perform casting to and from object since there is a single overload that accepts reference (ref object address that is). Here is an example:

Tubo tubo = new Tubo();
object param = tubo;
Tubo read = (Tubo)Thread.VolatileRead(ref param);

Isn’t the following code much better?

Tubo tubo = new Tubo();
Tubo read = MyThread.VolatileRead(ref tubo);

The questions is whether my code is correct or not. Sure it looks like correct but one never knows for sure when dealing with threading. Feedback appreciated.

.net CodeRush DevExpress DXCore DXCore plugin Visual Studio

Meet “Go To Implementator” DXCore plugin for Visual Studio

The problem

One of the biggest annoyance when doing unit-test-friendly projects is that you have to deal with interfaces much more than you usually would. This isn’t bad by itself but it will effectively kill your F12 aka “Go To Definition”. In other words F12 won’t show you the code anymore but rather the interface definition of the method or property. Which is not what I like and I guess not what you like as well.

Let’s see an example:

imageWhen you F12 (or right click, Go To Definition) on DoTubo() you’ll get catapulted to the interface declaration of the method. Which might be what you want but mostly it isn’t. I’d like to see  the Tubo.DoTubo() method declaration where the code I am interested is. Specially because often an interface is really implemented just by one class, at least in design time.


This is what I’d like to see. And this is what you’d get if you weren’t using IAnnoy interface but rather Tubo type directly.

The solution

Good news is that now there is a way to use the go to method implementation. Even better news is that it is free. As a free lunch.

I’ve created a DXCore plugin named “Go To Implementator” that does exactly that. When over a interface’s method or property reference it will give you an option to go directly to (one of the) implementation. Sounds fine?


1. If you don’t have CodeRush already installed then do install its Express version which is free or even better, go with full version (which is not free but it is well worth it).

2. Download attached zip file and unpack its content into either [USER]\Documents\DevExpress\IDE Tools\Community\PlugIns or [Program files [x86]]\DevExpress [DX version, i.e. 2009.3]\IDETools\System\CodeRush\BIN\PLUGINS.

3. Run Visual Studio. Go to DevExpress/Options… menu and select IDE/Shortcuts node the left.

4. Create a new shortcut: click on the first icon under Shortcuts title. Click on Key 1 text box on the left and press F12 (you are telling which key to respond to). Pick “Go to interface implementation” command from Commands combo box. The last step is to click on checkbox Focus/Documents/Source/Code Editor on the usage tree list on right side – a green checkmark should appear. Note that you can bind this action (or any other) to a different shortcut or even a mouse shortcut or any other way supported by CodeRush.


Take also note that there is a “Parameters” text box. I’ll use it pass parameters to my action later on in the article.

Test & use

Create a console application and past in there this code:

class Program
static void Main(string[] args)
IAnnoy annoy = new Tubo();

interface IAnnoy
void DoTubo();

class Tubo : IAnnoy
public void DoTubo()

Position the caret on DoTubo() method reference. There are two ways to invoke my plugin.

Context menu

Right click, there should be an submenu “Go To Implementator” in context menu:


Keyboard shortcut (F12)

Just press F12. But what if you are not on a interface method/property reference? The default “Go To Definition” will be called like it would be without this plugin.

Dealing with more than one interface implementation

So far there was only one interface implementation. But what happens if there are two or more classes that implement the interface?

Let’s add another implementation to the crowd:

class AnotherTubo : IAnnoy
public void DoTubo()

Now both Tubo and AnotherTubo implement the IAnnoy interface. Right click context menu should give both options in no particular sort order, like this:


Let’s pick AnotherTubo class. Plugin will remember this choice and next time it will be placed on the top:


But what about F12?

If there is no default class assigned then it should present you a smart tag with options:




However, if a default is available it would go straight to the implementation rather then presenting this smart tag.

Customizing the action

Popup menu behavior is fixed and can’t be customized in current version. The action, one that you can bind to a keyboard shortcut or whatever else input CodeRush is supporting can be customized. There are two parameters (parameters are a comma delimited string that you pass to Parameters text box when you are creating/editing shortcut in DevExpress/Options… – see the 4. step in installation) you might use.


You can disable invoking Go To Definition when action doesn’t do anything. The default behavior is to pass through when action does nothing. So why would you need this option? In case you are using the action from non F12 shortcut or if you want the action to do its job and nothing else.


When there is a default class for action available no smart tag is shown by default. You can override this behavior by passing ShowPopupAlways parameter. Then smart tags menu will be shown always when there is more than one class suitable regardless the default value is present or not.

Here is an example of passing both parameters:


The conclusion

I hope you’ll find this plugin useful. I am starting to use it and it saves me a lot of clicking. And thanks to DXCore it was really easy to create it.

Let me know if you have ideas how to enhance it or anything else, all feedback is welcome.

1.0.0 (18.1.2010)

  Initial release

1.0.1 (19.1.2010)

  Bug fix: it worked only within project scope.

1.0.2 (19.1.2010)

  Too strict parsing used which might resulted in no go to implementor option at all.

1.0.3 (21.1.2010)

  Didn’t work on partial classes.

1.0.4 (26.1.2010)

  Fixed navigational bug (thanks to Quan Truong Anh for finding the bug and creating a repro case)

1.0.5 (16.7.2010)

  Added some logging – make sure DevExpress/Options…/Diagnostics/Message Logs is turned on (if you are turning it on then you have to restart IDE).
  No new functionallity besides logging – you might consider this version if plugin doesn’t work well and you want to understand why. (10.20 kb)


Important: this is the last version supporting DXCore/CodeRush 10.1.x and lower.

Even more important: I’ve created a dedicated page and all further improvements will be published throug that page. This post won’t be updated anymore.


About DevExpress skinning and custom skins

Here is the thing. DevExpress WinForms components support custom skinning. Out of the box there are plenty of skins you might use just by assigning a simple property with a name of the skin. Every DevExpress WinForms control will follow the skin settings and will look fancy and so will your application. That’s great. But if you want more advanced skinning you are in for troubles.

Let’s see my case. An application I am building for a customer of mine supports skinning. However I had to slightly modify out of the box skins with some adjustments and I’ve added few new glyphs which I use in my custom controls (they follow skinning UI as well since entire application does). Here is how I started. I’ve opened SkinEditor, a tool provided by DevExpress and created new skins based on their skins, i.e. MyCaramel from Caramel, etc. Once I had “my” skins I’ve adjusted some properties still using SkinEditor. Finally I’ve created a “skin resource” assembly. That’s all easily done via SkinEditor. So far so good. But there are problems ahead.

First problem – adding custom glyphs to skin

Since I have custom controls that have custom glyphs I had to add those glyphs to skins. After all they belong in the skin assembly since they will be also changed when skin changes. I could add them somewhere else, but that would be asking for troubles – better to have “grouped” resources in one place. But there is no way to add custom glyphs to my skin via SkinEditor. By design. Obviously nobody at DevExpress ever supposed that custom skins might be used for custom controls.

Second problem – updating the custom skin

Next, much more annoying problem, is updating custom skin to a newer DevExpress version. Even when a minor DevExpress version is released the out of the box skin definition might change a bit – here and there. So, the template you have built your custom skin from has changed but your custom skin still “sits” on the top of the old template version. It might even result in a runtime exception if you don’t upgrade the skin while application uses newer version of DevExpress components. And go wonder, SkinEditor doesn’t have an “upgrade custom skin” option. You have to recreate the original project (what a fun when you are dealing with 20+ skins – you have to add separately) and reapply all changes you might to out of the box skins. Eeek.

Third problem – skin size

If you use a lot of custom skins they will use a lot of space (each skin is about 500KB) even though you might not be using all of DevExpress controls and thus you don’t require full skins. The relatively big size might be a problem if you distribute your application via internet and even if you don’t your application uses more memory without any apparent benefit. SkinEditor doesn’t support removing of skin elements and even if you modify skin.xml definition (by removing unnecessary nodes) SkinEditor will add them again when you open the project next time.

Fourth problem – nor skin nor its assembly can’t be unloaded

Once the skin assembly is loaded to your application (main AppDomain) it can’t be unloaded. And once skin is registered it creates a hash table of all resources (a ton of Images – I am not 100% about this but it pretty much looks like it) and you can’t unloaded any of them. So, when you register a skin assembly it will remain loaded until the application is closed and all resources will be loaded to hash table in the form of images (souds like a sort of duplication to me). There is no way to load a skin from a custom AppDomain.

Solutions to problems

The first problem can be solved “manually”. I say manually, but you can pretty easily create some XML manipulation and file copy code. While SkinEditor doesn’t support adding custom glyphs you can still add them manually in two steps – save the graphics to the proper folder of the SkinEditor project and modify skin.xml file by adding proper XML nodes pointing to newly added glyphs. After some trial and error I was able to accomplish this task.

I’ll write about the solution to the second problem in a later post. I’ll also provide an utility that does a part of the job.

I have an idea how to solve the third problem but didn’t solve it yet nor I am sure whether it will work.

The fourth problem is the most hard to solve due to the current implementation. I am not sure whether it is even possible or whether does it make sense to invest much energy into this.


While skinning works pretty nicely in DevExpress controls its implementation is not the best one. Specially support for custom skinning isn’t very well thought and SkinEditor can be enhanced with these problems in mind.

The good news is that with little effort I’ve managed the overcome the most important issue – how to create slightly modified out of the box skins and how to update them to new versions (automatically). I’ll talk more about this solution in a later post.

What do you think? Do you use DevExpress skinning feature? Did you create your own skins?


Bridging IPTV over wireless using two Linksys WRT54GL routers and DD-WRT firmware

The motivation

I had a need to bridge IPTV using a wireless connection. Immediately I faced several problems which I finally managed to overcome and since not much information is available on internet I’ve decided to write my recipe down.

Note that there is a simple albeit expensive solution: use Ruckus wireless bridge (it is supposed to work pretty much out of the box). Since spending something like 200€ is a bit too much for this stunt I’ve decided to go with two Linksys WRT54GL routers instead. They are much cheaper and there is a challenge, who doesn’t like a challenge? And sending a bunch of network packets back and forth shouldn’t be that hard, should it? Ehm.

Current state

My ISP/IPTV provider is SIOL whose major stockholder is government. I have their modem/router that broadcasts IPTV UDP multicast stream on one of its LAN ports. And then I have a set top box (a lousy Sagem IAD81, doesn’t have any wireless capability whatsoever) connected with network cable to the router on the one end and to the (not yet LCD) TV set on the other end. This combinations works albeit picture quality isn’t good, but that’s due to the too-slow stream from the IPTV provider issue (it is a 4Mbps MPEG2 stream, not enough when there is a lot of dynamics on the screen).


The goal

Instead of the LAN cable change to wireless using two Linksys WRT54GL routers, like this


The hardware

As stated, two Linksys WRT54GL v1.1 (evergreen) routers.

The firmware

Finally I settled with DD-WRT BrainSlayer version 13525. I’ve tried many other versions and Tomato 1.27 as well, but more about it later.

The trial and error process

Knowing correct IPs

First thing one needs to know is what IP can and should be assigned to both routers – each one requires its own IP. Since IPs are assigned from provider based on MAC address of the STB (provider doesn’t care about anything else besides STB) it is not exactly known what additional IPs can/should one assign. So far every (unofficial) post about watching TV on computer suggested to use STB’s IP increased by 1. i.e. if your STB has an IP of you’ll want to use This isn’t documented officially anywhere and worse, I needed two additional IPs, not one. Hence I decided to ask about it on provider’s support forum. I’ve got no official answer, just the usual +1 answer from a peer.

Then I tried mail support only to get a person who doesn’t know what is an IP and how to get them. First he sent me link to unofficial posts about +1 (how to watch IPTV on computer by assigning IP manually) and to expensive Ruckus alternative being sold by them. I wasn’t happy about it and insisted on what IPs exactly can I use if I need two additional IPs, not only one. Since provider assigns them they should know, shouldn’t they? At the end his final answer was: it won’t work if you assign IPs manually. Never. (he clearly contradicted himself showing total lack of any clue). After that provider’s mail support didn’t respond to me anymore. So, thanks SIOL, my dear provider, for being dumb. Somehow they didn’t surprise me with that attitude.

In the lack of any official response I’ve decided to assign IP+1 to host side WRT54GL (one being close to provider’s router, left on my picture) and IP+2 to client side WRT54GL.

Oh, and how do I know the STB’s IP? If you have Sagem IAD81 STB you can press Menu, Blue, Yellow buttons. Or is it Menu, Yellow, Blue, who knows – try it and a diagnostics screen appears sooner or later including the assigned IP.

Installing and configuring correct firmware


Before flashing your router do read how-to. Such as this from DD-WRT website. If you don’t do it correctly you might “brick” your router for good.

DD-WRT recommended build 13064

WRT54GL out of the box comes with Linksys firmware which isn’t exactly rocket science and doesn’t support what I was looking for. This doesn’t matter since GL model is meant to be flashed and its firmware developed from community. Hence I first tried DD-WRT currently recommend build 13064. (go to DD-WRT router database and type in your router model to find the recommended build). I flashed both routers and configured them to Client Bridge mode. Only to find that it does work for electronic program guide (html pages) but not for multicast, resulting in no picture or sound. When asking in (very friendly and useful) DD-WRT forum for Broadcom devices (WRT54GL uses Broadcom hardware) I was redirected to use WDS mode instead (here is the comparison between various bridge modes) . Apparently WDS is much better in terms of compatibility but you need administrative access to both routers, which was not a problem for me.

I configured both routers in WDS mode without any security, DHCP or WLAN and tried. This time I’ve got picture and sound but they were somewhat distorted. Soon I found out that the stream that client side router provided was just ~700Kbps instead of 4Mbps. The stream quality on the host side router was fine. Eeeek. After trying a ton of different settings (I didn’t even know what to look for) I gave up. Stream was slow no matter what I did.

Now, looking back I am not sure whether I did manually assign the transfer fixed rate. There are posts on the internet that one has to limit the WDS transmission rate to a some value (I saw different reports saying 6, 9, 12, 18, … Mbps).

Tomato 1.27

Next firmware I’ve tried was Tomato 1.27. The same “small, lean and simple” firmware I am using for my internet router. Again I’ve set both routers in WDS mode (after re-flashing). From the start it didn’t work but then I’ve manually assigned transmission rate to something like 18Mbps and the picture and sound appeared in all their glory (read: as good as it gets – which is not good – due to my provider’s settings). But there was a serious problem which I’ve discovered after 1 minute. Provider’s router stopped providing IPTV stream for some obscure reason. Its IPTV section was froozen, other parts were still working. Only a hard reset on provider’s router fixed that, but only for another minute. Again, no setting I’ve changed helped. And resetting the main router every minute didn’t look as a viable solution to me. Call me strange, if you wish.

I asked both my provider (they are the admins of their router placed in my house, the one with the problems) about it and the guy behind Tomato. The first one couldn’t help (no big surprise) while the other didn’t respond.

So I was stuck with two solutions that didn’t work for one or the another reason. And I was so close.

DD-WRT experimental BrainSlayer build 12874

With no “official” DD-WRT or Tomato firmwares available I’ve went with experimental builds. I’ve tried “DD-WRT BrainSlayer build 12874” build with same results. I like the name though. You’ll find it here. Before using DD-WRT experimental builds make sure you read this page.

The solution that works: DD-WRT BrainSlayer build 13525

Finally this is the build that worked for me. Find it here. I’ve flashed both routers with this build. Reset both to WDS and nothing else (per wireless settings I’ve used Network Mode=G only, Channel=2 and SSID=tv on both) In addition I’ve set wireless transmission fixed rate to 36Mbps on both and enabled Frame Burst check box (below Transmission Fixed Rate settings on Wireless/Advanced Settings). And a miracle happened – the stream begin to flow to the STB in full speed.

Beware that while this solution works for me it might not work for you or you might even brick your router(s). Consider yourself warned. I merely described my solution.

The drawbacks of twin routers/WDS solution

The only drawback is that stream sometimes, like a hickup, looses some quality and artifacts in form of squares appear for a brief moment. I am not sure whether this is a feature of wireless connection or of non exactly stream oriented router firmware. This is the only drawback I’ve found so far.


  • The guys in the DD-WRT forums for responding to my noob questions.
  • Luka Manojlovič, a fellow MVP for providing support

Anti credits

  • To my IPTV provider SIOL for being really clueless and not helpful at all.

26.10.2010 Update: According to feedback from Jože, my solution requires twice the bandwith necessary because packets travel forth and back due to my settings. He proposes to switch wrtgl next to the router to AP and the wrtgl next to the stb to Repeater Bridge and to remove WDS. Add this script to the later “ifconfig eth1 allmulti” (without quotes, Administration/Commands menu). This way it should work the same but without double traffic. I didn’t try it yet, but if you do, let me know. <- won’t work.

.net 4.0 VS 2010

Enabling and understanding code contracts in Visual Studio 2010 beta 2

Code Contracts are a new way to do both runtime and static checking of your code coming with .net 4.0/Visual Studio 2010.


Visual Studio 2010 beta 2. To enable Code Contract project tab you need to update code contracts by downloading the latest version from Code Contracts web page. You’ll find very good introduction documentations on the same side from Documentation link (PDF).

Here is a really simple example of a code that uses Code Contracts

static void Main(string[] args)
    decimal c = Divide(4, 0); // fails validation because b == 0
    List<int> list = null;
    Add(list, 5); // fails validation list == 0

static decimal Divide(decimal a, decimal b)
    Contract.Requires(b != 0);
    return a / b;

static void Add(IList<int> list, int element)
    Contract.Requires(list != null);
    Contract.Ensures(list.Count == Contract.OldValue(list.Count) + 1);

Pay attention to Contract static class and its Requires (pre-condition) and Ensures (post-condition) methods. There is lot more to these two methods i.e. you can even access original argument values through OldValue method – make sure you read the documentation.

Just the code by itself won’t do much. To enable both runtime and static checking you have to open project properties and check Perform Runtime Contract Checking and Perform Static Contract Checking checkboxes. If the static analysis has been checked then you’ll see warnings in the Error List (and Output) window regarding contracts failures. If you enable runtime checking you’ll get assertions (by default, but you can easily switch to exceptions) when the program execution hits contract checking failure.

The interesting aspect of Code Contracts is how it implements post conditions – it injects the proper code at the place of the post condition methods. Something like Post Sharp has been doing for years. Looks like AOP is slowly getting into the .net after all.

Try it for yourself.

CodeRush DevExpress

Developer Express published roadmap for 2010

First new “feature” is stepping down from three releases per year to two releases per year. Regardless how it sounds, it makes sense. A lot of sense. Developers and other staff spent a lot of time preparing releases and I don’t mean implementing new features but just preparing and testing the releases. From now one they will have more time for coding new features. As per DevEx clients this is good news as well – having to do major updates less time per year provides similar benefits. Bottom line is that we have more features, less work and possibly less bugs.

From the technologies perspective it looks like WPF and Silverlight are getting mainstream while WinForms is dropping down from first place (that said it isn’t a dead product, far from it, it is just not the most important anymore – I am very pleased to see this shift happening). ASP.NET MVC will get some beta versions (“we shall be testing the waters with beta versions of the data grid, menu, navigation bar, and tab control”) while ASP.NET is still the most important of the two.

Visual Studio 2010 is going to be supported big time including CodeRush for VS2010.

These are news in brief from what I can read. But don’t take my word for granted, read it yourself at