My Development KB

Odds and ends related to software development

System.BadImageFormatException when mixing x86 and AnyCPU projects

Posted by Ben G on January 7, 2010

System.BadImageFormatException: Could not load file or assembly ‘MyAssembly, Version=3.0.3658.19308, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

Cause: occurs when you are referencing a DLL or project with its target platform set to x86 from a project set to AnyCPU or x64.

Posted in .NET | Leave a Comment »

12+ hours “Installing update n of n” on Windows Vista 64-bit

Posted by Ben G on January 6, 2010

Yesterday I needed to reboot my system. I saw that it had updates waiting to install, so I chose the “Install updates and shut down” option. It reached the “Installing update 1 of 9… Do not power off or restart your computer” stage, and then just sat there. Stuck for hours. There was pretty frequent hard-drive activity.

I was afraid to power down the system, as I’ve read of it corrupting the OS and requiring a complete reinstall, so just left it. After about 12 hours, it apparently finished the updates and shut down all the way. It then booted fine with no errors.

So, it appears that sometimes those updates can take an obscenely long time. When in doubt, better to give it a while than to force a reboot.

Posted in Vista | Tagged: , , , , , | Leave a Comment »

Silverlight: System.ArgumentException with DataGridTemplateColumns and UserControls with x:Name

Posted by Ben G on November 4, 2009

I had a UserControl that specified an x:Name value like this:

<UserControl x:Class="CatManagement.UI.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" x:Name="Me">

I assigned an x:Name because I was wanting to bind certain UI elements to custom properties defined on my user control. However, this caused a problem when I used this user control in a DataGridTemplateColumn like this:

<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<local:AssignUserControl DataContext="{Binding}" />
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>

The problem was that the following exception was thrown whenever a second DataGrid row was inserted:

 

System.ArgumentException was unhandled by user code
Message=”Value does not fall within the expected range.”
StackTrace:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.UIElement_Measure(UIElement element, Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.Controls.DataGrid.InsertDisplayedElement(Int32 slot, UIElement element, Boolean wasNewlyAdded, Boolean updateSlotInformation) ….
[snip]
The problem was the x:Name specified on my usercontrol. Apparently, that resulted in multiple items in the same visual tree sharing the same x:Name value. Removing that attribute solved the problem.

 

Posted in .NET, SilverLight | Leave a Comment »

Controlling .NET System.Net Tracing via the Registry

Posted by Ben G on June 29, 2009

We have a Click Once-deployed project that I wanted to set up for instrumentation and tracing. Because the project deploys to a rather obscure folder defined by Click Once, it makes it a very difficult thing to have our support personnel troubleshoot issues in the field by applying a modified app.config file that enables tracing.

I set up our internal trace sources programmatically to read the switch value from the registry, which worked fine. However, when it came to configuring the System.Net trace sources, I ran into problems. After a lot of searching it appears impossible to gain access to those system trace sources without using some shady reflection techniques which I’m not comfortable with in a production environment. Without access to those TraceSource objects, it is impossible to programmitically add my own switches and listeners.

My eventual solution was to configure the System.Net trace sources in the app.config file, but use a custom switch that reads its value from the registry. It took me a bit to figure out how to do this, so I’m reposting it here:

My custom switch looks like this:


Public Class RegistrySwitch
    Inherits SourceSwitch

    Public Sub New(ByVal name As String)
        MyBase.New(name)
        Me.Value = GetSwitchValue()
    End Sub

    Public Sub New(ByVal name As StringByVal value As String)
        MyBase.New(name)
        Me.Value = GetSwitchValue()
    End Sub

    Private Shared Function GetSwitchValue()
        Dim switchValue As String = GetRegistryValue("TracingLevel""Off")

        Select Case switchValue
            Case "True""1""-1""On"
                switchValue = "All"
            Case "0""False"
                switchValue = "Off"
        End Select

        Return switchValue
    End Function

End
 Class

The GetRegistryValue function (code not shown) simply reads the specified value from our product’s key in the registry.

Then my app.config file looks like this:
  <system.diagnostics>
    <
trace autoflush="true" />
    <
sources>
      <
source name="System.Net" tracemode="includehex" maxdatasize="1024" switchName="NetworkSwitch" switchType="MyProject.RegistrySwitch, MyProject">
        <
listeners>
          <
add name="System.Net"/>
        </
listeners>
      </
source>
      <
source name="System.Net.Sockets" switchName="NetworkSwitch"  switchType="MyProject.RegistrySwitch, MyProject">
        <
listeners>
          <
add name="System.Net"/>
        </
listeners>
      </
source>
      <
source name="System.Net.Cache" switchName="NetworkSwitch"  switchType="MyProject.RegistrySwitch, MyProject">
        <
listeners>
          <
add name="System.Net"/>
        </
listeners>
      </
source>
    </
sources>
    <
switches>
      <
add name="NetworkSwitch"  value="Off"/>
    </switches>
    <
sharedListeners>
      <
add name="System.Net" type="MyProject.MyTextWriterTraceListener, MyProject" initializeData="network.log" />
    </
sharedListeners>
  </
system.diagnostics>

Notice that I had to define the CLR type of my switch not in the <Switches> node where the switch is named, but in the switchType parameter on each <Source> that references the switch.  Also note that even though the Value of the switch is set to Off in this configuration file, that value is overwritten when my RegistrySwitch subclass initializes with the value from the registry.

Also note that in this example, my listener is a custom type. It is a TextWriterTraceListener that places the log file in a valid user data path.

Posted in .NET | Tagged: , , , , , , | Leave a Comment »

Unable to launch ClickOnce .application from SilverLight 2

Posted by Ben G on June 23, 2009

Ran into a problem. The following SilverLight code works to launch a URL, but fails when launchign a .application ClickOnce URL:

HtmlPage.Window.Navigate(uri)

It is caused by security settings preventing the launching of unsafe content from code as opposed to a user-initiated action. I guess that is why the HyperlinkButton control works just fine with a .application URL in its NavigateUri property.

To get around this, I subclassed the HyperlinkButton class as shown below:

 Public Class MyHyperlinkButton
    Inherits HyperlinkButton

    Public Sub NavigateTo(ByVal url As String)
        Me.NavigateUri = New Uri(url)
        Me.OnClick()
    End Sub
End
 Class

The NavigateTo method has access to the protected OnClick method of the HyperlinkButton that initiates the navigation. This navigate takes place through a security path different from HtmlPage.Window.Navigate().

I created an invisble instance of MyHyperlinkButton on my Silverlight page.  Then from anywhere in my Silverlight code-behind, I can call the NavigateTo(url) method on the invisble hyperlink control to successfully launch the ClickOnce application.

Whether I’m exploiting an unknown security hole here or not, I do not know. It is possible that Microsoft may deem this a security risk and close this work around. In the mean time, for SL2, it works.

Posted in SilverLight | Tagged: , , , , | 2 Comments »

IIS7 + WCF service: 405 method not allowed

Posted by Ben G on June 11, 2009

Recently moved a site from IIS 6 to IIS7 and all of a sudden all WCF services stopped working. A quick sniff showed they were returning 405 “method not allowed” or “invalid verb”. A search on google turned up the following page which solved the problem. Turns out the WCF SVC handlers weren’t mapped.

http://dotnetdreamer.com/2009/03/21/azure-services-method-not-allowed-405/

Posted in Uncategorized | Tagged: , , , , | Leave a Comment »

Still a chance to get Xceed’s WPF datagrid free

Posted by Ben G on May 26, 2009

Xceed is moving their free Express datagrid for WPF to a commercial Standard version. However, there are a few days (19) left to register for the Express version and get a free license to the Standard version, or a $300 voucher to be applied to other versions. If you might have need of Xceed’s controls in the future, it’s worth doing now: http://xceed.com/freegrid

Posted in Uncategorized | Leave a Comment »

SilverLight Error: “could not download the silverlight application”

Posted by Ben G on April 28, 2009

This error occured when first trying to access my silverlight application on the web server:

“InitializeError error 2104: could not download the silverlight application, check web server settings”

 

A brief search online showed the solution:

In IIS On the Web Server

1) Go to Site Properties -> HTTP Headers

2) Click MIME Types

3) Click New

4) Fill the follow fields:
    Extension: .xap
    MIME type: application/x-silverlight-app

That solved the problem for me.

Posted in SilverLight | Tagged: , , , | Leave a Comment »

MethodCaller V2: Multiple Method Calls

Posted by Ben G on February 16, 2009

In my last post, I introduced a solution that I put together for invoking UI code in response to ViewModel changes or events. Please read that post for a full explanation. After using the code a bit, I found the need to easily specify multiple methods to be invoked in response to a single ViewModel change. I extended the framework adding a couple new attached collection properties that allow me to specify multiple method calls, as well as a little clean-up to simplify the framework.

Here is a summary of my changes:

Losing the MethodCaller.OnEventMethodCall property

I realized that since the OnEventMethodCall object derives from MethodCall, there’s no reason to have a separate attached property for specifying an OnEventMethodCall. So I dropped the MethodCaller.OnEventMethodCall attached property. The MethodCaller.MethodCall property should be used instead:

        <mc:MethodCaller.MethodCall>
            <mc:OnEventMethodCall EventName="Click" MethodName="SelectPerson">
                <mc:MethodCall.Arguments>
                    <mc:MethodArgument Value="{Binding}" />
                </mc:MethodCall.Arguments>
            </mc:OnEventMethodCall>
        </mc:MethodCaller.MethodCall>

This makes it cleaner, and also I can create further MethodCall subclasses down the road if needed and use the same attached property to set them up.

Multiple MethodCalls in a trigger

I added a new attached property called MethodCaller.SetMethodCalls that takes in a MethodCallCollection object. This allows me to specify any number of MethodCall objects to be invoked when the trigger fires:

         <Setter TargetName="uxRow" Property="mc:MethodCaller.SetMethodCalls">
            <Setter.Value>
                <mc:MethodCallCollection>
                    <mc:MethodCall MethodName="Focus" Target="{Binding ElementName=uxText}"  />
                    <mc:MethodCall MethodName="BringIntoView" />                                
                
</mc:MethodCallCollection>
            </Setter.Value>
        </Setter>

Additionally, this MethodCaller.SetMethodCalls attached property would be used to specify MethodCall’s (or OnEventMethodCall’s) via a <Style>. Basically, anywhere you use a <Setter> to set the property. You’ll notice in the snippet above, that we’re passing in a new <MethodCallCollection> object. The SetMethodCalls property has no default value, so when setting it you must pass in a new MethodCallCollection.

Wiring multiple events on the same object

The last change is almost identical to the one I just mentioned. I added another attached property called MethodCaller.MethodCalls that exposes a MethodCallCollection object. The difference between this property and the SetMethodCalls property described above is that this collection is already initialized and instantiated, so you can just add to it without creating a new MethodCallCollection object:

        <mc:MethodCaller.MethodCalls>
            <mc:OnEventMethodCall EventName="Click" MethodName="SelectPerson">
                <mc:MethodCall.Arguments>
                    <mc:MethodArgument Value="{Binding}" />
                </mc:MethodCall.Arguments>
            </mc:OnEventMethodCall>
            <mc:OnEventMethodCall EventName="MouseLeftButtonUp" MethodName="Focus" />
        </mc:MethodCaller.MethodCalls>

(Note: creating a read-only attached property of type collection can be tricky because you need to initialize the collection, but unless you do some special setup, the Getter is not called upon first access like you might expect. And setting a default value via the Attached Property’s Default Value mechanism doesn’t work either, because the value you specified is a shared value and not unique to the instance of the dependency property. See Bill Kempf’s post and John Gossman’s post for more information and explanation of the why’s and how’s.)

Summary

In working with the MethodCaller framework, I found these changes to be useful, so I wanted to post them. The latest code can be downloaded here. I may make another post in the future walking through some of the actual code behind this solution in case anyone is interested.

Thanks for reading!

—Benjamin

Posted in M-V-VM, WPF | Tagged: , , , , , , | Leave a Comment »

MethodCaller: Invoking Methods between the View and the ViewModel

Posted by Ben G on February 14, 2009

(Note: since this post, I have posted a Version 2 of the MethodCaller solution. Click here for a description of the changes and the latest source code.)

The Problem

I’ve become a huge fan of the MVVM pattern for development with WPF. I’m definitely still learning the finer points of this pattern. I’ve been using it now in my private projects for some time now and one thing that I have bumped up against in several places is the issue of how to trigger View/UI code based on ViewModel events or changes. This becomes especially important as I try to really tweak the user experience so that the movement through the application is very fluid.

Of course, databinding makes it a cinch to bind View and ViewModel properties together. And that covers the vast portion of issues related to reflecting VM changes in the View. But there seem to be some cases where some code in the View or UI needs to be executed based on ViewModel changes. Take the following example:

Let’s say I have an ItemsControl housed in a ScrollView bound to a PersonsViewModel that exposes a BindingList of PersonViewModel’s. The PersonViewModel exposes an IsSelected property that the View’s DataTemplate uses to visually indicate the item’s selected state like this:

        <DataTemplate DataType="{x:Type local:PersonViewModel}">
            <Label x:Name="uxRow" Content="{Binding Name}"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding IsSelected}" Value="True">
                    <Setter TargetName="uxRow" Property="Background" Value="LightBlue" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>

Now, if the underlying PersonViewModel can become selected in some way other than the user clicking on the item in the ItemsControl, there is a good chance that the item may currently be outside the ScrollViewer’s viewing area. So somehow we need to call BringIntoView() on the Label to cause the ScrollView to scroll to the selected item.

The big question is, how? Being as we’re talking about items generated at run-time and we’re dealing item containers that may or may not even be created yet, it’s a bit of a problem to somehow link up the ViewModel “event” of an item becoming selected to a UI method on a specific UI container like Label.BringIntoView().

I did quite a bit of searching and was unable to find any solutions to this problem. In fact, I was unable to find even any mentions of this problem on the web, so that left me wondering if I was doing something fundamentally wrong in the structure of my application and the fact that I was running into this problem at all was a warning flag signalling poor design. (If someone out there has some input on this question, please speak up!)

However, any way I looked at it, it seems like for a really polished UX there are cases where some UI code needs to be executed based on changes at the VM level where simple property-to-property bindings don’t solve the problem.

The Proposed Solution

After some hacking about, I created a solution using attached behaviors that seems to work quite well for my purposes. I must credit Mike Hillberg and his MethodCommand solution and Marlon Grech and his Attached Command Behaviors solution for guidance and inspiration as I waded into this.

So using the same example given above, here’s what the XAML implementing my solution looks like:

        <DataTemplate DataType="{x:Type local:PersonViewModel}">
            <Label x:Name="uxRow" Content="{Binding Name}"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding IsSelected}" Value="True">
                    <Setter TargetName="uxRow" Property="Background" Value="LightBlue" />
                    <Setter TargetName="uxRow" Property="mc:MethodCaller.MethodName" Value="BringIntoView" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>

Notice the second <Setter>. When IsSelected becomes true on the underlying PersonViewModel, the string “BringIntoView” is sent to the MethodCaller.MethodName attached property. That custom property invokes the specified method name on the underlying Dependency Object, which is the Label. That’s pretty simple and painless.

So, this is fine and dandy, but what if the method I need to call requires some arguments? Well, that requires a slightly more advanced solution, but it’s not that difficult. Here’s what that solution looks like:

        <Setter Property="mc:MethodCaller.MethodCall">
            <Setter.Value>
                <mc:MethodCall MethodName="SomeMethod">
                    <mc:MethodCall.Arguments>
                        <mc:MethodArgument Value="Some argument" />
                        <mc:MethodArgument>
                            <clr:Int32>100</clr:Int32>
                        </mc:MethodArgument>
                        <mc:MethodArgument Value="{Binding PropertyName}" />
                    </mc:MethodCall.Arguments>
                </mc:MethodCall>
            </Setter.Value>
        </Setter>

So here we’re using a different attached property, MethodCaller.MethodCall, which takes an object called MethodCall. This object contains the MethodName and a collection of Arguments to pass to the invoked method. Additionally, it also has a Target property (not shown above) that allows you to specify the object on which to invoke the method if it something other than the dependency object on which the setter is acting. Both the Target property and the MethodArgument.Value property support data binding.

There is one more extension to this functionality that I’ve created that comes in handy: the ability to execute a method in response to an Event, instead of in response to a property change as shown above in the DataTrigger. Here is an example of what that solution looks like:

         <Label Focusable="True"  x:Name="uxRow" Content="{Binding Name}">
            <mc:MethodCaller.OnEventMethodCall>
                <mc:OnEventMethodCall EventName="Selected" MethodName="BringIntoView" 
                                      EventSource="{Binding}" />
            </mc:MethodCaller.OnEventMethodCall>
        </Label>

You can see here, we’re using a third attached property, MethodCaller.OnEventMethodCall, that takes an OnEventMethodCall object. The OnEventMethodCall object is a subclass of MethodCall and adds two new properties: EventName and EventSource (which also supports binding). The OnEventMethodCall object adds a handler to the specified event on the event source (which defaults to the underlying dependency object) and when the event fires, it invokes the specified method.

So in the XAML above, we’re subscribing to the Selected event on the underlying data context (a PersonViewModel referenced by {Binding}). When that event fires, we’re executing the BringIntoView method on the Label. This accomplishes the same goal as the example above that uses the DataTrigger method to listen for a change in IsSelected.

Additionally, this event handling solution can work the other way: it can handle a UI event and invoke a ViewModel method, as in the example below:

    <TextBox x:Name=”uxText”>
        <mc:MethodCaller.OnEventMethodCall>
            <mc:OnEventMethodCall EventName=”TextChanged” Target=”{Binding}” MethodName=”FindPerson”>
                <mc:MethodCall.Arguments>
                    <mc:MethodArgument Value=”{Binding Text, ElementName=uxText}” />
                </mc:MethodCall.Arguments>
            </mc:OnEventMethodCall>
        </mc:MethodCaller.OnEventMethodCall>
    </TextBox>

In the example XAML above, when the TextChanged event fires on the TextBox, the FindPerson method is called on the underlying data object (in this case, the PersonsViewModel) and the TextBox.Text is passed in as an argument.

Known Issues

One limitation to the present solution is that only one MethodCaller.OnEventMethodCall property can be set per Dependency Object. So that limits you from being able to set up event handlers on multiple events for the same object. This is something that I plan on solving by exposing an attached property that takes a collection of OnEventMethodCall objects. (Version 2 of the solution adds support for multiple events.)

Also, OnEventMethodCall can only handle events that follow the standard signature of EventName(ByVal sender As Object, ByVal e As EventArgs). (The e parameter can be any subclass of EventArgs, of course.)

There are some areas of the attached behavior where we just silently bail if some of the require information is missing (MethodName for example). To be maximally helpful, we should probably throw exceptions in those places to help the developer spot the problem quicker. I may sharpen this area up in a future update.

Source Code and Demo

(Note: since this post, I have posted a Version 2 of the MethodCaller solution. Click here for a description of the changes and the latest source code.)

You can download the source code for the support attached properties and objects, as well as a demo application here.

The demo app demonstrates the following scenarios:

  • Invoking a UI method call via DataTrigger
    • PersonViewModel.IsSelected -> Label.BringIntoView()
  • Invoking a VM method based on a UI event
    • Label.MouseLeftButtonDown -> PersonsViewModel.SelectPerson()
    • TextBox.TextChanged -> PersonsViewModel.FindPerson()
  • Invoking a View method based on a VM event
    • PersonsViewModel.FoundPerson -> Window.FoundPerson()

Summary

Feel free to use this code, but use at your own risk. It has not been tested extensively and I’m sure it has some bugs here or there that will come up as different scenarios are used.

Please post any comments, thoughts, criticisms, suggestions, or insight. I’m eager to learn all I can.

—Benjamin

Posted in M-V-VM, WPF | Tagged: , , , , , | Leave a Comment »