Archive for the ‘WinAPI’ Category

Accessing Virtual Earth SOAP-API from C/C++ via gSOAP

Monday, April 27th, 2009

I wrote a small example application on how to access the Virtual Earth SOAP-API from a native C/C++ program.

You can find the sample and a description of all steps on MSDN Code Gallery

Here is the project:
Virtual Earth SOAP API with C/C++ via gSOAP

C++/CLI quiz: What is the exact callstack?

Saturday, April 18th, 2009

I have a small quiz:
Here is a small code, compiled with “/clr” (this is important).
Can you tell me, what is the exact callstack inside the method “Foo”?
(And how can you prove this)

struct V
{
  V() {}
  V(const V &v) 
  {
    this->i = v.i;
  }
  int i;
};
 
class C
{
public:
  void CallFoo()
  {
    V v;
    Foo(v);
  }
  virtual void Foo(V v)
  {
    // TODO: What is the callstack!?
  }
};
 
int main()
{
  C c;
  c.CallFoo();
}

Any hints can be posted as comments.
By the way: VS208 does not show you the exact callstack, but it gives you a hint, that there is something that you do not see ;)

Sharepoint Designer ist now free!

Thursday, April 2nd, 2009

The Office Sharepoint Designer 2007 is now a free download!

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=baa3ad86-bfc1-4bd4-9812-d9e710d44f42

WebService in native Code (WS-*)

Monday, March 30th, 2009

After the support for the SOAP-Toolkit was retired, there was no library from Microsoft, to write or consume Web-Services in native code. The suggested solution was to move to the .NET-SOAP classes. Of course, this is not always a solution, for big native code-bases.

It seems that MS has reflected this situation and also has found, that it is a “must have” to have a native WS-* library.

Starting with Windows 7 and Windoes Server 2008 R2, the OSwill have build-in support for native Web-Services.

The APIis called WWS-API (Windows Web Service API). To get an overview and also some examples, you can take a look at the code.msdn-Site.

Also, if you have an existing application and want to move to WWSAPI, you can join a virtual lab, to get help in implementing your web-service (either consuming or exposing).

EDIT:
Nikola added an comment, that WWSAPI will be also available on XP-SP2 and later! These are really great news!
You can already download the beta-bits, see:
Release of WWSAPI beta for Windows XP, Vista, Server 2003 and Server 2008

IE8 smashes Visual Studio 2005 / 2008 Class-Wizard

Sunday, March 29th, 2009

It seems that the new IE8 has some conflicts with Visual Studio 2008 (incl. SP1). After you installed IE8, you are not able to use the call-wizard for MFC projects anymore. It always gives you an error that there is a bug on the page:
Visual Studio 2008 bug after installing IE8

Currently there is a workaround, until a “real” fix is present:

  • Open regedit
  • Under HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Internet Settings \ Zones
    create a new key called 1000 (if it isn’t already there)
  • Under 1000, create a DWORD entry with:
    • Name = 1207
    • Type = REG_DWORD
    • Data = 0×000000

Visual Studio 2008 hotfix for IE8

You can also download the zipped reg-file.

Just for completeness: There is a connect entry since 9 days…

Addition: The problem also occurs with VS2005 (and maybe earlier versions ;) )

More infos is available from the VC-Teamblog.

Change of Win-API semantics via application manifest!

Wednesday, March 18th, 2009

Starting with Windows 7, the application manifest is becoming more and more important.

In Windows Vista, you need a manifest to bypass the application virtualization. In Window 7, you need a specific application compatibility-manifest to get correct API function behaviour ;)
For example, a race condition in GetOverlappedResult is only solved, if you explicit specify in your manifest, that you want a correct behaviour of this function.
Also a bug in CreateFileEx is only solved if you specify this in your manifest.

Of course, this is in general not a bad idea. But the manifest only allows to enable all new features or nothing. There is no way to exlicit enable only one of the bugfixes.

Here is just a small document of the “Windows 7 - Application Manifests - Compatibility”.

Windows Communication Protocols

Friday, March 13th, 2009

Microsoft is publishing many of their “closed” protocols on the internet.
The starting site is: Microsoft Protocol Programs and Open Specifications.

Here is just a small list of available protocol downloads:

Building vcproj-Files with msbuild

Thursday, March 12th, 2009

If you want to batch-build VC++ projects you can either use devenv or msbuild.
msbuild has many option in which you can change and log the build process.

Here is just a example of a simple .proj-template for starting of batch-builds with msbuild:

<Project 
  DefaultTargets="Rebuild" 
  ToolsVersion="2.0" 
  Verbosity="detailed" 
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 
  <ItemGroup> 
    <Project Include="Project1Directory\Project1.vcproj" /> 
    <Project Include="Project2Directory\Project2.vcproj" /> 
    <!-- and so on --> 
  </ItemGroup> 
  <Target Name="Rebuild"> 
    <VCBuild 
      Projects="@(Project)" 
      Configuration="Debug|Win32" 
      Rebuild="true" 
      ContinueOnError="false" 
    /> 
    <VCBuild 
      Projects="@(Project)" 
      Configuration="Release|Win32" 
      Rebuild="true" 
      ContinueOnError="false" 
    /> 
  </Target> 
  <Target Name="Build"> 
    <VCBuild 
      Projects="@(Project)" 
      Configuration="Debug|Win32" 
      ContinueOnError="false" 
    /> 
    <VCBuild 
      Projects="@(Project)" 
      Configuration="Release|Win32" 
      ContinueOnError="false" 
    /> 
  </Target> 
  <Target Name="Clean"> 
    <VCBuild 
      Projects="@(Project)" 
      Configuration="Debug|Win32" 
      Clean="true" 
      ContinueOnError="false" 
    /> 
    <VCBuild 
      Projects="@(Project)" 
      Configuration="Release|Win32" 
      Clean="true" 
      ContinueOnError="false" 
    /> 
  </Target> 
</Project>

You need just to save this file with the extension .proj” and call “msbuild” from the same directory. It will then do a “Rebuild” (see “DefaultTargets”).
Or you can do a “Clean” with “msbuild /t:Clean”.
You can also log to a file with “msbuild /v:d /fileLogger”.
Also, if you do not need a specific build-order of your projects, you can just include every vcproj-File in your subfolders by changing

  <ItemGroup> 
    <Project Include="Project1Directory\Project1.vcproj" /> 
    <Project Include="Project2Directory\Project2.vcproj" /> 
    <!-- and so on --> 
  </ItemGroup>

to

  <ItemGroup> 
    <Project Include="**\*.vcproj" /> 
  </ItemGroup>

Also, msbuild returns 0 if the build was sucessfull, otherwise “1″. So you can determine the result of the build in your batch-files.

So you can see: msbuild is very powerfull…

All-in-One Code Framework

Thursday, March 12th, 2009

If you need examples of some of the current Microsoft technologies, you have many technologies and programming languages available. For each of these technologies/languages you need to find a fitting example.

On CodePlex there is now an example-collection for most of the available technologies (COM, ActiveX-Control, ActiveX-Host, ADO, ADO.NET, Outlook-Customizing, DLL, DLL-delay-loaded, LIB, P/Invoke, CLR-hosting / named-pipes, mailslots, shared-memory, remoting) and programming languages (C/C++ (native / MFC / ATL) / C# / VB.NET):

Check out: All-In-One Code Framework

Windows 7 Beta UAC “improvements”

Wednesday, January 21st, 2009

In the Windows 7 Beta 1, there is a new “feature” in UAC (User Account Control). This new feature seems to help reduce UAC-Dialogs in specific situations, by selecting one of the follwing settings:

  • Always notify on every system change (seems to be the Vista-Style
  • Notify me only when programs try to make changes to my computer.
  • Notify me only when programs try to make changes to my computer, without using the Secure Desktop.
  • Never notify.

This sound really great!
But after looking at this, I thought: How the hell did they implement this? Will there be a list of APIs which are “safe-to-call” in one of the settings?

But after reading this answer from an MS guy in the kernel newsgroup, I could not laugh anymore…
This solution only accepts changed from MS applications!
This solution is one of the the worsts solution and might lead to some work for lawyers… but I hope that this is only a beta feature and will either be removed or opened for other (signed) apps.

I will wait and see…

Writing MiniDumps in C#

Saturday, December 13th, 2008

After creating my previous post (MiniDump support in .NET4), I tried to figure out how to write minidumps (MiniDumpWriteDump) without needing unmanaged code. I could not find any example… so I wrote one (which also works for x86 and x64/IA64).
Here is the example:
MiniDumpWriteDump direct from C# for x86 and x64/IA64.

VS2008 Service Pack 1 is available!

Monday, August 11th, 2008

Today, the first service pack for Visual Studio 2008 has shipped:
http://www.microsoft.com/downloads/details.aspx?FamilyID=27673c47-b3b5-4c67-bd99-84e525b5ce61&displaylang=en

But it seems that the installer is not very user-friendly:

If you previously installed a Visual Studio 2008 Hotfix, you must run the Hotfix Cleanup Utility before installing Visual Studio 2008 SP1. For more information, see Visual Studio 2008 Hotfix Cleanup Utility for Installing Visual Studio 2008 SP1.

Also, the KB article with the list of all fixes is not yet updated:
http://support.microsoft.com/kb/945140/en-us

Hopefully this SP will fix many bugs ;)

Main disadvantage of (really) AppLocal deployment

Monday, May 5th, 2008

In my last post I described how to (really) deploy CRT/MFC DLLs into the same directory as the application (xcopy deployment).

“Really” means, that it will never load any DLLs installed in the WinSxS directory. This is archived by removing the “publicKeyToken” from the manifest. If you leave the “publicKeyToken” inside the manifest, then it will force loading of (possibly) installed WinSxS versions (and updates/redirections).

The option of really AppLocal installations are not explaind on any Microsoft side (or at least I could not find it). Only the “normal” (semi) AppLocal installation is (a little bit) explaind, for example here:
Visual C++ Libraries DLL Deployment.

One of the main reasons for this is the new focus from Mircosoft to Security.

The main disadvantage of really AppLocal installations is, that Microsoft is not able to update or patch your installation (or better the CRT/MFC components of your installation). And this sees to be anathema to Microsoft.
The same is also true for static linked applications.

So I fear, that Microsoft will

  • remove or deprecate static linking in the next version of VS
  • remove the possibility to really AppLocal installations in the next OS /MFC/CRT DLLs

Hopefully, this will not come true…

Howto: Deploy VC2008 apps without installing vcredist_x86.exe

Saturday, May 3rd, 2008

There are several reasons for xcopy deployment of an application (also known as application local). One main reason is that you are independent of what the target computer has installed.
Also your application always uses the “correct” (or better: tested) version of DLLs, regardless of what MS installed or updated (see: .NET2 SP1 update breaks old apps!?).

The easiest way to overcome the problem is to link static against the CRT/MFC. But in some scenarios this is not an option and not possible.

But to be independent from OS updates or from vcredist_x86.exe installations of other apps, you need to do the following steps:

  • Remove the auto-generation of manifests (from all DLLs) and change the manifest generation form your EXE to an external manifest; you can do this by choosing: Project|Properties|Configuration Properties|Manifest Tool|Input and Output|Embed Manifest: No
  • Recompile your application and modify the external manifest as follows:
  • Copy your application and the external manifest to your deployment directory
  • Open the manifest-file (appname.exe.manifest) and remove the “publicKeyToken” from all MFC/CRT/ATL/OpenMP entries. Please leave the publicKeyToken to the “Microsoft.Windows.Common-Controls” entry.
  • Copy all neccessary directories under %ProgramFiles%\Microsoft Visual Studio 9.0\VC\redist\x86 to your deployment directory
  • In all sub-directories (Microsoft.VC90.CRT, optional: Microsoft.VC90.MFC, Microsoft.VC90.ATL, Microsoft.VC90.OPENMP, Microsoft.VC90.MFCLOC) open the manifest-file and also remove the publicKeyToken
  • Also lookup the version info from these manifest files and correct the version-info of the corresponding entries in your application manifest file
  • Save all manifests and let your program run; it should now run on all supported OS without installing anything…

After doing all these manifest stuff you can also embed the manifest into your application (EXE). And of course: The same can be done with x64 and IA64 apps.

I have made an example of the default MFC app (4.6 MB) for reference.

The (simple) manifests for the new MFC feature pack and the application looks like:

Application.exe.manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
      </requestedPrivileges>
    </security>
  </trustInfo>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.30411.0" processorArchitecture="x86"></assemblyIdentity>
    </dependentAssembly>
  </dependency>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.30411.0" processorArchitecture="x86"></assemblyIdentity>
    </dependentAssembly>
  </dependency>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="x86" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity>
    </dependentAssembly>
  </dependency>
</assembly>

Microsoft.VC90.CRT.manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <noInheritable />
    <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.30411.0" processorArchitecture="x86" />
    <file name="msvcr90.dll" /> 
    <file name="msvcp90.dll" /> 
    <file name="msvcm90.dll" />
</assembly>

Microsoft.VC90.MFC.manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
    <noInheritable />
    <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.30411.0" processorArchitecture="x86" />
    <file name="mfc90.dll" /> 
    <file name="mfc90u.dll" /> 
    <file name="mfcm90.dll" /> 
    <file name="mfcm90u.dll" />
</assembly>

Instead of putting the “Microsoft.VC90.MFC” and “Microsoft.VC90.CRT” directories into the application folder, you can also just put the files from these folders into the application directory. The main advantage is, that your app will also work on W2k-SP4.

Here is also my older post for VS2005.

Available hotfixes for VC2005-SP1 / VC2008 RTM / VC2008-SP1

Wednesday, April 30th, 2008

There are already several hotfixes available for VC2005 SP1 and VC2008 RTM. Here is a short overview:

Updated: 2008-11-06
Updated: 2009-03-09
Updated: 2009-03-13
Updated: 2009-03-18
Updated: 2009-05-08
Updated: 2009-05-13
Updated: 2009-05-23
Updated: 2009-10-06

MFCNext / VS2008 VC++ Feature Pack is RTM

Monday, April 7th, 2008

The feature Pack for VC++ 2008 is now available for download.

It is some kind of confusing:
You can download the feature Pack for the englisch version only (ENU)!

If you have installed a localized version of VS (e.g. german), you must wait until the release of SP1. Hopefully the ENU-SP1 will also include the Feature Pack…

If you have a non-english OS the installation will fail! You need to change the system-language and formats to “en-us” and re-run the installation… this is a typically US bug…

Also one note: If you want to use the new Ribbon UI (Office 2007 UI, also known as Fluent UI), you must agree to the Office 2007 license!

Here are the links:
Download-Site
Direct download link
Redistributable package (x86)
Docu: MFC Feature Pack
Docu: TR1 Extensions

Just upgrade to VS2008! Even without an existing license!

Friday, April 4th, 2008

According to the Microsoft Website Visual Studio 2008 Pricing there is no need to buy the full product. You can always buy the upgrade for VS2008 Standard or Professional if you have:

  • An earlier version of Microsoft Visual Studio
  • Any other developer tool (including free developer tools, such as Visual Studio Express Editions or Eclipse)

That looks interesting! So, download the express edition, then you can buy the upgrade version of VS2008!

I just made a copy of the page to be sure, that if MS removes this sentense in the future, I have a copy to witness:
VisualStudio2008Pricing_2008-04-04.xps

Unhandled exceptions in VC8 and above… for x86 and x64

Wednesday, April 2nd, 2008

Starting with VC8 (VS2005) it is not possible to catch all unhandled exceptions with your installed exception-filter (via SetUnhandledExceptionFilter). In some situations, the CRT forces the call of WER (Windows Error Reporting). One situation (/GS buffer overruns) can never be catched in your filter. If you want to catch all exception inside your filter, you need to intercept calls to SetUnhandledExceptionFilter to prevent the removing of all previous installed filters.

See also my previous post about this problem:
“SetUnhandledExceptionFilter” and VC8″

Here is the code to “hook” the SetUnhandledExceptionFilter which works now for x86 and x64:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
 
#if defined _M_X64 || defined _M_IX86
LPTOP_LEVEL_EXCEPTION_FILTER WINAPI 
  MyDummySetUnhandledExceptionFilter(
  LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter)
{
  return NULL;
}
#else
#error "This code works only for x86 and x64!"
#endif
 
BOOL PreventSetUnhandledExceptionFilter()
{
  HMODULE hKernel32 = LoadLibrary(_T("kernel32.dll"));
  if (hKernel32 == NULL) return FALSE;
  void *pOrgEntry = GetProcAddress(hKernel32, 
    "SetUnhandledExceptionFilter");
  if(pOrgEntry == NULL) return FALSE;
 
  DWORD dwOldProtect = 0;
  SIZE_T jmpSize = 5;
#ifdef _M_X64
  jmpSize = 13;
#endif
  BOOL bProt = VirtualProtect(pOrgEntry, jmpSize, 
    PAGE_EXECUTE_READWRITE, &dwOldProtect);
  BYTE newJump[20];
  void *pNewFunc = &MyDummySetUnhandledExceptionFilter;
#ifdef _M_IX86
  DWORD dwOrgEntryAddr = (DWORD) pOrgEntry;
  dwOrgEntryAddr += jmpSize; // add 5 for 5 op-codes for jmp rel32
  DWORD dwNewEntryAddr = (DWORD) pNewFunc;
  DWORD dwRelativeAddr = dwNewEntryAddr - dwOrgEntryAddr;
  // JMP rel32: Jump near, relative, displacement relative to next instruction.
  newJump[0] = 0xE9;  // JMP rel32
  memcpy(&newJump[1], &dwRelativeAddr, sizeof(pNewFunc));
#elif _M_X64
  // We must use R10 or R11, because these are "scratch" registers 
  // which need not to be preserved accross function calls
  // For more info see: Register Usage for x64 64-Bit
  // http://msdn.microsoft.com/en-us/library/ms794547.aspx
  // Thanks to Matthew Smith!!!
  newJump[0] = 0x49;  // MOV R11, ...
  newJump[1] = 0xBB;  // ...
  memcpy(&newJump[2], &pNewFunc, sizeof (pNewFunc));
  //pCur += sizeof (ULONG_PTR);
  newJump[10] = 0x41;  // JMP R11, ...
  newJump[11] = 0xFF;  // ...
  newJump[12] = 0xE3;  // ...
#endif
  SIZE_T bytesWritten;
  BOOL bRet = WriteProcessMemory(GetCurrentProcess(),
    pOrgEntry, newJump, jmpSize, &bytesWritten);
 
  if (bProt != FALSE)
  {
    DWORD dwBuf;
    VirtualProtect(pOrgEntry, jmpSize, dwOldProtect, &dwBuf);
  }
  return bRet;
}
 
LONG WINAPI MyUnhandledExceptionFilter(
struct _EXCEPTION_POINTERS *lpTopLevelExceptionFilter)
{
  // TODO: MiniDumpWriteDump
  FatalAppExit(0, _T("Unhandled Exception occured!"));
  return EXCEPTION_CONTINUE_SEARCH;
}
 
int _tmain()
{
  SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);
  BOOL bRet = PreventSetUnhandledExceptionFilter();
  _tprintf(_T("Prevented: %d"), bRet);
 
  abort();  // force Dr.Watson in release!
}

Screencast: API Logging with the Application Compatibility Layer

Thursday, March 6th, 2008

Hi all!

Today I did a screencast on how to use the application compatibility layer (and especially the APILogger shim) to do API logging.

This is a very interesting screencast if you want to log and display API calls of other programs in a very nice and simple way.

So enjoy (14:59 min):
http://www.kalmbach-software.de/screencasts/UsingAPILogger

Here are also the links which are shown in the presentation:

Screencast: Static link to the C-Runtime to prevent vcredist and overcome “Application configuration” problems

Monday, March 3rd, 2008

Here is a short screencast which shows how to adjust the project settings to link against the static C-runtime (CRT).

This prevents that you must ship the CRT-DLLs with your application. Your application just works after copying the exe to the target computer.

This is a “german” screencast:

http://www.kalmbach-software.de/screencasts/VC2008EE-StaticLinkCRT/