With .NET Framework 3.5 Extension Methods were introduced to .NET developers. The concept of extension methods allows you to

“[… ] ‘add’ methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.”

While the most common use for extension methods are LINQ standard query operators, extension methods provide aplenty of new possibilities. One issue one comes along is the correct naming if extension methods and their corresponding classes.

The signature of a extension method differs slightly from a common signature as the first parameter is preceded by the this modifier:

public static int WordCount(this string that)

I haven’t found much about naming conventions, most about naming the methods itself, how to organize them or what you should not do with them. If you have read through Robert C. Martin’s Clean Code you might know that naming is an essential foundation of clean code. I’ve read through a lot of code outside and inside of Microsoft, however, I haven’t seen anybody following global guidelines. There might be group specific conventions but nothing that seems to be applied by the majority of developers.

1. Name the type parameter that

This seems to be very odd, but naming the type parameter that has quite some charm. When reading the signature you immediately see the type parameter, when reading through the method body you always know that that is the type parameter the extension is written for. When reading through many extension methods I found it very pleasant to read those methods following this convention.

public static int WordCount(this string that)

2. Create dedicated static classes for each type

No matter whether you put the extension methods in a separate library, in a specific sub-folder within your project or somewhere random

a) Do create separate files for each class containing extension methods.
b) Do create separate classes for each set of extension methods for a certain type.

Once you follow these simple rules you can think straight forward about naming of classes containing extension methods. If you collect all extension methods within a single class (or file) you might end ob with a lot of obsolete code while your application evolves. Due to rewriting your code and refactoring your application same extensions might become obsolete or some classes you extend do not exists anymore in your project. Using dedicated files make maintaining your codebase much more easy.

Classes for Extension Methods

3. Use the Extension suffix

During our day job we realized that naming the class with the suffix Extension provide good semantics of the class. This indicates clearly that you are dealing with a collection of extensions. For example, while using the using the Visual Studio Object Browser you can easily identify those classes providing extension methods.

public static class StringExtension
{
    public static int CountWords(this string that)
    {
        ...
    }
}

4. Name what is being extended

It seems to be a good practice to name classes after what they extend. If you follow the previous two guidelines this should be a straight forward job. In addition your code is good to read and easy to understand. In practice we came along various conflicts with already existing naming guidelines. Anyway extensions are a relatively new concepts and one would expect that there might be conflicts with already existing naming conventions. The following will illustrate one of those conflicts:

Naming conventions for Extension Methods

By convention interface names should start with a capitalized ‘I’. So odes ICalculator. Following the above guidelines you might consider naming the corresponding class providing extension methods for the interface ICalculator type CalculatorExtension. In this case it seems reasonable to neglect the convention for interfaces:

Consequently, ICalculatorExtension provides extension methods for the ICalculator type, CalculatorExtension provides extension methods for the type Calculator. This approach will not only increase the maintainability of your codebase, I will also allow new team members to orientate quickly in your codebase.

There are various reasons for and against naming conventions for extension methods. Once writing Reactive Extensions for .NET this might get even more complicated as you will write a lot of extension methods for dedicated purposes. However, for common codebases the provided guidelines might help to develop easy to read and maintain, clean code.

Posted at Wednesday, January 13, 2010 11:24:03 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 
Clean CodeI do not agree with all statements in Clean Code by Robert C. Martin. One of the sections I though is completely obsolete was a statement  about disinformative names:

“A truly awful example of disinformative names would be the use of lower-case L or uppercase O as variable names, especially in combination. The problem, of course, is that they look almost entirely like the constants one and zero, respectively.”

The corresponding example he gives is the following:

Disinformative names in Clean Code

So far I though it is obvious not to write such code, however, I came across similar code these days.

for (int o = 0; o < args.NewItems.Count; o++)
{
string s = args.NewItems[o].ToString();
...
}

What’s the problem here? The variable name o is used for a counter and initialized with 0. While this is already hard to read, o might indicate that we deal with an object here. So when having just a brief look over this code you might get the impression it iterates through a set of objects. This is further supported by the usage of the NewItems property here, as in .NET object references is quite commonly used to resolve e.g. a key/value pair within collections.

When using a counter variable without meaning one should use common names such as i or j that a commonly recognized as counter variables.

for (int i = 0; i < args.NewItems.Count; i++)
{
string s = args.NewItems[i].ToString();
...
}

This is only a slight modification but already improves the readability of the code.

Posted at Tuesday, December 22, 2009 2:54:07 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Today, I run into a quite annoying error message while developing a application for Windows Mobile 6.1.

"An error message is available for this exception but cannot be displayed because these messages are optional and are not currently installed on this device. Please install ‘NETCFv35.Messages.EN.wm.cab’ for Windows Mobile 5.0 and above or  ‘NETCFv35.Messages.EN.cab’ for other platforms. Restart the application to see the message."

The required files are located at C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v3.5 \WindowsCE\Diagnostics, assuming you have installed the Windows Mobile SDK. I copied the file NETCFv35.Messages.EN.wm.cab to my device and run the installation. So far it worked fine, until the same exception popped up again.

Using the .NET CF Logger, from Power Toys for .NET Compact Framework 3.5, I was able to track it down to the following error:

"Failed to load [System.SR, Version=3.5.0.0, Culture=neutral, PublicKeyToken=969DB8053D3322AC]"

To do so, you choose the device you want to log and select which logging options you want. The log files can be found then in your application folder on the mobile device.

.NET CF Logging Options

With this new input, I found Martijn Hoogendoorn's blog entry. He came across the same issue some time ago and provided a solution to this miracle. If you have a look inside the .cab file, check the _setup.xml file.

 NETCFv35.Messages.EN.wm.cab _setup.xml 

Extract and rename the file SYCCFA~1.001 to System.SR.dll and include it into your project. Rebuild, deploy and debug it - it should work fine.

 

 

Posted at Monday, September 08, 2008 2:49:47 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [3] #      | 
What Is IronRuby?
Posted in .NET | Coding

If you are interested, go to Manning Publications Co. and get an (almost) free White (green) paper about IronRuby. It will cost you only your e-Mail address and clicking the opt-out link as soon as you received the first newsletter.

"IronRuby is an implementation of the Ruby language on the .NET Framework. That means when it’s complete it will have the same language features as Matz’s Ruby Implementation (MRI) 1.8.6 but backed up by the intrinsic power that the .NET Framework harnesses."

What is IronRuby - Green Paper

Source: http://manning.com/free/green_carrero.html

Posted at Thursday, August 28, 2008 2:12:28 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 
RESTful .NET
Posted in .NET

There is an upcoming book I am looking forward to: O'Reilly's RESTful .NET by Jon Flanders.

That's what the cover text says so far:

"RESTful .NET is the first book that teaches Windows developers to build RESTful web services using the latest Microsoft tools. Written by WFC expert Jon Flanders, this hands-on tutorial demonstrates how you can use WCF and other components of the .NET 3.5 Framework to build, deploy and use REST-based web services in a variety of application scenarios. No prior knowledge of REST or WCF is required to get started."

I am thinking about the REST concept now for a while and I am really interested in the way Jon is going to address some of the issues such as secure REST endpoints. He will also address the ADO.NET Data Services which follow the REST principles quite well. I am not to optimistic right now about it, since REST is not as easy as it is commonly thought.

The book is scheduled for October and so I just added it to my wish list, not to forget about it.

Posted at Friday, June 13, 2008 8:14:39 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

I still wonder why I can't use the switch-statement on typeof in C#?! Finally, I found Peter Hallam answering to this. Irrespectively his arguments, it works for the try-catch-finally statement quite well. So why not for switch?! 

Posted at Friday, April 25, 2008 10:08:02 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

These days I won't have much time for blogging since I am working on the refresh for the WebComposition/DGS web site. The final site is not online, yet. However, I can give you a first glance how the new site will look like. Stay tuned.

WebComposition/DGS Refresh

The documentation will cover the most vital design aspects of the WebComposition/DGS approach as well as all necessary information to write your own extension for the service. I am working hard to make the live demos available  as soon as possible as part of the site.

Posted at Friday, April 18, 2008 11:42:03 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

Sometimes it is maybe necessary to bring some order into your unit tests in Visual Studio. Indeed, this is not really the idea of unit testing, however it might be necessary for a variety of reasons. Facing this issue, I had to search the MSDN documentation for a while.

I was desperately looking for some syntax like:

[TestMethod(Order = 1)]

However, the only way to bring some order in your tests is, by creating some ordered tests in addition to your unit tests.

To do so, you first create a set of unit tests. In my case, some of the tests should be only executed after other run successfully. Otherwise the result might look like:

Failed Unit Test

Now we create a new test project called Order Test:

Add New Ordered Test

When opening the project you actually can arrange the order of the previously written unit tests:

Arrange an Ordered Test

Running the test then is possible by selecting the test from the Test View window. Your tests will actually only appear as one entry in the list but you will see that all the selected tests run successfully - in the correct order.

uccesfull Ordered Test

Posted at Monday, April 07, 2008 3:38:38 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [2] #      | 

Jim Nakashima gives some insight view how the Cider adorners work [1].

[1] http://blogs.msdn.com/jnak/archive/2006/04/24/580393.aspx

Posted at Wednesday, January 23, 2008 11:16:48 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Shawn Burke shows how to debug .NET source code in Visual Studio. all you need is to install the Visual Studio 2008 QFE [1] and then follow Shawn's instructions [2].

[1] https://connect.microsoft.com/VisualStudio/Downloads/...
[2] http://blogs.msdn.com/sburke/...

Posted at Friday, January 18, 2008 9:12:32 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Andrew Matthews describes another interesting pattern in [1], which he called Ambient Content Pattern :

"Provide a place to store scope or context related information or functionality that automatically follows the flow of execution between execution scopes or domains."

[1] http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/

Posted at Wednesday, January 02, 2008 2:38:13 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Microsoft offers free copies of the following books at [1]:

Introducing Microsoft LINQ by Paolo Pialorsi
Introducing Microsoft ASP.NET AJAX by Dino Esposito
Introducing Microsoft Silverlight 1.0 by Laurence Moroney


[1] http://csna01.libredigital.com/

Posted at Wednesday, January 02, 2008 8:39:36 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Since I read "Design Patterns. Elements of Reusable Object-Oriented Software" by the GoF the very first time in 1999, I am a big fan of patterns at all. Making heavy use of factory patterns such as the Factory Method or Abstract Factory I came along with a useful pattern we call a Declarative Factory. A Declarative Factory is based especially on the Attribute construct in the .NET Framework and allows you to extend new classes with factory capabilities in a zero-effort manner. The idea behind this pattern is to extend your application with new constructs in form of extensions without touching already existing code. This is possible when your extensions are provided by container objects. The key element here is about the new elements which you are not aware in your code yet.

This pattern is much like a Abstract Factory, however, there is no need  to create a concrete Factory class.
Also you add factory capabilities to  a new class by only adding the corresponding attribute.

Declarative Factory Pattern

First we have a look at the actual container object. Here we tell the container object to provide factory capabilities to create ConcretePrototype instances. The FactoryContainer can be any class we are using within our application, as example this could be a sub-class of ListViewItem in a WPF-based application.

[DeclarativeFactory(typeof(ConcretePrototype))]
public class FactoryContainer { }

The declaration of the ConcretePrototype is also straightforward. The IPrototype is the common interface for all prototypes that can be created by the Declarative Factory. If this pattern is applied to a WPF-based object this could also something like a DependencyObject or a FrameworkElement. In this case the DeclarativeFactory cold provide factory capabilities for the corresponding types.

public class ConcretePrototype : IPrototype

The attribute itself looks as following:

DeclarativeFactory Attribute

The magic now, lies in the way how to invoke the factory method provided by the Declarative Factory.

FactoryContainer container = new FactoryContainer();

DeclarativeFactoryAttribute[] a_attrib =
   (DeclarativeFactoryAttribute[]) container.GetType().GetCustomAttributes(
typeof(DeclarativeFactoryAttribute), true); IPrototype prototype = a_attrib[0].Create() as IPrototype;

You just resolve the factory attribute and call the factory method. Very easy, isn't it? However, you have to keep a few things in mind about this pattern.  First of all, it makes no sense if you already know about the class you want to instantiate. So, there is absolutely no reason to apply the Declarative Factory to the class itself. In this case you should definitely stay with common patterns such as the Factory Method. If you are going to make you project extensible where new types are provided through container objects this pattern appears to be very handy .

You can download the example source code for this pattern (under MS-Pl) at CodePlex [1].

 

[1] http://www.codeplex.com/declarativefactory

Posted at Tuesday, January 01, 2008 12:33:33 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

web.config files can be easily extended using the configSection tags.

A brief overview is given by Aaron Johnson on his blog [1], referring the original MSDN documentation [2].

[Update 12/31/2007]

Also another brief summary by Dieder Tierman [3] and a very good How-to on MSDN [4] how to write own section handlers.

[1] http://cephas.net/blog/2003/09/26/extending-webconfig-in-aspnet/
[2] http://msdn2.microsoft.com/en-us/library/0hyxd0xc(vs.71).aspx
[3] http://ms-dotnet.blogspot.com/2007/01/create-custom-configuration-section-in.html
[4] http://msdn2.microsoft.com/en-us/library/2tw134k3.aspx

Posted at Monday, December 31, 2007 9:42:34 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Sometimes, simple things end up as epic battles. If you try to MSN Search and Google for the nasty "You have create a Service" page for IIS hosted WCF services, you will and up with a lot of pre-release information and noise in the search results. Actually, you might spend days in finding some relevant information.

You have created a service.

Yesterday, I was finally pointed to the right place in the MSDN documentation [1] where you can find this specific information:

<serviceDebug httpHelpPageEnabled="Boolean"
    httpHelpPageUrl="Uri"
    httpsHelpPageEnabled="Boolean"
    httpsHelpPageUrl="Uri"
    includeExceptionDetailInFaults="Boolean" />

With the serviceDebug tag it should be possible to get rid of the page. It is easy to find as long as you know you have to search for HTML help page.

[1] http://msdn2.microsoft.com/en-us/library/ms788993.aspx

Posted at Friday, December 21, 2007 9:18:05 AM (W. Europe Standard Time, UTC+01:00) 
Comments [1] #      | 
XLINQ Summary
Posted in .NET | Coding

I just found this nice LINQ to XML summary [1] on The Code Project.

[1] http://www.codeproject.com/KB/vista/LINQ_3.aspx#LoadingXML

Posted at Sunday, December 09, 2007 11:58:39 PM (W. Europe Standard Time, UTC+01:00) 
Comments [1] #      | 

The new Web Programming Model [1] of WCF and the .NET Framework brings some very useful features such as the WebGet and the WebInvoke Attribute and the capability to deal directly with HTTP requests. But how do we access the HTTP request in these methods? Dealing with HTTP requests and responses using the System.Net namespace is quite straight forward. Therefore, we have a look in sending and receiving a simple HTTP request:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(myUrl);
byte[] a_dataBytes = Encoding.UTF8.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = a_dataBytes.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write(a_dataBytes, 0, a_dataBytes.Length);

WebResponse
response = request.GetResponse(); StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var content = responseReader.ReadToEnd();

Now we want to access the HTTP context within a operation with the following signature:

[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "{uri}")]
bool Put(string uri);

Accessing the context of the incoming request is straightforward using the WebOperationContext class.

IncomingWebRequestContext context =
    WebOperationContext.Current.IncomingRequest;

var length = context.ContentLength;
var type = context.ContentType;
var headers = context.Headers;

Since the documentation does not provide many example code, and the ORCAS samples do not cover this yet, I had to figure out how to access the content of the incoming request. After spending hours on MSN Search, Google and the MSDN Library I finally tried out something. In some general examples, either a Message or a Stream is passed over as single parameter to the operation. Hence, I changed the contract as follows:

[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "{uri}")]
bool Put(string uri, Stream stream);

Reading the content then is easy:

var reader = new StreamReader(stream);
string content = reader.ReadToEnd();

This solution however comes up with one major drawback: If you try to access your foo.svc via browser you will end up some error telling you "For request in operation Post to be a stream the operation must have a single parameter whose type is Stream.". Also calling foo.svc?wsdl will end up in some exception in the WSDL export extension.

 

[1] http://msdn2.microsoft.com/en-us/library/bb412169(VS.90).aspx

Posted at Sunday, December 09, 2007 9:22:53 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Maybe this is a bug: Creating a ContextMenu as child of a Canvas, the event handlers CanExecute and Execute have never been executed? This took me almost two hours to figure out why. Basically I do my command binding like

CommandBinding exitCmd =
    new CommandBinding(DesignerCommands
.Exit);
exitCmd.CanExecute +=
   
new CanExecuteRoutedEventHandler(exitCmd_CanExecute);
exitCmd.Executed +=
 
new ExecutedRoutedEventHandler(exitCmd_Executed);
CommandBindings.Add(exitCmd);

To me, it looks like there is a minor problem in command binding [1] whilst using command binding this manner in controls which never get the focus (such as a Canvas). Since the handlers are never fired. An easy workaround is to add additional command binding within your XAML code.

<ContextMenu.CommandBindings>
    <
CommandBinding Command="e:MyCommands.Exit
"
                    CanExecute="exitCmd_CanExecute
"
                    Executed="exitCmd_Executed"
/>
</ContextMenu.CommandBindings>

I checked a couple of web sites and found also [2], where the problem is described a bit more in detail. Also Aaron describes a second work around that requires some lines of code.

[1] http://msdn2.microsoft.com/en-us/library/ms741839.aspx
[2] http://www.wiredprairie.us/journal/2007/04/commandtarget_menuitem_context.html

Posted at Monday, May 07, 2007 12:21:14 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

I am working on a user interface (UI) for a client tool of our current project. Though, the last two have been a epic battle fighting with a various of minor things. However, each and every of these things does cost a remarkable amount of time.

Starting with WPF many developers will spend mcuh time with skinning in WPF. It's a cool thing, but you should leave these things to designers. It is a enormous time sink. You make huge progress in the beginning but end up with endless fine-tuning in the end. The first have a look at the Windows Vista User Experience Guidlines [1]. The really thing: you don't have to read everything online, just download the 630 pages as PDF document [2]. You will see that skinning should be used carefully. Much more important are some new guidlines to keep in sync with the Vista UI. BTW: if you are looking for the Vista icons you should have a look at [3] (but I haven't told you that and so use them only to inspire you by creating own icons).

Well, what's about the cool stuff such as the new Command Link in Vista? Should be a new control? Well, not that easy. Daniel Moth found out [4] to check the Vista Bridge Samples [4] comming with the Windows SDK. you should go definitely for the Windows SDK Update for Vista [6]. Daniel also gives a first impression how to use the TaskDialogs provided by the VistaBridgeLibrary [7].

Now you will definitely run into trouble if you don't create a manifest file for you application using the following dependency:

<dependency>
  <dependentAssembly>
    <assemblyIdentity
      type="win32"
      name="Microsoft.Windows.Common-Controls"
      version="6.0.0.0"
      processorArchitecture="x86"
      publicKeyToken="6595b64144ccf1df"
      language="*"
    />
  </dependentAssembly>
</dependency>

In my case I also had to use strong-named assemblies since they are used within VSIP [8] packages. You will realise that the VistaBridgeLibrary uses friendly assemblies, Junfeng gives a short introduction into friendly assemblies at [9]. You'll discover that is not as easy since there have been some changes in Visual Studio 2005. Adrian figured out how it works at [10]. David cover's the further steps in [11] and also provides a small tool to obtain the public key token of a signed assembly ready to be copy 'n' pasted into your Assembly.cs file.

[1] http://msdn2.microsoft.com/en-us/...
[2] http://download.microsoft.com/download/...
[3] http://www.istartedsomething.com/20060924/vista-fitted-nearly-finished/
[4] http://www.danielmoth.com/Blog/2006/06/vistabridge_12.html
[5] http://msdn2.microsoft.com/en-us/library/...
[6] http://www.microsoft.com/downloads/...
[7] http://www.danielmoth.com/Blog/2006/06/...
[8] http://www.microsoft.com/downloads/...
[9] http://blogs.msdn.com/junfeng/archive/2004/07/...
[10] http://geekswithblogs.net/dotnetrodent/archive/...
[11] http://davidkean.net/archive/2005/10/06/1183.aspx

Posted at Friday, April 27, 2007 8:05:36 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

Some hints on Visual Studio on Windows Vista at [1].

[1] http://msdn2.microsoft.com/en-us/vstudio/aa964140.aspx

Posted at Thursday, November 23, 2006 9:16:41 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Good to know where to find the Pre-released Microsoft .NET Framework 3.0 Uninstall Tool [1].

[1]  http://www.microsoft.com/downloads/details.aspx?FamilyId=AAE7FC63-D405-4E13-909F-E85AA9E66146&displaylang=en

Posted at Thursday, November 09, 2006 8:23:39 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 
CodePlex
Posted in .NET | Coding | Microsoft

Microsoft's community development portal [1] and the Shared Source portal [2].

[1] http://www.codeplex.com/ 
[2] http://www.microsoft.com/resources/sharedsource/default.mspx

Posted at Thursday, July 13, 2006 10:47:38 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 
vshost.exe
Posted in .NET | Microsoft

Several times I got the question waht the vshost.exe is in Visual Studio Express Editions [1]. If you are familiar with Visual Studio the answer is easy: It is called hosting process . And is decribed in [2]:

"The hosting process is a feature in Visual Studio 2005 that improves debugging performance, enables partial trust debugging, and enables design time expression evaluation. The hosting process files contain vshost in the file name and are placed in the output folder of your project."

[1] http://msdn.microsoft.com/vstudio/express/
[2] http://msdn2.microsoft.com/en-us/library/ms185331.aspx

Posted at Saturday, June 24, 2006 10:45:36 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 
MSDN TV
Posted in .NET | Coding | Microsoft

I have just added the MSDN TV [1] and MSDN Webcast [2] feeds to my blogroll.

[1] http://msdn.microsoft.com/msdntv/
[2] http://msdn.microsoft.com/events/webcasts/default.aspx

Posted at Tuesday, May 16, 2006 10:03:38 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

Maria brought the Consolas Font Pack for Visual Studio 2006 [1] to my attention. After installing, the Consolas font is set up as default font in Visual Studio 2005. At least on my Portégé M200 it is very readable.

[1] microsoft.com/downloads

Posted at Wednesday, May 03, 2006 11:20:38 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

John Rivard explains why the each Visual Studio does only support one specific .NET Framework.

Posted at Tuesday, February 07, 2006 6:06:33 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 
You prefer emacs?
Posted in .NET | Coding | Tools

For all those developers who prefer Emacs there it is. Emacs shortcuts put of the box supported by the Visual Studio 2005.

"The following shortcut key combinations mimic commands available in Emacs and are used while editing code in the integrated development environment (IDE)."

Link: http://msdn2.microsoft.com/en-us/library/ms165528.aspx

Posted at Tuesday, December 13, 2005 3:21:41 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 
Threading in .NET
Posted in .NET | Coding

If you have some trouble in updating GUI elements since they are not created by the thread just running

delegate void onSensorChangeParameterDelegate(int index, int sensorValue);
void kit_OnSensorChange(int index, int sensorValue)
{
  if (InvokeRequired)
  {
    BeginInvoke(new onSensorChangeParameterDelegate(kit_OnSensorChange), new object[] { index, sensorValue });
    return;
  }
  txtInfo.Text = String.Format("Index={0}, Value={1}", index, sensorValue);
}

So the method is handed over to the GUI thread, where txtInfo is a TextField, and processed there. Jon has written a great article [1] about threading in .NET and how it can be done.

[1] http://www.yoda.arachsys.com/csharp/threads/winforms.shtml

Posted at Monday, December 05, 2005 10:14:58 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

There is a shortcut within Visual Studio i did not know yet. Press [Ctrl],  [Alt] and arrow down. The following dialog shown below should appear. Using the up and down arrow it's possible to cycle through the open files.

There is some redundancy with the dialog showing up when [Ctrl] + [Tab] is pressed thus both provide the same functionality.

Posted at Monday, November 28, 2005 6:48:41 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

While playing with Indigo I spend several hours on duplex services and clients finally leading to an annoying issue. I tried two different examples, one from the book Programming "Indigo" and another one from the WinFX SDK documentation [1]. In both cases I spend hours writing down all the code, e.g. the examples in the book do not fit with the current release of the WCF anymore. So some minor fixes have been necessary. Having both examples I tried to start the clients, but they did not receive any response from the service. If you are patient enough (which means waiting 5 to 10 minutes) the client will result in a ChannelConnectException.

What is wrong? Bindings? Any mistake in the XML config-files? The solution is as simple as it could be: Just right-click the web site in the solution browser and choose Start Options... 

Uncheck NTLM Authentication which is checked by default and restart your service and client.

After restarting the service and the client, the client is processing, the service is responding and the Quick Console shows the expected output:

[1] winfx.msdn.microsoft.com

Posted at Thursday, October 06, 2005 12:49:17 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

Have you realized already this cool feature in Visual Studio 2005?

If you write down some interface or class names which do not exist yet, they appear in black (as long as you still use the default settings for the editor). As soon as you write down the appropriate class or interface the color changes from black to light blue. Why this is cool? It makes it pretty easy to find typos in your code right before compiling. If you see such code not in the appropriate color, either you have a typo in its name or the class or the interface is not implemented yet. It makes a lot of sense when you write down code but the implementation of a class or interface is not yet available because it is written by another person. It's a nice feature in VS 2005.

Posted at Wednesday, October 05, 2005 2:28:52 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

While preparing some demos to show cool stuff at PDC 05 I installed the hot new DirectX SDK Update August 2005 [1]. Unfortunately VS 2005 does not like the update. After starting my already testet applications using DirectInput an Exception occured. A LoaderLock was detected... what the heck?

Actually you can find something about this issue in the Visual C++ 2005 Library and Runtime Enhancements transcript [2]. Also Tone Engel has found this isue already and posted the solution in his blog [3].

 

Just set a new string value mda = "0"  under HKEY_LOCAL_MACINE\SOFTWARE\Microsoft\.NETFramework. Looks like it does not solve the problem, but at least the error message disapears.

[1] http://www.microsoft.com/downloads/search.aspx?displaylang=en&categoryid=2
[2] http://msdn.microsoft.com/chats/transcripts/vstudio/vstudio_091604.aspx
[3] http://tonesnotes.org/2005/08/23/loaderlock-warning-2005-beta

Posted at Tuesday, September 06, 2005 5:34:25 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

If you have to use orften contracts in Microsoft Communication Foundatation aka Indigo, sometimes you become really bored by implementing all the interfaces. Visual Studio 2005 helps you saving a lot of time by choosing the interface your class inherits from. Using the Implement Interface menu item you will get all the methodes required by the interface.

Posted at Saturday, September 03, 2005 12:06:58 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 
Indigo
Posted in .NET

Just to remember: Indigo download page [1] (RC1).
And the corresposnding "Longhorn" Devleoper Center [2] Indigo site.
The WinFX SDK [3] provides a lot more information, check out the sections Indigo and Samples.

After installing the Indigo RC1, I found the Digital Identities icon in my control panel. But does not seem to work, yet.

Arun Gupta has already experienced (more or less painful) how the GettingStarted example [4] works.
The updated WinFX (beta RC1) is available as iso image [5]. 

Because I am pretty sure, I will need this soon, here are some information about removing previous versions [6].

Anyway, using this installing order you finally can create Indigo services:

  • IIS
  • Visual Studio 2005 beta2
  • Indigo and Acalon beta RC1
  • WinFX SDK beta RC1

 

[1] microsoft.com/downloads
[2] http://msdn.microsoft.com/Longhorn/understanding/pillars/Indigo/default.aspx
[3] http://winfx.msdn.microsoft.com/library/
[4] http://weblogs.java.net/blog/arungupta/archive/2005/06/indigo_beta1_rc_1.html
[5] download.microsoft.com
[6] http://lab.msdn.microsoft.com/vs2005/uninstall/

Posted at Monday, July 18, 2005 6:21:46 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

I need this so often, but every time I forget, how it works (from Visual Studio Help).

Project Folder Not Secure Dialog Box

You attempted to create a project on a UNC path. By default, a UNC path is not a trusted location for a project. Your project may not run correctly when you attempt to debug or run from this location. For more information, see Configuring Security Policy.

The following tools modify the policy affecting the file share.

  • .NET Framework Configuration Tool (Mscorcfg.msc)
  • Code Access Security Policy Tool (Caspol.exe)

Mscorcfg.msc

One simple way to modify the policy affecting a file share is to give a specific file share FullTrust permission using mscorcfg.msc. You must be an administrator on the computer to make this change.

To give a file share FullTrust permission

  1. Start mscorcfg.msc.
  2. Expand the Runtime Security Policy node, the Machine node, the Code Groups node, the All_Code node, and then highlight the LocalIntranet_Zone node.
  3. In the right pane select Add a Child Code Group.
  4. Choose Create a new Codegroup and enter a name for the code group, then click Next.
  5. Choose a Condition Type of URL, then enter the UNC path to the share location of your project, using the format file///\\servername\sharename\* where \\servername\sharename is the name of the share. Click Next.
    Note   Make sure to add the asterisk at the end of the path.
  6. Choose Use Existing Permission Set of FullTrust, then click Next.
  7. Click Finish.
  8. Restart Visual Studio.

Caspol.exe

Using caspol.exe to accomplish this change, you would use the following command line (you must be an administrator on the computer to make this change.):

caspol -m -ag 1.2 -url urlname FullTrust

See Also

Configuring Security Policy

Posted at Tuesday, February 15, 2005 8:46:09 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

There has been a problem with FTP for a while. The Color Picker as well as the Image Browser did not wanted to work properly! The solution can be found there:

"Finally ...

Thanks to Kenneth Solberg (http://www.khix.net), the FTB Web Dialogs finally do work !

The Hack (noticed that I didnt use the word solution):

1) Save a copy of the web.config file from the dasBlog root to the ftb directory

2) Open up that web.config file from the ftb directory.

3) Edit the Authorization Config section to such:
<authorization>
 <allow users="*" />
 </authorization>

4) Remove the Authentication Elements from the config file.

5) Save the File.

6) Save a copy of the SiteConfig Folder and Contents from the dasBlog root to the ftb directory as well.

7) Refresh and Click on the Font-Fore Color, Font-Back Color and Insert Code Buttons of the FreeTextBox and watch the wonderful Web Dialog pop up successfully.

I would never have figured out why and how as there was absolutely no written documentation anywhere (that I could find anyways...)
"

Source: gotdotnet Messageboard

Posted at Sunday, December 05, 2004 10:43:32 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Hat man ein ArrayList und will die darin gespeicherten Integer-Werte in ein Array auslesen, klappt dies in C# ganz umständlich aber zuverlässig mit folgendem Befehl:

int[] args = (int[]) arrayList.ToArray(typof(int));

 

Posted at Monday, November 29, 2004 8:15:47 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Jetzt, da die echte Domain für sämtliche Request verwendet werden kann, habe ich begonnen einige kleine Probleme auf der Seite zu beheben. Ein Problem trat regelässig auf, wenn man im Kalender von dasBLog einen Tag ausgewählt hatte. dasBlog ruft darauf die Seite default.aspx?date= auf. Natürlich klappt das nicht, wenn die default.aspx Seite in blog.aspx umbenannt wurde. Wie fast alle in .NET kann das Problem mit einem Dreizeiler gelöst werden:

if (Request.QueryString["date"] != null)
{
    string
query = "blog.aspx?date=" + Request.QueryString["date"];
    Server.Transfer(query);
}

Das reicht und jeder Request der auf der Startseite eingeht und vom Kalender stammt wird abgebochen und es wird anstelle dessen die Seite blog.aspx zurückgeliefert. Beliebig verfeinern lässt sich das Ganze, indem beispielweise noch auf die Referrer-Url abgefragt wird. Eine Bedingung in der Form

Request.UrlReferrer.ToString().Substring("blog.aspx") < 0

genügt da schon.

Hack The Planet!

Posted at Sunday, November 28, 2004 9:12:17 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Leider kann man .NET Applikationen nicht ohne weiteres von Desktop Systemen auf Comapct Framework basierte Systeme kopieren. Das CF unterstütz nicht den vollen Umfang des .NEt Frameworks. Zwei Probleme die bei der Portierung multi-thread-fähiger Applikationen auf das CF auftreten können werden im folgenden gelöst:

Die erste Falle lauert im Aufruf

System.TimeSpan yield = new System.TimeSpan(10);
System.Threading.Thread.Sleep(yield);

Das CF unterstütz den Sleep-Aufruf nicht mit einerm TimeSpan Struct als Paramter. Ein Integer ist hier die Lösung und im Handumdrehen implementiert:

System.TimeSpan ts = new System.TimeSpan(10);
int yield = ts.Milliseconds;
System.Threading.Thread.Sleep(yield);

Spannender wird es beim Aufruf der WaitOno-Methode. Diese wird im CF lediglich ohne Paramter unterstützt. Wer neben dem externen Signal auf einen timeout wartne möchte, kann dies lange tun. Eine einfache Möglichkeit bietet ein PInvoke-Aufruf:

[System.Runtime.InteropServices.DllImport("CoreDll.dll")]
private extern static System.Int32 WaitForSingleObject(
    System.IntPtr Handle,
    System.Int32 Wait);

Jetzt kann der Aufruf

foo.WaitOne((int)((bar - System.DateTime.Now.Ticks), false);

durch folgenden Dreizeiler ersetzt werden:

System.IntPtr hProcess = foo.Handle;
System.Int32 iWait = (int)((bar - System.DateTime.Now.Ticks));
WaitForSingleObject(hProcess, iWait);

Kompilieren, auf das mobile Gerät kopieren und wieder ist ein Tag gerettet.

Posted at Tuesday, November 16, 2004 2:49:03 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Zeit zur Selbstbeweihräucherung! Mit den beiden Kollegen Saternus und Kindzorra haben wir den Besuchern des Wissenschaftstages im September unsere Technologien und das Zusammenspiel mit Fischertechnik näher gebracht! Ein voller Erfolg, und jetzt der Lohn:

Martin, Oliver and me at fischertechnik Fan-Club

Posted at Thursday, November 11, 2004 11:55:51 PM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

06:42 Uhr ICE startet Richtung Berlin. Dabei bin ich gerade erst schlafen gegangen, das war eine harte Nacht, mehrere hundert LOCs sind mir aus den Fingern gefallen. Da Programmieren durchaus eine Kunst ist, sollte man die Muse, hat sie einen denn endlich geküsst, nicht mit einem Plattschuss erlegen, sondern sich direkt Ihrer Fügung hingeben.

 

Irgendwann gegen Mittag kommt der Zug an. Verspätung. Ach ja, die Queen ist heute in Berlin, da muss halt ein Zug schon einmal 30 Minuten 500 Meter vor dem Bahnhof warten. Zu spät zum Termin angekommen, haben sich die Kollegen der TU Berlin als extrem freundliche Zeitgenossen herausgestellt. Kollege Saternus, auch mit von der Partie, hat sich schon dem Kaffee gefrönt. 

 

The Master and Martin

 

 

An dieser Stelle muss man das wirklich lobenswert erwähnen: noch nie habe ich jemanden getroffen, der mit einer solchen Hingabe aber auch Geduld, die von ihm verfasste API erklärt hat. Leider hatte ich OneNote nicht auf dem Laptop installiert, also musste der vi des Windows herhalten und mit notepad.exe wurden spontan 3 Seiten mitgetippt.

 

Martin and me

 

Nachdem die Accounts für eine hier nicht näher genannte Sourcecode-Verwaltung angelegt waren, wurde auch gleich das Aus- und Einchecken an der Datenbank geübt. Mit neuem Sourcecode auf der Platte wird die Rückreise wieder angetreten. Während Kollege Saternus sich durch den Feierabendverkehr bis zum Flughafen durchschlagen muss, habe ich Glück: der Bahnhof ist nur ein paar Fußminuten um die Ecke: "Ahhhh, Berlin..." das war definitiv ein kurzer Besuch aber ein lohnenswerter. Während der ICE Sprinter mit nahezu der Take-Off-Geschwindigkeit einer Boing 757-200 entgegen des nächsten Sonnenaufgangs gondelt, werden noch liegen gebliebene Aufgaben erledigt. Das Outlook Postfach wurde schlielich noch mal schnell auf den aktuellen Stand gebracht und die 70 noch nicht gelesenen Mails haben sich enorm reduziert. Nichts desto trotz liegen noch 917 zwar gelesene aber nicht abgearbeitet Mails im Postfach nichts kritisches aber einfach Mails mit Links, Texten oder Informationen, die noch nicht verarbeitet sind. Im Akt dieser Arbeitswut sind natrlich auch einige Antwort-Mails der digitalen Feder entsprungen müssen später nur noch weggeschickt werden!

 

 

21 Mails to send

 

Wieder einmal neigt sich ein 19 Stunden Arbeitstag dem Ende entgegen mit dem Gefühl .NET ist doch eine feine Sache.

Posted at Thursday, November 04, 2004 12:40:14 AM (W. Europe Standard Time, UTC+01:00) 
Comments [0] #      | 

Ein Fehler wie folg popt plötzlich bei dem Kunden hoch: und dieser ist recht erstaunt, denn vor 5 Minuten hat die Applikation ja noch einwandfrei funktioniert.

Nach dem ersten Schreck sehen wir als erfahrener Entwickler, dass der Fehler eindeutig in der Konfigurationsdatei liegen muss!

Ja, sieht ja ganz gut aus. Und der Connection String, der vor 5 Minuten vom Kunden angepasst wurde scheint auch zu stimmen. Eine Test-Applikation kann sich mit dem angegebenen String ohne Probleme verbinden: Von Hand geht das auch, das XML ist wohlgeformt, um nicht zu sagen, ein besseres XML gibt es auch der weiten Welt nicht!

Na, den Fehler schon gefunden? Nein? Dann mal hierher schauen:

Na, jetzt ist es doch klar, oder? In der Tat, benötigt man nicht mehr als diese beiden kleinen Ausschnitte um den Fehler zu finden: Das Schöne am Arbeiten mit XML Dokumenten ist, dass man die Dokumente Formatieren kann wie man möchte, ob man jetzt 2 oder 4 Whitecaracter einrückt, oder ob man den Tabulator verwendet ist egal... und wenn einmal ein Leerzeichen zwischen den Tags steht, nun denn, das fördert die Lesbarkeit des Dokumentes. Mit einer Ausnahme: Vor dem <?xml darf nun mal KEIN Leerzeichen stehen, sonst wird das Dokument falsch geparst. Zu blöd, dass der Kunde beim “ndern der config-Datei versehentlich ein Leerzeichen hinzugefügt hat. Nunja, da der Kunde diesn un weiß, erkennt er auch den, wen nur marginalen Unterschied in den obigen Bildausschnitten...

Posted at Friday, October 29, 2004 4:51:06 PM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 

Aus dem Film "Sneakers" aus dem Jahr 1992 mit Robert Redford kann ich mich noch an den Satz "no more secrets" errinern. In diesem Sinne steht dieser Eintrag unter dem Titel "no more errors".

Aufgrund einer Anfrage bin ich dazu gekommen, ein kleines Tool zu schreiben, welches eine bestehende  Datenbank mit zusätzlichen Einträgen füllt. Um sicherzustelen, dass dieses Tool keinen Unfog treibt, wird die komplette Entwicklung test-getrieben durchgeführt. Das hierfür verwendete Tool ist, wer hätte es auch anders erwartet NUnit. Um von Anfang an eine saubere Trennung wischen Tests und Programm zu erhalten wurden alle Tests in eine eigene Klasse respetive eine eigene File verfrachtet.

Bevor wir überhaupt mit der Entwicklung der GUI anfangen wird zunächst all die Funktionalität im System sichergestellt. Ein sehr primitiver Test: den Connection String für die Datenbank aus der.config-Datei zu laden:

[Test]
public void CanRetrieveConnectionString()
{
    Assert.IsNotNull(connectionString);
}

Dieser Test is einer der einfachsten, und einder der wichtigsten, denn klappt es hier nicht, klappt gar nichts. Un man sollte auf diese einfachen Tests wirklich nicht verzichten.

Natürlich müssen wir zum Testen auch Daten in die Datenbank pumpen, die wir später wieder entfernen müssen:

[TestFixtureSetUp]
public void FixtureSetUp()
{
   
// create uploader
   
uploader = new ManiacKeyUploader();
   
connectionString = uploader.ConnectionString;

    // fill database with test data
       //...
   }
}

Natürlich wird dies alles wieder in der [TestFixtureTearDown] alles wieder aufgeräumt, schilesslich sollen am Ende ja keine Karteileichen rumliegen: Was bringt das ganze, fragt man sich jetzt?

Wie man schön sehen kann, ist einer der Test fehgeschlagen. Ganz wichtig: Es handelt sich hierbei um einen Test, der vor den letzten Änderungen fehlerfrei durchlief. D.h. man kann mit Bestimmtheit sagen, dass in den letzten 5 Zeilen Code-“nderungen der Fehler begraben liegt, der sich auf den bereits vorhandenen Code auswirkt! DIESER Fehler wäre unter "normalen" Entwicklungsbedingungen nie mehr aufgetaucht und vermutlich erst beim Produktivbetrieb aufgefallen... Welche Kosten man durch ein solches Vorgehen spart... der vermdeindliche Mehraufwand lohnt sich allemal. Wer jetzt noch immer nicht davon überzeugt ist: Das Verhältnis Produktivcode zu Testcode liegt im Moment bei 1:2 und durch das test-getriebene Vorgehen wird der ganze Code wesentlich kleiner, schöner und effektiver.

Link: www.nunit.org

Posted at Friday, October 29, 2004 10:00:10 AM (W. Europe Daylight Time, UTC+02:00) 
Comments [0] #      | 
Copyright © 1995-2009 by Andreas Heil. aheil is a registered trademark of Andreas Heil. All rights reserved.
The opinions expressed herein are my own personal opinions and do not represent my employers' views in any way. Content and thoughts expressed on these pages and the weblog are subject to be changed. Out of date posts should not be considererd as my current thoughts and opinions.