Skip to main content

Posts

Showing posts with the label WPF

Import a .pfx file at build time

For our desktop applications (WPF and even Winforms), we are still using ClickOnce . Although the technology is rather old, it still serves our needs. An important part to securely deploy our applications through ClickOnce is signing the application and the deployment manifest using a public/private key pair. During local development, you can use a PFX file and select it on the Signing tab for your project. If you build the project for the first time and you didn’t provide the PFX password yet, you get an error like this: C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(3476,5): Error MSB3326: Cannot import the following key file: . The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user’s personal certificate store. C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\Microsoft.C...

Visual Studio Extension - Convert a WPF project to .NET Core 3.0

Brian Lagunas created a nice extension that helps you to convert your existing WPF projects to .NET Core 3.0. After installing the extensions, right click on your WPF project and select the "Convert Project to .NET Core 3" option. Nice one!

WPF Debounce trick

Sometimes you have to appreciate the power and simplicity that WPF(and by extend XAML has to offer). While having to do a lot of voodoo magic with Reactive Extensions to support debouncing , in WPF it can be reduced to one binding property,  the Delay Binding Property . You can use the WPF Delay binding property to debounce binding events. For example following code will debounces the key input until nothing changes for 0.5 seconds: Text="{Binding UserName,UpdateSourceTrigger=PropertyChanged,Delay=500}" Sweet!

ReactiveList: ObservableCollection on steroids

If you ever build an MVVM style application before(using WPF, Silverlight, UWP,…) you probably used the ObservableCollection class.  It implements the INotifyCollectionChanged interface and can be seen as the counterpart of INotifyPropertyChanged. Through this interface the ObservableCollection notifies its subscribers about items being added, deleted, moved, … Unfortunately the ObservableCollection is rather limited in it’s behavior and doesn’t fit well in a truely observable architecture. Luckily the ReactiveUI framework and more specificly the ReactiveList solve exactly this problem… Let’s describe a scenario I had to build that was hard to do using ObservableCollection and a walk-in-the-park with ReactiveList: In our application we have to show a list of alerts and update the list when new alerts arrive. However alerts can arrive at a high pace and we don’t want to update the UI continuously but only when at least 5 alerts are raised. In our original implementat...

Telerik WPF controls: XAML vs NoXAML

On a WPF project we are using the WPF controls from Telerik. Inside the Telerik folder we noticed that their are actually 2 versions of the binaries available; a ‘normal’ and a NoXaml version. So what’s the difference and which one should I choose? The normal assemblies contain some components together with a default set of styles and ControlTemplates. As most assemblies contain multiple components this can start to add up, as styles and templates for every component are provided. This also means that some of these assemblies are big. To decrease the file size, a NoXaml version of the assemblies was created including only the components themselves but no xaml code(styles, brushes, controltemplates,…). However as the NoXaml version doesn’t contain any visualization information, using these alone will not make much sense. No visual output will be rendered on the screen. A NoXaml dll should therefore always be combined with a theme dll. So which one should you pick? If you are onl...

WPF–Using the XmlnsDefinitionAttribute causes issues when loading a WPF form in an Addin

Yesterday a colleague asked me for help. She was building an addin for ESRI ArcGis and she wanted to load a WPF form and show some related data. The problem was that when loading the WPF form some of the DLL’s were searched in the Addin folder but for some of the DLL’s, .NET was looking inside the bin folder of the main application. Easy solution would be to just copy over all addin assemblies to the bin folder of ArcGis. Of course this was not what we want as it removes the advantages of the whole addin concept. So the big question is; why are some DLL’s loaded from the correct location and others not? Let’s have a look at the WPF form first: In this form the services DLL was loaded correctly whereas the caliburn.micro dll(still my favorite MVVM framework ) was not. The difference is that the services DLL namespace is constructed using the clr-namespace syntax whereas the Caliburn.Micro namespace is constructed using an URL. Where does this URL come from? WPF defines a CLR ...

WPF/WinForms: Set the Windows Identity as the CurrentPrincipal

In a WPF application we created(yes, WPF is still alive and kicking), security is based on the Windows Identity people used to login on their systems. However we noticed that when we checked the current Identity through System.Threading.Thread.CurrentPrincipal.Identity , we got the following back:  {System.Security.Principal.GenericIdentity}     [System.Security.Principal.GenericIdentity]: {System.Security.Principal.GenericIdentity}     AuthenticationType: ""     IsAuthenticated: false     Name: "" To change this, we used the following line of code: AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal); After doing that, calling System.Threading.Thread.CurrentPrincipal.Identity returned : {System.Security.Principal.WindowsIdentity}     [System.Security.Principal.WindowsIdentity]: {Syst...

ReactiveUI - The base class or interface 'Splat.IEnableLogger' could not be resolved

I’m building an application where I’m experimenting with ReactiveUI , an MVVM framework built on top of the Reactive Extensions. It’s the perfect fit if your application has a lot of interactivity and data that changes a lot. When I started using it, after installing the “reactiveui” nuget package , it immediately failed with the following error message: The base class or interface 'Splat.IEnableLogger' in assembly 'Splat, Version=1.6.2.0, Culture=neutral, PublicKeyToken=null' referenced by type 'ReactiveUI.IReactiveObject' could not be resolved. It is an annoying issue in the NuGet package where ReactiveUI.Core has a dependency on a Splat version >= 1.0. according to the package configuration. The problem is that the  latest version of Reactive UI couldn’t work with older Splat versions. After updating Splat to the latest version, the issue was solved. I hope the creator of the NuGet package fixes this, as this is really annoying for everyone...

WPF Rendering Issue

A colleague mentioned that he had a strange UI error on his second monitor for a WPF application he’s working on: This looks like a WPF rendering issue. 2 possible solutions I could think of: Change the Rendering Mode using the following code snippet: RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; Disable Hardware acceleration by adding the following registry key:   HKEY_CURRENT_USER\SOFTWARE\Microsoft\Avalon.Graphics\DisableHWAcceleration, DWORD value=1 More information can be found here: https://msdn.microsoft.com/en-us/library/aa970912(v=vs.110).aspx

Learning Reactive Extensions(RX) by example: ReactiveTrader

You are interested in learning Reactive Extensions( http://rx.codeplex.com/ )? But you don’t know where to start or you don’t see a practical use case? Have a look at the ReactiveTrader application created by the guys from Adaptive. From the site: Reactive Trader is a client-server application demonstrating some of the problems needing to be dealt with when building reactive, or event driven, user interfaces. It was initially built as a demonstration application for a presentation we gave at ReactConf 2014 . What makes this example really nice is the fact that it exists for multiple platforms like HTML5, iOS, WPF,…

WPF Performance Tips

With the recent announcements about new WPF features , it’s time to re-introduce some WPF related blog posts. When browsing through the CodeProject articles, I noticed this great post about WPF performance: http://www.codeproject.com/Articles/784529/Solutions-for-WPF-Performance-Issue This is one of the most complete performance guides I’ve ever seen and certainly useful for every WPF (and even XAML) developer. Here is the list of topics covered: Basic knowledges of WPF rendering. Pixel Snapping in WPF Application WPF Visual Rendering Detect issues with WPF performance suite - Performance Profiling Tools for WPF Detect Software Render Detect Undesired Rendering Make a trade-off between graphique's quality and performance. Disable Pixel Snapping and Anti-Aliased option RenderOption UIElement.CacheMode and BitmapCache Make a trade-off between architecture and performance...

Upgrading to Caliburn.Micro 2.0

As Microsoft announced some new WPF features , I found a good excuse to do a WPF blog post . Recently I had to do some changes to an WPF application I built some time ago. While implementing the change, I noticed that a new version of Caliburn.Micro was available. I always loved Caliburn.Micro , it is still one of the best MVVM frameworks out there. Now doing this upgrade wasn’t that hard but wasn’t a walk in the park either. Here are some of the problems I encountered: Bootstrapper<T> no longer exists. Instead you have to inherit from BootstrapperBase . Inside the Bootstrapper override the OnStartup method and call the DisplayRootViewFor<> method: protected override void OnStartup(object sender, StartupEventArgs e) {            DisplayRootViewFor<IShell>();  } EventAggregator.Publish now takes an action to marshal the event. You can still use the EventAggregator.PublishOnUITh...

Caliburn.Micro: Async/Await

Caliburn.Micro always had the concept of Coroutines which allowed you to write asynchronous code in a synchronous way. Starting from .NET 4.5 with the introduction of the async and await keywords, Microsoft introduced the concept of Coroutines in the language itself. So if you want to use the same code in Caliburn.Micro with the async syntax, it becomes: More information here: http://caraulean.com/blog/2013/07/15/using-caliburn-micro-with-async-await/

DebugSettings.IsOverdrawHeatMapEnabled property

When looking at some ways to optimize the performance of my Windows Store application, I stumbled over the following property: DebugSettings.IsOverdrawHeatMapEnabled . This property helps you determine where and when an app draws objects on top of one another. It’s not uncommon to find objects being drawn that you may not have known were even in the scene.   This visualization is useful during application development for detecting layout, animation, and other operations that are graphics processing intensive. Some other useful tips can be found in the Optimize loading XAML article.

WPF ChildWindow

I always wondered what could be the use of the ChildWindow in WPF? Last week I discovered a good reason to use it. When you create a new window from inside your application, like in this example: var dialog = new MyDialog(); dialog.ShowDialog() If you press Alt-tab when the dialog is open, and you come back to the application pressing Alt-tab again, the main window will be shown but not the dialog. The reason is that the dialog has not been declared as owned by the main window. I found a solution on CodeProject mentioning to set the owner of the Dialog window to the MainWindow like this: public MyDialog() { InitializeComponent(); this.Owner = App.Current.MainWindow; } An alternative solution can be found in the Extended WPF Toolkit which contains a ChildWindow class. This class offers the same behavior without the extra code.

WPF 4.5: Airspace problem solved(...or not)

The airspace problem was one of the most annoying issues when integration a Win 32 component(like WinForms) with WPF. The problem is that each render technology belongs to only one airspace only. So when you place Win32 components in your WPF application they behave as a black hole for input leading to all kind of issues. I blogged about this issue before and even showed a possible workaround . With WPF 4.5 the issue is finally solved! To do this 2 extra properties are added to the HwndHost class(the base class for WindowsFormsHost ): IsRedirected and CompositionMode . IsRedirected: Set this property to true to solve the airspace problem. (It’s not enabled by default.) CompositionMode: Specified how deep the integration should go. It has multiple possible values: None : this is the default behavior and no integration is done: the airspace problems are still here. OutputOnly : The airspace problem are solved but the user (and the input system) can’t interact with the hosted ...

Caliburn.Micro: Design time support

WPF and Caliburn.Micro are a powerful combination. You create a viewmodel and related view, name your controls appropriately  and all magic happens automatically. Controls are bound to the View Model’s properties and methods for you. The problem is that it is all happing at run time not at design time. So when you are developing inside Visual Studio or Expression Blend you aren’t able to see how the form will look like with bound data. Caliburn.Micro supports design-time binding out-of-the-box. How can we configure this? In the constructor of my ViewModel, I check if we are executing in design time: public class SampleViewModel : Screen { public SampleViewModel() { if (Execute.InDesignMode) LoadDesignData(); } } In this sample I populate my ViewModel with some sample data at design time. private void LoadDesignData() { this.Sessions.Add(new ProfilerSessionViewModel() { Id = Guid.NewGuid(), Duration = "30ms", Name = "Session 1", Started = Dat...

Caliburn Micro: configuring the Window dialog

Caliburn Micro offers you the WindowManager to display a dialog. You only have to specify the viewmodel and Caliburn will do the rest, it finds the corresponding usercontrol, embeds this usercontrol into a window, binds view and viewmodel together and shows the result to the user. var loginViewModel = new LoginViewModel();  WindowManager windowManager = new WindowManager(); SettingsViewModel vm=new SettingsViewModel(); windowManager.ShowDialog(vm); But what if you want to change the behavior or the look of this window? As Caliburn.Micro creates this window for you, you don’t have direct control over it. Therefore the WindowManager.ShowDialog method has an extra overload which allows you to specify a settings object (as a Dictionary<string,object>). How can we use this? An example… dynamic settings = new ExpandoObject(); settings.WindowStyle = WindowStyle.ToolWindow; settings.ShowInTaskbar = true; settings.Title = "This is a custom title"; ...

Caliburn.Micro: Using a local resource as a proxy to your viewmodel

For a project we are doing we are using the ArcGis WPF components. As we want to use a MVVM architecture we try to use databind wherever possible(by using Caliburn.Micro). The problem is that one of the WPF components (the GpsLayer) inherits from DependencyObject, but the DependencyObject is not linked to a DataContext. Microsoft states that the DO should inherit the DataContext from the containing FrameworkElement, but that in fact doesn't happen. The only samples we found that worked were using the StaticResource approach: <Window.Resources> <local:MainViewModel x:Key="MainViewModel" /> </Window.Resources> <Grid DataContext="{StaticResource MainViewModel}"> <esri:Map Extent="-14268281.1311858,2195120.17402859,-7232639.54776086,7467160.93387503"> <esri:ArcGISTiledMapServiceLayer Url="http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer" /> <esri:GraphicsL...

WPF: Referring to a resource dictionary in another assembly

For a client I created a re-usable set of resource dictionary files. So I embedded them in a separate assembly that can be referenced in other WPF projects. But I always forget the correct syntax to refer to these resource files. So just as a reminder to myself: <ResourceDictionary Source="pack://application:,,,/YourSharedAssembly;component/Subfolder/YourSharedResourceFile.xaml"/>