Mind ‘win32manifest’ when interop-ing

Tags: , , , , ,
No Comments »

For those who look for a quick solution:

Try switching off the win32manifest-switch in Visual Studio.

Here is the long story.

Hi! As you may already know we are working on the best .NET – ARIS interface there is so far. It’s an interface that makes heavy use of an old C-Api, using interop and p/invoke.

In Mid-December Benjamin found a very strange behavior that almost spoiled my Christmas. We had just release Version 1.1 when he called me: “Arisan crashes with Vista64.” I was shocked. “And with Vista32 as well”. I felt annihilated. We had done so much testing with various versions of XP, Vista and it worked fine with any of those OSes.

After some testing I saw that ARIS didn’t deliver any pointers at all. That’s rather bad for an interface to C that uses pointer in every call.  After one more day we had more evidence: We had switched to .NET3.5 and VS2008 some month ago and our old versions, that were compiled using the .NET2.0-compiler, still worked.

I was so terrified. The 3.5-framework should be similar to the 2.0-framework, just some (not so) little enhancements. A bug in the 3.5-compiler?

To provide a quick solution we re-wrote parts of the fancy 3.5-syntax, to make our newest enhancement compile with the 2.0-compiler again. That worked (at least we thought so) and we released version 1.1.1.

Then a very frustrating time began. We read articles over and over and quickly found this very interesting post. The problems described there where exactly what we saw.  So we followed the track of the nxcompat-flag and DEP, but it didn’t lead us anywhere.

The C-Api we interface is well documented, but it calls hundreds of other components and one of them crashed deep inside an undiscovered country.

We read pages of differences between 2.0- and 3.5-compiler, new compiler-flags (should have paid more attention here), any documentation we could find, but nothing seemed to help.

We had a feeling it could have something to do with Vista UAC, but we didn’t find any matching explanations to our problem. Being really desperate we started this thread at the MS forums. As you can read there, no one could provide a solution that worked.

I was really sad, because the last thing I wanted to do was to switch the entire development of arisan back to VS2005. I got prepared for a very sad life from now on.

But five days ago my life turned to happiness again. One more time I started of by googling words like “.NET compiler 2.0 3.5 differences” and one more time I read the new features of the 3.5-compiler. This time I obviously paid more attention to the compiler-flags and read about the /win32manifest and /nowin32manifest – switches. I didn’t have much hope left, but tried to set the /nowin32manifest switch.

It worked! Everything worked! The C-Api delivered pointers again. I tried switching the win32manifest on and off and a day later Benjamin confirmed my results. We had found it. But after a long time of suffering (for me it felt like half a year) we still were skeptical and thought we needed a deeper understanding of the problem.

The win32manifest and UAC

Finally we had something to look for and quickly found valuable information on the great I’m just sayin’ blog. The documentation of the switches helped as well, so here is a summary:

The win32manifest is not the .NET-manifest.

The win32manifest is part of the UAC (user access control). UAC was introduced with Vista as an answer to more and more security threads. One of its ideas is to keep malicious software from secretly starting to work. If you work with Vista you may have noticed a lot of dialogs that ask you for permission to run certain programs. THAT is UAC.

Now the win32manifest inside an application tells the OS what level of permission it needs to run. There are levels like “asInvoker” (default), “highestAvailable” or “requireAdministrator”. In case the OS (and the current user) can provide the requested permission, the program runs as a trusted process (according to the granted access level). Of course, 90+% (just my estimation) of the programs on you Vista-machine don’t have a win32mianifest,  because it’s a new feature and older applications just don’t have it. (And I think a majority of newer applications won’t have it either). In order to be compatible with no-win32manifest applications on one hand and providing security on the other hand, Vista can do a miracle called “virtualization”. It’s a bit like running a process in a sandbox: Vista provides anything the process may need to run: disk space, memory, a registry etc. So the process feels cosy.

But anything provided this way is separated from the main system. The process uses a copy of the registry, writes to a special parts of the HDD drives and accesses the memory in a controlled way (not sure about the memory thing…). For me this is a great achievement of Vista, almost magic. I can’t tell in detail how it works (mainly because I don’t have a clue), but it works good and doesn’t cost notable performance.

So on your Vista machine you have processes that run virtualized and others that run non-virtualized. “Non-virtualized” is also called “UCA-compatible” or just “compatible”, so I’ll adopt this wording here.

You could say that Vista trusts compatible processes a little bit more than virtualized processes. That doesn’t mean virtualized processes are evil, but.. well… maybe… under certain circumstances… not 100% trustworthy. (Here is another nice article)

Note three facts here:

  1. The state (virtualized/compatible) always counts for a process and is set when the process starts. When you start an .exe-file, Vista decides how to run it.
  2. Because of 1) there is no sense in attaching a win32manifest to components that do not start a process, like .dlls. Thus .dlls don’t have a win32manifest.
  3. The state (virtualized/compatible) of a process doesn’t change during its lifetime.

So if a .dll is used by a virtualized process, its code also runs virtualized. And if the same .dll is used by a compatible process, its code runs compatible.

Interaction

With some of that in my mind, I could explain the problems we had with our interface software arisan: arisan is a .dll you reference in your .NET-application and use it. As mentioned above arisan calls a native (so non-.NET) .dll using p/invoke-interop-techniques. Now this native .dll starts a bunch of new processes: a database-server, a database-driver, some middle-layers, etc. I am pretty sure non of this newly started processes is based on applications with a win32manifest – so they all run virtualized.

But the .NET-applications we use to test the arisan.dll started running compatible as we switched to VS2008 and the 3.5-compiler. So our test application (compatible) called arisan.dll (compatible), arisan.dll (compatible) called C-Api.dll (compatible). C-Api.dll started new processes (virtualized !!) and called functions there. And in the end a compatible (fully trusted) process asked a virtualized (less trusted) process to fill some pointers… and that’s the point where Vista interferes and says: “Dudes, are you drunk? No way!”

It was a bit of bad luck that the clash of a virtualized and a compatible process happened so deep inside a software we couldn’t debug and only threw some strange, meaningless error-messages, but on the other hand Vista could have told us more. Maybe there is some place in Vista where the clash is logged. If someone knows – please let me know, too. Let me get this straight: Vista is absolutely right here, but I’d wish more information when it happens. I don’t exactly know how, but you could do harmful things if you could easily exchange all sorts of pointers between virtualized and compatible processes…

Solution

So finally the solution was easy. Both processes have either to run virtualized or non-virtualized. Since we can’t make a third-party software run compatible, we have to make our .NET-application run virtualized: We just need to prevent .NET from inserting a win32manifest to executables.

Using the compiler from the command-line the compiler-flag /nowin32manifest does it.

In VS2008 same switch can be found on the “Application”-tab of the project properties.

image

The manifest-area is enabled for ‘console applications’ and ‘Windows applications’. It is disabled for class libraries.

Another way to handle this problem is to switch off UAC completely. But we strictly advice you against this solution. UAC is one of Vista’s main features and it is designed to provide shelter for your precious data in times of evil viruses and brutal intrusion attempts 🙂

Epilog- bad fix

After we understood the problem, we saw that the ‘fix’ we provided as V1.1.1 couldn’t do much. Ok – it made the demos run, because the executable compiled with the 2.0- come without a win32manifest and thus run virtualized. But users trying it with VS2008 still had the same issues.

Actually we cannot provide a technical solution with the arisan.dll, because if the running mode depends on the executables that use arisan. So we’ll write detailed information and everyone lived happily ever after.

x += x++;

Tags: ,
1 Comment »

Ok, what does this expression do or mean? First of all: never write something like this in your code. Nobody understands the meaning with a single look and that will lead to confusion and maybe to a bug in your software someday.

Now let’s take a deeper look. First you may think about the difference between x++ and ++x. If you write it as a single statement both expressions are equal, but if you use it as a part of a complex expression the first will evaluated to the value of x before increasing it; the second one will evaluate to the new value of x. So y = x++; leads to a different result for y as y = ++x;.

x+=a simply is a ‘shortcut’ for x=x+a.

Now let’s do it step by step. For example x is 5. Then first x will be increased by one to 6 but the old value will go into the formula that remains as x=x+5. Since x was increased before the result will be 11.

If you think that is all right, than please take a break and test it with your favorite compiler. If you are a C or C++ guy you will in fact receive 11 as an answer and everything is fine. But if you are a C# or java guy x will be 10. Why?

.Net as well as the Java Runtime are stack machines. The expression will be put on the stack step by step before evaluating the whole thing. At that time x is 5. x will be changed to 6 by the x++ part, but that only happens in the main memory. The old value (5) is still on the stack. After executing the whole expression the changed x will be overwritten by 10 (5+5).

And once again: NEVER write code like this!

throw null;

Tags: ,
No Comments »

I found this somewhere and I think it’s worth to write a short (only a very short) entry.

throw null;

If you use this expression in your C# code it will throw a NullReferenceException. That is because the throw-statement needs an object of type Exception as its single parameter. But this very object is null in my example.

I like this way to produce some exception while testing code.

Flow

Tags: , , ,
2 Comments »

It was very silent here in the past month. That was mainly because I was working on my diploma thesis until the end of September. After that I did my final exam and started working in Bonn. Now it is December and almost 2009. I’m sitting in a plane to Australia for holiday and have much time to write articles. I will try to keep this blog alive and will write articles more frequently.

Today I will introduce Flow. With Flow you can model the behavior of nodes in a wireless sensor network (WSN) in a data driven and event driven manor. I developed Flow as part of my diploma thesis.

Flow is build as a Visual Studio Addon (a VS Package) on top of the DSL-Tools containing three different domain specific languages to describe different parts of the software running on a sensor node. These different DSLs are working together and using most of the techniques I described earlier in this blog. E.g. my library JaDAL was initially build to support this diploma thesis.

You will find screenshots, more explanations and Flow itself on http://flow.irgendwie.net. While the webpage and the software are available in English the thesis itself is a pdf-document and can only be downloaded in a German version.

The software is fully working and if no wireless sensor network is available you can use a node simulator to evaluate Flow. The code is released under the new BSD license and also available for download.

Screenshots:

Dataflows modeled with Flow looks like that:

dataflow

The simulated sensor nodes are represented as Windows forms programmed by such dataflows:

simulatednode

For more information just visit http://flow.irgendwie.net.

Microsoft Technical Summit in Berlin

Tags:
No Comments »

From 11/19 to 11/21/2008 I will be at the Microsoft Technical Summit in Berlin. The Technical Summit itself starts on 20th; on the 19th I will attend the 4th Academic Day.

If anyone will be at these conferences and likes to meet please drop me a line.

See you in Berlin. 🙂

Using Geonames.org webservice from .Net

Tags: , , ,
1 Comment »

Lately I was looking for a way to translate geo coordinates (latitude and longitude form my gps device) to some sort of text or names. As you know I’m trying to geotag my photos using a gps logger and PhotoTagStudio. This data can be used to visualize the place a photo was taken on a map (e.g. Google Maps or flickr!). The next step can be to use this data to describe the photo as well.

I think one should be able to translate a geo coordinate into at least the name of the county, the state and the city; maybe to the district or a street name, too. To achieve this I found the geonames.org webpage. This page collects exactly the data I need and allows searching via the website and a webservice.

The webservice itself consists of approximate 30 REST methods one can call by querying an URL. Most of these calls return a XML document (or optional a JSON document). Unfortunately  there is no SOAP / WSDL version of this webservice. For a .net and C# developer a SOAP webservice is very easy to consume but for such a REST / XML webservice you have to create the URLs yourself and parse the resulting XML document.

I started to create a library to query the webservice. This library provides a few static methods mapped to the most useable webservice-methods and returns good shaped .Net objects. These objects carry all the data coming from the webservice. At the moment this library is in an early beta status but you can use it in your own projects. It can be found on Codeplex: GeonamesDotOrgDotNet, there you will find a small example and a demo application. When using this library you should take a look at the documentation of the geonames.org webservices since the interfaces are nearly the same.

I hope this is useful for someone. I will extend the library in the next weeks. Feature requests are welcome, so is help on the coding side.

Currently the following webservice calls are supported:

  • findNearby
  • findNearbyPlaceName
  • findNearByWeather
  • findNearbyWikipedia
  • get
  • hierarchy
  • children
  • gtopo30
  • srtm3

At the end a few random screenshots and a code snippet. For more information please take a look at the Codeplex project page.

// finding some place in Berlin, Germany
// (using prefix m for decimal literals)
Geoname Place =
GeoNamesOrgWebservice.FindNearbyPlaceName(52.51m, 13.4m);

// getting all parents
IEnumerable ParentPlaces = Place.Hierarchy();

// display the partents
// (will print out something like:
//  “Globe > Europe > Germany > Land Berlin > Berlin >”)
foreach (Geoname x in ParentPlaces)
Console.Write(x.Name + ” > “);

The Classes of the Library:

classes

A screenshot of the demo application to test the library:

testapp

DirectiveProcessor for VSX

Tags: , , , ,
No Comments »

I created two DirectiveProcessor for Visual Studio to use in the T4 system. I added the classes to JaDAL hoping someone can use them in her project or use the code as an example when creating new DirectiveProcessors.

Let’s start with a short introduction to DirectiveProcessors. DirectiveProcessors are used in .tt-files to provide data to the template. The DirectiveProcessor can take parameters from the declaration in the .tt-file and adds some code to the compiled template. This code (often properties) can be used from within the template. For example the DSL Tools are generating one DirectiveProcessor for each DSL model. In a template form the DSL Tools you will see a line like the following:

<#@ Language1 processor=Language1DirectiveProcessor
requires=fileName=’Sample.mydsl1′#>

This line uses the Language1DirectiveProcessor and provides it with one parameter (fileName). The DirectiveProcessor adds code to the template to open the given file and creates (in this case) a ExampleModel-property to use in the template code.

I created two DirectiveProcessors to use the data of simple Xml-files and Visual Studio Project files in the templates. The code of the two DirectiveProcessors is very straight forward and maybe one could advance it (e.g. make it compatible with templates written in Visual Basic).

Using the XmlFileDirectiveProcessor

Add a line like the following to your .tt-file:

<#@ XmlFile processor=XmlFileDirectiveProcessorFileName=example.xml#>

Inside this template you can access the (full qualified) filename via the this.XmlFileName-Property and the Content of this file (as a XDocument) via the this.XmlFile-Property.

Using the VsProjectFileDirectiveProcessor

Add this line to your template:

<#@ ProjectFile processor=VsProjectFileDirectiveProcessorFileName=x.csproj#>

A property named this.ProjectFile will be added to the template. This property provides you with an instance of the VsProjectFile-class containing the project file contents. This class contains only very little functionality (feel free to add some more and submit it back to me!). Just take a look at the source code of this class. The method GetAllFiles() returns a string array of all files found in the project (supporting C++ and C# project files – .vcproj and .csproj).

Setup

An entry in the registry is needed to allow the T4 system to find custom DirectiveProcessors. Just add the following entries to your registry and don’t forget to point to the right location of the JaDAL.dll.

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0Exp\
Configuration\TextTemplating\DirectiveProcessors\VsProjectFileDirectiveProcessor]
“Class”=”BenjaminSchroeter.Dsl.DirectiveProcessors.VsProjectFileDirectiveProcessor”
“CodeBase”=”D:\\JaDAL\\bin\\Debug\\JaDAL.dll”

[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0Exp\
Configuration\TextTemplating\DirectiveProcessors\XmlFileDirectiveProcessor]
“Class”=”BenjaminSchroeter.Dsl.DirectiveProcessors.XmlFileDirectiveProcessor”
“CodeBase”=”D:\\JaDAL\\bin\\Debug\\JaDAL.dll”

These registry keys are for the Experimental Hive of Visual Studio. To register the DirectiveProcessors for the normal Visual Studio instance the registry key starts with HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0
\TextTemplating\DirectiveProcessors\

Tagcloud reloaded

Tags: ,
No Comments »

There was not that much going on here lately. Wolfram and I are very busy these days, but we didn’t forgot about the blog. There are many ideas for articles but to few spare time to write them. Fortunately this will become a little bit better in a few weeks.

For the meantime I build a nice tagcloud to remember you what’s usually going on her:

wordle

Produced with Wordle. Images of Wordles are licensed Creative Commons License.

Stay tuned!

Getting rid of the DSL model explorer

Tags: , , ,
3 Comments »

Every DSL you create with DSL Tools has a model explorer. This model explorer is a tool window in Visual Studio displaying the elements of your model in a hierarchical way. This is often a nice feature but sometimes a hierarchical view of your data is not appropriate. So I came to the question: How to remove the explorer from the generated code?

I could not find any option in the DSL design to remove the model explorer, but if you look at some of the .tt files you will find somewhere a query for this.Dsl.Explorer != null. For example in the package.tt file that generates the package.cs which is responsible for registering the tool window for the model explorer:

<#
    if(this.Dsl.Explorer != null)
    {
#>
    [VSShell::ProvideToolWindow(         typeof(<#= dslName #>ExplorerToolWindow),          MultiInstances = false,          Style = VSShell::VsDockStyle.Tabbed,          Orientation = VSShell::ToolWindowOrientation.Right,          Window = "{3AE79031-E1BC-11D0-8F78-00A0C9110057}")]
    [VSShell::ProvideToolWindowVisibility(         typeof(<#= dslName #>ExplorerToolWindow),          Constants.<#= dslName #>EditorFactoryId)]
<#
    }
#>

Even if I did not find any option to set the Dsl.Explorer property of the model to null (you did not see the Explorer property anywhere in the DSL diagram) it seems that the developers of the DSL Tools had this use case in mind.

To remove the Dsl.Explorer from your DSL model open the .dsl file with a text editor and go to the end. There you will find some XML tags like the following:

<Explorer ExplorerGuid="6c276297-6acd-4e9a-8740-b61ba834004b"  Title="HardwareDescription Explorer">
    <ExplorerBehaviorMoniker      Name="HardwareDescription/HardwareDescriptionExplorer" />
</Explorer>

Just delete these three lines and generate your code once again. Maybe you should reset your Experimental Hive, too.

I tested a DSL with a removed Model Explorer without any problems. It seems the developers of the DSL Tools did a very good job on the code generation templates . The generated ModelExplorer.cs file contains only a single line:

// This source file is empty because    this DSL does not define a model explorer.

That should be a good proof that a DSL can run without the model explorer even if it might be not supported by the DSL Tools. 🙂

The List<T>.ForEach() method

Tags: , ,
No Comments »

We all know and love the foreach keyword in C# and use it for loops every day:

List<int> list = new List<int>();
/* fill the list */
foreach (int i in list)
    Console.WriteLine(i);

But the generic List<T> class contains a useful method for small loops, too. The method is called ForEach() and has only one parameter: an Action<T>.

delegates: Action<>, Func<> and Predicate<>

The Framework 3.5 defines a few generic delegate types for actions and functions. In this case a function is something that returns a value (think back to your math class) and actions are something that do not return a value but do something (maybe think back to physics class). All these delegates are defined with zero, one, two, three and four parameters:

public delegate voidAction();
public delegate voidAction<T>(T obj);
public delegate voidAction<T1, T2>(T1 arg1, T2 arg2);
public delegate voidAction<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
public delegate voidAction<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);

public delegateTResult Func<TResult>();
public delegateTResult Func<T, TResult>(T arg);
public delegateTResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
public delegateTResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegateTResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);

And there is one more delegate. The Predicate<T> (philosophy class, you know). A predicate comes to a logical decision (true or false; bool return value) based on a single object:
public delegate bool Predicate<T>(T obj);

All these delegates are generic so you can use them in a type save way with the type parameters you need.

Back to the ForEach() method

As I explained above, the ForEach() method takes an Action<T> parameter. In my example this is an Action<int> delegate:

list.ForEach( delegate(int i) {Console.WriteLine(i);} );

This anonymous delegate declaration is not that nice, but we can use Lamda types here:

list.ForEach(i => Console.WriteLine(i));

But let’s take a look at the method we’re calling: void Console.WriteLine(int). That is exactly the definition of the needed Action here. So we can write the code line even shorter:

list.ForEach( Console.WriteLine );

I like this code. It is very short, elegant and readable. It says: “For each [entry of] the list: write it out”. Great.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in