Enable Software Rendering in WPF programmatically

From my previous post, I talked about troubleshooting WPF graphic issues. One of those options is to set a registry key to enable software rendering for WPF on that machine only. But that can be an intrusive setting and may not suit everyone’s needs.

There is a another option, which is to enable software rendering in code. If you are working on .NET 3.5 framework, there’s a way to set that up..unfortunately you have to set that up per window or per target control. But might be useful for those that want to selectively tweak rendering mode for each window.

private void ConfigureSoftwareRendering()
{
    if (shouldEnableSoftwareRendering)
    {
        HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
        HwndTarget hwndTarget = hwndSource.CompositionTarget;
        hwndTarget.RenderMode = RenderMode.SoftwarewareOnly;
    }
}

If you’re developing in .NET 4 framework, then you have another option, which is to set up software rendering per process….like so.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
         if (shouldEnableSoftwareRendering)
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
    }
}

You might be wondering why we should use software rendering for WPF applications. It depends on the end-user hardware configuration which might have “WPF-unfriendly” drivers, or just no graphics card. In some situations software rendering might be faster than hardware rendering … hope this helps.

Share this post :
Posted in WPF. 1 Comment »

Graphic issues with WPF

Graphic issues with WPF are not uncommon at all. This may be partially due to graphic card drivers having varying effects with hardware rendering on WPF applications . The same application may look different on PCs with different hardware specifications. In our situation, we had an image rendering with jagged lines on a couple of PCs, and looked fine on others.

In order to troubleshoot if it’s a hardware problem, or your code, I find that the simplest approach is to first disable hardware rendering on your machine, by modifying a registry key. That registry key might not be on your machine, so add it if it isn’t.  By default if that key is absent, WPF assumes hardware rendering should be enabled.

After you reboot, and the graphic problem has disappeared because your PC is now using software rendering, you know for sure that your code is fine. Next you will have to update your graphics card driver, computer bios, and make sure you have at least .NET Framework 3.5 SP1 installed.

Here’s a link for Guidelines for troubleshooting graphic issues on WPF. It’s quite useful, and covers what I discussed above. Give this a go, it has helped identified our graphics problem very swiftly.

Posted in WPF. 1 Comment »

Declarative state of mind

Over the years, we have seen C# language evolve into a more dynamic language, and also have seen numerous frameworks and APIs out there implementing a more declarative style. Famous example would be LINQ, and one can appreciate how the language flows and how readable it is. For too many years we have programmed in a procedural manner, and we have forgotten who the target audience for our code is…..yes the audience is us, the programmers!!!!

Procedural code can be hard to read, which makes code hard to maintain. To be declarative is to write code in a way that declares your intention fluidly using fluent interfaces. I’ve come up with an example that illustrates this.

Read the rest of this entry »

Posted in C#. Tags: . Leave a Comment »

Parallel MSBuild

Did you know MSBuild can now run your build using all the cores on your proccessor? So if your development machine has multi-cores, and your solution is fairly large (perhaps more than 15 projects, but it varies), and you’re developing in .NET Framework 3.5 or higher, you should give parallel builds a go, and see if there’s any savings in compile time.

Scott Hanselman has 2 great articles on this. He explains how to incorporate parallel builds into Visual Studio, and also talks about how to run parallel build in your build process and scripts.

Take note that it’s not a guarantee that it is always going to make your solution build faster, it also depends on your machine specifications as well as how your project dependency structure. If that structures is linear rather than a tree structure, there would not be much benefit running parallel builds. Also take care about how your project references are used, because running parallel build might cause some unexpected locking problems.

On a more positive note, I’m working on a solution with around 57 projects, and using an 8 core PC. Running parallel build, it shaved off 25 seconds off the usual 2 minutes build. For argument’s sake, if I build my solution say 50 times a time (which is a very optimistic value in my opinion),  I save about  20 minutes a day from compiling (assuming you have an 8 hour work day). That’s a big savings, and that benefit grows over the weeks and months for every developer on your team. Don’t forget your build scripts and automated builds too!

ResourceDictionary: Use with care

Seems like WPF is plagued with memory leaks and problems, if not handled with care. Resource dictionary is another potential pain point, the current project I’m working on is one such victim.

Consider an UserControl that references a ResourceDictionary in it’s MergedDictionaries. Consider that the referenced ResourceDictionary references other ResourceDictionaries, and so on. Now consider that you render 30 of these user controls on a window, each user control creates a unique instance of the same ResourceDictionary, plus much more. Now you suddenly have heaps of memory being allocated, unnecessary memory for that matter. Apparently this occurs in .NET 3.5 only, not 4.0.

Read the rest of this entry »

WPF DynamicResource memory leak

After some troubleshooting on WPF memory leaks, I came across a memory leak that occurs when using DynamicResource on resource keys declared in Application.Resources. You can read about this problem being discussed on msdn forum and stackoverflow. To fix this problem, fortunately there’s a patch for .NET 3.5 and .NET 4.0 resolved this issue.

If you’re developing in Silverlight, no issue as there’s no DynamicResource. If you’re developing in WPF, I urge you to consider if there’s a need at all to use DynamicResource. If you’re not using SystemColors, SystemFonts or themes in your application, StaticResource should be considered because DynamicResource are re-evaluated at runtime whenever the resource is requested which is an overhead. If you’re not familiar about their usages, you can read more about them here.

Posted in WPF. Tags: . Leave a Comment »

WPF memory leaks

After working on a WPF application for a couple of months, I’ve noticed that the application was leaking a large chunk of memory. After some memory profiling, the culprit was not very apparent. It seems that it was a combination of issues that contributed to the leak. One of the biggest problem was that data-binding was not done “properly”.

So what do I mean by “data-binding not done properly? Apparently if your DataContext does not implement INotifyPropertyChanged, you’re in big trouble!! Here’s a link from Microsoft that explains the phenomenon….

After much research, I came across a fantastic article explaining all the possible errors one can make to cause a memory leak. Some of these are not WPF inherent problems, they are just typical memory leak culprits dominant in all .NET applications, e.g. failure to unsubscribe an event handler; while some are just obscure and weird. But rest assured that some of the weird ones are fixed in .NET Framework 3.5 SP1 and .NET Framework 4…. So if you develop in WPF, this article is a MUST READ!!!!!

Lastly, a word of caution. Remember to start performance testing and memory profiling quite early in the stages of development. It’s a misconception that these activities can be put off until the late stages. If you do that, you have to bear the consequence of not being able to fix these problems because it becomes too hard to change code and change design…you have been warned.

Share this post :

Dude where’s my byte?

I’ve encountered a very interesting problem today, the mystery of the missing byte. It all began when one of tests starting failing on my development machine after I got latest from repository. The problem revolves around saving a checksum (byte array) to a varbinary column on SQL Server 2005. The checksum that was generated in code (which is unique for each machine) has a trailing byte of zero in the byte array, and after being saved to SQL Server, the zero byte is missing!!!!!

It was doing my head in, I went through the code and database creation scripts, and finally managed to find the problem. Apparently in the database scripts, there was a line ‘SET ANSI_PADDING OFF‘. This tells SQL Server to truncate off trailing zeros for varbinary and trailing spaces for varchar types. This setting takes into effect during table creation, so whatever you specified stays in effect after. In order to change “setting” for that table, you have to drop the table and re-create it with new setting, like so..

DROP TABLE T1;

SET ANSI_PADDING ON;
GO

CREATE TABLE Table1
-- and so on

SET ANSI_PADDING OFF;
GO

MSDN has recommended that you leave the setting to ON, and for very good reason. I doubt you would want things to auto-magically disappear or be modified without your knowledge, but should be should be made explicit and known. It would have saved me hours of troubleshooting, and I hope it will save hours for you too! Please see the ANSI_PADDING MSDN page for more info.

Share this post :

Strategy and Decorator Pattern

It’s been a long time since I posted anything, been very busy with work. Many things have changed and I am currently working as an independent contractor.  My latest gig at the moment is working on a WPF product! :) woo hoo!

Today I’m going to talk about using the Strategy and Decorator Pattern together, as it turns out they work pretty well together. Strategy pattern is a good way to encapsulate your algorithms, or in my case I want to use it to encapsulate reusable code, following the principle to keep it DRY. With the introduction of Action and Func classes in .NET framework, I have found that writing callbacks to be so much more accessible. For instance, you may sometimes need to repeat lots of Try…Catch statements in your code, and find that hard to keep DRY. This is where using callbacks are useful, like so…

Read the rest of this entry »

Silverlight 4 Beta released

Interesting news from PDC in LA, Silverlight 4 beta has been released, and comes full a very impressive suite of features and toolset supported by VS 2010.

If you have VS 2010 beta installed, you can play around with SL4.

Read more about it here.

Follow

Get every new post delivered to your Inbox.