<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Reflections of my thoughts... &#187; Uncategorized</title>
	<atom:link href="http://codereflect.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://codereflect.com</link>
	<description>on programming tips and trending topics...</description>
	<lastBuildDate>Wed, 08 Feb 2012 08:58:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Visual Studio 2011 IDE advancements</title>
		<link>http://codereflect.com/2011/11/18/visual-studio-2011-ide-advancements/</link>
		<comments>http://codereflect.com/2011/11/18/visual-studio-2011-ide-advancements/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 05:58:30 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[Visual Studio 2011]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1827</guid>
		<description><![CDATA[New Visual Studio is around the corner. Microsoft Corporate Division VC, Somasegar has given a sneak peak to new IDE features in his blog. I find this is promising. Especially, with Visual Studio 2010, we&#8217;ve found completely revamped architecture for extending Visual Studio. On the other hand, Whole Tomato is a company, which had shown [...]]]></description>
			<content:encoded><![CDATA[<p>New Visual Studio is around the corner. Microsoft Corporate Division VC, Somasegar has given a sneak peak to new IDE features in his blog.</p>
<p>I find this is promising. Especially, with Visual Studio 2010, we&#8217;ve found completely revamped architecture for extending Visual Studio. On the other hand, Whole Tomato is a company, which had shown what customers really wanted out of Visual Studio. Their Visual Assist X plugin is an excellent piece of art. There are other famous guys who sells similar softwares like DevExpress. But I personally prefer VA, because it&#8217;s light weight and not leaving much confusions with cluttered interfaces like others. </p>
<p>Visual Studio Power Tools is another awesome free option to improve your productivity. But I believe Microsoft can do well with their IDEs. Ever since Visual Studio 2003, we&#8217;ve not gained anything better out of Microsoft IDEs. Almost 8 years, though Microsoft has introduced a bunch of technologies and language improvements especially for C#, the IDE remains a substandard for the world&#8217;s biggest developer community.</p>
<p>Visual Studio 2011 is a positive improvement where the art of search with regular expression integrated well with to find information quickly.</p>
<p><a href="http://blogs.msdn.com/b/somasegar/archive/2011/11/17/visual-studio-11-ide-advances.aspx" target="_blank">Read the full scoop here in Soma&#8217;s blog</a></p>
<p><img alt="" src="https://byfiles.storage.live.com/y1pD_3RCoCOZUnxiLh8-EPRexlZtvIYjwnzsBbrquFs4GKrRr4GFyvOKZa4RJqizv4StuUcMzWGkEc/image6.png?psid=1" title="Visual Studio 2011" class="alignnone" width="524" height="204" /></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2011/11/18/visual-studio-2011-ide-advancements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What iPad lacks? An impression on seeing the keynote and tech spec</title>
		<link>http://codereflect.com/2010/01/28/what-ipad-lacks-an-impression-on-seeing-the-keynote-and-tech-spec/</link>
		<comments>http://codereflect.com/2010/01/28/what-ipad-lacks-an-impression-on-seeing-the-keynote-and-tech-spec/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 14:36:10 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1086</guid>
		<description><![CDATA[I was so excited about watching the keynote video of iPad launch at Apple website. I am really excited to own on iPad. The multi-touch features and hardware itself is just amazing on the demo. Also I&#8217;d be happy to see the best iPhone applications on the same platform. Despite the pros, I noticed about [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_1087" class="wp-caption alignleft" style="width: 310px"><a href="http://codereflect.com/wp-content/uploads/2010/01/hero20100127.jpg"><br />
<img class="size-medium wp-image-1087 " title="hero20100127" src="http://codereflect.com/wp-content/uploads/2010/01/hero20100127-300x245.jpg" alt="Steve Jobs with iPad" width="300" height="245" /></a><p class="wp-caption-text">Steve Jobs with iPad</p></div>
<p>I was so excited about watching the keynote video of iPad launch at Apple website. I am really excited to own on iPad. The multi-touch features and hardware itself is just amazing on the demo. Also I&#8217;d be happy to see the best iPhone applications on the same platform.</p>
<p>Despite the pros, I noticed about the cons of the new product. Don&#8217;t think that I am owning one iPad but I am writing this based on the impression from Key note and the technical specification. Also this post is fresh and I am not influenced by any tech pundit&#8217;s writing and guesses on the iPad.</p>
<p>[Updated 3.00 AM JST]</p>
<p>iPad still doesn&#8217;t support Adobe Flash. Irony is that iPad running Mac OS X  and can&#8217;t believe it doesn&#8217;t support flash. I can&#8217;t think of a &#8220;computer&#8221; which has no flash installed in it. (During the demo, the websites which has flash is displayed as unsupported. Check it out)</p>
<p>Steve Jobs already said in his presentation, the netbooks are cheap laptops. I agree that iPad has a gorgeous display. But has not good storage. I hope this is to promote the mobile me services of Apple. In my opinion more storage must get for a cheap price because this is not a phone.. Almost similar to a notebook or a high form of a netbook.</p>
<p>The device lacks a webcam. It even doesn&#8217;t contain a basic VGA webcam. What if I need to show up myself to my friends? Apple is seamless in their user experience while they restrict of make the user handicapped in terms of storage. Also Jobs dint mention about the iChat application.</p>
<p>When comes in to storage, the iPad basic capacity is 16 GB and they&#8217;re not running any iPhone OS, instead it&#8217;s powered with Mac OS X 10.5.8 or above. Which means that you&#8217;ve to spend few more room for the OS out of the basic 16/32/64 GB. Apple dint mention about any external storage which can be connected through the USB port. I hope it isn&#8217;t possible.</p>
<p>Again comes on the hardware specification. iPad is not really great. It has a great battery life around 10 hours and also it does have a great video accelerator. But still it&#8217;s 1 Ghz processor inside it. Most of the iPhone games are too reduced version of PC/Console version and limited in many ways. I think they must have more efficient processor specification. Even the so called &#8220;cheap laptops&#8221; has 1.6 Ghz processors.</p>
<p>The TV out capabilities are not built-in we&#8217;ve to buy a Dock to VGA adapter for enjoying the TV/Projector connectivity.</p>
<p>The device is capable of playing video up-to 720p. Still it&#8217;s not full HD. Also the resolution is 1024&#215;768. It&#8217;s not really a big room. again I believe with the multi-touch panning and zooming of course the browsing experience will be good.</p>
<p>Also I doubt the gaming experience and convenience beside the accelero-meter. Also I don&#8217;t think to have a great typing experience with iPad. With iPhone one hand is enough for typing, but this case is different. For heavy typing we may have to depend on external keyboard.</p>
<p>Despite of all drawbacks, apple knows how sell a product and make business around it, that&#8217;s how they&#8217;re grown in these years. People loves spend and own for an Apple.</p>
<p>One more thing, Steve Jobs presentation was not really charming this time. The updates about how things are going on literally he took the head postion of &#8220;The biggest mobile company in the world&#8221; was not accepted well I guess. Also during the end, the presentation was slow and was out of sync. He doubted in many places. Never seen this before from Jobs. Let&#8217;s wait and see till we get one in hand.</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2010/01/28/what-ipad-lacks-an-impression-on-seeing-the-keynote-and-tech-spec/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google IME for Indian Languages</title>
		<link>http://codereflect.com/2009/12/26/google-ime-for-indian-languages/</link>
		<comments>http://codereflect.com/2009/12/26/google-ime-for-indian-languages/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 04:45:13 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://codereflect.com/2009/12/26/google-ime-for-indian-languages/</guid>
		<description><![CDATA[Most of us are really fond of Google transliteration service, which also incorporated in their popular services like Gmail and Blogger to compose mails and blogs in our own languages.[See Google Transliteration] As we all know, we can add the text input support for as many languages from the regional settings menu of Windows (you [...]]]></description>
			<content:encoded><![CDATA[<p>Most of us are really fond of Google transliteration service, which also incorporated in their popular services like Gmail and Blogger to compose mails and blogs in our own languages.[See <a href="http://www.google.com/transliterate/" target="_blank">Google Transliteration</a>]</p>
<p>As we all know, we can add the text input support for as many languages from the regional settings menu of Windows (you can see this in the control panel)</p>
<p><a href="http://codereflect.com/wp-content/uploads/2009/12/image5.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://codereflect.com/wp-content/uploads/2009/12/image_thumb2.png" width="431" height="491" /></a> </p>
<p>Even if you can add the language support, in fact they’re not get going well with a transliteration manner. If you type something, Malayalam it should appear as ??????. unfortunately Windows badly fails to do that.</p>
<p>If you’ve really enjoyed the Google transliteration service, they’re ready to provide the same text service as offline service through <a href="https://www.microsoft.com/windows/ie/ie6/downloads/recommended/ime/default.mspx" target="_blank">IME</a>. No more copy paste from transliteration IME page your window.</p>
<p>Navigate to <a href="http://www.google.com/ime/transliteration/">http://www.google.com/ime/transliteration/</a> and select your preferred language, finish download and install it.</p>
<p>Google Transliteration IME is currently available for 14 different languages &#8211; Arabic, Bengali, Farsi (Persian), Greek, Gujarati, Hindi, Kannada, Malayalam, Marathi, Nepali, Punjabi, Tamil, Telugu and Urdu.</p>
<p>Google Boasts it has</p>
<ul>
<li>Offline Support – No dependency with internet connection</li>
<li>Easy Keyboard – Dictionary enabled keyboard to enter rare and complex words</li>
<li>Word Completions &#8211; Dictionary based word completions for prefixes.</li>
<li>Quick Search(you should expect this from Google) &#8211; Single click web search for highlighted word.</li>
<li>Personalized Choices &#8211; Remember user corrections for personalized service.</li>
<li>Customize suggestions page size, display font </li>
</ul>
<p><a href="http://www.google.com/ime/transliteration/help.html#features" target="_blank">More features can be found in this page</a></p>
<p>Okay here’s a simple and quick demonstration in my mother tongue.</p>
<h2>1. Enable the language bar ( if it’s not enabled )</h2>
<p><a href="http://codereflect.com/wp-content/uploads/2009/12/image6.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://codereflect.com/wp-content/uploads/2009/12/image_thumb3.png" width="291" height="181" /></a> </p>
<h2>2. Select the language from language bar. You can see the Google Transliteration service on the right bottom of the screen (by default)</h2>
<p><a href="http://codereflect.com/wp-content/uploads/2009/12/image7.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://codereflect.com/wp-content/uploads/2009/12/image_thumb4.png" width="547" height="224" /></a> </p>
<p>Note that This is a per Window Settings (like the normal IME operation). i.e if you’ve two notepads running and you selected Malayalam for one of them, the other will not be affected by this settings.</p>
</p>
<h2>3. Now start typing</h2>
<p><a href="http://codereflect.com/wp-content/uploads/2009/12/image8.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://codereflect.com/wp-content/uploads/2009/12/image_thumb5.png" width="574" height="189" /></a> </p>
<p>Now you’ve the basic education on transliteration services (if you’re a newbie). Now go ahead explore more. Chat, mail, or anything in your local language. Thanks Google for taking care of our mother tongue!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2009/12/26/google-ime-for-indian-languages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to burn an image file to USB in Ubuntu Linux?</title>
		<link>http://codereflect.com/2009/11/25/how-to-burn-an-image-file-to-usb-in-ubuntu-linux/</link>
		<comments>http://codereflect.com/2009/11/25/how-to-burn-an-image-file-to-usb-in-ubuntu-linux/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 15:15:00 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://codereflect.com/?p=1054</guid>
		<description><![CDATA[This is a quick tip. In Windows, we&#8217;ve lot of free and paid alternatives to write an image file to USB device(e.g ImgBurn, Win32DiskImager). Let me explain my requirement. If I get a bootable ISO image file of an operating system like Ubuntu or moblin how would you do that if you&#8217;re in a Linux [...]]]></description>
			<content:encoded><![CDATA[<p>This is a quick tip. In Windows, we&#8217;ve lot of free and paid alternatives to write an image file to USB device(e.g <a href="http://www.imgburn.com/">ImgBurn</a>, <a href="http://launchpad.net/win32-image-writer/0.2/0.2/+download/win32diskimager-RELEASE-0.2-r23-win32.zip" target="_blank">Win32DiskImager</a>). Let me explain my requirement. If I get a bootable ISO image file of an operating system like <a href="Ubuntu.com" target="_blank">Ubuntu</a> or <a href="http://moblin.org/" target="_blank">moblin</a> how would you do that if you&#8217;re in a Linux environment? A byte-exact copy of the ISO image must be placed on the USB drive. It is not sufficient to simply copy the image file to the drive.</p>
<p>It&#8217;s quite simple to do that</p>
<p>unmount the USB device if it&#8217;s automatically mounted to the system.</p>
<p><strong>Step 1</strong></p>
<p>You can either use<code> # umount &lt;usb-drive&gt; </code>command or directly unplug using your nautilus file manager(windows shell equivalent)</p>
<p><strong>Step 2</strong></p>
<p>Image Writer is a small python executable script that detects your USB drive and writes the image to it. The advantage of using image writer is that it will not inadvertently overwrite your system hard drive. <a href="http://git.moblin.org/cgit.cgi/moblin-image-creator/plain/image-writer">Download Image Writer</a>. Navigate to the desired location where you kept the image writer and change its permission to execute.</p>
<blockquote><p><code># cd &lt;directory with downloaded image-writer file&gt;<br />
# chmod a+x ./image-writer<br />
# ./image-writer &lt;image file&gt;</code></p></blockquote>
<p>Now you&#8217;re done!</p>
<p>There&#8217;s a alternative method using &#8216;dd&#8217; which you can see in the following link. But it&#8217;s very risky. It may erase your whole system files if it&#8217;s not used carefully.</p>
<p>Source: <a href="http://moblin.org/documentation/test-drive-moblin/using-moblin-live-image" target="_blank">moblin help</a></p>
<p><img alt="" /></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2009/11/25/how-to-burn-an-image-file-to-usb-in-ubuntu-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to write your own trace function?</title>
		<link>http://codereflect.com/2009/03/11/how-to-write-your-own-trace-function/</link>
		<comments>http://codereflect.com/2009/03/11/how-to-write-your-own-trace-function/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 13:34:15 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sarathc.wordpress.com/?p=763</guid>
		<description><![CDATA[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&#8217;s displayed by debugger during debugging. You can see it in [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;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 <a title="DbgView" href="technet.microsoft.com/en-us/sysinternals/bb896647.aspx" target="_blank">DbgView </a>captures the system wide debugging string and it displays in it&#8217;s own window without debugging any of the process.</p>
<p>Mainly <a title="OutputDebugString" href="msdn.microsoft.com/en-us/library/aa363362(VS.85).aspx" target="_blank">OutputDebugString</a> function provided by Kernel32 DLL is used for &#8220;outputing&#8221; debug strings. There are other altenatives available like <a title="TRACE" href="msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx" target="_blank">TRACE</a>,<a title="ATLTRACE2" href="msdn.microsoft.com/en-us/library/dhxsse89.aspx" target="_blank"> ATLTRACE2</a> 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&#8217;s nothing but impossing restrictions on the number of parameters.</p>
<p>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</p>
<p>[sourcecode language='cpp']<br />
CString csMessage;<br />
csMessage.Format(_T(&#8220;My Data:%d&#8221;), nData );<br />
OutputDebugString(csMessage).<br />
[/sourcecode]</p>
<p>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&#8217;s better to write our own trace functions. </p>
<p>The following function is  <a href="en.wikipedia.org/wiki/Varargs" target="_blank">variadic function</a> which can be used as printf function with <a href="msdn.microsoft.com/en-us/library/75w45ekt(VS.80).aspx" target="_blank">format specifierss</a></p>
<p>[sourcecode language='cpp']<br />
void M4DTrace( LPCTSTR lpctFormat, &#8230; )<br />
{<br />
    static TCHAR szBuffer[1000];<br />
    va_list ArgList;<br />
    va_start( ArgList, lpctFormat );<br />
    _vstprintf_s( szBuffer, lpctFormat, ArgList );<br />
    va_end( ArgList );<br />
    OutputDebugString( szBuffer );<br />
}<br />
[/sourcecode]</p>
<p>Instead of _vsntprintf_s, you can use another formating function called <a href="http://msdn.microsoft.com/en-us/library/ms647551(VS.85).aspx">wvsprintf</a><br />
but I found it has some problems formatting float variables in the list. The above function can runs under both UNICODE and MBCS environment.<br />
<a href="http://www.unixwiz.net/techtips/outputdebugstring.html">If you need to know under the hood of OutputDebugString, please check this article</a><br />
Updated[2009-Apr-17) &#8211; updated formatting with _vstprintf_s instead of _vsntprintf_s</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2009/03/11/how-to-write-your-own-trace-function/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to check a given number is exact power of two?</title>
		<link>http://codereflect.com/2008/10/01/how-to-check-a-given-number-is-exact-power-of-two/</link>
		<comments>http://codereflect.com/2008/10/01/how-to-check-a-given-number-is-exact-power-of-two/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 16:32:03 +0000</pubDate>
		<dc:creator>@sarat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sarathc.wordpress.com/?p=550</guid>
		<description><![CDATA[When I was digging into OpenGL texture mapping, I was checking with some sample code (I&#8217;m not remembering from where I downloaded that), inside the code, I found a simple line to check whether the texture dimensions are power of two or not. If the texture is non power of two, the program had to [...]]]></description>
			<content:encoded><![CDATA[<p>When I was digging into OpenGL texture mapping, I was checking with some sample code (I&#8217;m not remembering from where I downloaded that), inside the code, I found a simple line to check whether the texture dimensions are power of two or not. If the texture is <a href="http://oss.sgi.com/projects/ogl-sample/registry/ARB/texture_non_power_of_two.txt">non power of two</a>, the program had to check whether the graphics hardware is capable of supporting non-power of two textures or not by querying <a href="http://www.opengl.org/registry/specs/ARB/texture_non_power_of_two.txt">GL_ARB_texture_non_power_of_two</a> string. Actually, I was much attracted with the single line of code which is checking the power of two using binary operators. It&#8217;s might be a simple logic for the programmers who deals with bits and bytes. But still it&#8217;s intresting. The sample code author had particularly mentioned the logic was adopted from SJ <a href="http://www.sjbaker.org/wiki/index.php?title=Cool_Code_list">Baker&#8217;s Cool Code List</a>.</p>
<p>Here&#8217;s baker&#8217;s method (??) for checking whether a <a href="http://www.sjbaker.org/wiki/index.php?title=Cool_Code_list">number is exact power of two or not</a>.</p>
<blockquote>
<p style="margin-left:0;"><strong>b = ((n&amp;(n-1))==0) ;</strong></p>
<p><strong> </strong><br />
(NB: This code sets &#8216;b&#8217; to TRUE if &#8216;n&#8217; is an integer power of two &#8211; in this context, both zero and one are considered to be powers of two.)</p>
<p style="margin-left:0;">This code actually works by changing the least significant &#8217;1&#8242; bit of &#8216;n&#8217; to a &#8217;0&#8242;. If &#8216;n&#8217; is a power of two, it only has one &#8217;1&#8242; bit &#8211; and zeroing it leaves you with zero as the answer. Hence, the inner expression is also a cute trick&#8230;</p>
</blockquote>
<p>If we would make it as a simple function it may appears as follows.</p>
<pre>
bool IsPowerOfTwo( int n )
{
    // Function returns true if the number if power of two
    return ((n&#038;(n-1))==0) ;
}
</pre>
<p>The logic is simply straight forward which can be interpreted by using Windows Calculator. Check it yourself. The link contains some other cool tips as well.</p>
<p> </p>
<p>Sidebar: Bakers also shared his interesting &#8220;<a href="http://www.sjbaker.org/wiki/index.php?title=Cruel_Code_list">Cruel Code List</a>&#8221; as well <span style="font-family:Wingdings;">J</p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2008/10/01/how-to-check-a-given-number-is-exact-power-of-two/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to call CUDA Programs from a C/C++ Application?</title>
		<link>http://codereflect.com/2008/09/29/how-to-call-cuda-programs-from-a-cc-application/</link>
		<comments>http://codereflect.com/2008/09/29/how-to-call-cuda-programs-from-a-cc-application/#comments</comments>
		<pubDate>Mon, 29 Sep 2008 17:21:21 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sarathc.wordpress.com/?p=532</guid>
		<description><![CDATA[Calling a CUDA function from your C/C++ file is very simple. It&#8217;s pretty straight forward as you call an extern function in C/C++. To start with, I believe you’ve added the CUDA program in your work space (or copy the program provided below and save as .cu file) and you could compile the file using [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:'Segoe UI';font-size:small;"><a href="http://sarathc.files.wordpress.com/2008/09/cudacpp.png"><img class="alignleft size-full wp-image-544" title="cudacpp" src="http://sarathc.files.wordpress.com/2008/09/cudacpp.png" alt="" width="250" height="174" /></a>Calling a CUDA function from your C/C++ file is very simple. It&#8217;s pretty straight forward as you call an extern function in C/C++. To start with, I believe you’ve added the CUDA program in your work space (or copy the program provided below and save as .cu file) and you could compile the file using CUDA compiler and finally the object files has been generated. Please check my previous post to know more about <a title="Compile CUDA under VS" href="http://sarathc.wordpress.com/2008/09/26/how-to-integrate-cuda-with-visual-c/" target="_blank">how to compile CUDA source in Visual Studio</a>. CUDA follows C language constructs and rationales. The CUDA compiler will generate the object files which contains the functions and definitions of your CUDA program. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">Let’s take a sample presented in a DDJ article </span><a href="http://www.ddj.com/hpc-high-performance-computing/207402986"><span style="font-family:'Segoe UI';font-size:small;">CUDA, Supercomputing for the Masses: Part 2</span></a><span style="font-family:'Segoe UI';font-size:small;">. The program increments the content of the array by one. Robb Farber has put an excellent effort to present CUDA in a simple manner in his high performance computing series on CUDA (Check DDJ). Please click on the link to know more about the program presented here.</span></p>
<p>[sourcecode language='cpp']<br />
// incrementArray.cu<br />
#include <stdio.h><br />
#include <assert.h><br />
#include <cuda.h></p>
<p>void incrementArrayOnHost(float *a, int N)<br />
{<br />
    int i;<br />
    for (i=0; i < N; i++) a[i] = a[i]+1.f;<br />
}<br />
__global__ void incrementArrayOnDevice(float *a, int N)<br />
{<br />
    int idx = blockIdx.x*blockDim.x + threadIdx.x;<br />
    if (idx<n) a[idx] = a[idx]+1.f;<br />
}</p>
<p>extern "C" void IncrementArray(void)<br />
{<br />
    float *a_h, *b_h;           // pointers to host memory<br />
    float *a_d;                 // pointer to device memory<br />
    int i, N = 10;<br />
    size_t size = N*sizeof(float);<br />
    // allocate arrays on host<br />
    a_h = (float *)malloc(size);<br />
    b_h = (float *)malloc(size);<br />
    // allocate array on device<br />
    cudaMalloc((void **) &#038;a_d, size);<br />
    // initialization of host data<br />
    for (i=0; i<n; i++) a_h[i] = (float)i;<br />
    // copy data from host to device<br />
    cudaMemcpy(a_d, a_h, sizeof(float)*N, cudaMemcpyHostToDevice);<br />
    // do calculation on host<br />
    incrementArrayOnHost(a_h, N);<br />
    // do calculation on device:<br />
    // Part 1 of 2. Compute execution configuration<br />
    int blockSize = 4;<br />
    int nBlocks = N/blockSize + (N%blockSize == 0?0:1);<br />
    // Part 2 of 2. Call incrementArrayOnDevice kernel<br />
    incrementArrayOnDevice <<< nBlocks, blockSize >>> (a_d, N);<br />
    // Retrieve result from device and store in b_h<br />
    cudaMemcpy(b_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost);<br />
    // check results<br />
    for (i=0; i<n; i++) assert(a_h[i] == b_h[i]);<br />
    // cleanup<br />
    free(a_h); free(b_h); cudaFree(a_d);<br />
}<br />
[/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:small;">So the above program creates a simple CUDA program which increments the contents of each element in the array by one. What I changed from the original source code is, I made the main function as a new function which follows the “C” language rules.[that’s why I put extern “C” in front of the code. Even if you don’t add extern “C” it will work fine with your C++ compiler.</span><br />
<span style="font-family:'Segoe UI';font-size:small;">Instead of including the CUDA file by #include preprocessor, it’s better to define it as an external function by extern keyword.</span><span style="font-family:'Segoe UI';font-size:small;">So your main program may appear as follows. </span></p>
<p>[sourcecode language='cpp']<br />
// IntegrationWithCPP.cpp : Defines the entry point for the console application.<br />
//</p>
<p>#include &#8220;stdafx.h&#8221;</p>
<p>// Forward declare the function<br />
extern &#8220;C&#8221; void IncrementArray();</p>
<p>int _tmain(int argc, _TCHAR* argv[])<br />
{<br />
    IncrementArray();<br />
	return 0;<br />
}<br />
[/sourcecode]</p>
<p>Finally link the program with cudart.lib <span style="text-decoration:line-through;">cudartd.lib(debug) or cudart.lib(release)</span> and enjoy your program!!!</p>
<p><span style="font-family:'Segoe UI';font-size:small;">That’s it. One thing I noticed is that, even if I define the main functions in CUDA file and my C++ file, I’m not getting any error from the linker. The linker gives error only if the main function in CUDA and C++ file having same prototype. Otherwise the version in the CUDA file will be called (from my experience so far).</span></p>
<p style="text-align:center;padding-bottom:0;line-height:0;margin-top:10px;margin-bottom:0;"><a href="http://feeds.feedburner.com/~r/SharingMyThoughts/~6/3"><img style="border-width:0;" src="http://feeds.feedburner.com/SharingMyThoughts.3.gif" alt="Sharing my thoughts..." /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2008/09/29/how-to-call-cuda-programs-from-a-cc-application/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to Integrate CUDA with Visual C++</title>
		<link>http://codereflect.com/2008/09/26/how-to-integrate-cuda-with-visual-c/</link>
		<comments>http://codereflect.com/2008/09/26/how-to-integrate-cuda-with-visual-c/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 13:54:01 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sarathc.wordpress.com/?p=520</guid>
		<description><![CDATA[If you want to program CUDA, first you will have to install latest nVidia CUDA Driver for your Graphics Hardware which supports desired CUDA version. Then you will have to install the CUDA Toolkit which includes the CUDA Compiler, Include file, lib file and binary files to develop your CUDA application. The bin folder under your CUDA installation location (most [...]]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">If you want to program CUDA, first you will have to install latest nVidia CUDA Driver for your Graphics Hardware which supports desired CUDA version. Then you will have to install the CUDA Toolkit which includes the CUDA Compiler, Include file, lib file and binary files to develop your CUDA application.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">The bin folder under your CUDA installation location (most probably C:\CUDA), you can see nvcc.exe which helps you to compile the CUDA program. If you give, nvcc my_cuda_filename.cu, the compiler will compile the source file and creates the executables (a.exe).<br />
</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">But in Windows world, most of the developers are much satisfied with the IDE Visual Studio. So may have to leave the world of command line compilation and source editing in favor of improving our productivity. If we can integrate the CUDA development to Visual Studio IDE, that&#8217;s pretty nice no? <span style="font-size:11pt;">In one of my previous post, </span><a href="http://sarathc.wordpress.com/2008/09/04/how-to-enable-syntax-highlighting-for-cuda-files-in-visual-studio-2005/"><span style="font-size:11pt;">I said about enabling syntax highlighting for CUDA files under Visual Studio</span></a><span style="font-size:11pt;">.</span></span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;"><span style="font-size:11pt;"> Now let’s check how we can support CUDA compilation under Visual Studio. CUDA compiler has a dependency with C++ compiler. It supports either Visual C++ 7.1 or 8.0. Currently it doesn’t support Visual C++ 9 (VS 2008).</span></span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><strong><span style="font-family:'Segoe UI',sans-serif;"> <span style="font-size:11pt;">Method 1 – Install CUDA Build Rule for Visual Studio 2005</span></span></strong></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">There’s a painless method by installing a </span><a href="http://forums.nvidia.com/index.php?showtopic=65111"><span style="font-size:11pt;">custom build rule for Visual Studio 2005 developed by JaredHoberock</span></a><span style="font-size:11pt;">. A cool installer is available to do the necessary settings. When you add the “.cu” files to your application, it shows a dialog box to select the rule you installed. Press “OK” button.</span></span></p>
<div id="attachment_521" class="wp-caption aligncenter" style="width: 478px"><a href="http://sarathc.files.wordpress.com/2008/09/add.png"><img class="size-full wp-image-521" title="Select CUDA Build Rule" src="http://sarathc.files.wordpress.com/2008/09/add.png" alt="Select CUDA Build Rule" width="468" height="299" /></a><p class="wp-caption-text">Select CUDA Build Rule</p></div>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">You can control the per-file (.cu file) configuration for your application by selecting the properties of the file from your solution explorer. See the figure below.</span></span></p>
<div id="attachment_523" class="wp-caption aligncenter" style="width: 478px"><a href="http://sarathc.files.wordpress.com/2008/09/copy-of-sampel.png"><img class="size-full wp-image-523" title="Detailed Build Configuration under Custom Build Event" src="http://sarathc.files.wordpress.com/2008/09/copy-of-sampel.png" alt="Detailed Build Configuration under Wizard" width="468" height="325" /></a><p class="wp-caption-text">Detailed Build Configuration under Wizard</p></div>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">The installer also adds new Project Type to create your new CUDA project which does the necessary settings for your application.<br />
</span></span></p>
<div id="attachment_525" class="wp-caption aligncenter" style="width: 478px"><a href="http://sarathc.files.wordpress.com/2008/09/wizard2005.png"><img class="size-full wp-image-525" title="Wizard to create new CUDA Project" src="http://sarathc.files.wordpress.com/2008/09/wizard2005.png" alt="Wizard to create new CUDA Project" width="468" height="322" /></a><p class="wp-caption-text">Wizard to create new CUDA Project</p></div>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Finally you can put the required CUDA libraries (e.g CUDA Runtime library &#8211; cudart.lib) in Project-&gt;Properties-&gt;Linker-&gt;Input-&gt;Additional Dependency.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">I think the installer won’t work for Visual Studio 2003. I think you can manually copy the rule file from $:\Program Files\Microsoft Visual Studio 8\VC\VCProjectDefaults\cuda.rules and specify this as the rule file for compilation. Anyway try it yourself.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><strong><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Method 2 – Manually Configure by Custom Build Event</span></span></strong></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Without Visual Studio, we can use nvcc compiler for compiling the CUDA files with various command line parameters. So the same setup we can use with Visual Studio as well. One of the advantages is that, we can use various Visual Studio Specific variables to identify various file locations.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"> </p>
<div id="attachment_522" class="wp-caption aligncenter" style="width: 478px"><a href="http://sarathc.files.wordpress.com/2008/09/build.png"><img class="size-full wp-image-522 " title="Custom Build" src="http://sarathc.files.wordpress.com/2008/09/build.png" alt="Custom Build" width="468" height="325" /></a><p class="wp-caption-text">Custom Build</p></div>
<p> </p>
<p class="MsoListParagraphCxSpFirst" style="text-indent:-.25in;margin:0 0 0 .5in;"><span style="font-family:'Segoe UI',sans-serif;"> <span><span style="font-size:11pt;">1.</span><span style="font-size:11pt;"><span style="font-family:'Times New Roman';line-height:normal;"> </span></span></span></span><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Select the CUDA source file from the solution explorer and take properties.</span></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;margin:0 0 0 .5in;"><span style="font-family:'Segoe UI',sans-serif;"><span><span style="font-size:11pt;">2.</span><span style="font:7pt 'Times New Roman';">  </span></span></span><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Select “Custom Build Setup” from the tree</span></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;margin:0 0 0 .5in;"><span style="font-family:'Segoe UI',sans-serif;"><span><span style="font-size:11pt;">3.</span><span style="font:7pt 'Times New Roman';">  </span></span></span><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">You can select the active configuration from “Configuration” combo box.</span></span></p>
<p class="MsoListParagraphCxSpLast" style="text-indent:-.25in;margin:0 0 10pt .5in;"><span style="font-family:'Segoe UI',sans-serif;"><span><span style="font-size:11pt;">4.</span><span style="font-size:11pt;"><span style="font-family:'Times New Roman';line-height:normal;"> </span></span></span></span><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Specify the following options under “Command Line”<br />
</span></span></p>
<blockquote>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">&#8220;$(CUDA_BIN_PATH)\nvcc.exe&#8221; -ccbin &#8220;$(VCInstallDir)bin&#8221; -c -D_DEBUG -DWIN32 -D_CONSOLE -D_MBCS -Xcompiler /EHsc,/W3,/nologo,/Wp64,/Od,/Zi,/RTC1,/MTd -I&#8221;$(CUDA_INC_PATH)&#8221; -I./ -o $(ConfigurationName)\&lt;your_cu_filename&gt;.obj &lt;your_cu_filename&gt;.cu </span></span></p>
</blockquote>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">The above configuration is to compile the source under debug configuration. For a release configuration, you will have to remove the symbol definition, _DEBUG (-D switch is to define symbols). Also the above command line ask to link with the static-debug version of C-Runtime library by specifying /MTd option. In the case of release build you will have to modify it to /MD or /MT. Please check the various <a title="CRT Versions" href="http://msdn.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx" target="_blank">C-Runtime versions</a> from MSDN and apply accordingly. Thus a sample command line for release version may look as follows. </span></span></p>
<blockquote>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">&#8220;$(CUDA_BIN_PATH)\nvcc.exe&#8221; -ccbin &#8220;$(VCInstallDir)bin&#8221; -c -DWIN32 -D_CONSOLE -D_MBCS -Xcompiler /EHsc,/W3,/nologo,/Wp64,/Od,/Zi,/RTC1,/MD -I&#8221;$(CUDA_INC_PATH)&#8221; -I./ -o $(ConfigurationName)\&lt;your_cu_filename&gt;.obj &lt;your_cu_filename&gt;.cu </span></span></p>
</blockquote>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">If you need to add Device Emulation option, you add -deviceemu switch in the command line. Thus you the compiler will generate code for GPGPU Emulation library. You can understand more about each switches from MSDN itself. The information about the other variables used has been specified at the end of this post.</span></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-indent:-.25in;margin:0 0 0 .5in;"><span style="font-family:'Segoe UI',sans-serif;"><span><span style="font-size:11pt;">5.</span><span style="font-size:11pt;"> </span></span></span><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">You can specify your own description for the custom build event under “Description” text box. (See the figure)</span></span></p>
<p class="MsoListParagraphCxSpLast" style="text-indent:-.25in;margin:0 0 10pt .5in;"><span style="font-family:'Segoe UI',sans-serif;"><span><span style="font-size:11pt;">6. </span></span></span><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Finally you have to specify the output file name under “Outputs”</span></span></p>
<blockquote>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">$(ConfigurationName)\&lt;your_cu_filename&gt;.obj</span></span></p>
</blockquote>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">7. If you<span>  </span>have included any CUDA files (probably will be having extension .cu or .cuh), you can specify it in the “Additional Dependencies option</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">In the command line string, we’ve used some visual studio specific build macros. </span><a href="http://msdn.microsoft.com/en-us/library/c02as0cs(VS.71).aspx"><span style="font-size:11pt;">You can see the entire list of Visual Studio Build Macros in MSDN</span></a><span>.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">8. Finally build your project and now see the output of CUDA compilation in your output Window.</span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><strong><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Adding a new build configuration</span></span></strong></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">Sometimes you have to build your file with CUDA emulation for many debugging purpose. <span style="font-size:11pt;"> </span><a href="http://msdn.microsoft.com/en-us/library/ms181716(VS.80).aspx"><span style="font-size:11pt;">Please check MSDN to know more about adding build configuration.</span></a></span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:'Segoe UI',sans-serif;"><span style="font-size:11pt;">I’ll explain how to call a CUDA Program from a C++ file in the next post. Thanks for your patience. I’m a newbie in CUDA. If you’ve better ideas and suggestions, please share with me through your comments. </span></span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"> </p>
<p style="text-align:center;padding-bottom:0;line-height:0;margin-top:10px;margin-bottom:0;"><a href="http://feeds.feedburner.com/~r/SharingMyThoughts/~6/3"><img style="border-width:0;" src="http://feeds.feedburner.com/SharingMyThoughts.3.gif" alt="Sharing my thoughts..." /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2008/09/26/how-to-integrate-cuda-with-visual-c/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Describing Windows XP and Vista Shutdown in Application context</title>
		<link>http://codereflect.com/2008/09/22/describing-windows-xp-and-vista-shutdown-in-application-context/</link>
		<comments>http://codereflect.com/2008/09/22/describing-windows-xp-and-vista-shutdown-in-application-context/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 20:24:09 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sarathc.wordpress.com/2008/09/22/describing-windows-xp-and-vista-shutdown-in-application-context/</guid>
		<description><![CDATA[In this post, I’m talking about some internals of Windows Shutdown in the context of applications. When the user or an application initiates shutdown request through ExitWindowsEx function, the Csrss.exe will be initiating the shutdown operation by sending a window message to the hidden window owned by Winlogon process. The subsystem process Csrss.exe contains handles, [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:'Segoe UI';font-size:11pt;"> </span></p>
<p><span style="font-family:'Segoe UI';font-size:11pt;">In this post, I’m talking about some internals of Windows Shutdown in the context of applications.</span></p>
<p><span style="font-family:'Segoe UI';font-size:11pt;">When the user or an application initiates shutdown request through <a href="http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx">ExitWindowsEx</a> function, the Csrss.exe will be initiating the shutdown operation by sending a window message to the hidden window owned by Winlogon process. The subsystem process <strong>Csrss.exe</strong> contains handles, Console (text) windows, creation and deletion of processes and threads and other various supports like ExitWindowEx etc&#8230;</span><br />
<span style="font-family:'Segoe UI';font-size:11pt;"><br />
The Winlogon process calls ExitWindowsEx function with some internal flags to continue the shutdown based on the security access rights of the currently-logged in user. Since the ExitWindowEx call has been made again, it falls back in the hand of Csrss.exe.</span></p>
<p><span style="font-family:'Segoe UI';font-size:11pt;">Csrss sends the WM_QUERYENDSESSION message to each thread in the process that has a Windows message loop. This message is like warning from the system that, the application has to respond for the shutdown operation. The shutdown can be preceded when the thread returns TRUE. If the thread returns FALSE, in most cases, the shutdown operation will be cancelled. The shutdown should be cancelled only for the valid reasons like CD burning, live recording etc…</span></p>
<p><span style="font-family:'Segoe UI';font-size:11pt;"><a href="http://sarathc.files.wordpress.com/2008/09/clip-image002.jpg"><img style="border-bottom:0;border-left:0;border-top:0;border-right:0;" src="http://sarathc.files.wordpress.com/2008/09/clip-image002-thumb.jpg" border="0" alt="clip_image002" hspace="12" width="273" height="335" align="left" /></a>Windows Vista supports more interactive shutdown(When the screen like left appears and I wondered when try to shutdown while the office applications are running. Now got the nuts and bolts of it <img src='http://codereflect.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ). One or many applications can cancel the shutdown operation under windows XP. In windows vista, if either of the application cancels shutdown operation, windows shows the list of currently running application and also the blocking application on the top of the window. If the user wants to shut his computer down, he can forcefully do that by clicking on the “Shut down now” button(red button in the figure). In this case windows sends WM_QUERYENDSESSION again with ENDSESSION_FORCEFULSHUTDOWN flag. If an application responds FALSE, Windows will continue shutdown instead of canceling it.</span></p>
<p><span style="font-family:'Segoe UI';font-size:11pt;">Windows Vista provides a facility to pro-actively describe about the reason for cancelling the shutdown. There are three new APIs at our disposal to manage shutdown cancellation string.</span></p>
<p>[sourcecode language='cpp']<br />
BOOL ShutdownBlockReasonCreate(HWND hWnd, LPCWSTR pwszReason);<br />
BOOL ShutdownBlockReasonDestroy(HWND hWnd);<br />
BOOL ShutdownBlockReasonQuery(HWND hWnd, LPWSTR pwszBuff, DWORD *pcchBuff);<br />
[/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:11pt;"><br />
The above functions are used to create, destroy and query the cancellation string for the window. The best time to create the string is at WM_QUERYENDSESSION function and destroys it once the application finished using it. (See the sample below for the usage)</span><br />
<span style="font-family:'Segoe UI';font-size:11pt;"><br />
Once the Query end session function returns true or managed to get out from the above described scenarios, Csrss then sends the WM_ENDSESSION Windows message to the thread to request it to exit. The application will get 5 second as time out as default (it’s defined in HKCU\Control Panel\Desktop\HungAppTimeout). If an application times out responding to WM_QUERYENDSESSION or WM_ENDSESSION, Windows will terminate it.<br />
</span><span style="font-family:'Segoe UI';font-size:11pt;"><br />
The behavior of the application time out is slightly different in Windows Vista and XP as we see in the picture below. <a href="http://msdn.microsoft.com/en-us/library/ms700677(VS.85).aspx">Please check MSDN (I don’t want to copy paste it here) to get the detailed table</a>.<br />
</span><span style="font-family:'Segoe UI';font-size:11pt;"><br />
If the thread doesn&#8217;t exit before the timeout, Csrss displays the hung-program dialog box (End Now). You can disable this dialog box by changing the registry value HKCU\Control Panel\Desktop\AutoEndTasks to 1. This dialog box indicates that a program isn&#8217;t shutting down in a timely manner and gives the user a choice of either killing the process or aborting the shutdown. There is no timeout on this dialog box, which means that a shutdown request could wait forever at this point.<br />
</span><span style="font-family:'Segoe UI';font-size:11pt;"><br />
Once all the threads that own windows in the process have exited, Csrss terminates the process and goes on to the next process in the interactive session.<br />
</span><span style="font-family:'Segoe UI';font-size:11pt;"><br />
OK Now you’re capable of handling the shutdown message for your application. Here’s a sample snippet for doing the same (MFC)<br />
</span></p>
<p>[sourcecode language='cpp']<br />
/* Map the following functions manually in your application (Win32 style)<br />
 */</p>
<p>BEGIN_MESSAGE_MAP(CShutDownTestDlg, CDialog)<br />
	ON_MESSAGE( WM_QUERYENDSESSION, QueryEndSession )<br />
	ON_MESSAGE( WM_ENDSESSION, EndSession )<br />
	//}}AFX_MSG_MAP<br />
END_MESSAGE_MAP()</p>
<p>LRESULT CShutDownTestDlg::QueryEndSession(WPARAM,LPARAM)<br />
{<br />
	// Block shut down<br />
	ShutdownBlockReasonCreate(m_hWnd, L&#8221;TV Show being recorded&#8221; );<br />
	return FALSE;<br />
	// return TRUE; // continue shutdown<br />
}</p>
<p>LRESULT CShutDownTestDlg::EndSession(WPARAM,LPARAM)<br />
{<br />
	// Destroy the shutdown string used earlier<br />
	ShutdownBlockReasonDestroy(m_hWnd);<br />
	return TRUE;<br />
}<br />
 [/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:11pt;">Here&#8217;s the pure MFC way to do the same</span></p>
<p>[sourcecode language='cpp']<br />
/* Add the function using class wizard or through property window (VS2003 or above)<br />
 */</p>
<p>BEGIN_MESSAGE_MAP(CShutDownTestDlg, CDialog)<br />
	ON_WM_QUERYENDSESSION()<br />
	ON_WM_ENDSESSION()<br />
	//}}AFX_MSG_MAP<br />
END_MESSAGE_MAP()</p>
<p>BOOL CShutDownTestDlg::OnQueryEndSession()<br />
{<br />
	// Block shut down<br />
	ShutdownBlockReasonCreate(m_hWnd, L&#8221;TV Show being recorded&#8221; );<br />
	return FALSE;</p>
<p>}</p>
<p>void CShutDownTestDlg::OnEndSession(BOOL bEnding)<br />
{<br />
	// Destroy the shutdown string used earlier<br />
	ShutdownBlockReasonDestroy(m_hWnd);<br />
	CDialog::OnEndSession(bEnding);<br />
}<br />
 [/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:11pt;">Hope you enjoyed this lengthy post. Thanks for <a href="http://msdn.microsoft.com/en-us/library/ms700677(VS.85).aspx" target="_blank">MSDN article</a>and Mark Russinovich for his book <a href="http://www.amazon.com/Microsoft-Windows-Internals-4th-Server/dp/073561917" target="_blank">Windows Internals</a>. Those were the light for my path. </span></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:d5415cdb-638d-4cc1-8140-78bba85d24e2" class="wlWriterSmartContent" style="display:inline;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Windows%20Vista">Windows Vista</a>,<a rel="tag" href="http://technorati.com/tags/Shutdown">Shutdown</a>,<a rel="tag" href="http://technorati.com/tags/Win32">Win32</a>,<a rel="tag" href="http://technorati.com/tags/API">API</a>,<a rel="tag" href="http://technorati.com/tags/MFC">MFC</a></div>
<p style="font-family:'Segoe UI';font-size:11pt;text-align:center;padding-bottom:0;line-height:0;margin-top:10px;margin-bottom:0;"><a href="http://feeds.feedburner.com/~r/SharingMyThoughts/~6/3"><img style="border-width:0;" src="http://feeds.feedburner.com/SharingMyThoughts.3.gif" alt="Sharing my thoughts..." /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2008/09/22/describing-windows-xp-and-vista-shutdown-in-application-context/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>When and How should we use MsgWaitForMultipleObjects?</title>
		<link>http://codereflect.com/2008/09/19/when-and-how-should-we-use-msgwaitformultipleobjects/</link>
		<comments>http://codereflect.com/2008/09/19/when-and-how-should-we-use-msgwaitformultipleobjects/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 17:22:45 +0000</pubDate>
		<dc:creator></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sarathc.wordpress.com/?p=487</guid>
		<description><![CDATA[Most of us have used WaitForSingleObject and WaitForMultipleObjects in our code. Well, what we can do more with MsgWaitForMultipleObjects (there’s no API called MsgWaitForSingleObject. You will understand the reason soon). MsgWaitForMultipleObjects wait for a wait-able kernal object and for the input messages in the current thread. You may find it very useful in some situations. [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family:'Segoe UI';font-size:small;"><a href="http://sarathc.files.wordpress.com/2008/09/296px-wooden_hourglass_31.png"><img class="alignleft size-full wp-image-491" title="296px-wooden_hourglass_31" src="http://sarathc.files.wordpress.com/2008/09/296px-wooden_hourglass_31.png" alt="" width="100" height="222" /></a>Most of us have used <a href="http://msdn.microsoft.com/en-us/library/ms687032.aspx" target="_blank">WaitForSingleObject</a> and <a href="http://msdn.microsoft.com/en-us/library/ms687025.aspx" target="_blank">WaitForMultipleObjects</a> in our code. Well, what we can do more with MsgWaitForMultipleObjects (there’s no API called <a href="http://msdn.microsoft.com/en-us/library/ms684242(VS.85).aspx" target="_blank">MsgWaitForSingleObject</a>. You will understand the reason soon). </span></p>
<p><em><span style="font-family:'Segoe UI';font-size:small;">MsgWaitForMultipleObjects wait for a wait-able kernal object and for the input messages in the current thread. </span></em></p>
<p><span style="font-family:'Segoe UI';font-size:small;">You may find it very useful in some situations. What if we can do the window painting, process the timer message even the UI thread in the wait state. Pretty cool no? Even I don’t know the under the hood of “Add Remove Programs” application, I believe that the application waits till the current un-install program finishes its execution and during this time, it’s even allows proper painting of its windows components. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">The function takes the following shape. </span></p>
<p>[sourcecode language='cpp']<br />
DWORD WINAPI MsgWaitForMultipleObjects(<br />
  __in  DWORD nCount,<br />
  __in  const HANDLE *pHandles,<br />
  __in  BOOL bWaitAll,<br />
  __in  DWORD dwMilliseconds,<br />
  __in  DWORD dwWakeMask<br />
);<br />
[/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:small;">You can get detailed information and various parameters from the MSDN documentation of the API. Here I’m describing only the important ones. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">You can pass multiple wait-able handles as an array to the function by specifying the size of the array. The maximum number of objects is MAXIMUM_WAIT_OBJECTS – 1 because the last wait object is used to indicate the availability of message by getting out from the wait function. If the function returned WAIT_OBJECT_0 + nCount, then it indicates that the new input of the type specified in dwWakeMask is arrived. You can get detailed information on the return value from MSDN documentation. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">The next important parameter is dwWakMask. It indicates the possible type of messages we wish to wait upon. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">Read further after checking the code OK? I want to convey few caveats of this API. It will be too early to describe here. Here’s the sample demonstration of the API </span></p>
<p>[sourcecode language='cpp']<br />
HANDLE hQuit = 0; // Mutex handle<br />
// Message definition<br />
DWORD DO_PROCESSING_MSG = 5555;</p>
<p>DWORD WINAPI ThreadFxn( LPVOID )<br />
{<br />
	MSG msg;<br />
	while( true )<br />
	{<br />
		// Wait for mutex and all input events<br />
		DWORD dwResult = MsgWaitForMultipleObjects( 1,<br />
									&#038;hQuit,<br />
									FALSE,<br />
									INFINITE,<br />
									QS_ALLEVENTS );</p>
<p>		// if message has been received<br />
		if( dwResult == WAIT_OBJECT_0+1 )<br />
		{<br />
			// Check if message arrived or not<br />
			if(PeekMessage(&#038;msg, (HWND)-1, 0, 0, PM_REMOVE))<br />
			{<br />
				// Translate and dispatch message<br />
				TranslateMessage(&#038;msg);<br />
				DispatchMessage(&#038;msg);<br />
			}<br />
			printf (&#8221; \n New Message Receieved &#8221; );<br />
		}<br />
		else // it&#8217;s time to quit<br />
		{<br />
			printf( &#8220;\nbye bye&#8221; );<br />
			break;<br />
		}<br />
	}<br />
	return 0;<br />
}</p>
<p>int _tmain(int argc, TCHAR* argv[])<br />
{<br />
	int nRetCode = 0;<br />
	// Create Mutex<br />
	hQuit = CreateMutex( 0, TRUE, 0 );</p>
<p>	DWORD dwTid = 0;<br />
	// Create new thread<br />
	HANDLE hThread = CreateThread(0,0,ThreadFxn,0,0,&#038;dwTid);</p>
<p>	// Post some message<br />
	for ( int i = 0 ; i < 10; i ++ )<br />
	{<br />
		// Post message to thread's queue<br />
		PostThreadMessage( dwTid, DO_PROCESSING_MSG, 0, 0 );<br />
		Sleep( 500 );<br />
	}</p>
<p>	// Signal the mutex to quit<br />
	ReleaseMutex( hQuit );<br />
	// Wait till the thread exits<br />
	WaitForSingleObject( hThread,INFINITE);<br />
	CloseHandle( hQuit );<br />
	return nRetCode;<br />
}<br />
[/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:small;"><strong>The tricky bWaitAll parameter. </strong></span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">If you check the bWaitAll parameter’s document in MSDN, you can find it is described same as WaitForMultiplObjects API. In the sample code above, we’re waiting for one kernel object and the thread messages we’re interested. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">What happens if we wait as follows ? </span></p>
<p>[sourcecode language='cpp']<br />
DWORD dwResult = MsgWaitForMultipleObjects( 1,<br />
					&#038;hQuit,<br />
					TRUE,<br />
					INFINITE,<br />
					QS_ALLEVENTS );<br />
[/sourcecode]</p>
<p><span style="font-family:'Segoe UI';font-size:small;"><strong><em>We’re passing bWaitAll parameter as true instead of FALSE. Which means that the function returns all the objects we’re waiting upon should be signaled. Here we’re passing only kernel object and even if you call “ReleaseMutex”, the thread will not be signaled until it receives a message in the thread’s queue. i.e the function actually waits for kernel objects + one more message in the thread’s queue. </em></strong></span></p>
<p><span style="font-family:'Segoe UI';font-size:small;"><a href="http://blogs.msdn.com/oldnewthing/archive/2005/02/17/375307.aspx" target="_blank"><strong>Raymond chen explains about another caveat with MsgWaitForMultipleObjects</strong></a><strong> </strong>and the queue state in his blog. I will explain the issue here in short. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;"><a href="http://msdn.microsoft.com/en-us/library/ms644943(VS.85).aspx" target="_blank">PeekMessage</a>(&amp;msg, NULL, 0, 0, PM_NOREMOVE) returns TRUE indicating that there is a message. Instead of processing the message, you ignore it and call MsgWaitForMultipleObjects. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">This wait will not return immediately, even though there is a message in the queue. That&#8217;s because the call to PeekMessage told you that a message was ready, and you willfully ignored it. The MsgWaitForMultipleObjects message tells you only when there are new messages; any message that you already knew about doesn&#8217;t count. The <a href="http://msdn.microsoft.com/en-us/library/ms684245(VS.85).aspx" target="_self">MsgWaitForMultipleObjectsEx </a>function lets you pass the MWMO_INPUTAVAILABLE flag to indicate that it should check for previously-ignored input. Seems</span><span style="font-family:'Segoe UI';font-size:small;"> It’s enough read more details from Raymond’s blog. </span></p>
<p><span style="font-family:'Segoe UI';font-size:small;">Sidebar: <a href="http://msdn.microsoft.com/en-us/library/ms961241.aspx" target="_blank">The windows CE documentation saying it&#8217;s possible to wait for CriticalSection object with MsgWaitForMultipleObjects</a>. I believe that could be their typo or something. But I never succeeds to call this API with Critical Section objects. Please let me know if someone could use it with Critical Section objects.<span style="font-family:'Lucida Grande';"> </span></span></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:2e8eea0f-4091-44f9-bee7-2e24ca7af72f" class="wlWriterEditableSmartContent" style="display:inline;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Tips">Tips</a>,<a rel="tag" href="http://technorati.com/tags/Win32">Win32</a>,<a rel="tag" href="http://technorati.com/tags/Kernel%20Objects">Kernel Objects</a>,<a rel="tag" href="http://technorati.com/tags/Windows">Windows</a></div>
<p style="text-align:center;padding-bottom:0;line-height:0;margin-top:10px;margin-bottom:0;"> </p>
<div style="text-align:auto;"><span style="line-height:19px;"><br />
</span></div>
<p><a href="http://feeds.feedburner.com/~r/SharingMyThoughts/~6/3"><img style="border-width:0;" src="http://feeds.feedburner.com/SharingMyThoughts.3.gif" alt="Sharing my thoughts..." /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://codereflect.com/2008/09/19/when-and-how-should-we-use-msgwaitformultipleobjects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

