Interesting (though useless) undocumented C# keywords (and corresponding IL instructions) described in Calling printf from C# – The tale of the hidden __arglist keyword on Bart De Smet’s B# .NET Blog.
Archive for the 'Tricks' Category
Undocumented C#
Today’s Sites/Blogs
- Ask the Performance Team (Thoughts from the EPS Windows Server Performance Team) – in their own words “… the Performance team covers a broad range of seemingly unrelated areas such as Core OS Performance, Printing, WMI and Terminal Services. Simply put – we’re a bit of a “catch-all” team. [...] Because we cover such a wide spectrum of technology, we see many different types of issues – some more frequently than others. So we thought we should share with the broader technical community. We’ll be sharing troubleshooting tips and technical information on areas of our specialty that we cover.”
- 45+ Excellent Code Snippet Resources and Repositories – it is what it says it is.
Threadsafe Events article at CodeProject explains problems one might encounter with .NET events in a multithreaded environment (not necessarily stating the absolute truth but still). Unfortunately, no-one has figured out the perfect solution, and we will have to choose “the best from all bad solutions” for some time still.
Asynchronous Callback Contexts article by the same author shows possible solution for event cancellation, particularly during object disposal: end-users do not expect components to raise events after they have been disposed or after they have unsubscribed from these events. The author refers to his Nito Asynchronous Library as a way to solve this issue.
Unattended .NET Installation
We needed to do unattended .NET 3.5 SP1 installation for our project, and at the same time we wanted to reduce the hard disk image size, so, after some Internet “crawling”, we found Silent .NET Maker synthesized – [a] script [that] builds custom .NET unattended, switchless, multimode installers/nLite addons, supporting all latest .NET framework versions, all its hotfixes and langpacks for win 2K/XP/2K3 x86 up to date. The thing really works, and we managed to get the size of full .NET 3.5 SP1 installer with all hotfixes down to something like 43MB (packed with 7-Zip) for 32-bit Windows XP. Not bad reduction! Aaron Stebner has also something to say about this topic.
DebuggerVisualizers – Boost C++ Libraries has nice introduction to custom Visual Studio debugger visualizers.
Font Burner
Font Burner makes it possible for you to use new fonts on your website, even if the end user does not have your chosen font(s) on his computer. There is nothing to install, neither on your computer nor on the end user’s, and the thing is free. The archive of offered fonts is really big (more than 1000 fonts). Really cool!
The only caveat is that, as it is using sIFR (Scalable Inman Flash Replacement, see more info) to change the fonts, it is likely rather impractical to use it for anything bigger than headings. Basically it hides the text and puts a Flash file in its place, and that Flash file is able to render the chosen font.
Nice collections of tips:
While searching for a solution to DRM-related troubles with film2home.fi video on demand service (gosh! no wonder that VoD purchasing rate is abysmal over here!) I have bumped into a Windows Media Player: WMP mini FAQ – an absolutely great collection of remedies to all kinds of Windows Media Player problems. Did not manage to solve my (in fact, film2home’s) problem though… :)
The Top 10 steps to optimize data access in SQL Server article series at CodeProject, despite some mistakes and arguable things, is not that bad starter’s guide for the SQL Server optimization question:
- Part I: Use Indexing
- Part II: Re-factor TSQLs and Apply Best Practices
- Part III: Apply Advanced Indexing and Denormalization
- Part IV: Diagnose Database Performance Problems
- Part V: Optimize Database Files and Apply Partitioning (is on the way)
“Bit Twiddling”
Needed to do some “weird” things recently that involved bit operations, e.g. to create masks with certain number of bits set. During my “research” I found few interesting places:
- Bit Twiddling Hacks – lots of snippets related to bit operations, e.g. counting, reversing, swapping, interleaving, testing, etc., etc., etc.
- Creating multiple numbers with certain number of bits set – this was the answer to my need, clean and simple
- Technical Interview Questions – has a lot of interesting topics, nicely categorized, although not all-encompassing, if comparing to the first link above
How to Debug Crashes and Hangs
How to Debug Crashes and Hangs article by Kirill Osenkov [MSFT] summarizes useful things about debugging in Visual Studio.
WPF Video Playback Problems
There is one severe problem with video playback in WPF/Silverlight that, for some reasons unknown to me, is getting very little (almost none) attention from both the community and Microsoft. Basically, it boils down to WPF being absolutely unable to properly play video content. Let me explain by using the following diagram:

First line shows video frames as they are in the video content. Second line depicts variable frame rate of the WPF renderer – as you know, WPF is changing the frame rate dynamically, and CPU load will affect frame rate too. There are two possible outcomes:
- WPF is using vsync (version 1), i.e. it synchronizing rendering to the screen with the screen refresh frequency. This is what you will get on Vista, and sometimes on XP (normally XP video drivers are not using vsync). The resulting video shown on the screen will have variable duration of frames, and the viewer will be present with artifacts like skipped video frames, “jerky” playback, where motion is not “smooth”/uniform, etc.
- WPF is not using vsync (version 2). It is the case normally seen on XP. The resulting video is even worse, as there is the tearing effect present now – upper and lower parts of the displayed video frame are not matching. This problem is not present on some XP machines, e.g. I do not see it on my home PC, while it is present on 100% of other machines.
This is a bit oversimplified picture, but good enough for our purpose. In reality, the resulting on-screen picture will depend also on the screen refresh frequency, but artifacts will be more or less the same. In both cases the video playback it totally unacceptable though.
The issue is very serious, and, unfortunately, it is unsolvable in terms of today’s WPF. I think it will be not solved in the near future either, as solving it would require WPF to adopt constant-frame rate rendering paradigm, and synchronizing it with the display refresh rate. This is not likely to happen, as it is a drastic change to the fundamentals of WPF, and, at the same time, it will waste resources in non-video related applications (now WPF can decide what frame rate it will use, and can dynamically change it, e.g. dropping frame rate for “still” scenes and increasing it when animations start).
In our software we had to go through a lot of extra pain to “overcome” this issue – we render video using DirectShow by incorporating Win32 host into our WPF application and implement all kinds of “tricks” to allow WPF content to get into the video window airspace (to display OSD’s, menus, etc.) by using e.g. clipping regions (say Goodbye! to transparency though). There are a few third party projects out there (WPF MediaKit by Jeremiah Morrill is an excellent example) that allow one to mix DirectShow and WPF, but none of them will fix the above mentioned issues, as the resulting picture is rendered by WPF renderer and all the artifacts will be there still.
Probably, for majority of people this is not really an issue (at least until you point them to it; after that they can see it on their own and they become very annoyed), especially if you are playing some kind of home-made content from the YouTube (although YouTube has HD content nowadays too), but it is completely unacceptable for people at least somehow concerned about the video playback quality. DVD/DivX player costing $30 will not have these problems, so it is difficult to explain why $1000 machine (33 times more expensive!!!) cannot produce even remotely as good video playback on $2000 HD TV set.
In addition to these video playback problems, WPF on XP suffers from the tearing issue not only during video playback, but also during “normal” WPF animations. And this has even more profound effect, as it makes it impossible to implement animated WPF applications on XP.
Microsoft’s reaction to the tearing issue on XP is problematic. We have tried to approach them via all possible channels – Microsoft Connect program, Microsoft Metro program, newsgroups, personal contacts, everything. They either deny the issue, or say that it is unsolvable for XP in general case, so they are not going to solve it (but they could easily solve it for something like 95% of all XP installations by solving it at least for ATI and Nvidia cards), or they say that they will not solve it for XP anymore, as XP is not available so nobody cares. And this last reaction is problematic again, as the issue is present not only on Windows XP Home/Pro, but on Windows XP Embedded and Windows Embedded Standard as well. These OS’s will be around for some time still, and Windows 7 Embedded will not come before 2010 and, being Vista-based, will be a resource hog – something not necessarily good for embedded system.
XAML Serialization
I am using XAML serialization instead of XML serialization more and more – IMHO it is much nicer and natural. There are few things to remember though, and XAML Serialization FTW does excellent job in enumerating those, although the list is not exhaustive.
API Hooking
Detours is a Microsoft library for instrumenting arbitrary Win32 functions (by Microsoft Research), unfortunately not free. There is a paper Detours: Binary Interception of Win32 Functions by Microsoft guys. In addition, there is API Hooking with MS Detours article on CodeProject.
Then, there is EasyHook – “The reinvention of Windows API Hooking” as they say themselves – which allows to hook APIs from managed code and write managed detours. This one is free, and from what is there it looks even more interesting than Microsoft’s Detour. And there is also a related CodeProject article.
Shadow Copying of Applications article on CodeProject shows simple technique allowing one to run shadow copies of .NET applications (like ASP.NET is doing for long time already).
Problem with C++/CLI + ATL Combo
Exactly… Wanted to use ATL (for CComPtr class and some other things) in my C++/CLI project (VS2008 with or without SP1) and… got nice assert on _CrtIsValidHeapPointer(pUserData) in dbgheap.c. Cool! Exactly that was missing to make my day better!
Some investigation, and I had answer to my problem. Actually two answers. Both pretty simple:
- As I had /NOENTRY specified in the No Entry Point item in the Linker/Advanced section of the project settings, I could add __DllMainCRTStartup@12 to the Force Symbol References item in the Linker/Input section of the project settings
- Alternatively, I could set No Entry Point item in the Linker/Advanced section of the project settings to No (as I said, I had /NOENTRY there)
I have tried both solutions, and both worked; I settled on the latter as more intuitive and clean. Always live, always learn…
Detecting .NET Framework Version
Using managed code to detect what .NET Framework versions and service packs are installed article on CodeProject shows how to do it purely in .NET, without resorting for interop and other “tricks”.
We use Microsoft RTC Client SDK 1.3 in our application to provide SIP telephony. Vista is not our priority, but, as all laptops and PCs nowadays come preloaded with Vista rather than XP, some time ago we decided to try our software on Vista. We’ve got everything working, except the phone – it was complaining about the RTCClient COM component. I wasted about half a day trying to “please” Vista to get RTC client running on it – checked forums, did all mumbo-jumbo things people claimed helped them – all in vain. In the end we simply abandoned the idea…
Today I decided to try it once more. And, guess what! Got it working in 10 minutes! :) All thanks to the post on MSDN Forum and then the corresponding blog post (mirror is here) by Laurent Etiemble.
The thing worked like a charm! Unfortunately, I cannot confirm if registering DLLs is a needed step – I do not have Vista near me, so I have made a script that my colleague at remote location tried on his Vista laptop and, to save time and reduce the “human-error” possibility/hassle, I included the registration part (regsvr32 for all DLLs) just in case.
Found this trick in the Jeffrey Richter’s Windows via C/C++ book (in Chapter 1). Visual Studio debugger has a very useful feature – it can monitor the thread’s last error code. You can display this error code together with its text description in the Watch window by typing $err,hr. In case some API call fails, the Watch window will show the error code (the one that would be returned by the GetLastError function). Thanks to the ,hr qualifier, the Watch window shows the error description as well (the string mentioned in the WinError.h header file for the occured error code).
Hardware Breakpoints
Toggle hardware data/read/execute breakpoints programmatically and Hardware breakpoints articles show how to use hardware breakpoints. Source code is available from both places.
How to find whether a GUI application is freezed or is not responding? – does exactly that… Everything is around the SendMessageTimeout function and SMTO_ABORTIFHUNG flag.
Here I am putting together all kinds of things that do not fit anywhere else…
Software development:
- 2008.04.19 There is a nice (but not new :) introduction to XamlWriter on Mike Hillberg’s blog
- 2008.04.10 Krzysztof Cwalina (author of Framework Design Guidelines) gave a lecture about framework design (3 hours long!) at the Redmond’s Microsoft Research Center. You can see it on the ResearchChannel (cool thing, by the way! and has a lot of videos from Microsoft Research). The lecture video is available for download as well (direct link)
- 2006.11.15 High Level Assembler anyone? I found it while I was looking for some assembler reference. In the end I found The Art of Assembly Language Programming book together with the above-mentioned thingy on the Webster – The Place on the Internet to Learn Assembly site. This HLA is a bit like the old macro assembler on the IBM mainframes but even cooler. :)
- Levenshtein Distance “between two strings is given by the minimum number of operations needed to transform one string into the other” (includes algorithm and implementations)
- ProgrammableWeb: API Dashboard – really impressive list of Web 2.0 APIs from ProgrammableWeb (WTF is Web 2.0??? buzzwords… buzzwords…)
- Using /clr and __declspec(thread) – a TLS wrapper for .Net
- CSLA .Net – quite interesting framework for business objects
- Hm… Saw it on Miguel de Icaza’s blog – expression a ?? b is equivalent to a != null ? a : b. Nice shortcut. Bet not many people know about it. ;)
Conceptual:
- { End Bracket }: Peripheral and Foveal Vision – interesting view at the human-computer interaction
Tricks:
Business:
Code Snippets and Tricks
Articles from various sources:
- 2007.10.09 IDesign has plenty of nice articles and WCF snippets, as well as C# and WCF coding guidelines.
- 2007.10.08 Use SimpleStyles to Easily Style System Controls from Expression Blend and Design blog.
- 2007.10.07 Maximizing WPF 3D Performance on Tier-2 Hardware from WPF SDK blog
- 2007.10.07 WPF: Expression Blend 2 and external resources (VS2008 version) by Laurent Bugnion
- 2007.10.07 Serializing Data Objects to XAML (and then dealing with ObservableCollection) by Robby Ingebretsen, and related Limited generics support in Xaml by Mike Hillberg
- 2007.10.07 RenderOptions.SetBitmapScalingMode by Robby Ingebretsen
- 2007.10.07 Mapping a Custom Property to x:Name by Robby Ingebretsen
- Brief anatomy of a ListBox
- XmlnsDefinitionAtrribute Is Pretty Nifty- a nice way of using namespaces in XAML
- ScrollViewer for Lefties shows how to re-style ScrollViewers so that ScrollBar ends up on the left.
- A set of resource-related articles by Ashish Shetty [MSFT]: Resources in WPF applications, How to: Reference a file embedded within a DLL in WPF, and More on resource loading in WPF (including pack://…).
- Create thumbnail of UIElement
- RefExtension – How to load XAML on-demand from Tom’s miniBlog – an interesting example of MarkupExtension usage for dynamic XAML loading.
- Dynamicly changing the staticresource to use on a control from the MSDN forum.
- Asynchronous Databinding – nice article by REZN8’s Andrew Whiddett published on Karsten’s blog
Articles from The Code Project (see all WPF articles):
