I recently encountered a problem creating new logins with SQL Server. Something that has worked for years suddenly stopped with the following error:

Password validation failed. The password does not meet Windows policy requirements because it is too short.

Since SQL Server was using Windows local security policy I went and checked that at Security Settings > Account Policies > Password Policy in Local Security Policy (available under Administrative Tools in Control Panel or by opening secpol.msc). As expected, these contained setting that I was not expecting, which were probably changed from the network by a system administrator.

However, I wanted to be able to enter shorter passwords, like 8 characters instead of 10, but this was disabled. Even if I was running as administrator, the option of changing this was disabled.

It is however still possible to modify these settings even if you cannot do it from the management console. You can do it from a command prompt as administrator.

  1. Open a command prompt running as administrator
  2. Run the following command to export the settings to a file. In my example, the target path is c:\temp\local.cfg, but it can be anything.

  3. Edit the file with notepad or another editor. The file is an INI file with sections and key-value pairs. The password settings are available under the [System Access] section. For changing the minimum length of the passwords modify the MinimumPasswordLength key.
  4. Save the file and run the following command to import the settings from the modified file.

  5. Close and open the Local Security Policy console again and check the settings.
, , , , Hits for this post: 1727 .

Visual Studio “14” CTP ships with a refactored C Runtime. The first thing you’ll notice is that msvcrXX.dll has been replaced by three new DLLs: appcrtXX.dll, desktopcrtXX.dll and vcruntimeXX.ddl (where XX stands for the version number so in this version it’s appcrt140.dll, desktopcrt140.dll and vcruntime140.dll).

crtdlls
You can see in this image that both desktopcrt140.dll and vcruntime140.dll depend on appcrt140.dll.

These three new DLLs export run-time routines in different categories, with some of them overlapping, as shown by the bellow table (assembled by directly analyzing the exports of the three modules).


Function

Appcrt140.dll

Desktopcrt140.dll

Vcruntime140.dll
Buffer Manipulation
Byte Classification
Character Classification
Console and Port I/O
Data Alignment
Data Conversion
Debug Routines
Directory Control
Error Handling
Exception Handling
File Handling
Floating-Point Support
Low-Level I/O
Process and Environment Control
Robustness
Searching and Sorting
Stream I/O
String Manipulation
System Calls
Time Management

Breaking CRT routines in several DLLs is not the only change. The CRT has been rewritten for safety and const correctness. Many of the routines have been re-written in C++. Here is a random example: the _open function, that was available in open.c was implemented like this in Visual Studio 2013:

In Visual Studio “14” CTP it is available in function appcrt\open.cpp and looks like this:

UPDATE

To read more about the refactoring see the VC++ team’s blog posts:

, , , , Hits for this post: 27364 .

My first Windows Store app (for Window 8.1) is now available in Windows Store. It’s called Your Chemical Name and shows names (and text) using chemical elements symbols in the Breaking Bad style.

yourchemicalname11

The application allows to:

  • customize the appearance of text, colors, background
  • customize the position of the text on the background
  • save image to a file
  • post image on a facebook album
  • share image with other apps

yourchemicalname12

yourchemicalname13

yourchemicalname14

You save the images to disk or share them on facebook or with apps supporting the Windows Share Charm.

yourchemicalname15

Here are a few screenshots:
yourchemicalname2

yourchemicalname3

yourchemicalname5

More about the application here.

Download Your Chemical Name from Windows Store.

, , , , , , , Hits for this post: 27605 .

Windows 8 features a Settings charm to display both application (the top part) and system (the bottom part) settings (you get it from swiping from the side of the screen). The system provides two entry points, Permissions and Rate and Review, the later only for applications installed through the store.

You can customize the settings charm by adding new entry points. For instance, you may want to add an About pane. If your application uses network capabilities then you have to add a privacy policy, otherwise your application will not pass the Windows Store Certification.

charms settingscharm6

In this post I will show how you can add new entries to the settings charm for Windows 8.1 applications (this won’t work for Windows 8 applications). We have to use two classes:

  • SettingsPane: enables the app to control the Settings Charm pane. The app can add or remove commands, receive a notification when the user opens the pane, or open the pane programmatically.
  • SettingsFlyout: represents a control that provides in-context access to settings that affect the current app. This class is new to Windows 8.1

The following code adds a new entry to the settings pane called Privacy policy and provides a handler for the command. In the handler we create a new instance of a SettingsFlayout and show it.

The text of the privacy policy is kept in a text file under the Settings folder. We asynchronously open and read the content of the file and when the text is available we create a new TextBlock control and use it as the content of the flyout content control.

Then we have to initialize the settings pane when the application starts.

When you start the application and swipe the right edge of the screen the charms bar shows up. Opening the Settings charm will now show two entries for the application: Privacy Policy and Permissions.
settingscharm2 settingscharm3

The next sample shows how to add an About page. It’s very similar actually.

Notice that the entries in the settings charm appear in the order they where added.
settingscharm4 settingscharm5

The content of the flyout can be any visual object (the simple TextBlock is used only for demo purposes). It is also possible to customize the flyout header, icon, background, etc. Here is the same About page with additional flyout settings.

settingscharm7

Here is some additional reading: Guidelines for app settings (Windows Store apps).

, , , , , Hits for this post: 35716 .

In WPF, Silverlight and Windows Phone it is possible to render a visual object into a bitmap using the RenderTargetBitmap. This functionality, that I find pretty basic, was not available for Windows Store applications. Fortunately, Windows 8.1 provides that functionality for Windows Store applications too, through the same RenderTargetBitmap class.

There are some limitations though:

  • it should be used in the code behind (not declared in XAML) because you have to call RenderAsync
  • collapsed visual objects are not rendered (only visible ones)
  • in rare circumstances the content can be lost due to the interaction with lower level systems; in this case a specific exception is triggered
  • the rendered target bitmap does not automatically scale when the current DPI settings change
  • the maximum rendered size of a XAML visual tree is restricted by the maximum dimensions of a DirectX texture

Here is a demo Windows Store application that has several controls and a button that when pressed a screenshot of the area shown in red (it’s a grid) is taken. The bitmap is saved on disk, but also displayed as the source for the image control shown in the preview area.

wsas1

The handler for the Click button even looks like this:

SaveScreenshotAsync is an async method that takes the reference to the FrameworkElement to be rendered to a bitmap (in this case the constrolsGrid) and returns a Task<RenderedTargetBitmap> that can be awaited on. As soon as we have the bitmap we set it as the source for the image control (imagePreview).

wsas2

SaveScreenshotAsync is an async method that takes the FrameworkElement to be rendered to a bitmap and returns a Task<RenderedTargetBitmap> that can be awaited on. This method first prompts the user to select a destination file for the rendered bitmap. When the file is available it calls SaveToFileAsync to rendered the bitmap and write it to the file.

SaveToFileAsync is an async method that takes the FrameworkElement to be rendered to a bitmap and the StorageFile when the bitmap is to be saved and returns a Task<RenderedTargetBitmap> that can be awaited on. The file is opened asynchronous for read-write access and the returned IRandomAccessStream is passed further together with the framework element and the bitmap encoder id (that specifies how the bitmap should be encoded, i.e. BMP, JPEG, PNG, GIF, etc.) to CaptureToStreamAsync.

CaptureToStreamAsync creates a new RenderTargetBitmap object and calls RenderAsync to render the visual tree of the framework element to a bitmap. After the bitmap is rendered it retries the image as a buffer of byes in the BGRA8 format. It then asynchronously creates a BitmapEncoder for the IRandomAccessStream stream that it received as an argument, it calls SetPixelData to set the pixels data (notice the BitmapPixelFormat.Bgra8 parameter that matches the pixels format returned by GetPixelsAsync) and later asynchronously flushes all the image data, basically writing it to the file. It then returns that RenderTargetBitmap object that it created, which is used eventually as the source for the image control.

Here is how the saved JPEG image (also seen in the preview screenshot above) looks likes:
wsas3

You can check the source code of the attached WinRT Screenshot demo (1537). It requires Visual Studio 2013 and Windows 8.1.

, , , , , , Hits for this post: 39909 .

Many years ago I published on my blog a helper class for working with the Windows console that was wrapping the Windows console API. Looking back at it I realized it was a pretty naive implementation. So I decided to start a new and make something more flexible and easier to use. Hopefully, I was more successful. The result is a small C++ template library called cppconlib, available on codeplex.

cppconlib is built with C++11 features and requires Visual Studio 2012 or newer. The library is available in a single header called conmanip.h and provides a set of helper classes, functions and constants for manipulating a Windows console (using the Windows console functions). The library features the following components:

  • console_context<T>: represents a context object for console operations; its main purpose is restoring console settings; typedefs for the three consoles are available (console_in_context, console_out_context and console_err_context)
  • console<T>: represents a console objects providing operations such as changing the foreground and background colors, the input mode, screen buffer size, title, and others; typedefs for the three consoles are available (console_in, console_out and console_err)
  • manipulating functions that can be used with cout/wcout and cin/wcin: settextcolor()/restoretextcolor(), setbgcolor()/restorebgcolor(), setcolors(), setmode()/clearmode(), setposx()/setposy()/setpos().

The library can be downloaded from here. Detailed documentation is available here.

cppconlib

Examples

The following example prints some text in custom colors and then reads text in a different set of colors.

cppconlib2

The following code prints a rhomb to the console:

cppconlib3

For more details and updates check the project at codeplex: https://cppconlib.codeplex.com.

UPDATE: A NuGet package for cppconlib is available.

, , , , , , , Hits for this post: 35085 .

A WinForms DataGridView control has the ability to automatically generate its columns and populate from a specified data source (which can be a DataSet, a simple list or something else). All you have to do is something like this:

When you do the same in MFC, it doesn’t work (supposing that you followed all the steps for hosting a WinForms control in an MFC application as described in MSDN).

dgv1

After debugging through the .NET framework sources I realized the problem was that the BindingContext property of the DataGridView control was null. This property represents a manager of the list of bindings for the control. If this is null then the control will use the binding context of the parent, which is usually a WinForms form. However, in this MFC application there is no WinForms form and the parent of the DataGridView control is null, which means the control does not have a bindings manager, and no bindings can be set.

The solution is to explicitly set the BindingsContext property to an existing binding context (a new object) before setting the data source.

dgv2

The lesson learned is that when you host a WinForms control in an MFC application some things won’t just work out of the box, if they rely on a parent form functionality. There is no such WinForms form and you might need to do additional manual initialization.

, , , , , , Hits for this post: 38194 .

Problem

I have recently migrated a C# 2.0 project registered for COM interop to .NET 4.5 and when I imported the type library in a C++ project with no_registry, suddenly I got some errors because the type library could not be imported. Here are the steps to reproduce:

  • create a .NET Class Library project and set platform target to .NET framework 4.5
  • check Register for COM interop
  • build the project
  • import the type library in a C++ project:

The result is the following error:

Solution

Searching for the solution I found that this was a known issue when you have both CLR 2.0 and 4.0 installed on the same machine. See this KB article: VC++ 2010 #import with no_registry fails with error C1083 or C3510. Unfortunately I was unable to fix the problem with the solution indicated there.

There are two tools that can generate a type library from an assembly:

  • tlbexp.exe: generates a type library from a specified .NET assembly
  • regasm.exe: registers metadata from an assembly to the Windows Registry, but in addition can create a type library from for the input assembly when /tlb switch is used.

When a project specifies to register for COM interop what Visual Studio does is similar to calling regasm.exe with /codebase switch specified. Since I had before problems with interop assemblies automatically generated by Visual Studio (with tlbimp.exe) I though it would be the same (only the other way around). Therefore I unchecked “register for COM interop” and added as a custom build step registration with regasm.exe, like this:

Not very surprisingly, the generated file was different and the #import command executed without problems.

Problem solved!

Cause

The question that arises is why are the two files, generated with Visual Studio and with regasm.exe, different? You can see they are different if you open them in an hex editor. But if you just use oleview.exe, the disassembled type library looks identical.

The obvious answer that occurred to me, but eventually proved wrong, was that Visual Studio is not actually using regasm.exe to register the assembly and generate the type library. It actually uses a MSBuild task for that.

When the RegisterForComInterop property is set in a .csproj an MSBuild task is executed.

The task can be found in Microsoft.Common.targets (in c:\Windows\Microsoft.NET\Framework\v4.0.30319\)

To check if I can reproduce, I have created MSBuild file (explicitreg.xml) with some hard-coded values that only runs that registration task.

But surprise: this produced the exact same output as the regasm.exe command. Comparing the diagnose logs from MSBuild (for the build of the .csproj and my custom file) I couldn’t spot any difference in the execution of the task. Also using the Process Monitor (procmon.exe from Sysinternals) to check access to the TLB file, I could clearly see the difference for the file writing, because different lengths were produced from Visual Studio build and explicit MSBuild run, though again I could not see any difference in the call stacks.

So, the actual cause for this behavior is still unknown to me and I would appreciate if anyone that knows the answer clarifies it.

, , , , , , , Hits for this post: 47596 .

It is possible to host WPF controls in a Win32 application, and the other way around, but because of the differences betweeb these technologies there are various issues that can appear. One of these is handling of keyboard input. Without diving too much into differences between WPF and Win32, I will show how to provide keyboard input for WPF controls hosted in a Win32 applications. For reading about the differences and the interoping between the two I suggest WPF and Win32 Interoperation.

Hosting a WPF Control in Win32

To host a WPF control in a Win32 application you need to follow several steps.

  • Create a new HwndSource, setting the parent window as it’s parent. This is a key object, that enables displaying of WPF content in a Win32 window.
  • Instantiate the WPF control or window
  • Assign the reference to this instance of the WPF control or window RootVisual property of the HwndSource object.

To simplify this process, I have this small helper class:

With this class I can create WPF controls like this:

Enabling Keyboard Input

While you can use the mouse with these WPF controls added like this, the keyboard in not enabled. To provide keyboard input for the WPF controls, we need to hook the HwndSource, adding a handler that receives all window messages. We must handle the WM_GETDLGCODE message to let the system know what kind of messages we want to handle on our own (in the WPF control).

This is how we add the hook:

And this is how the hook procedure looks (defined as a static member of my CWpfControlWrapper):

By returning all these dialog codes will let the system know that the window wants to process arrow keys, tab keys, all keys and receive the WM_CHAR message.

Enabling TAB Navigation

Even though the WPF controls now have keyboard input, it turns our that navigating with TAB (forward) or TAB+SHIFT (backwards) does not work.

Here is an example where I have an MFC application with four WPF controls, two buttons and two text boxes. One button and one text box, as well as the OK and CANCEL buttons have tab stops.

The sample dialog box looks like this:

Pressing the TAB key should allow navigating from button 1 to edit 1, then button OK, button CANCEL and then back to button 1. Button 2 and edit 2, not having the tab stop style defined, should not be included in the navigation.

As already mentioned, this does not work, however. After reading about a solution for this problem, it looked like the key lied in the IKeyboardInputSink interface, that both HwndSource and HwndHost implement. This interface provides a keyboard sink for components that manage tabbing, accelerators, and mnemonics across interop boundaries and between HWNDs. Apparently the solution was to:

  • derive the HwndSource class
  • override the TabInto method (actually, since this is a sealed method you’d have to define a new override for it) and implement there the tabbing logic
  • use this derived HwndSource to present WPF content in a Win32 window

Though I tried several things I didn’t manage to make it work. However, since I already had a hook for all window messages, and explicitly asked for receiving WM_CHAR, it was possible to use this to handle TAB and TAB+SHIFT. So here is an addition to the ChildHwndSourceHook above:

So if we get a WM_CHAR and the wParam is VK_TAB, then we query the parent for the next tab stop (for forward navigation if SHIFT was not pressed, or backwards navigation if SHIFT was also pressed). If there is such a tab stop we set focus on that window.

The FindNextTabStop method (added as a member of the CWpfControlWrapper class) looks like this:

It does the following:

  • it gets the next/previous window in the z-order (which defines the tab stop order)
  • when it reaches the end/top of the z-order, it starts all over again, which enables looping through the child windows of the parent
  • if the next child the in z-order is the current control, then it finished looping through the children of the parent and it stops
  • if the current child in the z-order has the WS_TABSTOP style set, then this is the window we are looking for

With this defined, it is possible to use the TAB key to navigate between the WPF controls on a Win32 window.

Here is the MFC demo application that you can try: Mfc-Wpf Tabbing (1228).

, , , , , Hits for this post: 51982 .

I recently ran into problems with an MFC application that was hosting some Windows Form user control in a modal dialog; the application hanged after it lost focus. The problem was the window received WM_GETDLGCODE message in an infinite loop making it impossible to handle anything else. After a lot of digging, I found that the cause was the missing WS_EX_CONTROLPARENT style of the window that hosted the WinForms control. What I want to do is summarizing the information about this Window style. The most information I’ve been able to pull came from Raymond Chen’s blog The Old New Thing.

First of all, there are two styles: DS_CONTROL and WS_EX_CONTROLPARENT.

WS_EX_CONTROLPARENT

The window itself contains child windows that should take part in dialog box navigation. If this style is specified, the dialog manager recurses into children of this window when performing navigation operations such as handling the TAB key, an arrow key, or a keyboard mnemonic.

WS_EX_CONTROLPARENT is a extended window style. It tells the dialog manager that it should treat the children of the window with this flag as direct children of the window’s parent (got that?). Raymond has a simple figure in this blog post When embedding a dialog inside another, make sure you don’t accidentally create duplicate control IDs.

DS_CONTROL

Creates a dialog box that works well as a child window of another dialog box, much like a page in a property sheet. This style allows the user to tab among the control windows of a child dialog box, use its accelerator keys, and so on.

DS_CONTROL is a style for dialog templates. The dialog manager translates this style into window styles and extended window styles. It removes WS_CAPTION and WS_SYSMENU (if existing) and adds WS_EX_CONTROLPARENT.

Bottom line is, the WS_EX_CONTROLPARENT style tells function that do control searches (such as GetNextDlgTabItem) that they should treat the dialog marked with the flag as a container of other controls (and iterate them) and not a single, big, control.

More readings:
What is the DS_CONTROL style for?
The dialog manager, part 2: Creating the frame window
Why doesn’t the TAB key work on controls I’ve marked as WS_TABSTOP?
Why do we need IsDialogMessage at all?

And references to similar problems as my own:
endless messages WM_GETDLGCODE when focus is lost
WS_EX_CONTROLPARENT

, , , , Hits for this post: 33565 .