Archive

Archive for the ‘Visual Studio’ Category

Visual Studio 2010 – Conditional breakpoints using String Comparison Functions (C/C++)

November 3rd, 2009 Sarath Comments

All we’re fond of conditional break points if we need to execute the program until some specific condition exists. We usually give numerical expressions to give conditional break points. If you don’t know about conditional break points, just have a look at MSDN documentation. or this one.

Now the C/C++ programmers are blessed with break with string conditions.

Just put a breakpoint in your source code and right click on that choose “Condition” to see the following window appear. You can give string comparison routines to set the break point.

image

Once you start debugging, you can see the break point hit on the condition you’ve given

image

Visual Studio Beta 2 currently supports the following functions (Taken from Habib Heydarian’s blog)

strlen, wcslen, _tcslen, strnlen, wcsnlen, _tcsnlen, strcmp, wcscmp, _tcscmp, stricmp, wcsicmp, _tcsicmp, strncmp, wcsncmp, _tcsncmp,strnicmp, wcsnicmp,_tcsnicmp,_stricmp, _wcsicmp, _strnicmp, _wcsnicmp

This may be changed or updated in the final release. Anyway enjoy your breakpoints!

Visual Studio 2010 – Code Metrics calculation

November 2nd, 2009 Sarath Comments

Visual Studio 2010 provides a new feature to calculate various the code metrics. Sadly this options are only available for Managed projects. Sorry native developers!

It allows to calculate the follow matrices of your project

  • Maintainability index
  • Cyclomatic Complexity
  • Depth of Inheritance
  • Class Coupling
  • Lines of code

Most of us mainly interested lines of code (LOC) as various other calculations in the project life cycle calculated based on this.

To calculate Code matrix, Right click on the Solution and choose “Calculate Code Metrics”

image

As you’re seeing above, you can see the information for the entire project and also for the individual items.

It’s possible to filter the results based on given criteria as you’re seeing below.

image

The coolest things is that, you can export these result to an excel sheet without any pain. Just right click on the item and “Open Selection in Microsoft Excel” as you’re seeing below

image

You can get it opened in the excel. See, the filters are automatically applied for header items!

image

To know more check MSDN website.

Visual Studio 2010 – Pin the watch box in source window

October 27th, 2009 Sarath Comments

To know the content of a particular variable during debugging, what we usually do is add it to the watch window or just hover the mouse over it and see the values as tool tip like window.

image

With Visual Studio 2010 You can pin this watch window in the source file like a notes. Whenever the data is changed, you can watch it instantly in the source file itself. Cool eh? See it here.

Start your Debugging

As you’re seeing above, hover the mouse on the required variable. Click on the pin button on the right end.

 

image

You can see close button to close the watch unpin button and expand button. You can also add the comments as you’re seeing above.

Once you step through debugging process, you can see this changing as below. if the data is updated, it will be displayed in red color.

image

 

It’s really cool when you’re watching the arrays.

image

You can selectively pin the array items and if necessary you can see the entire array as usual.

This can be moved from the current line of display. The blue color pin on the left side of the source window will move along and on hovering, it will display to which line this watch is attached with.

The interesting thing is that Visual Studio can remember your pins and can restore when you start over the debugging.

What the drawback I found in this, we can’t specify symbols for watch variables in this window. If it’s there, we do simple memory analysis and other handy display options easily.

This is a simple use case of this feature. It will be very handy in many critical debugging situations. For e.g. while working with multiple threads etc…

Visual Studio – Using wildcard characters in the symbol pattern for a breakpoint

October 26th, 2009 Sarath Comments

If you even came across WinDBG, you might have experienced using “bm” command for setting one more breakpoints based on the pattern we’re specifying.

For e.g if we put break point like bm Create*, the debugger will put the break points in the function with starts with Create.

The similar feature is available in Visual Studio as well. As an example, consider the following class ‘CPerson’

image

and suppose if we want to set the break points on all set function, we can do as do as follows.

Take New Break Point from Debug Menu

image

Give your wild characters to break at desired function

11

Once you start debugging you can see that break-points appears as specified…

image

Cool isn’t it?

TR1 – How to use array class?

August 17th, 2009 Sarath Comments

The C++ Standard Template Library (STL) provides a framework for processing algorithms on different kind of containers. However, ordinary arrays don’t provide the interface of STL containers (although, they provide the iterator interface of STL containers). As replacement for ordinary arrays, the STL provides class std::vector. However, std::vector<> provides the semantics of dynamic arrays. It manages data to be able to change the number of elements. This results in some overhead in case only arrays with static size are needed.

New new C++ provides a new class called array which is static in usage but able use a standard C++ container. It also provides access to the underlying data. Thus it’s possible to use as raw array pointers. See the sample snippet below to too see how to use array class. A better documentation can be found at boost::array page.

[sourcecode language='cpp']
// using array class
void FooTR1Array()
{
std::tr1::array arr = {1,2,3,4,5};

using namespace std;

cout << "Contents of array " < copy( arr.begin(), arr.end(),
ostream_iterator(std::cout,”\t”));
cout << "Size of array - " << arr.size() < cout << "Front of array - " << arr.front() < cout << "Front of back - " << arr.back() < cout << "Array max Size- " << arr.max_size() < cout << "Array [3] - " << arr[3] < cout << "First element using pointer - " << *arr.data() <

// array swapping - both arrays should have same properties and size
std::tr1::array arrNew = {111,222,333,444,555};

cout << "Contents of array 2" < copy( arrNew.begin(), arrNew.end(),
ostream_iterator(std::cout,”\t”));

// swap array
arr.swap( arrNew );

cout << endl<< "Contents of array 1 after swapping with array 2" < copy( arr.begin(), arr.end(),
ostream_iterator(std::cout,”\t”));

cout << endl<< "Contents of array 2 after swapping with array 1" < copy( arrNew.begin(), arrNew.end(),
ostream_iterator(std::cout,”\t”));
}
[/sourcecode]

Categories: C++, Code, Tips, Visual Studio Tags: , , ,

Windows 7 Ribbon – Part 2 – How handle ribbon control events?

July 2nd, 2009 Sarath Comments

In this installement, let’s see how to handle the events of the ribbon control. I strongly reconmmend you to read the previous post on the basics of ribbon the way it’s being created. This is a continuation of the previous post.

To handle the events, the IUICommandHandler interface is implemented by the application and defines the Command handler methods for framework events.  The following function has to be implemented in the derived class.

Execute
Executes or previews the Commands bound to the Command hand`ler.

UpdateProperty
Sets a property value for a bound Command, for example, setting a Command to enabled or disabled depending on the state of a View.

For each Command in a View(Application.Views in the XML file), the Ribbon framework requires a corresponding Command handler in the host application. A new handler or an existing handler must be bound to the Command through the IUIApplication::OnCreateUICommand notification method.  This method is executed when the UI component is created. It’s possible create new command handler by querying IID_PPV_ARGS intefac. Any number of Commands can be bound to a Command handler.

The Command handler serves two purposes. First, it can update the values of properties for any command to which it is bound, such as setting a command to enabled or disabled. Second, it can execute or preview any commands to which it is bound.

In the previous instalment we’ve seen CRibbonImplementer class. So here we will be modifying the class. We’ll be creating the the handler

Step 1 – Include the generated .h file contains control IDs to the implementation .h/.cpp file of CRibbonImplementer

b1

Step 2 & 3 – Derive ribbon implementer class from IUICommandHandler and add the interface to COM Map

b2

Step 4 – Modify OnCreateUICommand function and add UI Handler on creating the control.

b3

Step 5 -  Add Execute handler to get notification when the button is clicked. This is like the normal message loop of a Win32 message loop system.b4

The final Step (6 ) – It’s necessary to implement IUICommandHandler::UpdateProperty as the base class doesn’t provide any implementations. We can leave this interface as unimplemented.

b5

The full Source code is given below. There’s no change in the other part of source code.

[sourcecode language='cpp']
#include “stdafx.h”
#include
#include
#include
#include
// Step 1: Include menu ribbon resource.h
#include “MenuRibbonRes.h”

class CRibbonImplementer:
public CComObjectRootEx,
public IUIApplication,
// Step 2: derive fromm IUICommandHandler
public IUICommandHandler
{
public:
BEGIN_COM_MAP(CRibbonImplementer)
COM_INTERFACE_ENTRY(IUIApplication)
// Step 3: IUICommandHandler add in teh COM Map
COM_INTERFACE_ENTRY(IUICommandHandler)
END_COM_MAP()

STDMETHOD(OnCreateUICommand)(UINT32 nCmdID, __in UI_COMMANDTYPE typeID, __deref_out IUICommandHandler** ppCommandHandler)
{
// Step 4: IUICommandHandler
// if my button is being created, the handler is created and attached
if (nCmdID == cmdMyButton)
{
return QueryInterface(IID_PPV_ARGS(ppCommandHandler));
}
return E_NOTIMPL;
}

/* Step 5: Implement execute function.
This function will be called on clicking
the controls attached to command handler */
STDMETHODIMP Execute(UINT nCmdID,
UI_EXECUTIONVERB verb,
__in_opt const PROPERTYKEY* key,
__in_opt const PROPVARIANT* ppropvarValue,
__in_opt IUISimplePropertySet* pCommandExecutionProperties)
{
HRESULT hr = S_OK;
switch (verb)
{
case UI_EXECUTIONVERB_EXECUTE:
if (nCmdID == cmdMyButton)
{
MessageBox(NULL, _T( “Clicked on My Button!” ),
_T(”My Button Execute”), MB_OK);
}
break;
}

return hr;

}

// unimplemented methods
// Step 6: Implement Update Property interface as well
STDMETHODIMP UpdateProperty(UINT nCmdID,
__in REFPROPERTYKEY key,
__in_opt const PROPVARIANT* ppropvarCurrentValue,
__out PROPVARIANT* ppropvarNewValue)
{
return E_NOTIMPL;
}

STDMETHOD(OnViewChanged)(UINT32 nViewID, __in UI_VIEWTYPE typeID, __in IUnknown* pView, UI_VIEWVERB verb, INT32 uReasonCode)
{
return E_NOTIMPL;
}

STDMETHOD(OnDestroyUICommand)(UINT32 commandId,
__in UI_COMMANDTYPE typeID,
__in_opt IUICommandHandler* pCommandHandler)
{
return E_NOTIMPL;
}

STDMETHODIMP UpdateProperty(UINT nCmdID,
__in REFPROPERTYKEY key,
__in_opt const PROPVARIANT* ppropvarCurrentValue,
__out PROPVARIANT* ppropvarNewValue)
{
return E_NOTIMPL;
}
};
[/sourcecode]

Visual Studio 2010 Tips – Zoom your source code as with Ctrl + Scroll mouse

July 1st, 2009 Sarath Comments

One of the coolest thing in Visual Studio 2010 is the zoom source code functionality( I don’t know if there is any official name for it). As we’re doing with Office Word, any browsers, you can quickly zoom in/out your source code without the pain of going to Tools->Option Menu to change the font size.

Do it with following steps

1. Open your source code

2. Press Control + Scroll Up for Zoom-In the source code

3. Press Control+ Scroll Down for Zoom-Out the source code

 

See the image of a zoomed source code.

Zoom

Windows 7 Ribbon – Part 1 – How to Integrate a Simple Ribbon to your MFC Application?

June 30th, 2009 Sarath Comments

The Office 2007 changed the the conventional menu to a new vibrant, beautiful, and useful(??) ribbons. After that many third party libraries (both commercial and non commercial) vendors provided components to integrate ribbons to our application. Finally Microsoft heed the MFC guys crying a loud to get support on ribbons. Microsoft included Ribbons and other office style controls with MFC Feature Pack for Visual Studio 2008.

The following figure depicts the anatomy of a typical Ribbon.

image

In the new version of Windows, Windows 7 , it supports ribbons natively and Microsoft allows us to create it using Ribbon Frame Work.  Few Accessories application like MS Paint, Wordpad etc. got UI lift with Windows Ribbons.

Developer can create ribbon using Ribbon Markup Language (similar to XML format). For the Windows Ribbon framework (Ribbon) to consume the Ribbon markup file, the markup file must be compiled into a binary format resource file. A dedicated Ribbon markup compiler, the UI Command Compiler (UICC), is included with the Microsoft Windows Software Development Kit (SDK) (7.0 or later) for this purpose. In addition to compiling the binary version of the Ribbon markup, the UICC generates an ID definition header file that exposes all markup elements to the Ribbon host application and a resource file that is used to link the binary markup to the host application at build time.

The workflow for the Ribbon is as follows

Ribbon-Flow

OK let’s create a simple ribbon step by step. You should have Windows 7 SDK installed and Visual Studio 2005 or above is required to compile this application. I’m taking a MFC Application do this instead of a Win32 application. I’m just creating a new MFC Dialog Based Application.

We can categorize the ribbon creation in to two categories.

  • XML Markup, used to define the Ribbon structure and organization of controls
  • C++ COM interfaces, used to initialize and handle events

Step 1: Create the XML file with your ribbon. Add this XML for the solution. The following XML is a simple ribbon contains the application a Tab,Group and a button inside it.

1

[sourcecode language='xml']









My Button
My Button











Squiggles Support in Visual C++ 2010

June 8th, 2009 Sarath Comments

One of the best editor features I’ve enjoyed in Visual Studio Editor with C# environment is the real time highlighting of syntax and semantic errors etc using Squiggles (wavy underline). As native programmer, I wished a lot of we enjoy similar kind of helpful features with Visual C++ editor.

The new version of Visual C++ (coming with Visual Studio 2010) has implemented squiggles display in the source editor. Hovering over the squiggle displays compiler quality syntax/semantic errors. See the sample image below

Image Courteously – Visual C++ Team Blog

This is really a helpful feature as we don’t need to wait for finding the errors until the build and this can save lot of time. This feature is implemented atop (or make use) of intellisense. In my experience most of the large C++ projects are not directly using Visual Studio for building. If you’re directly using Visual Studio, you can benefit the entire features in a centralised manner. But the new features are certainly helps developers even if they’re using external build systems. The error list window will show the errors identified by the intellisense and this helps you to fix the issues before starting external build.

More technical details and information are available at Visual C++ team blog

How to write your own trace function?

March 11th, 2009 Sarath Comments

Most of us are using TRACE, ATLTRACE macros, OuputDebugString API for  debugging purpose during our development. [Go to end and check the function if you don't want to hear more about the basics of debug strings] Debug strings are used for debugging purpose and it’s displayed by debugger during debugging. You can see it in the output window of most of the debuggers (especially in Visual Studio) and also some smart utilities like DbgView captures the system wide debugging string and it displays in it’s own window without debugging any of the process.

Mainly OutputDebugString function provided by Kernel32 DLL is used for “outputing” debug strings. There are other altenatives available like TRACE, ATLTRACE2 macros, afxDump function etc. and most of these are actually wrapping OutputDebugString API and provides flavored functionalities like formatting like printf string, dumping MFC objects etc. The most widely used are TRACE macros. There are some more alternatives for TRACE macros like TRACE0, TRACE1, TRACE2 (deprecated now). It’s nothing but impossing restrictions on the number of parameters.

Trace macros are supposed to work with debug build of the applciation and in release mode, the traces will not be available. If we approach OutputDebugString API, we will have to first format string using sprintf or CString::Format function and then pass to API. But this adds the burden of declaring temporary buffer/CString objects every time we call this function as follows

[sourcecode language='cpp']
CString csMessage;
csMessage.Format(_T(”My Data:%d”), nData );
OutputDebugString(csMessage).
[/sourcecode]

You will always have to repeat the above code wherever you need a debug trace. Ofcourse TRACE macro can be used as printf like function, but only in debug mode. So it’s better to write our own trace functions. 

The following function is  variadic function which can be used as printf function with format specifierss

[sourcecode language='cpp']
void M4DTrace( LPCTSTR lpctFormat, … )
{
static TCHAR szBuffer[1000];
va_list ArgList;
va_start( ArgList, lpctFormat );
_vstprintf_s( szBuffer, lpctFormat, ArgList );
va_end( ArgList );
OutputDebugString( szBuffer );
}
[/sourcecode]

Instead of _vsntprintf_s, you can use another formating function called wvsprintf
but I found it has some problems formatting float variables in the list. The above function can runs under both UNICODE and MBCS environment.
If you need to know under the hood of OutputDebugString, please check this article
Updated[2009-Apr-17) – updated formatting with _vstprintf_s instead of _vsntprintf_s