Require your application to run with administrator privilages

Sometimes your application requires to run with administrator rights. For example to access some restricted resources on a computer. Within .Net we can adjust our application in such a way, the user is asked to run the application with elevated administrator rights. In this way the application is executed with administrator rights, hence has less restrictions. Downside of this is that also more harm can be done with bad written code (think of erasing all files on the harddrive of a user).

Read More…

Posted in C# at February 9th, 2016. No Comments.

When to use or not to use var in C#

The var keyword let you declare a local variable implicit. During compilation, the type of the variable is determined. It allows you to quickly define a variable, where the type of the variable is trivial. Using the var keyword can lead to some discussion when code guidelines are made up, since some people say it makes programming easier but people may also argue that code is less readable. Read More…

Posted in Best practices, C# at June 25th, 2015. No Comments.

E-book about threading in C#

Multithreading allows us to execute code parallel. Each thread performs a part of the execution. A good example is a user interface and the rest of the program. With the use of threading, the user interface doesn’t frees when executing the rest of our program.

Threading can be a difficult to debug when errors occur in your program. Therefore it’s important to understand the concepts and pitfalls of threading very good when using it. Joseph Albahari wrote a very good e-book, which describes the concepts of threads and how they can be used in C#. The e-book is free and can be found here.

Posted in C#, Threading at November 28th, 2013. No Comments.

Design by contract

Design by contract is a technique, introduced by Betrand Meyer and applied within the Eiffel programming language. The concept allows a programmer to document the rights and responsibilities of everyone who uses your code. A contract (not to be confused with a .Net WCF contract) can contain the following elements:

  • A precondition;
  • An invariant;
  • A postcondition.

Preconditions state the conditions that must be met in order to enter the method. For example a parameter “i” must have a positive value. Postconditions describe the conditions of the result of the method. An invariant states the condition which will be always be true, seen from a perspective from the calling party. Using the pre-, postconditions and invariants you can also show the correctness of a program. Read More…

Posted in Best practices, C# at March 3rd, 2013. No Comments.

The HandleProcessCorruptedStateExceptions: catching unmanaged exceptions in C#

When calling unmanaged code (for example C++) from within managed code, you want to be sure when accessing this unmanaged code from your managed code exceptions will be proper caught. When an access violation occurs within the unmanaged code (for example when trying to access a freed pointer), you want to catch this exception. These types of errors wil corrupt the process the unmanaged code is running in. A lot of people will put a catch (Exeption e) around it to be sure just all exceptions are caught from the (untrusted) external unmanaged code. To have a clear distingtion between corrupted process exceptions and all other exceptions, the development team of the .Net framework at Microsoft changed the CLR exception system so that all kinds of corrupted process exceptions will not be delivered anymore to your managed code.

There are however some ways to have the old CLR behavior (and retrieve the corrupted process exceptions within the CLR):
– Add an entry in your application configuration file:

legacyCorruptedState­­ExceptionsPolicy=true

An example configurationfile would look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <runtime>
 <legacyCorruptedStateExceptionsPolicy enabled="true" />
 </runtime>
</configuration>

– Mark the method with the following attribute:

[HandleProcessCorruptedStateExceptions]

When using solution 1, your whole application will use the old mechanism. When using solution 2, only the method which is marked will be using the old mechanism.

There is a very good reason why you want to catch all process corrupted state exceptions: when using unmanaged libraries, you don’t want to crash your application due to a failure in the library. A very good in-depth description of the Unhandled Process Corrupted State exception can be found here: http://msdn.microsoft.com/en-us/magazine/dd419661.aspx

Posted in C# at September 10th, 2012. 3 Comments.

Enable WCF trace logging

To point down problems in WCF, you can enable tracing. The WCF listeners produce valuable information to trace down errors. You can see the incomming and outgoing traffic. By default, tracing is off. To enable it, simply add the folowing section to the app.config file of your application you’re trying to debug:

<configuration>
   <system.diagnostics>
      <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
            <listeners>
               <add name="traceListener" 
                   type="System.Diagnostics.XmlWriterTraceListener" 
                   initializeData= "c:\log\Traces.svclog" />
            </listeners>
         </source>
      </sources>
   </system.diagnostics>
</configuration>

When you run your application and WCF is used, a file “traces.svclog” is created on “c:\log”. Be sure you have rights to write to the defined location. With the use of the “Microsoft Service Trace Viewer”, which is a part of the Visual Studio suite, you can view the created file. Since this viewer is asociated by default to files of the svclog-type, you can double click on the log file to open it in the WCF viewer.

Posted in C#, Debugging, WCF at August 29th, 2012. No Comments.

Mock objects

An often used technique within unit testing is mocking of objects. Mocking means that you create an instance of an object, which responds exactly as you want. This comes in really handy when you for example want to unit test a piece of code which interacts with some piece of hardware. By simply mocking the hardware you can “simulate” the hardware in order to test your code which access this hardware.
NUnit has by default a framework for mocking objects. This framework is also used by unit testing the nunit framework. When you have an interface and don’t need to implement all methods which are available within this interface, you can simply create a mock object from this interface by using “DynamicMock” within the NUnit framework:
DynamicMock myExampleMock = new DynamicMock(typeof(IMyExample)); // Creates a mock object from the defined interface
myExampleMock.ExpectAndReturn(“AmethodName”, // the method name
“abc” // return value
Null  // expected arguments);
IMyExample myExampleInstance = (IMyExample)securityTokenServiceMock.MockInstance;
This will create an instance of an object which implements the given interface. With the “ExpectAndReturn” you can define methods on your mockup and implement how they will react on performed method operations. For example in the example above, when you call “AmethodName” on your myExampleInstance, the string “abc” will be returned.
To use the mockup framework, beside adding the nunit.framework.dll, you also have to add the nunit.mock.dll assembly to your project.
Posted in C#, TDD at July 2nd, 2012. 1 Comment.

Debugging WPF bindings

WPF and bindings can cause a lot of stress when your data binding doesn’t seems to work. From .Net 3.5 and up, you can enable trace information regarding bindings.

Add the following namespace in the header of your component:

xmlns:diag=”clr-namespace:System.Diagnostics;assembly=WindowsBase”

To your binding, add the following line:
diag:PresentationTraceSources.TraceLevel=High

For example:

<Window x:Class="DatabindingExample" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
 Title="MyWindow" Height="300" Width="300">
 <Grid>
 <TextBox Text="{Binding Path=Name, diag:PresentationTraceSources.TraceLevel=High}" />
 </Grid>
 </Window>
Also, to view the tracing, it is important to change the log level of Visual Studio regarding WPF. Go to Tools->Options, a dialog will appear. Click on the left on “Debugging->Output window”. You will see within the section “WPF Trace Settings” a line for binding. Set the loglevel for this on at least “Warning”.
Posted in C#, WPF at June 14th, 2012. No Comments.