Code Repo    |     RSS
MD's Technical Sharing



Thursday, June 3, 2010

Error accessing VC80.idb during compilation of VC++ project

If you're getting the following error
Could not delete file ‘c:\project\obj\release\vc80.idb
Make sure that the file is not open by another process and is not write-protected.
while building large VS solution with many VC++ projects, in a random and inconsitent manner, most likely you have just hit another Visual Studio bug. VS, by default, attempts to build multiple projects concurrently on system with multiple processors, which may cause the above error if different projects share the same IDB (VC++ Minimum Rebuild Dependency) file.

There are several solutions for this, but the simplest one would be to tell VS not to build multiple projects concurrently. To do this, open Tools>Options>Projects and Solutions>Build and Run, and set the value of Maximum number of parallel project builds to 1. However, with this method, your solution will take longer to build.
Read More »

Monday, May 3, 2010

Identifying used and unused resources in a Visual Studio's project Resources.resx file

If you often use project resources in a Visual Studio project, be it VB or C#, eventually you will end up with a big resource file (e.g. Resources) containing many unused items. This is because, when you remove the code that uses the resoure, very often you will forget to remove the actual resource item.

There are solutions to this problems such as using commercial code refactoring tool or making some minor modifications to Resources.Designer.vb/Resources.Designer.cs and relying on the compiler to generate warnings about unused resources. In this post, I choose to take a different approach: use a batch script.

My complete batch script will accept 4 parameters from the command line, listed from left to right:

1. Path to the VB.NET source code files, e.g. WindowsApplication1\*.vb
2. Name of project resource file, e.g. WindowsApplication1\My Project\Resources.resx
3. Name of file where all resources' usage are written, e.g. all_resources.txt
4. Name of file where all unused resources are written, e.g. unused_resources.txt

It makes use of the FOR extended syntax (FOR /F) to parse the resource file and FINDSTR to find where all the resources are referred to. It will only work properly with VB source code files, where most developers often use My.Resources.XXXX to access the resources. As FINDSTR simply performs a string search, the batch script will not care about code that are commented out, as well as resources that are accessed not by using the Vb's My namespace. If you want to use this with C# source code, you'll need to edit the call to FINDSTR to match your method of accessing the resources, e.g. Project1.Resources.Resource1 instead of My.Resources.Resource1.

The rest of this post will analyse some interesting points I encountered when writing it - hope this will be useful for those having similiar problems.

Batch script - powerful despite being crude

Many people may think that batch script is a thing of the past, since there are so many alternatives today - Windows PowerShell, Perl, or a .VBS file. Yet sometimes I still use it due to its powerful but simple nature. Take a look at the code to search for the resource:

FOR /F "tokens=*" %%a IN (%TMPFILE%) DO (
.........
        FINDSTR /S /P /N /C:"My.Resources.%%c" %SRCPATH% >> %OUT_ALLTOKENS%                  
        REM FindStr returns an errorlevel of 0 if the string was found, 1 and above if it was not found.
        IF ERRORLEVEL 1 (
.........
        )
.............      
    )
)


The call to FOR /F
and FINDSTR can easily translate into 10-20 lines of .NET code, unless you use some existing text processing libraries. Here, almost everything is done, just simply remember the syntax, available via FOR /? or FINDSTR /?.

Another example is how to generate a random file name:

:GETTEMPNAME
set TMPFILE=%TMP%\mytempfile-%RANDOM%-%TIME:~6,5%.tmp
if exist "%TMPFILE%" GOTO :GETTEMPNAME


The equivalent .NET code would be:

string filename = Path.GetTempFileName()

However, batch scripts are still very crude. For example, although Windows XP batch scripts allow the use of block statement via (........), don't expect everything to work as they do in a modern programming language. The following would cause problem:

IF (%1) == () (
    ECHO Missing first parameter: path to the VB.NET source code files (e.g. WindowsApplication1\*.vb)
    EXIT /B 1
) ELSE (
    SET SRCPATH=%1
)

Execution would terminate shortly upon reaching ECHO, without any indication why. I believe it would take many people some time to figure out what causes it and fix it. The following will work:

IF (%1) == () (
    ECHO Missing first parameter: path to the VB.NET source code files, e.g. WindowsApplication1\*.vb     
    EXIT /B 1
) ELSE (
    SET SRCPATH=%1
)

Also the above example demonstrates how to check for missing parameter. This would have made more sense in C# or VB.NET, just compare against an empty string (e.g. "").

There are many other useful code snippets in this batch script, for example, how to use delayed environment variable expansion, or how to use double quotes as delimiters in FOR /F. I will not explain it in details - the code is well commented, take some time to study it yourself.
Read More »

Thursday, February 4, 2010

.NET forms on Windows 7 at 125% zoom level

If you have ever tried to personalize your Windows 7 desktop and chose to zoom to 125%, as per the following screenshot, you'll perhaps notice that some applications do not display so well:

Believe it or not, the 125% or 150% zoom mode does not simply decrease the dpi of the display and make it look bigger, unlike the advanced display settings in Windows XP:


In fact, when the 125% or 150% zoom mode is set, Windows 7 does (at least) the following two things:
  1. Increase the default font size
  2. Tell every window (including child window) to increase its size
It's up to the application to handle the change in font size and window size gracefully. If it does not, the application interface may look distorted, with text truncated or displayed outside its designated area and graphics being tiled up or stretched.

Interestingly the 125% or 150% zoom mode cannot be used during a Remote Desktop session.

Effects on .NET forms

Under 125% or 150% zoom, the size of a .NET form will increase proportionally. The following changes will have to be made for the form to display properly:
  1. All form controls should have their Anchor property set appropriately. 
  2. Most importantly, the AutoScaleMode property of every form should be set to Dpi and not Font. AutoScaleMode of user controls can be set to either Dpi or Inherit. 
 If set inappropriately, only the form will resize while the controls do not resize, causing display distortion.

Also, do not open the form designer from inside Visual Studio 2008 under 125% or 150% zoom mode. Otherwise, Visual Studio will "zoom" the form (perhaps in an attempt to obey the Windows settings faithfully) by increasing its Size property and forgets (or is unable) to restore the original size when the zoom mode is set to 100%. If this happens, you'll have to manually resize every form back to their original size.

I am not sure if it's a Visual Studio bug, or it's just supposed to be that way.
Read More »

Sunday, April 5, 2009

Configuring Visual Studio to Debug .NET Framework Source Code

1. Install the Visual Studio 2008 QFE. Note this functionality is not available on the Express versions of the Visual Studio 2008 products.

2. Start Visual Studio 2008 and bring up Tools > Options > Debugging > General. If you are running under the Visual Basic Profile, you will need to check the box on the lower left of the Options Dialog marked "Show All Settings" before continuing (other profiles won't have this option).

Set the following two settings:
Turn OFF the "Enable Just My Code" setting
Turn ON the "Enable Source Server Support" setting

3. Next, bring up the "Symbols" Page and set the symbols download URL and a cache location. Specifically, set the three settings below:

Set the symbol file location to be: http://referencesource.microsoft.com/symbols
Set a cache location. Make sure this is a location that your account has read/write access to. A good option for this is to place this path somewhere under your user hive (e.g. c:\users\sburke\symbols)

Alternatively, use NetMassDownloader for the .Net Framework which allows you do download .Net Framework source code in batch mode.


Reference


Full reference source code for .NET framework: http://referencesource.microsoft.com/netframework.aspx

Read More »

Thursday, March 12, 2009

Debug TodayScreenPlugin/HomeScreenPlugin

For PocketPC, make sure your today screen item is visible on the device and it is using the latest build so the debug files match up with the executable. Go to the Debug Menu, and choose "Attach to Process..." Change the Transport line from Default to Smart Device. Change the Qualifier drop down to the type of device you are using. If you haven't selected any devices lately you'll have to click the browse button and manually select your device type.


You'll see a list of processes running on your handheld, but only EXE processes can be attached to. Shell32 is the process that loads the today screen. If you are viewing the today screen it should say "Desktop" for the title.


Select the shell32.exe process and click Attach. Set a break point in the WM_PAINT handler of your today item click the start menu on the device. You should catch the WM_PAINT message the today menu invalidates your today item causing a refresh/redraw.


To debug a Home Screen Plugin (Smartphone) at runtime, you must attach the debugger to the home.exe process.


References:

1. http://russryba.vox.com/library/post/debugging-today-screen-items-in-visual-studio-2005.html

2. http://msdn.microsoft.com/en-us/library/aa455227.aspx

Read More »

Friday, February 13, 2009

Debug a Windows CE setup DLL

::GetModuleFileName(g_hInstDLL, szName, nSize);
::
MessageBox(hwndParent, szName, _T(""), MB_OK);


where g_hInstDLL is the handle to the loaded module, usually available in the DLL entry point:


BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
//assign the handle here
g_hInstDLL
= (HINSTANCE)hModule;
break;
}
return TRUE;
}


  • Change the setup DLL project properties-> Configuration Properties->Linker -> General -> Output File. Change the existing value to $(OutDir)/STPXXXX.dll where STXXXX.dll is the filename found in step 3 and rebuild the DLL.
  • Go to Tools -> Attach To Process, select device or emulator and attach to process tmarshaller.exe
  • Breakpoint should now be hit and debugging can be done.
  • After debugging, remember to change the linker output file name back to how it was (e.g. $(OutDir)/Setup.dll )

    Reference:

    http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/03b20581-1479-44aa-ba9d-caf1c313c4eb

    Read More »

    Monday, December 29, 2008

    Attached the debugger to a running .NET Compact Framework process

    To attach the debugger to a running process on the device:
    • On the Debug menu, click Attach to Process.
    • In the Transport box, select Smart Device.
    • To populate the Qualifier box, click Browse.
    • In the Connect to Device dialog box, select the correct device type, and then click Connect.
    • To populate the Attach to box, click Select.
    • In the Available Processes box, select the process name, and then click Attach.
    • You are now attached with the native debugger.
    By default, devices, including emulators, do not allow the managed debugger to attach to processes that are already running. Attaching the managed debugger to an already running process is a situation that you typically encounter in device solutions that include both managed and native code.

    To enable the managed debugger to attach to a running process:
    • Open the Registry Editor for the target device, expand Windows Mobile 5.0 Pocket PC Emulator, and then create the following key:
    • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\Managed Debugger.
    • Create a DWORD named AttachEnabled.
    • Set the Name as AttachEnabled, and the Value as 1.
    • You may need to restart Visual Studio, or at least close the running application on the device which you want to attach to.
    Without this registry modification, there will be an error:

    "Unable to attach to the process. Attach is not enabled for this process with this debug type."

    Reference: http://msdn.microsoft.com/en-us/library/ms228818.aspx
    Read More »

    Wednesday, December 24, 2008

    Setup VS2005 to use Microsoft Symbol Server

    One of the first things you will want to do after installing visual studio is to set it up to automatically pull down the correct symbols for system components when debugging. You do this by configuring Visual Studio to use the Microsoft Symbol Sever.


    In VS 2005, do the following:

    1. Open Visual Studio. Goto Tools->Options
    2. Expand the “Debugging“ node
    3. Click on the “Symbols“ node under “Debugging“
    4. Click on the icon that looks like the new folder icon to add a new .pdb location
    5. Type the following for the location “smysrv*symsrv.dll*c:\symbols*http://msdl.microsoft.com/downloads/symbols“
    6. In the Cache symbols from symbol servers to this directory, enter the local path you used in step 5. In this case “c:\symbols“
    7. Click Ok.

    To test it out, try attaching to some windows process like iexplore.exe (if you have IE running). Goto debug->windows->modules. You should now see that symbols are loaded for all the system dlls and iexplore.exe. You can also open the local path used in step 5 and you should see folders for all the dlls that have been debugged so far.


    You only need to run against the symbol server initially until it pulls down all the symbols you care about. Once that's done, go back to the options dialog and unclick the PDB location. As long as you leave the "cache location" entry filled in, VS will continue to pull from the cached images... very quickly.


    Obviously the cache will need to be reprimed if your system DLLs get updated by anything. VS should see that the PDBs are out of date and avoid misrepresenting the stack, at least.


    Reference:

    http://geekswithblogs.net/mskoolaid/archive/2005/12/17/63418.aspx

    Read More »

    Thursday, December 11, 2008

    How to disable compilation warnings in Visual Studio

    Retrieving the warning ID:


    The warning ID can be taken from the Build Output. In the following example, the warning ID is 0169 (we only need the numeric part).

    test.cs(17,9): warning CS0169: The private field 'foo.c' is never used


    VB.NET projects: By modifying project file (.vbproj)


    To suppress this warning in VB .NET we need to manually edit project .vbproj file.

    1. Close VS.
    2. Open .vbproj file. Find tag and add the warning ID there separated by commas. Don’t place any whitespaces and newlines in this tag! There is one section for each configuration (Release/Debug) so you need to edit all of them.
    3. Save the .vbproj file and open VS.

    After this, you shouldn't’t get specified warnings during the build nor should you see warning underline during editing.


    Examples:


    (1) Type is not CLS-compliant


    A variable, property, or function return is declared with a data type that is not CLS-compliant.

    For an application to be compliant with theCommon Language Specification (CLS), it must use only CLS-compliant types.

    To disable these warnings, use the following warning numbers: 40025,40026,40027,40028


    Reference: How to disable 'not CLS-compliant' warnings?, http://www.vbforums.com/archive/index.php/t-481759.html


    (2) XML-comment related warnings

    XML comment block cannot be associated with any language element that supports the application of XML documentation comments. XML comment will be ignored.


    XML comment has a tag with a 'cref' attribute '^abc.txt' that could not be resolved. XML comment will be ignored.


    Use 42312,42309


    Reference: http://www.helixoft.com/vsdocman-faqs/disable-warnings-for-xml-comments.html


    VB.NET projects: using Visual Studio Team Suite:


    In the Project Properties > Code Analysis section, expand your warning messages and uncheck the one you don't want to show up.


    Reference: http://www.vbforums.com/archive/index.php/t-481759.html


    C# projects: change build properties

    To disable warnings, add the warning numbers separated by comma to the Suppress Warnings text box under Project Properties/Build:


    Suppress warnings from code


    In C#:


    A pretty cool feature in .NET 2.0 is the ability knowingly disable a list of warnings using the #pragma directive.


    using System;
    public class foo
    {
    // Disable warnings for unused or unassigned fields
    #pragma warning disable 0169, 0414
    // No warning
    int a;
    // No warning
    int b = 0;
    // Restore warnings for unused or unassigned fields
    #pragma warning restore 0169, 0414
    // Warning CS0169 issued
    int c;
    // Warning CS0414 issued
    int d = 0;
    }


    Reference: http://blogs.msdn.com/kaevans/archive/2005/11/06/489681.aspx


    In C++:


    // Disable warning messages 4507 and 4034.
    #pragma warning( disable : 4507 34 )

    // Issue warning 4385 only once.
    #pragma warning( once : 4385 )

    // Report warning 4164 as an error.
    #pragma warning( error : 164 )


    // Or all the above 3 in one line:
    #pragma warning( disable : 4507 34; once : 4385; error : 164 )


    Reference: http://msdn.microsoft.com/en-us/library/2c8f766e%28VS.80%29.aspx

    Read More »

    Monday, November 3, 2008

    Custom .NET CF User Control not rendered in Design View

    When designing user controls for .NET CF, certain controls will only render at run-time. At design time, they are shown as place holders

    The reason is because the OnPaint event of the user control calls several functions which are potentially device-specific, preventing the designer from rendering the control in design view for security reasons

    To fix this, a file named DesignTimeAttributes.xmta should be added to the solution containing the custom user control classes. The XMTA file must contain at least the following:

    <?xml version="1.0" encoding="utf-16"?>

    <Classes xmlns="http://schemas.microsoft.com/VisualStudio/2004/03/SmartDevices/XMTA.xsd">

    <Class Name="MyNamespace.MyClass">

    <ToolboxBitmap>typeof(Mooseworks.GI.SimpleGraph)</ToolboxBitmap>

    <Editor>

    <Type>Mooseworks.GI.SimpleGraphEditor, MwSimpleGraphEditor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=15EF1E3443EA1F6B</Type>

    <BaseType>System.ComponentModel.ComponentEditor, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089</BaseType>

    </Editor>

    <DesignTimeVisible>true</DesignTimeVisible>

    <DesktopCompatible>true</DesktopCompatible>

    </Class>

    </Classes>


    'DesignTimeVisible' tells the designer to render the control in design view.

    'DesktopCompatible' tells the designer to render the control in all cases


    If you are using imports of unmanaged dlls or API calls, you should add the

    DesktopCompatible attribute with a value of true to the class. You should also

    assure that import calls of device specific dlls do not occur while in design mode.


    Without the 2 properties the control will not be rendered in design view and will only be showed

    as placeholders.


    Compiling will creating 2 files e.g. MwSimpleGraph.dll for the classes and MwSimpleGraph.PocketPC.asmmeta.dll

    for the XMTA files.


    If the control is rendered in PocketPC project design view but not in smartphone design view (or

    vice versa), make sure the configuration of the project/solution is set to Any CPU.


    Reference: http://www.mooseworkssoftware.com/VS2005%20Control.htm

    Read More »

    Saturday, October 18, 2008

    Sharing resource files between different VS projects

    A .NET resource file created by VS contains:

    1. Resources.resx: XML declaration of all resources

    2. Resources.Designer.vb: autogenerated by VS custom tool (VbMyResourcesResXFileCodeGenerator) during the build process. This file facilitates the accessing of resources from .NET code (e.g. My.Resources namespace in VB and [ProjectName].Resources in C#). Everytime the resources file changes, VS will run the tool to re-generate the resources designer file. The re-generation process can also be done manually by right clicking the .resx file and choose Run Custom Tool.

    3. In the property of the .resx file, CustomTool is set to VbMyResourcesResXFileCodeGenerator and CustomToolNamespace is My.Resources (for VB). Build action for .resx file should be Embedded Resources

    To share resources file between 2 projects:

    1. In the first project, proceed to create the resource file as per normal

    2. In the 2nd project, create the resource file as per normal. After that, remove the .resx file and .designer.vb from the project (you may need to enable View->Show All Files in order to see these files under Project). Proceed to add the .resx file and .designer.vb file from the first project into the current project as link

    3. For these 2 added files, make sure the Build Action, Custom Tool and Custom Tool Namespace has been set accordingly.

    Note: If resources are shared between desktop and device projects, there are chances that the code generated by the custom tool for the desktop project will overwrite that of the device, causing incompatibilities and build errors. As a work around, if such errors occur, before building, right click the resources file and choose Run custom tool.
    Read More »

    Thursday, September 18, 2008

    VS IDE check if Design Mode is active

    Useful when desining user controls - in order to make certain functionalities available in design mode but not in runtime and vice versa.

    public bool IsInDesignMode()
    {
    bool returnFlag = false;

    #if DEBUG
    if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
    {
    returnFlag = true;
    }
    else if (Process.GetCurrentProcess().ProcessName.ToUpper().Equals("DEVENV"))
    {
    returnFlag = true;
    }
    #endif

    Debug.WriteLine("IsInDesignMode returns " + returnFlag.ToString());
    return returnFlag;
    }


    Reference: http://devlicio.us/blogs/derik_whittaker/archive/2006/09/25/Determining-if-the-.Net-IDE-is-in-Design-Mode.aspx
    Read More »