By Robert Ellison. Updated on Saturday, September 24, 2022.
Mark Jackson, my co-founder at Cucku, is blogging re-mastered debugging tips from StackHash. StackHash is now an open source project and all of the great content from the original site has been taken offline. This new project is a great resource for debugging on the Windows platform, especially post-mortem crash dump analysis. If that’s your thing do yourself a favor and subscribe to Mark’s blog.
Wasted far too long on trying to get WCF to work with custom basic authentication this week. Custom in the sense that I need to look up the username and password in a database and not have IIS attempt to match the credentials to a Windows account. Given how well WCF 4.0 supports RESTful services in general it’s a bit shocking that basic auth over SSL isn’t supported out of the box. It seems like you should be able to derive and hook up a class from UserNamePasswordValidator, set the transport clientCredentialType to Basic and be ready to go. I’ve heard that this works for self-hosted services, but no dice in IIS.
Basic access authentication is a simple protocol and so in the end I added a helper method that checks for access (and in my case returns the user information for later use) at the start of each call into the service. It’s very simple:
Check WebOperationContext.Current.IncomingRequest.Headers for an ‘Authorization’ header. If it’s there decode and validate the credentials.
If the header is missing or the credentials are incorrect add the WWW-Authenticate header to the response - WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"myrealm\""); – and then throw a WebFaultException with a 401 Unauthorized status code.
This triggers a browser to prompt for your username and password and then try the request again. When calling the service in code you can add the ‘Authorization’ header preemptively and skip the 401 response entirely.
(Published to the Fediverse as:
Basic HTTP auth for an IIS hosted WCF 4 RESTful service #code#wcf#iis#rest How to implement .NET Basic HTTP auth for an IIS hosted WCF 4 REST API.)
By Robert Ellison. Updated on Thursday, November 12, 2015.
Two new Catfood releases.
Catfood WebCamSaver 3.10 adds support for simultaneous updates in 4 and 16-cam modes. The WebCam Directory has also been completely overhauled. WebCamSaver is a rather voyeuristic screensaver that lets you watch live feeds from around the world. As well as a screensaver the feed is available in my World Webcams Google Gadget.
Catfood PdfScan 1.20 follows hot on the heels of 1.10. The main update is showing a preview of each scanned page which is super handy if you always forget which way pages are supposed to go in your document feeder. Mentioning no names…
(Published to the Fediverse as:
Catfood: WebCamSaver and PdfScan #code#webcamsaver#pdf#pdfscan Latest updates to Catfood WebCamSaver and Catfood PdfScan)
Catfood Earth 3.10 includes rotation to longitude / solar time, volcanoes, a screen saver, time zone updates and more. Catfood Earth uses satellite imagery and a variety of data feeds to render jaw-dropping live desktop wallpaper.
Catfood PdfScan 1.10 saves your selected paper size and feeder choices. There is also an option to keep PdfScan open after saving a scan, something that had been bugging me when slogging through large digitization projects. PdfScan is a free tool for scanning stuff into a PDF file.
Catfood Weather 2.00 includes weather alerts and an updated UI. Catfood Weather provides a free, taskbar based weather forecast for US locations.
By Robert Ellison. Updated on Thursday, November 12, 2015.
I’ve just moved ITHCWY comments over to Disqus. BlogEngine.NET now supports Disqus out of the box, but doesn’t export comments to anything that Disqus is willing to eat. I’ve knocked up a quick converter that takes a full BlogML export from BlogEngine.NET (and at least in theory any other source of BlogML) and converts the comments to WXR. You can import the WXR file under the Generic option in Disqus.
The tool is a Windows console application that takes two parameters, the BlogML import file and the WXR output, i.e.:
BlogMLtoDisqus.exe C:\BlogML.xml C:\ForDisqus.wxr
It isn’t fancy and there is no error checking so it will either work or die horribly. If the latter, leave a comment and I’ll try to fix it for you.
Here are two scenarios where merged ResourceDictionary objects are the way forward.
I’m working on a WPF project that needs to be single instance. Heaven forbid that the WPF team should pollute the purity of their framework with support for this kind of thing (or NotifyIcon support but that’s another story) so I’m using the code recommended by Arik Poznanski: WPF Single Instance Application. I like this because it both enforces a single instance and provides an interface that reports the command line passed to any attempt to launch another instance.
An issue with using this code is that you need to write a Main function and so App.xaml is set to Page instead of Application Definition. Once you’ve done this the program works fine but the Visual Studio designer fails to load resources in UserControls (and in Windows containing those UserControls).
The fix is to factor all of the application level resources out into a separate ResourceDictionary (i.e. MergedResources.xaml). Once you’ve done this merge the new ResourceDictionary into App.xaml as follows:
Next, in each Window or UserControl reference the same ResourceDictionary:
The designer will now be able to find the correct resources for each UserControl and Window.
The second scenario is factoring resources and other Xaml into a DLL. To pull resources in from a referenced assembly you just need to use a Pack Uri when merging in the remote ResourceDictionary:
If you’re putting Windows and UserControls in the DLL use exactly the same approach to reference the resources using ResourceDictionary.MergedDictionaries and you’ll get designer support for these as well.
(Published to the Fediverse as:
Merging Resource Dictionaries for fun and profit #code#.net#c##wpf#xaml Get designer support for XAML loaded from a DLL by merging resource dictionaries in .NET WPF.)
WPF: When it's good it’s very, very good and when it’s bad it’s like sautéing your own eyeballs.
When you’re about to launch a process that will trigger an elevation prompt it’s polite to decorate it with the little UAC shield so the user knows what to expect. Of course there’s no such capability in WPF, and WPF controls have no handles so you can’t use SendMessage / BCM_SETSHIELD as with Windows Forms.
System.Drawing.SystemIcons.Shield seems promising, but it returns the wrong icon on Windows 7 (at least in .NET 4).
SHGetStockIconInfo will allow you to get the correct icon, but isn’t supported on Windows XP. I’ve just added the necessary interop signatures for SHGetStockIconInfo to pinvoke.net so I won’t duplicate that code here. Once you have the interop you can get the correct icon as a BitmapSource using the following code:
(Published to the Fediverse as:
UAC shield icon in WPF #code#.net#c##wpf#uac#pinvoke How to add the correct UAC shield icon for each Windows version in .NET WPF using Win32 interop.)
By Robert Ellison. Updated on Sunday, September 30, 2018.
I've written an extension for BlogEngine.NET that automatically adds several different geographical tags to blog posts. I knocked this up for my Hikes blog. It might be useful for any blog where some of the posts are related to a real world location.
To get started download GeotagFromKML.zip (2.24 kb) and copy GeotagFromKML.cs to the App_Code\Extensions folder in your BlogEngine.NET instance.
The extension does two things. Firstly it looks for a link to a KML file when post is added or updated (it does this because each of my hike posts includes a Google Earth KML file for the hike). If a KML link is found then a paragraph is added to the post containing the longitude and latitude of the first coordinate in the KML file. The paragraph uses the Geo microformat. You can customize the text in settings for the extension. You can also regenerate by deleting the paragraph and saving the post.
The second function is to add ICBM and Geo Tag META tags when serving a post that contains the geotagged coordinates. You can take advantage of this without linking to a KML file, just include a location like this in your post:
Once you have geotagging up and running you might also want to add GeoURL to the list of ping services for your site.
.NET doesn’t support rebooting, logging off or shutting down your computer though a managed API. Searching for the best way to do this brings up three options: WMI, shutdown.exe and ExitWindowsEx.
I regard WMI as the last resort of the desperate. Weakly typed magic string juju.
Calling Process.Start(“shutdown.exe /r /t 0”) might work, but how would you know? And you’ve got the overheard of starting a new process just to accomplish a reboot. Lazy.
The best way to reboot is P/Invoke to ExitWindowsEx. Unfortunately there’s some really awful sample code out there which will either fail to do anything or mask any errors. I’ve included a drop-in class below that fixes these problems.
If you read all the way through the documentation for ExitWindowsEx you’ll find this:
To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege. For more information, see Running with Special Privileges.
So just calling ExitWindowsEx won’t do anything. The sample code below adjusts the process token and then reboots (change the flags passed to ExitWindowsEx to shutdown instead, or to pass in a different reason). You’ll also get a Win32Exception if a failure occurs. Catch this, and you can tell the user that they need to reboot manually.
By Robert Ellison. Updated on Sunday, September 30, 2018.
Here's a frustrating WPF scenario — you use the ApplicationCommands class to add Cut, Copy and Paste commands to toolbar and then put a TextBox on another toolbar. Click in the TextBox and the commands remain disabled. WTF, WPF?
The problem is with focus scopes. Your window is a focus scope and so are any menus or toolbars. This has the desirable property of allowing commands to target the control you were in immediately before invoking the command. You want paste to target the text box you're editing, not the menu item or button you clicked to request the paste.
So far so good. The problem is that the commanding system isn't smart enough to target the control with keyboard focus if it's in a nested focus scope. Remember that the window itself is a focus scope so our TextBox in a ToolBar (also a focus scope) is nested and immune to commands from our menu or toolbar.
Here's a simple window that demonstrates the problem:
Ignore the PreviewCanExecute handler for now. If you run this window and click in the main TextBox the paste button and menu item are enabled. Click in the toolbar TextBox and pasting isn't an option. Well, Ctrl-V still works and there's a context menu but you know what I mean.
The problem can be fixed by adding a command binding for ApplicationCommands.Paste and handling the PreviewCanExecute event:
When the window loads we're making note of the focus scopes for the toolbar and menu. Then when PreviewCanExecute fires we check to see if the element with the keyboard focus is in a different focus scope (and also that the window doesn't have keyboard focus). We then set the CommandTarget for the menu item and button to the element that has keyboard focus.
A handler isn't required for CanExecute as the command will take care of this with respect to the new CommandTarget.
Run the window again and you'll see that the paste button is enabled for both of the TextBox controls. When you click the button (or menu item) our PreviewCanExecute handler ignores the new keyboard focus and the command is sent to the desired control.
One drawback of this approach is that keyboard focus isn't returned to the TextBox after the command executes. The CommandTarget remains in place so you can keep pasting and the command remains enabled but you lose the visual cue that lets you know where the target is. I haven't figured out a clean approach to this yet. When I do, I'll update this post. Better yet, if you've figured it out leave a comment.
(Published to the Fediverse as:
WPF commands with nested focus scope #code#wpf#.net#c##xaml How to persuade a WPF application to paste into a selected control when the control is in a different focus scope.)