Archive

Archive for the ‘Code’ Category

How to keep your mouth shut – interesting article by Scott Berkun

October 3rd, 2009 Sarath Comments

keep-silence I am a hard fan of Scott Berkun especially because of great essays and his book “The Art of Project Management” (it has a new updated version called “Making things happen”) which is one of the best management books I’ve ever read. Trust me, it doesn’t contain any bullshits. It talking about the common stuffs in Project management with common sense.

This time I am really interest to quote about his new article in posted in his Blog “How to keep your mouth shut?” Why I am quoting this here because this is a common problem we face including myself  in our day to day life. At least I am experienced few things he mentioned in his blog post.

As a rule, if you insist on speaking your mind, you will inevitably find yourself in an environment where everyone hates you.  Most people can not handle the truth. And the more you shove it in their face, the easier it is for them to ignore you. You simply become the person who always complains, rendering any good ideas you have entirely impotent. Your ideas will be shot down simply because of the reputation of the mouth they come from.

When you’re working under good teams you will get applauded regardless of the senior audience. But he talks about the time where he worked in a team where no one spoke their mind in public.  Few people worked hard or asked tough questions. Quality of work, and morale, was low.

In this kind of situation people may consider your view points as wrong or arrogant.

If you don’t know the angle being played, anything you say might ruin the plan.

This is a great rule to follow before you raise objections or offer big ideas. No matter how right you are, if you care about effecting change, you should never open your mouth without some sense of who will agree with you and who won’t.  If you can anticipate the angles and responses, and judge, even by guessing, if there is a 80%, 20% or 0% percent chance anyone in good standing will follow your lead in support of what you say, you know whether it’s worth opening your mouth. It’s a world of difference of perception when someone respected says, after you speak, “he might be right” and when there’s only silence. And of course, in most cases your percentages go up if you raise your objections in private, rather than in a large meeting where egos are at stake.

We must have experienced situations where our words took in wrong sense. May be we’re talking or raising the hands when we are foreseeing some issues, dealing with BS management, poor tracking, planning, unrealistic estimations and schedule. But remember, someone more powerful than you should have to agree with what you’re saying, otherwise the situation comes like your words got misinterpreted. Trust me, it’s hard to convince your seniors and you will have to do your homework on how to convince them if you’re seeing some wrong or may we need to understand ourselves why such a decision has been made. For this Berkun has another interesting essay – How to survive bad managers?

If you’re saying something, just think twice whether it’s gonna be respected or agreed by your audience. If we’re feeling our ideas or opinions are great, we should have the convince the audience about your view point. Our actions and images are the core things behind these acceptance. If you’re having a bad track record it simply hard get proved unless you’re introducing something great to change the status quo.

On the other hand(receiving end), we’re not comfortable in changing the coziness we’ve, sometimes even if realize it’s a mistake. In the classic book code complete Steve McConnel says -

Any fool can defend his or her mistakes—and most fools do —Dale Carnegie

If a person refuses to admit a mistake, the only person she’ll fool is herself. Everyone else will learn that they’re working with a prideful programmer (person) who’s not completely honest. That’s a more damning fault than making a simple error. If you make a mistake, admit it quickly and emphatically.

If she refuses to admit a mistake, the only person she’ll fool is herself. Everyone
292 else will learn that they’re working with a prideful programmer who’s not
293 completely honest. That’s a more damning fault than making a simple error. If
294 you make a mistake, admit it quickly and emphatically.

The post is still incomplete because these kind of things may vary from people to situation. Some good related essays from Scott is here.

[Updated 2009-10-13 12.00 Noon JST]

Fixed typos. reduced the usage of BS :) (Sometimes I forgetting I am not an American :)

How to Debug Child Process Using WinDBG/Visual Studio?

September 20th, 2009 Sarath Comments

Have you ever came across a situation where you need to debug a child process created by your application or external application?

Usually when we need to debug an application (process) usually we’ll be attaching the particular process to debugger by executing in debug mode from the debugger itself or use “Attach process” option provided by debugger.

image 

You can debug the processes where you’ve the right debug privileges. But suppose if you’re working in a system where your application is launched by someone else and you’re facing some catastrophic errors in some critical point of execution where you’ve no chance to attach it to debugger. (e.g during startup)

In this situation usually developers modify the source code if the want to debug and put some delay, or call “DebugBreak” API to debug the program. But in some situations this is also not practical. So what we’ve to do?

We’ve two debuggers that developers use in very common. Visual Studio Debugger is one of the most popular debugger in Windows. Okay before talking about Visual Studio I’d show how we could achieve this with WinDBG, the most powerful debugger under Windows. But it’s not that flexible like Visual Studio. It’s a beast! with all power to rule the process :)

WinDBG Way

I’ve created a small program which will be crashing in the startup itself. I am not going to write a launcher to create the process, I will do that from the command line. The steps to debug the child process are

1. Launch the parent application which is going to create the desired process.

2. Attach the parent process to WinDBG (Hope you’re all set with your symbol server and source file paths for better debugging)

3. Enable Child Process debugging by giving command “.childdebg 1”  (pass 0 if you want to disable it. See the documentation)

4. Resume the process by hitting “Go” and let the parent process to create the child process.

5. You can see that WinDBG will “Break In” when the new process is created.

6. Now you can start debugging by setting Break points, watch, etc…

Visual Studio Ways

The previous method was not at all painful no? But Visual Studio doesn’t  natively support debugging multiple process. According John Robbins, it requires a serious architectural change in Visual Studio. There’s no straight way to do this. There two known method to do this.

Using Image File Execution Option with Visual Studio

Setup:

   1. Run regedit.exe
   2. Goto HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
   3. Create a new key for your exe (example: foo.exe)
   4. Create a new string value under your exe. The name of the string value is ‘Debugger’, and the value is ‘vsjitdebugger.exe’

Here is a sample registry script to do this: (save as .reg file after changing sample.exe to your application’s name)

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sample.exe]
"Debugger"="vsjitdebugger.exe"

The above method is exploiting one of native debugging feature provided by Windows. Ensure that the modification at registry is reverted back once you finish with debugging. Otherwise whenever the application is started, it will automatically starts with Visual Studio Debugger. See this blog entry for more details

Google Chrome Debug Macros

The people at Google (or those who contributed) are so smart and they’ve created few Visual Studio Macros to enable you to debug the child process. They found in some situations the Image File Execution Option doesn’t work well. And they’ve written some efficient macros to debug the child processes using Visual Studio.

You can see the macros and how to debug article in Chrome website.

Happy Debugging!

What’s the difference between max_size and size functions of std::tr1::array?

August 18th, 2009 Sarath Comments

Well, I don’t know the answer. It’s not well documented. From the discussions went under comp.lang.C++ group, what I understood is that

STL containers in general provide both of these member functions. size() tells you how many elements there are currently in the container, and max_size() gives you an estimate of the maximum possible number of elements that you could put into the container.

As array is of having fixed number of elements, both functions acts similar and returns same value. Thanks Pete Becker

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

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: , , ,

Cg Tips – Swizzle Operator

August 17th, 2009 Sarath Comments

Intended Audience – Newbies of Graphics Programming.

nVidia Cg has a swizzle operator (.) that allows the components of a vector to be rearranged to form a new vector. Cg has different packed data types called vectors like float2,float4, color, color3, color4 etc. Okay giving example will make things a bit more clear.

float3(a,b,c).zyx; – This will initialize a float3 vector as float( c, b, a ). the values given are just reversed.
float4(a,b,c,d).zzyx; – This will initialize a float4 vector as float( c, c, b, a ).
float4(a,b,c,d).w; – This will initialize vector with d

Which means that you can repeat or omit the elements and just create a new one with the given order and values. The characters x,y,z and w represent the first, second, third and fourth components of the original vector respectively(You can also use r,g,b and a for the same purpose). You wont suffer with any performance hit as it’s brilliantly implemented in the hardware. It can be also used to convert a scalar to vector.

color.xxxx  – Initalizes a float4(a,a,a,a);

OK let’s take a simple fragment program. The original image is as follows. Let’s make this a bit more pale with swizzle.

Let’s pass throgh the following cg program which uses the swizzle.

struct Output {
float4 color : COLOR;
};

Output texture_frag(float2 texCoord : TEXCOORD0,
uniform sampler2D decal : TEX0)
{
Output OUT;

OUT.color = tex2D(decal,texCoord).xyyz; // Use swizzle
return OUT;
}

OK Just have a try!

Categories: Code, OpenGL 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]

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











How to create a list from vector?

June 11th, 2009 Sarath Comments

The following sample demonstrates, how to convert a vector to list(in other words, how to create a list from vector).

The simplest way is to iterate through all elements of container and add it to the destination container. the following snippet make use of std::copy function to copy contents from source to destination container. The destination and source iterator will be automatically incremented inside on each iteration. Before using this function you will have to ensure the destination container has enough room to hold the source elements. For that it may necessary to resize the container. See the snippet below. Note that you can use this technique with anu containers which supports iterator(actually that’s the purpose of std::copy function).

[sourcecode language='cpp']
#include
#include

#include
#include

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector vec;
// prepare the vector
for (int i = 0; i < 10; i++ )
{
vec.push_back( i+1 );
}

// construct list with the size of vector
list lis(vec.size());

// iterate and copy the content to list
copy( vec.begin(), vec.end(), lis.begin());

// output the content to console
copy( lis.begin(), lis.end(), ostream_iterator(cout, “\t” ) );

return 0;
}
[/sourcecode]

Categories: C++, Code, Tips Tags:

How to reverse a string (using library function)?

June 9th, 2009 Sarath Comments

Reversing a string is one of the first programs we write when we learn about loops. Anyway you don’t have to write the usual loop again to reverse a string. You can use _tcsrev ( _strrev ) function to reverse a character buffer. See the sample below

[sourcecode language='cpp']
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR buff[] = _T( “Hello World!”);
_tcsrev( buff );
_tcprintf( buff );
return 0;
}
[/sourcecode]

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

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