My Development KB

Odds and ends related to software development

WPF – TextBox lagging performance

Posted by Ben G on August 11, 2010

I had a WPF TextBox that was showing a painful lag when typing. Tracked it down to the fact that a parent in the visual tree had a Bevel BitmapEffect applied. It wasn’t obvious to me that a BitmapEffect like that would affect the visual performance of any descendant controls, but it does. The fix for me was simple.

Instead of structuring my tree like this, with the children nested under the Border with the Bitmap effect:

<Border>
<Border.BitmapEffect>
<BevelBitmapEffect />
</Border.BitmapEffect>
<Grid>
<!--Children-->
</Grid>
</Border>

I simply changed it to this, moving the BitmapEffected element out of the ancestry of the rest of the tree:

<Grid>
<Border>
<Border.BitmapEffect>
<BevelBitmapEffect />
</Border.BitmapEffect>

</Border>
<Grid>
<!--Children-->
</Grid>
</Grid>

Now the grid that contains the children is a sibling of the BitmapEffected Border, not a descendant.

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

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 »

 
Follow

Get every new post delivered to your Inbox.