Thursday, January 26, 2017

MFC dialog properties do not display Control Events or Message properties

Problem: I was creating a new dialog in an old MFC project, and notified that the new dialog did not display any entry under the dialog properties' Control Events section or the Messages section. There was however no problem running the dialog - even capturing click events etc.. So the problem was annoying, but not much more.

Analysis: In dialogs where this displayed correctly, I noticed that the difference was in the constructor of the dialog class. My code had something like:
 
MyDlg::MyDlg() : CDialog(IDD_MY_DIALOG, nullptr)

Solution: Some of the working classes had:

MyDlg::MyDlg() : CDialog(IDDnullptr)

...where IDD was defined like this in the header file:

enum { IDD = IDD_MY_DIALOG };  

Solution: It turns out that the enum line in the header is needed to make Visual Studio connect the dots between the dialog and its dialog class. It is actually also being explained in this StackOverflow article.

Thursday, June 5, 2014

Computer on/off event viewer filter

Sometimes I want to track when I turned my computer on or off, including when it went to sleep or woke back up again.  To do that, I have created a custom view in Event Viewer on my Windows 8 system (should be the same for all systems from Vista and beyond, I assume). Go to Custom Views and click on "Filter current custom...". Switch to the XML tab and check the "Edit query manually" in the lower part. Now, paste the following in there:

<QueryList>
  <Query Id="0" Path="System">
    <Select Path="System">
    *[System
        [Provider
            [@Name='Microsoft-Windows-Kernel-Power'
            or @Name='Microsoft-Windows-Power-Troubleshooter'
            ]
            and TimeCreated    [timediff(@SystemTime) &lt;= 2592000000]
        ]
    ]
        or
    *[System
        [Provider
            [@Name='Microsoft-Windows-Kernel-General']
            and ( (EventID &gt;= 12 and EventID &lt;= 13) )
            and TimeCreated    [timediff(@SystemTime) &lt;= 2592000000]
        ]
    ]
   </Select>
  </Query>
</QueryList>

Basically, it is the equivalent of this, but only showing event 12 (switch off) and 13 (switch on) for the Kernel General source:




Please remember to "Save filter to custom view" if you want quick access to it later.

Wednesday, May 21, 2014

Buggy Windows 8 network charms - works from command-line!

I have struggled with two network related problems on my older laptop for some time after upgrading it to Windows 8 and later 8.1. Both problems occur when I try to go to the Settings charm (Winkey+I), in the submenu under the networking icon (upper left of the icons). Both however seem to have one very simple workaround: Using the command-line equivalents.

Problem 1 - Connect to WLAN: Sometimes, registering to a known WLAN does not work, or the connection is randomly or immediately lost after being registered. Sometimes, the desired WLAN network is not even visible in the networks list, although any other WLAN capable device (e.g. a phone etc.) can find the WLAN in question.

Solution 1 - Connect to WLAN from the command line: For some reason, connection works great when doing it from the command line. To see all avaiable WLANS:

netsh wlan show networks

Issue the following command to connect to one of them:

netsh wlan connect name=WlanName

-where WlanName is the name of the WLAN. Observe that this name is case sensitive!

Those are the basics - explore other possibilities by using the help system (a ? sign  will give you available commands).

Possible mitigating factor to this problem: I am using an Intel 4965AGN network card, which some suggest is not supported under Windows 8. However, the Windows Compatibility Center suggests otherwise - at least for Windows 8 (while 8.1 is marked with "no info"). I have had bluescreen problems with both the Windows 8 native driver and the latest Intel driver, but the latest Dell driver works for me (version 12.4.3.9 dated May 28, 2009) on my Latitude D830 without bluescreen problems.

Problem 2 - Connect to RAS (PPTP) connection: When trying to connect to one of my RAS connections (VPN to another location), sometimes I loose the WLAN connectivity even by clicking the desired RAS connection on the Settings-networking charm, without even clicking its Connect button that will now be displayed. Needless to say, when my WLAN is gone, so are my chances to connect to the RAS connection. I am stuck.

Solution 2 - Connect to RAS from the command line: Again, performing the same task from the command line succeeds without any hassle. Here's the command:

rasdial "RAS connection name" username password

More information about problem 2: What happens when clicking the RAS link, seems to be that the WLAN Extensibility Module crashes and logs an event 10003 and an event 10000, "WLAN Extensibility Module has failed to start" with a reference to the file IWMSSvc.dll and an error code 1726

Friday, May 16, 2014

Wrong search order in Windows 8.1 Start menu

I have been using Windows 8.1 now for a little more than half a year, and I can safely say that compared to Windows 7, I still can not come up with one single thing I like better. Take search from within the (horrible) start menu. In Win7, bring up the start menu and type some text related to the document you want to open - voilla, chances are that the document you wanted is among the top 5 hits displayed.

Problem: In Win8 (updated to version 8.1 by now), you can also search from the start menu - by default searching "Everywhere". You only get the upper two documents it finds, which are mostly files you have not touched for years. Press the Win-F key instead to search through your files, and you end up with a screenful of ancient files you haven't used since Jesus walked the streets of Jerusalem.

Workaround: My best workaround is to use following key combo instead: Win-E, then Ctrl-E (I only use the mouse when I am forced to, luckily at least keyboard control works pretty well in Win8) Now you can type your search term and instantly get proper search results from inside good old Windows Explorer. The Win-E key combo brings up Explorer in My Computer (if you haven't changed the default), then Ctrl-E places you in the search field in the upper right corner. It is uglier than the Win-F charm, but much more charming.

So why, Microsoft, can't you let Explorer serve these results even to the Win-F file search mechanism? Man do I miss Win7.

Friday, December 20, 2013

Visual Studio Solution dependent code sections

If you have a Visual Studio project that is part of several solution files (which in most cases is a bad practice - if conditions allow it, rather build a DLL that could be referenced from any solution), you may want to implement solution specific code fragments. In my case, I had a COM interface class that needed to specify a unique CLSID in its IMPLEMENT_OLECREATE call.

The solution: Create a solution specific preprocessor directive. This has been tested in C++ on VS2010:
  1. Define the parameter SOLUTION_$(SolutionName) in Project properties - Configuration Properties - C/C++ - Preprocessor - Preprocessor definitions. Note that the term $(SolutionName) should be written exactly as you see it here - these are MsBuild style variables.
  2. Now in your code, add #ifdef sections checking for the solution name.
  3. If you need to render an error in case none of the solution names defined are found, include a #define SOLUTION_FOUND inside each of your sections and check that it is defined afterwards. If not generate an #error to stop the compiler.
The code will look something like:

#undef SOLUTION_FOUND
#ifdef SOLUTION_MySolutionName1
     (some code specific to that solution)
     #define SOLUTION_FOUND
#endif
#ifdef SOLUTION_MySolutionName2
     (some code specific to that solution)
     #define SOLUTION_FOUND
#endif
#ifndef SOLUTION_FOUND
     #error None of the defined solutions were found. Build can not continue.
#endif

Wednesday, December 11, 2013

Source files missing from project, but still there (Linking error)

Situation: Some .cpp and .h files shared between several Visual Studio Project files in different VS solutions (I know - bad practice, but it was not my idea and I could not change it) were being relocated to a separate directory beside the solution dir of the project I was working on. By unloading the project in VS, then manually editing the .vcxproj file, it was a simple task to search and replace string entries like:

     ClCompile Include="folder\
with
     ClCompile Include="($SolutionDir)..\folder 

Since the job involved much more reorganizing, and there was a lot of other files in the project as well, it was not unexpected that several referencing and linker errors occurred along the way. 

Symptom: In the end I was faced with a linker problem I was not able to get rid of. LNK2001 and LNK2019 errors were filling my screen. I diffed the old and the new .vcxproj files to search for what I had lost along the way, but found no apparent problem at first. Not until I closely examined what reference the linker could not find, making sure that both a header entry and an implementation body (usually in a corresponding .cpp file) were actually present in the project. Somehow some of the files were not!

Problem: It turns out that for file references, the .vcxproj file simply ignores files written with MsBuild variable references like my ($SolutionDir)..\folder\file.cpp -They show up when you view the .vcxproj file in a text editor, but not from within Solution Explorer. Update: Seems like the MsBuild variable actually sometimes works (see the strikeout above), but not in the combination with double dots for jumping one step up in the folder hierarchy. Needs verification what conditions are for this problem to occur.


Solution: Once I had replaced the ($SolutionDir)..\folder entries in the .vcxproj file with the more boring and less flexible ..\..\folder, everything was fine.

Monday, November 25, 2013

Perforce: Translation of file content failed

This error practically introduced me to the Perforce version control system, and had no obvious explanation:

Scenario: I wanted to create a view of an existing file hierarchy containing many files on my local hard drive. As a part of the procedure, I executed the "Get latest revision". All but two files were transferred from the Perforce server, but two of the files logged the error "Translation of file content failed near line X". The file was missing when I looked at the physical location I was populating.

As many entries on the web mentions, encoding was the problem, but there are two places in P4V to set encoding - under Tools-Administration under Connections (which did not cut it for me), and:

Solution: Go to Connection-Choose Character Encoding and select the correct encoding.

I found the correct encoding by checking with a colleague who had it working. Otherwise: Trial and error will get you there (slowly).

Thursday, October 31, 2013

Backslash i Cord på norsk Mac

(How to get a backslash in Cord on a Mac with a norwegian keyboard layout - in Norwegian)

Tasten til høyre for ?-tasten gir deg backslash på norsk Mac.

Den kan iflg. mange nettfora nås via Alt-Shift-/ eller Alt-Shift-7, men dette fungerer ikke i fjernstyringsverktøyet Cord. I Cord er ofte backslash nødvendig for å få logget på et domene når man fjernstyrer en Windows-PC (man må typisk skrive domenenavn\brukernavn)

Sunday, October 6, 2013

Converting physical computer to virtual: Bluescreen

I have finally taken the leap and upgraded my trusty but painstakingly slow Windows Vista computer to Windows 8. I wanted to do a fresh install, but it is always nice to have a path back to using the old OS in case something goes wrong with the new installation. What better choice than doing a conversion of the physical Vista computer to a virtual one (a P2V)!

The free VMware vCenter Converter specializes in just that - it is an easy download and run application (the documentation is also good, but you won't really need it).

Caveat: Your only option is to do a full copy of your disk volume, which means you really need an extra disk drive of some kind (I used an external one) with at least the same amount of free space as the total capacity of your physical disk with all its partitions. It is fast however - a couple of hours was all it took to clone my 160 Gb drive - fully acceptable.

I went with all recommended/standard options and chose a VMware Workstation or other VMware virtual machine as the destination type, since I wanted VMware Player to handle the computer from inside my new Windows 8 after the installation.

Problem: The first conversion failed at around 96% with an error message stating that it could not update drive letters. However, the virtual disk and the .vmx file was already there, so I went ahead and tried to boot it from VMWare Player, making sure the network interfaces on the toolbar were all turned off to avoid the physical computer and the virtual one to find each other. Of course, the VM would not boot, but went into the bluescreen of death (BSOD) after the initial progress bars.

Cause/Solution: One of the recommended settings was to use SCSI as the virtual disk controller. On a second conversion attempt, I only changed this to IDE (corresponding to the physical controller in my computer). Another couple of hours later, my VM was ready and booted fine.

Wednesday, September 11, 2013

TFS 2012 authenticates trusted domain users, but not groups

I am configuring my first Team Foundation Server (TFS) 2012 in a domain we can call TFSdomain, that has a one-way trust to another domain where most users will access TFS from, let's call it the UserDomain. I tried to add UserDomain\Domain Admins to the Team Foundation Administrators group to let one of the group's users, UserDomain\Administrator have access to the TFS Web Administration. It did not allow access.

The UserDomain\Domain Admins is also a member of the local BUILTIN\Administrators which is a member of the Team Foundation Administrators group. This gives access to TFSdomain\Administrator, but not to UserDomain\Administrator.

I then added UserDomain\Administrator directly to the Team Foundation Administrators and tried again. Now I was allowed access as expected.

I then noticed the icon of the UserDomain\Administrator entry in the Team Foundation Administrators group. It shows the icon for a single user - not for a group. It is also not possible to see group members from the TFS Administration Console.


Have I discovered a bug in TFS 2012, or is there some other reason for this behavior?


Saturday, May 25, 2013

Language neutral Pin shortcut to Start Menu using C#

Problem: I needed a program that would automatically pin an existing shortcut on the desktop to the start menu, regardless what localization the Windows user was using. I was using Windows Server 2008 R2 with a couple of alternate languages to English installed for testing. The program was written in C#. I hit the wall a copule of times while trying to make c# code from an earlier implementation written in VB.NET - this is a summary of what I got to work in the end:
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
Object oShell = Activator.CreateInstance(shellAppType);
Shell32.Folder oFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, oShell, new object[] { 0 }); //25 = common desktop, 0 is local desktop
 


if (System.IO.File.Exists(ShortcutTarget) & (oFolder != null))
{
   Shell32.FolderItem oFolderItem = oFolder.ParseName("somefile.lnk");
   Shell32.ShellLinkObject oShellLink = (Shell32.ShellLinkObject)oFolderItem.GetLink;
   if (oShellLink != null)
   {
      // Find localized shell32 verb used to pin shortcut to the start menu (so that it works in any language)
      StringBuilder szPinToStartLocalized = new StringBuilder(MAX_PATH);
      IntPtr hShell32 = LoadLibrary("SHELL32");
      LoadString(hShell32, 5381, szPinToStartLocalized, MAX_PATH); // 5381 is the DLL index for "Pin to start menu", ref. http://www.win7dll.info/shell32_dll.html
      string localizedVerb = szPinToStartLocalized.ToString();

      foreach (Shell32.FolderItemVerb verb in oFolderItem.Verbs())
      {
         if (verb.Name == localizedVerb)
         {
            verb.DoIt();
            break;
         }
      }
   }
}


You need to reference Shell32 - i.e. Microsoft Shell Controls and Automation on the COM tab of your "Add reference" dialog in VS2010. Also make sure you copy the shell32.interop.dll along with your application when you move the application out of your bin folder.

The following problems were encountered and solved on the way:

BadImageFormatException when entering the method containing this code. The code worked well on a Windows Vista computer, but crashed when running on Server 2008 R2. I assume this happened because of the fact that Server 2008 R2 is a 64 bit OS, and this did not work well with using the unmanaged Shell32.
Solution: Change the target CPU of your application to x86. If you use VS2010 Express, this tip on StackOverflow may be helpful to you - Make sure to read all the answers if you are stuck.

InvokeVerb did not work. Before ending up using the line verb.DoIt(), I tried using oFolderItem.InvokeVerb(verb.Name), which used to work in an earlier VB.NET implementation of the same code. I have no explanation to why this did not work, but it did not. A conspiracy theory is that Nike paid them off to just do it...

By the way, this earlier post mentions a problem I encountered trying to do the same in VB.NET some time ago. It probably applies here too, which is why the top three lines of the code looks like they do.

Saturday, February 23, 2013

How MSBuild could make a file inparseable

Problem: A text file that was being parsed from an assembly being part of a developing system. In the developer environment, this worked great. After having deployed the text file and the necessary assemblies to a different location using MSBuild, where MSBuild also replaced a couple of strings inside the text file, parsing would no longer work.
  • Looking at the file in a text editor (i use Notepad++) confirmed that the edited version looked fine.
  • Editing the file in the developer environment manually (not running MSBuild on it) worked fine - the file was parseable afterwards.
Obviously, MSBuild made the file inparseable So how could MSBuild make the text file inparseable? The command touching the file was
<MSBuild.ExtensionPack.FileSystem.File 
     TaskAction="Replace" 
     RegExPattern="Something" Replacement="SomethingElse"
     Files="%(filename)"/>
Only when tracing the code parsing the file it became clear to me that the file now contained some extra characters at the beginning of the file. Then it occurred to me:

Solution: MSBuild changed the file encoding. To make sure MSBuild used the right encoding, I had to add one more key/value pair to the MSBuild tag mentioned above:
TextEncoding="Windows-1252"
I found this by inspecting the file encoding on the source and destination text files. My source file was reported as ANSI, whileas my destination file was reported as UTF-8. It was however not as simple as putting "ANSI" as the TextEncoding, as described in this excellent StackOverflow article, which also lead me on the right path to "Windows-1252".

In my opinion, MSBuild should have retained the original encoding on the files it touches instead of  defaulting it into something unwanted. But then again, that's wat keeps bread on my table... Thanks, MS...

Monday, November 12, 2012

Failing Office automation when run from a service

Scenario: I needed to create a small script to automate the conversion of a Word document into PDF. There's plenty of help out there to script this by using the Microsoft.Office.Interop namespace, for example this simple one. I tried both writing a Powershell script and a compiled C# .exe with the same result: When running from the desktop, everything works fine, whileas running from a scheduled task or from CruiseControl running as a system service failed. If CruiseControl was running from its debug console window however, everything ran fine.

Problem: It seemed clear that the Office libraries required a logged on session to run in, as  also Microsoft confirms here in their Q257757 article.

Solution/workaround: I came across this hack - reposting it here for my own easy access to the knowledge:
  1. Browse to or create this folder: C:\Windows\SysWOW64\config\systemprofile\Desktop on 64 bits Win7/Win2008 - for 32-bits Windows, substitute SysWOW64 part of the path with System32. You might have to change some permissions to get there and you of course need to have administrative rights.
  2. Make sure the user credentials running the service or scheduled task you want to use has full control access permissions to the folder.
I have no idea how this trick can make it all work, but it does - at least in my case. Since Microsoft does not recommend or describe it however - use solely at your own risk. Not suitable for rocket launchers, weapon systems etc..

Friday, June 8, 2012

"Could not find a part of the path" from MSBuild/CruiseControl.NET

This case turned out to be a no-brainer, but for my own (and others who may need it) later reference, here it is:
Scenario: I had set up a test environment for testing MSBuild targets run from CruiseControl.NET. The target I wanted to run was supposed to do simple file operations like copying and unzipping files to a specific disk letter, which in my test environment happened to be a subst to a folder on my local hard drive. Windows 7 64-bits with UAC (User Account Control) on was used, running CruiseControl.NET elevated to give it necessary privileges.
Problem: When running the MSBuild target itself, things worked like a dream. However, when running the target from CruiseControl.NET, it always grinded to a halt at the first attempt to copy/unzip data to my disk
Cause: This is the no-brainer: Since CruiseControl.NET ran with elevated privileges (i.e. started with "run as an administrator"), it did not see the substed drive I had set up from a non-elevated cmd window.
Solution: Simply start a cmd window elevated (run as administrator) and do the same subst from there, and voilla! - it works.

Sunday, March 4, 2012

SyncBack hang/freeze on Windows 7 - SMB version problem

Problem: SyncBack Free is a brilliant free tool for synchronizing two folders' contents fast and accurate. I had been using a Windows XP computer with two network cards standing as a bridge between two networks to sync folders between two computers residing on each side of the bridge. Old of age the XP computer were looking forward to its retirement as a young Win7 computer were set up to take over its place. The same SyncBack running the same SyncBack profile on the Win7 computer completely hung the SyncBack process within seconds after syncing was attempted. Only a reboot would kill the process - not even Task Manager managed to take it down.

Factors in the picture:
  • The two remote computers were running Win7  and Server 2008 R2.
  • Syncing between a local folder on the Win7 computer and one of the remote computers would work. Just not syncing between the two remote computers.
  • It made no difference whether Windows Shell (on the Copy/Delete tab) was used to sync or not.
  • Copying files between the remote computers from Windows explorer works just fine.
Problem reason: The reason proved to be SMB version. WinXP uses SMB 1.0, whileas Win7 uses SMB 2.0. For some reason, SyncBack does not manage to copy files between two remote computers as long as the computer is set up to use SMB 2.0.

Solution: Disable SMB v. 2.0, forcing the Win7 computer to revert to using SMB 1.0. This excellent article on Petri explains how - or here in short: From an administrative command line window run the following commands and then reboot to activate (Observe that "bowser" is actually correctly spelled - or rather, it is spelled the way that the computer understands):
sc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled
If you need to revert to SMB 2.0, use the following commands:
sc config lanmanworkstation depend= bowser/mrxsmb10/mrxsmb20/nsi
sc config mrxsmb20 start= auto 
I have not put any effort into researching whether security is an issue with these settings or whether other functionality is negatively affected, for me it gave me what I needed, so I am happy.

Friday, December 9, 2011

Administrator cannot change, delete or take ownership of file

Problem: It is well known that if a file is locked in Windows, an administrator can take control of the file by taking ownership of it, give himself permissions to write/delete it and then perform pretty much anything he needs to do with the file. Sometimes, however, you just receive an error message when you try to take ownership, even though you are an administrator, and even though the command prompt or Windows Explorer you are working from has been started by right-click - "Run as administrator"

Solution: Open Computer Management and open shared folders - open files. If the file in question is being held by someone that has opened the file over a fileshare, you first have to terminate their connection to the file before you can manipulate it. Of course, you should first make sure you are not disturbing any work they are doing on the file.

Tuesday, October 4, 2011

Cannot connect to any computer except DC

Problem: The only network traffic (ping etc.) that could pass in a Win7/Server 2008 R2 domain was from each client computer to the domain controller. No client computer could contact each other. Even the domain controller could not initiate contact towards a client computer.

Reason: In the Server 2008 R2 active directory domain organizational unit (OU), a Group Policy Object (GPO) had been created to disable the local client's firewall and allow any network traffic (which was ok from a security point of view, since the network was completely disconnected from anything outside). When applied, the firewall was indeed not started, but somehow the idea backfired by blocking all but those client computer connections made to the DC.

Solution: The Firewall service was reenabled in the GPO:
Policies-Windows Settings-Security Settings-System Services-Windows Firewall-Startup type=Automatic
Instead the Firewall setting was set to off for the domain profile (which is the active profile for computers within a domain):
Policies-Windows Settings-Security Settings-Windows Firewall with Advanced Security-Domain Profile Settings-Firewall state = off

It seems absolutely illogical to me that switching off the firewall service would block most network traffic. Maybe some special case in my domain caused it - nevertheless, there was no doubt that my changes were the solution to my problem - even proven by the fact that reversing them would lead to reintroducing the problem.

Saturday, September 10, 2011

PHP scripts stopped working when moved

Problem: After having moved some PHP scripts from one web server to another, they stopped working , or only worked partially. One of the webpages showed all the HTML and the upper part of PHP generated code, but strangely after a certain point the rest of the PHP code had just been ignored.

Solution: I loaded one of the script files in the open source DevPHP editor and chose Format on the menu. The Mac (CR) option was checked. I changed it to Windows (CRLF), uploaded the file again and reran it. Voilla, it worked!

Obviously, some PHP parsers may be more picky than others with how they read line breaks.

Monday, September 5, 2011

ODBC 32 vs. 64 bit

Scenario: I needed to connect 32 bit software running on a 64 bit Windows 7 OS to an SQL server via ODBC. Using a User DSN, everything was fine - setting up a System DSN instead, the application could no longer find it or and connect to the database. I preferred setting up a System DSN, so that any user logged on to the computer would be able to run the software without further hassle in setting up the needed ODBC connection.
Cause: An ODBC System DSN in 32 and 64 bit versions are two separate matters, hence a 32-bit application will not see a 64 bit ODBC System DSN and vice versa. User DSNs are however visible on both sides. Confusing.
Gotcha: Both the 64 and 32 bit version of the ODBC tool's is named odbcad32.exe. Hence, the Win7 standard method of writing this in the search field at the bottom of the start menu would always give you the 64 bit version. You have to run %windir%\syswow64\odbcad32.exe (for instance via the run dialog, keyboard shortcut winkey-r) to start the 32 bit ODBC application.
Reference: Microsoft's Knowledge Base article 942976

Tuesday, August 16, 2011

Cannot logon to newly installed SQL Server

Problem: After a fresh install of SQL Server 2008 R2 on a Windows 7 computer, where Windows user group BUILTIN\Administrators were given administrative rights, I was not able to log on to the database from Microsoft SQL Server Management Studio while logged on to Windows as a user who was a member of the Administrators group and thus should have been granted access. The error received was: Login failed for user 'COMPUTERNAME\user'. (Microsoft SQL Server, Error: 18456).

Solution: Turn off User Account Control, or if you prefer to leave it on, make sure you start SQL Server Management Studio as an administrator (right-click the icon and select Run as administrator).