Programming‎ > ‎

VisualStudio

Visual Studio Tips

Here are Visual Studio tips and VS specific programming tips.

Updated: 1/20/2020

Index


How can I set the installer icon in vdproj?

After creating the msi installer with vdproj, I could not find any property to set the icon appears in "Programs and Features" in Control Panel. It turns out that vdproj has "ARPPRODUCTICON" in "PRODUCT" section. The default is "ARPPRODUCTICON" = "8:". Since you added an icon for your application, just search "ICON" = "8:..." in the vdproj. Copy it to replace "8:" to "8:...".

Top


How to fix signtool error "Store IsDiskFile() failed"?

the path to the certificate must be relative to the installer output path, not the current working directory. What a bummer!

Top


How can I copy a project and have different name?

Sometimes you want to copy a project with a different name and namespace.Here is how.

  
  1. Copy the directory and remove version control files (*.vspscc etc.).  
  2. Rename the csproj to your liking.  
  3. Edit csproj tag <RootNamespace> which specifies anything you add to use this namespace.  
  4. Edit csproj tag <AssemblyName> which specifies the name of the compiled assembly.
  

Top


How can I resolve the issue "Unable to start debugging"?

While working on a 64 bit application under VS2010, I got the error saying Error while trying to run project: Unable to start debugging.The Microsoft Visual Studio Remote Debugging Monitor has been closed on the remote machine. The reason why it talks about the remote debugging monitor is that Visual Studio 2010 is a 32 bit app and thus in order to debug a 64 bit app, it has to use a remote debugging monitor. I don't know why this happened but you just restart the visual studio to fix this problem.

Top


How can I have data file for unit test?

I needed the data file for unit tests and I added it to the project with properties to be Build Action : Embedded Resource and Copy to Output Directory: Copy Always. By doing so, the unit test output directory has the data. I thought thatAssembly.GetExecutingAssembly().Location will give me the location. That is true only under Debugging a particular unit test item. When I ran the entire unit tests, Assembly.GetExectingAssembly().Location points to TestResults\(...)\Out directory. Unfortunately the data was not copied. In order to make a copy of the data into Out directory, you have to do the following:

 
  1. Right click on Solution Items → Local.testsettings and Open it. 
  2. Test Settigs dialog. Click on Deployment.  Check Enable deployment. 
  3. Add Files ...
  

Top


How can I pass the linker option to CL

When I was working on compiling an opensource which uses nmake to build, I needed to pass the libpath to cl.exe. Note that LIB command takes /LIBPATH:(dir). Here is how

  
  cl -I (include directory) /link -LIBPATH:(lib directory)
  

Top


How can I do Concurrency Profiling under VS2010?

Under VS2010 higher version (> Professional), you find a menu "Analyze" which contains "Launch Performance Wizard ...". When I tried Concurrency profiling, I was told that user mode events are lost. Unfortunately the message is not clear about what to do. Here is how to modify the registry. If you have done the edit correctly, then you get

  
  Profiling started.  
  Profiling process ID 1672 (FibRWS).  
  Warning VSP1530: Reading ETW configuration from the registry.  
  <<<<<<<< 
  see this after modifying registry  ...
  
You may want to read here. Note that Monitor\EtwConfig key does not exist asdefault.
 
  Create a registry key at HKCU\SOFTWARE\Microsoft\VisualStudio\10.0\VSPerf\Monitor\EtwConfig,  
  with the following DWORD entries in decimal. 
  Start with values shown here:    
  FlushTimer 0    BufferSize 256    MinBuffers 512    MaxBuffers 1024
  After these setting, I was able to get concurrency profiling worked.
  

Top


How can I get the Solution Configuration combobox in the toolbar?

When I was showing the project to the newbie, his VisualStudio toolbar did not have the solution configuration and the solution platform combobox. I had a hard time finding what I should do his Visual Studio. Here is how:

  
  Menu → Tools → Customize → Commands   
  Select "Toolbar" radio button  
  Select "Standard" in the list box.  
  Select the location in the Controls box you want to insert the command  
  Press "Add Command ..." button.  
  Select Categories → Build  
  Move the scrollbar on the right to the bottom  
  Select "Solution Configuration" and press OK.  
  Do it again for "Solution Platforms" and press OK
  

Top


How can I start emacs with VS environment?

When I started learning about CUDA(CUDA BY EXAMPLE by J. Sanders and E. Kandrot), samples are compiled with cl.exe. In order to do this, I had to run vcvars32.bat. I usually look at the source code with emacs and I wanted to compile the program from emacs. Here is what I did:

  
  1. I created a short cut with Target as     
     %comspec% /c c:\Users\ytosa\AppData\Roaming\emacs.bat  
  2. I edited emacs.bat referred in 1 as     
     "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" amd64      
	 & "C:\Program Files (x86)\emacs\emacs-23.2\bin\runemacs.exe"
  
Note that nvcc does not accept Visual Studio 10 version of cl.exe and thus I have to use VS9 version of cl.exe.You can now compile CUDA sample in emacs: M-x compile with nvcc sample.cu -o sample.

Top


How can I fix the VS2010 setup project error 'The target version of the .NET framework in the project does not match'?

I had a setup project under VS2009 and get the error under VS2010. The exact message is : WARNING: The target version of the .NET Framework in the project does not match the .NET Framework launch condition version '3.5.30729'. Update the version of the .NET Framework launch condition to match the target version of the.NET Framework in the Advanced Compile Options Dialog Box (VB) or the Application Page (C#, F#). I googled and found http://allen-conway-dotnet.blogspot.com/2010/07/help-my-net-setup-package-is-throwing.html. In order to fix this warning, you do the following:

   
  1. Open the tree for the Detected Dependencies.   
  2. Double Click on Microsoft .NET Framework.   
  3. On the right handside, you get Launch Conditions tab.   
  4. Right click on .NET Framework and get Properies.   
  5. Change Version to .NET Framework 4 (or 4 Client Framework).
  

Top


How can I fix VS2010 compiler error:Interop type XXX cannot be embedded?

We were porting VS2008 .NET libraries to VS2010 and we encountered a strange error:Interop type XXX cannot be embedded. Use the applicable interface instread. This message is confusing, since VS2008 had no issue. I googled the message and found the solution http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx. Our code were tries to instantiate a COM object. Here is the portion of the explanation.

  
  Typically, to change your code to use an interface type instead of a class type you just need   
  to remove the 'Class' suffix and compile the code! Another way to find what the applicable   
  interface is - look at the definition of the class type. The class usually derives from one   
  or more interfaces. Look at the definition of each interface - one of them will have CoClass  
  attribute and this is the interface that you are looking for.
  

Top


Where can I find a lookup table for HRESULT value?

In case you don't have VS handy, then go to the internet: http://blogs.msdn.com/b/eldar/archive/2007/04/03/a-lot-of-hresult-codes.aspx

Top


How can I enable "show all files" in Solution Explorer?

Solution Explorer as default does not show all items in the tree view. In particular, I want to see what are contained in the Service Reference item I just added. You need to click the 2nd toolbar button on the Service Explorer. Here is the result of clicking.


Top


Why is the compiler not able to find Windows SDK directory?

If WindowsSDKDir environmental variable is not set, then vcvars32.bat tries the following:

  
  :GetWindowsSdkDir  
  @call :GetWindowsSdkDirHelper HKLM > nul 2>&1  
  @if errorlevel 1 call :GetWindowsSdkDirHelper HKCU > nul 2>&1  
  @if errorlevel 1 set WindowsSdkDir=%VCINSTALLDIR%\PlatformSDK\  
  @exit /B 0  :GetWindowsSdkDirHelper  
  @for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\Microsoft SDKs\Windows" /v "CurrentInstallFolder"') 
   DO ( if "%%i"=="CurrentInstallFolder" (	 SET "WindowsSdkDir=%%k" )  )  
  @if "%WindowsSdkDir%"=="" exit /B 1  @exit /B 0
  
Note that it requires the execution of reg query. If you do not have right to execute the command, it will default to %VCINSTALLDIR%\PlatformSDK\ which does not exist under Visual Studio 9.0. Thus all include and lib for WindowsSDK will not be available to you. One way to avoid is to run Visual Studio "run as administrator" trick.

Top


How can I use TFS under Explorer?

If you have used TortoiseSVN, it is integrated into Explorer. I'm now working under Team Foundation Server and I was missing that feature. It turned out that it is available as a Microsoft Team Foundation Server 2008 Power Tools. Note that there is a version for VS2005. Make sure that you download the version for VS2008(Both have the same name).You can download it from here.

Top


How can I create a 64bit Setup project for my 64 bit application?

I had a 32bit/64bit project and created a setup project. It turned out that the property for the setup project Platform is greyed out and N/A, even after selecting .NET framework 3.5. (Microsoft says that .NET framework 2.0 is 32 bit only). Thanks to Mario, there is a simple solution. In vdproj, modify TargetPlatform to 3:1.


  Step 1.    
  "TargetPlatform" = "3:0" should be changed to    
  "TargetPlatform" = "3:1"
  Step 2. 
  Right Click on "Application Folder" icon and then Properties Modify DefaultLocation 
  [ProgramFilesFolder]
  ... 
  to 
  [ProgramFiles64Folder]  
  ...
  

Top


How can I change the Team Foundation Server checkout local path?

I wanted to change the local directoroy for checkouts under the TFS. It is hidden.File → Source Control → Workspace → Choose to pick the workspace and click Edit for local path.

Top


How can I identify where I leaked memory in C++?

You sometimes get the following:


  Detected memory leaks!{77} normal block at 0x00374A28, 27 bytes long. 
  Data: <           > CD CD CD ... 
  CDObject dump complete
  
Unfortunately this does not tell me where I leaked memory. Fortunately there is a way to find out where I leaked memory.

You have to handle "malloc" and "new" separately.


  /////////////////////////////////// 
  // Memory Leak Location Detect
  ///////////////////////////////////
  #include "stdafx.h"
  // replace malloc and free with detailed one
  //////////////////////////////////////////////
  #define _CRTDBG_MAP_ALLOC
  #include <crtdbg.h>
  // replace new with more info new
  //////////////////////////////////////////////
  #ifdef _DEBUG
  #define new  new(_NORMAL_BLOCK, __FILE__, __LINE__)
  #endif
  void setDbg(int flag){
  #ifdef _DEBUG  
  int nFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);  
  // clear flag  
  nFlag &= ~(_CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_DELAY_FREE_MEM_DF  | _CRTDBG_LEAK_CHECK_DF             
              | _CRTDBG_CHECK_EVERY_16_DF | _CRTDBG_CHECK_EVERY_128_DF | _CRTDBG_CHECK_EVERY_1024_DF);  
  nFlag |= flag;  
  _CrtSetDbgFlag(nFlag);
  #endif
  }
  
  int _tmain(int argc, _TCHAR* argv[])
  {  
    // memory leak detect  //////////////////////////////////  
	setDbg(_CRTDBG_LEAK_CHECK_DF );  
	char *p2 = (char *) malloc(27);  
	char *p1 = new char[100];  
	return 0;
  }
  

Then, you get the file and the location:


  Detected memory leaks!Dumping objects ->f:\cpp\checkmem\checkmem\checkmem.cpp(29) : 
  {78} normal block at 0x00374A80, 100 bytes long. Data: <                
  > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
  f:\cpp\checkmem\checkmem\checkmem.cpp(28) : 
  {77} normal block at 0x00374A28, 27 bytes long. Data: <                
  > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
  Object dump complete.
  The program '[1048] checkMem.exe: Native' has exited with code 0 (0x0).
  

Here is another way, using CRT source which comes with Vistual Studio.


  0.  Make sure that your memory leak is repeatable at some specific value:    
      Here is the sample memory leak:   
	  Detected memory leaks!   Dumping objects ->   {190} normal block at 0x0199E2A0, 4120 bytes long.    
	  Data: <        P o     > 00 00 00 00 00 00 00 00 50 7F 6F 01 00 00 00 00   
	  Object dump complete.
	  Here (190) is the critical value. It points to the 190th memory allocation caused the leak.
	  In Windows applications, this number may not be repeatable.  The following is only applicable 
	  when this number is repeatable.
  1. In Visual Studio 8 IDE, you load your project.
  2. Open File -> C:\Program Files\Microsoft Visual Studio 8\Vc\crt\src\dbgheap.c
  3. First set a break point in _heap_alloc_dbg(...)  
	 Here--->           
	 if (_crtBreakAlloc != -1L && lRequest == _crtBreakAlloc)                               
	   _CrtDbgBreak();
  4. Run your program.   It will break at the line.   Now you change the value of _crtBreakAlloc to the   
     value you found.   In the case above,  you use the watch list window to set _crtBreakAlloc to 190.
  5. Remove the break point we set and let it run.   
	 When lRequest == _crtBreakAlloc, it will break.
  6. Use your Call Stack window to locate who allocated the memory.
  

Top


How can I detect memory corruption in C++?

This is a variation of the memory leak case. In the case of memory leak, we set up _CRTDBG_LEAK_CHECK flag. Here we enable _CRTDBG_ALLOC_MEM_DF and _CRTDBG_CHECK_ALWAYS_DF (or variants EVERY_16_DF, EVERY_128_DF, EVERY_1024). The following code causes Unhandled exception in _CrtCheckMemory():


  // include all the portion above _tmain() here from the memory leak section...
  int _tmain(int argc, _TCHAR* argv[])
  {  
    // memory leak detect  
	setDbg(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF);  
	char *p = (char *) malloc(10);  
	p[10] = 'a';  
	free(p);         
	// assertion occurs here
  }
  

Top


How can I build many projects at once?

I end up accumulate many solutions/projects in my work and I wanted to buid all of them at once. It turned out that there is a command linetool called devenv is available for this purpose. The following is the step to do this.


  1. New → New Project → Blank Solutions.   I named this solution as BuildAll.
  2. In Solution Explorere, right-click on Solution 'BuildAll'. 
     Under this new solution, Add → Add Existing Projects.
     You pick *.vcproj.  Repeat this procedure to add the projects you want.
  3. Again right-click on Solution 'BuildAll' and set Project Dependencies ...   
     and Project Build Order ....
  
Now the solution BuildAll is ready to be built by command line. Open a Command Prompt window and issue the following:
    
  devenv BuildAll.sln /rebuild Debug  devenv BuildAll.sln /rebuild Release
  
will build Debug and Release versions. Note that you may have to name the solution by an explicit pathname, including the directory.

Top


How can I schedule the build every day?

Teh previous item allows me to build all the projects I have.Now I like to schedule the build every day. Here is how.


  1. Start → All Programs → Accessories → System Tools → Scheduled Task.
  2. Click Add Scheduled Task.  You get Scheduled Task Wizard.
  3. Write a batch file or shell script
     Note that devenv returns at the end the following line and thus
	 you can tell whether it suceeded or not.
	 ---------------------- Done ----------------------
	 Rebuild All: 8 succeeded, 0 failed, 0 skipped
  4. You select this batch file or shell script
  5. You get the following
  
  
  
Here is the good Batch file command site http://www.allenware.com/icsw/icswidx.htm.

Top


How can I have tstring like TCHAR?

The following can be used for both UNICODE and MBCS:

  
  typedef std::basic_string<TCHAR> tstring;  
  typedef std::basic_stringstream<TCHAR> tstringstream;
  

Top


How can I turn off optimization of a function?

Usually the optimization is set to your entire solution. Sometimes you want to make the part of the code optimization off.Here is how.

  
  #pragma optimize("gt", off)  
  ... (region of code)  
  #pragma optimize("", on)
  

Top


How can I remove WinCE SDK and drivers?

I got the error message saying that WinCE emulator driver (VPCAppSv.sys) running on WinXP SP2 is disabled. This is due to the fact that AMD64 has Data Execution Prevention (DEP) feature for which WinXP automatically enables Physical Address Extension mode.according to Microsoft page. Unfortunately Visual Studio .NET 2003 installs CompactFramework SDK which includes this driver. In order not to get thiserror message popup, it is easiest to remove this framework.

  
  1. Add or Remove Program in Control Panel  
  2. Select Microsoft Visual Studio .NET 2003  
  3. Select Option 2 in Visual Studio .NET Setup  
  4. Select Add or Remove Features  
  5. Select Language Tools  
  6. Select Visual Basic .NET  
  7. Uncheck Smart Device Programmability  
  8. Select Visual C# .NET  
  9. Uncheck Smart Device Programmability 
  10. Select Setup
  
I was wrong. This does not work. I still got it.

Top


How can I set x64 environment?

I'm used to run C:\Program Files\Microsoft Visual Studio 8\common7\Tools\vsvars32.bat, which is customized on the pc from vcvars.txt in the same directory or c:\Program Files\Microsoft Visual Studio 8\VC\bin\vcvars32.bat. I was looking for a similar one for x64 on a Win64 or Server 2003 (64bit) or Vista 64 OS. The name is c:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\amd64\vcvarsamd64.bat. Actually you have more choices on 64 OSes in that you can compile x86 and x64code using


  On a 64 bit OS,  
  %comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 8\VC\vcvarsall.bat"" choice
  On a 32 bit OS,  
  %comspec% /k ""C:\Program Files\Microsoft Visual Studio 8\VC\vcvarsall.bat"" choice
  where  choice = x86, amd64(or x64), ia64, x86_amd64, or x86_ia64
  
Here you can use amd64 or x64 interchangeably. The option ia64 is for Itanium. The choice x86_amd64 is for cross-compilation on x86 platform.

Top


How can I turn off autosave option?

Somehow VS2005 takes long long time to run autosave information.I could not stand waiting for more than one minute and thus looked for a way to turn it off. Here is how:

   
  Tools → Environment → AutoRecover    
  Uncheck Save AutoRecover information every ...
  

Top


How can I find out the appname from ProcID?

I wanted to find out the process name using process ID which is shown in Dbgview. Visual Studio Help now only lists .NET routines. Here is the Win32 equivalent. You must link with psapi.lib

  
  #include <psapi.h>  
  ...  
  // you must do "delete []" after the use of this routine  
  TCHAR *getProcName(UINT procID)  
  {    
    // without the correct flag, you get a garbage result.    
	HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, procID);    
	if (process)    
	{      
	  TCHAR *buffer = new TCHAR[512];      
	  DWORD res = ::GetModuleFileNameEx(process, NULL, buffer, 512);      
	  return buffer;    
	}    
	else      
	  return 0; 
  } 
  

Top


How can I create Debug Redistributable?

Microsoft packages Visual Studio dlls into Redistributable. Unfortunately only release dlls are packaged. Therefore, if you need Debug dlls, you have to do it yourself. I needed to do this, since I wanted to test debug version of HPC Cluster MPI exe. Here is how.


  1. You create a setup package and add ->Merge Module.
  2. Select Debug runtime CRT, OpenMP, and/or MFC.
  3. Select Policy module corresponding to the dlls selected in 2.
  4. Build msi.
  5. run installer 
  

It turned out that Visual Studio points the wrong version number of dlls in the executable manifest, i.e. it still uses the older version number even though the merge module is from SP1. The policy module allows to use the newer version of dlls even though the exe manifest contains the older version.You can verify this easity by looking at the manifest file. Therefore, if you don't include policy modules, your executable cannot find the right dlls under Visual Studio SP1. You can diagnose this problemby running sxstrace.

Top


How can I fix the error C101008D: Failed to write the update manifest to the resurce of file

This error is caused by Symantec File System AutoProtection and Visual Studio interaction. There is a long discussion and at the end and the conclusion was the Symantec AutoProtection is the cause: http://social.msdn.microsoft.com/Forums/en-US/clr/thread/dbb6c5db-9c34-46e6-af95-b56bf95ed345w
The way to avoid this message is:

  
  1. Open Symantec Endpoint Protection -> Antivirus and Antispyware Protection ->Options  
  2. Right click -> then Click Tab named as "File System Auto-Protect".  
  3. Uncheck "Enable File System Auto-Protect
  

Certainly you don't want this disabled not too long. Fortunately enabling is easy: Open Symatec Endpoint Protection ->Fix.

I tried to add exception for mt.exe but did not work. If you have another way of avoiding, please let me know.

Top


How can I format __int64 in printf?

Use "%I64d" for __int64.

Top


VS2008 fails to install on Server2003 64bit

When you try to install Microsoft Visual Studio 2008 on a computer that is running a 64-bit edition of Windows Server 2003, the installation may not be successful. Specifically, the installation process may stop during the installation of the Web Designer Tools component. Read http://support.microsoft.com/kb/954361 for solution.

Top


Which Windows SDK should I use?

The Windows SDK is now Version 7. You can download it from here. The thing you need to do after the installation is for VS2008 to use version 7. This is not done automatically. After the installation, you have Windows SDK Configutation Tool in the Windows menu or at "C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\WindowsSdkVer.exe".In my case the default was v6.0A. Run this to set it to v.7.0.

Top


How can I solve "syntax error : identifier '__RPC__out_xcount_part'" ?

When I created a new MFC project, I encounted this error.


  1>stdafx.cpp1>c:\program files\microsoft sdks\windows\v7.0\include\objidl.h(11280) : 
    error C2061: syntax error : identifier '__RPC__out_xcount_part'
  1>c:\program files\microsoft sdks\windows\v7.0\include\objidl.h(11281) : error C2059: syntax error : ')'
  1>c:\program files\microsoft sdks\windows\v7.0\include\objidl.h(11281) : fatal error C1903: 
    unable to recover from previous error(s); stopping compilation
  
It turned out that I was using DirectX SDK(Debruary 2007) version but I installed lately Windows SDK v.7.0. It turned out that Microsoft developer modified rpcsal.h in DirectX SDK\include without considering the back compatibility. He even did not change the header portion of the file which still carries the year 2004. I diffed the files and found that there were many changes between DirectX SDK (February 2007) vs. (August 2009). I changed myVisual Studio Tools → Options → Project And Solutions→ VC++ Directories. I made sure that I'm referring the 2009 version in Include files andLib Files. This error went away.

Update:
This is not good enough. You have to make sure that WindowsSDK include must come before DirectX include.

Top


Home

Updated 8/25/2010