Posts

Get a Visual Studio 2010 .NET Setup Project to Update a Previous Installation

Here is a good post about getting an Visual Studion Setup project to generate a .msi that will update a previous installation rather than demanding that the existing install be uninstalled before it can be reinstalled:

 

http://www.simple-talk.com/dotnet/visual-studio/updates-to-setup-projects

 

I followed the steps in the ‘How to update your product’ section.

 

The only catch is that the setup project will only update files that have had their version number changed even if the files them selves _have_ changed. To ensure that all files are included in the installation package, I had to make sure that all of the projects in my solution changed their version numbers on each build, to do this I edited each project’s AssemblyInfo.cs file and replaced:

 

with:

This causes a new version to be generated on each build and forces the set-up project to include them in the installation package!

 

.NET, WPF – BitmapImage File Locking

Q: How can I stop BitmapImage, in .NET Windows Presentation Foundation (WPF) from locking the source image file?

 

A: By default BitmapInfo seems to lock the source image file so that you can use the bitmapinfo object and modify or delete the source file at the same (or similar) time. For example, this C# will probably yield a locked image file:

 


var bitmap = new BitmapImage(new Uri(imageFilePath));
// use bitmap...

 

You can get around this locking problem as follows, it’s a little bit more long-winded but it worked for us….

 


var bitmap = new BitmapImage();
var stream = File.OpenRead(imageFilePath);
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
stream.Close();
stream.Dispose();
// Use bitmap.....

 

Example of Calling Dispatcher Directly from non-UI code in .NET WPF

.NET’s Threading module isn’t the best, it has the look of a model that was designed by the type of software people who like to keep practical multi-threading a good long arm’s length away. It’s workable but sometimes it requires that you jump through hoops to do simple everyday things with threads – like updating a UI element from a non UI thread etc. You may see errors akin to the following:

“Must create DependencySource on same Thread as the DependencyObject.”

“This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.”

To get around this all a .NET developer needs to do is to remember a few ritualistic looking invocations to appease the .NET small gods – but of course I can never remember the details so am recording one such here:

To dispatch to the UI from a non-UI thread and non-UI code, use something like the following:

.NET WPF, Set Bitmap – Must create DependencySource on same Thread as the DependencyObject error

In WPF when you try to assign a bitmap to a property that’s bound to a UI element from a worker thread you may get the following error:

 

“Must create DependencySource on same Thread as the DependencyObject”

 

A simple way around this problem without having to jump through hoops and dispatch to the UI thread is to just freeze the bitmap before assigning it, like this:

 


var bitmap = new BitmapImage(new Uri(CurrentImageFilePath));
bitmap.Freeze();
this.CurrentImage = bitmap;

 

I hope this helps someone who’s stuck with this annoying error!

 

Using OpenCV from .NET C++/CLI

I am happy to report that I have had a reasonably easy run of using OpenCV from a .NET C++/CLI project, I was initially worried that the two might not play well together, but so far – so good! I am wrapping some machine vision code that uses OpenCV in a C++/CLI assembly so that I can call it from C# code. I have kept the rather creepy CLI stuff to a minimum it just implements the interface, everything else is vanilla C++ using the standard library.

 

The only thing I had to do to get rid of build errors was to make sure that each _proper_ C++ file in the project had the following value for the ‘Common Language RunTime Support’ build setting -> ‘No Common Language RunTime Support’!

 

So if you are toying with the idea of developing some OpenCV based software from within C++/CLI, I say give it twirl it makes interacting with .NET much easier than (say) using COM or similar!

 

Breakpoints Not Working / .NET C++/CLI

I was having some trouble getting Visual Studio 2010 to stop at breakpoints in some unmanaged C++ code that’s in a C++/CLI project that I am working on, and as we all know Software Developments rapidly stops being fun if your debugger is broken!

I am using C++/CLI as a thin wrapper around this vanilla C++ functionality so that I could export it to .NET. All was working fine except that the breakpoints in the C++ code did not work. After some searching I found this post:

http://rhnatiuk.wordpress.com/2010/11/13/managednative-debugging-in-cc

The post suggested that I should set the ‘Enable unmanaged code Debugging’ setting of the start-up project (not the C++/CLI project), so I enabled it and the brakepoints started working fine – so big thanks Roman for the tip!

Microsoft C# Coding Style Guidelines & Visual Studio

These days most software developers need deal with more than one software development technology and programming language on a day to day basis. This often means that they have to switch back and forth between coding styles, with this in mind I noticed that although the MS coding guidelines for C# in .NET recommend K&R style braces for code blocks, e.g:

 


if (sneeze) {
  nose.Blow();
}

 

By default Visual Studio’s auto code formatting stuff will format your code with braces on newlines, e.g.:

 


if (sneeze)
{
  nose.Blow();
}

 

Very interesting indeed, I wonder are there internal coding style conflicts within Microsoft…

.NET Convert.ToDecimal() and Scientific Notation

I ran into a problem the other day with .NET’s Convert.ToDecimal() , it turns out that it doesn’t handle scientific Notation! Pass it something like “8E-5” and the poor thing just throws an exception…

 

The software in which the problem surfaced was developed as a web application that must deal with numbers read from an Excel chart and so the formats encountered are many and varied!

 

This post points out that you can use this instead:

 


Decimal.Parse(val, System.Globalization.NumberStyles.AllowExponent);

 

But just to be safe I am now using:

 


Decimal.Parse(val, System.Globalization.NumberStyles.Any);

 

And it does work for Exponents, hopefully along with everything else!

.NET Remoting Events & Multihomed Host

I was on-site with a client at a pharamacutical production facility last week and they they showed me a strange problem that they were having with .NET Remoting running on a sub-network configured with a multihomed host that sits on both the sub-net and the factory ethernet.

 

The sub-network consisted of 11 Machine Vision inspection station PCs that happily inspect product on the production line and report their results and status asynchronously to a single ‘dashboard’ system running on the multi-homed host. We had developed the inspection stations with vanilla C++ and the ‘dashboard’ system in C# .NET, they all communicate via .NET Remoting.

 

The dashboard system connects to each of the inspection stations in turn and passes a remoting object of a shared interface, the inspection stations raise events across the sub-net by calling back on this shared interface.

 

All was well with tonnes of nice events being raised and received, until one day they all just stopped! The client was sure that nothing could have changed to cause this as the whole system was under qualification and therefore everything (software/configuration etc.) must stay static. However on further investigation it turned out that the dashboard PC had recently been added to the factory ethernet – and sure enough, once the factory network was whipped out and the dashboard restarted the events came flooding back!

 

Anyway it seems that when the dashboard system was connected to the factory network it communicated to the inspection stations using its factory NIC identity and IP address.  When the stations tried to callback they used this factory IP address and the callback events were lost as the PC knew of no  way to route the traffic onto the factory network (and hence back to the dashboard system).  On further investigation we found that the inspection station PCs (which were given static IP addresses) did not have a default gateway configured so we configured the dashboard’s local IP address as the gateway for each and the problem was solved!  This change ment that any network traffic destined for any network other than the local sub-net would be automatically sent to the dashboard system.

So, to cut a long and boring story short, if you’re having .NET remoting callback problems with a multihomed host take a look at the network configuration and make sure that t he PCs that raise the events are able to route them back to the receiver PC no matter which network it initially calls on..

Dual Personality Properties with Lambdas in .NET

Some time ago (!) I wrote about an investigation that I had carried out into how a literal value could be mapped to and stored as a lambda expression/delegate in C#.  This was important for me at the time because I needed to find some way to have a ‘value’ and a ‘value rule’ appear the same to callers.  I wanted to define a type whose value when queried could either come from the evaluation of a previously specified ‘rule’ or could simply be retrieved from a real, previously stored value – without the caller knowing the difference at all.

 

This type of concept is common in functional and logic programming languages – in these languages the separation between functionality (code) and data is very blurry, what is data one minute can become code the next, and visa verse.  It is harder to achieve (at a high level) in procedural languages but the addition of lambda expressions in .NET 3.0 brings us a a lot closer (in .NET 3.0)!

 

The following might help to demonstrate how such a type might work, imagine a generic class called DualProp whose job is to yield a typed value when requested, this value could have been previously stored as a real value or could be obtaind by evaluating a previously specified lambda expression:

 

 

Two properties are defined, an integer property called ‘speed’ and a bool property called ‘visible’.  Visible’s value depends on the evaluation of the delegate compiled from the lambda expression that was assigned to it:

So when queried, visible’s value is ‘true’ if speed’s current value is greater than 5.

This scheme should allow us to build up whole sets of properties some of whose values are real and others whose are dynamically computed based on the values of others.  The values on which the lambda expressions depend can themselves be real or computed.

 

This type of set-up could be very handy, especially when used as part of a data driven user interface.  A data driven user interface is typically laid out and behaves in accordance with some specified meta-data, this meta-data is usually static (no meta-rules, just meta-data!).  Employing a scheme such as this should allow us to specify meta-data which can be dynamic, in that some of the meta-data can dynamically change based on applying ‘rules’ to some of the real data.

 

Imagine a CAD/CAM system for a laser drilling machine, it will have various logical tools defined that represent the different laser cutting tools onm the laser cutting machine. The laser tool’s various parameters can be viewed and changed on the CAD/CAM interface via a data driven property-page type interface. As usual the meta-data for this interface will specify a list of parameters along with some other data like:

 

  • Name – Attribute’s Name
  • Type – Attribute’s Type (Number/Boolean/String etc.)
  • Visibility – Is this Attribute visible for editing
  • ReadOnly – Can the attribute’s value be changed?
  • Min – Attribute’s Minimum allowed value
  • Max – Attribute’s Maximum allowed value
  • HelpString – Some help text for the attribute

 

Rule based properties should allow us to do things like set the min & max values based on another parameter’s value or force a parameter to be read-only based on the value of yet another parameter (by specifying a rule for the visibility attribute).  Anyway, I hope to expand on this in a future post.

 

Meanwhile, Here is the code for the DualProp class: