tag:blogger.com,1999:blog-27615824183641093732024-03-14T09:57:14.149+05:30Creative CreatureManishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comBlogger24125tag:blogger.com,1999:blog-2761582418364109373.post-27636292338099672622014-03-04T10:43:00.003+05:302014-03-04T10:43:28.549+05:30Windows Heap, Stack and Leaks - A story with pictures Well the title was just to attract your attention, anyways this is just for me to remember certain things related to windows stack and heap corruption issues.<br />
<br />
Links:<br />
<ol>
<li><a href="http://code.msdn.microsoft.com/CppResourceLeaks-ad3b7fdb" target="_blank">C++ Resource Leaks</a></li>
<li><a href="http://code.msdn.microsoft.com/CppStackCorruption-dc4f7396" target="_blank">C++ Stack Corruption</a></li>
<li><a href="http://code.msdn.microsoft.com/CppStackOverflow-30c558bf" target="_blank">C++ Stack Overflow</a></li>
<li><a href="http://code.msdn.microsoft.com/CppHeapCorruption-5daa7d3c" target="_blank">C++ Heap Corruption</a></li>
</ol>
And in case the links are dead, I have converted them into full page images, refer them if and only if the links are dead or changed.<br />
<br />
Enjoy !<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-fHtNarUcZ4g/UxVgRk_dfSI/AAAAAAAAAeY/-RfIYOEbV2o/s1600/CppHeapCorrupt%E2%80%8B%E2%80%8Bion.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-fHtNarUcZ4g/UxVgRk_dfSI/AAAAAAAAAeY/-RfIYOEbV2o/s1600/CppHeapCorrupt%E2%80%8B%E2%80%8Bion.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-m_U0S6H1my0/UxVgS1Pu92I/AAAAAAAAAec/bEp4qJjWiqI/s1600/CppResourceLeaks.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-m_U0S6H1my0/UxVgS1Pu92I/AAAAAAAAAec/bEp4qJjWiqI/s1600/CppResourceLeaks.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-lckDVrztIeU/UxVgRMCJgRI/AAAAAAAAAeQ/jFmeszecalQ/s1600/CppStackCorrup%E2%80%8Btion.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-lckDVrztIeU/UxVgRMCJgRI/AAAAAAAAAeQ/jFmeszecalQ/s1600/CppStackCorrup%E2%80%8Btion.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-Kt8wb9lHDWQ/UxVgTiAGD-I/AAAAAAAAAeo/3Z-SCEMLcGY/s1600/CppStackOverfl%E2%80%8Bow.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-Kt8wb9lHDWQ/UxVgTiAGD-I/AAAAAAAAAeo/3Z-SCEMLcGY/s1600/CppStackOverfl%E2%80%8Bow.png" /></a></div>
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-70054483938663384942013-09-20T13:18:00.000+05:302013-09-20T13:21:01.337+05:30Generate Lib From DLL<span style="font-size: large;">Introduction </span><br />
To avoid installing and fighting against MSYS and Cygwin, you can just extract exported symbols from libvlc.dll to generate a .lib (libvlc.lib) and link your program against it. <br />
<br />
<span style="font-size: large;">Open Visual Studio Command Prompt</span> <br />
It can be found within the Visual Studio Tools menu entry:<br />
Start / Program Files / Microsoft Visual Studio / Visual Studio Tools / Visual Studio Command Prompt.<br />
<br />
<span style="font-size: large;">Extract Symbols </span><br />
Within the command prompt type: <br />
<pre class="brush:c++">dumpbin /exports "C:\Program Files\VideoLAN\VLC\libvlc.dll" > "C:\Program Files\VideoLAN\VLC\libvlc.def"
</pre>Edit the <span style="color: blue;"><b>libvlc.def</b></span> file and modify it to get something like this: <br />
<pre class="brush:c++">EXPORTS
libvlc_add_intf
libvlc_audio_get_channel
libvlc_audio_get_mute
libvlc_audio_get_track
libvlc_audio_get_track_count
libvlc_audio_get_track_description
libvlc_audio_get_volume
...
</pre><span style="font-size: large;">Generate the .lib </span><br />
Still within the command prompt type:<br />
<pre class="brush:c++">lib /def:"C:\Program Files\VideoLAN\VLC\libvlc.def" /out:"C:\Program Files\VideoLAN\VLC\libvlc.lib" /machine:x86
</pre>Of course, you'll need to adapt the path according to your configuration.<br />
<br />
<span style="font-size: large;">Source </span><br />
<a href="https://wiki.videolan.org/GenerateLibFromDll" target="_blank">Generate Lib From DLL</a><br />
<br />
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-89019576596752681502013-09-07T20:16:00.000+05:302013-09-07T20:42:07.794+05:30Generating DTMF tones using C++<span style="font-size: large;"><b>What are DTMF tones ?</b></span><br />
<br />
<div style="text-align: justify;">DTMF tones are the tones used in telephones for tone dialing. The DTMF tones are sums of two sine wave tones at following frequencies: </div><pre class="brush:c++"> 1209 Hz 1336 Hz 1477 Hz 1633 Hz
ABC DEF
697 Hz 1 2 3 A
GHI JKL MNO
770 Hz 4 5 6 B
PRS TUV WXY
852 Hz 7 8 9 C
oper
941 Hz * 0 # D
</pre><br />
<b><span style="font-size: large;">How to generate DTMF tone samples</span></b><br />
Generating sine wave samples is easy using the following formula:<br />
<pre class="brush:c++">sample=sin(n*2*pi*f/samplerate)</pre><span style="color: red;"><b>Where</b></span> <br />
<ul><li><b>n</b> is the sample number (starting from 0)</li>
<li><b>f </b>is the frequency you wan to generate</li>
<li><b>samplerate </b>is the rate you are playing the samples through your sound card</li>
</ul><div style="text-align: justify;">Generating DTMF tones using this method is quite easy by just summing two of those sine waves.For example, for calculating samples for 8 kHz sample rate at 8 bit (unsigned) data, use the following function:</div><pre class="brush:c++">sample(n) = 128 + 63*sin(n*2*pi*f1/8000) + 63*sin(n*2*pi*f2/8000)</pre><div style="text-align: justify;">Where f1 and f2 are the frequencies of the sine waves in DTMF tone. </div><br />
<span style="font-size: large;"><b>C++ Code (For 8 KHz Sampling Rate)</b></span><br />
<pre class="brush:c++">#include <windows.h>
#include <math.h>
#define M_PI 3.14159265358979323846
class DTMF
{
public:
DTMF(char digit, int iMilliSeconds = 100, WORD wSampleRate = 8000)
{
m_iPacketLength = iMilliSeconds * 8000/1000;
m_pTone = new BYTE[m_iPacketLength];
if(m_pTone == NULL){
return;
}
int lowtone_frequency = 0;
int hightone_frequency = 0;
switch(digit)
{
case '1': case '2': case '3': case 'A': lowtone_frequency = 697; break;
case '4': case '5': case '6': case 'B': lowtone_frequency = 770; break;
case '7': case '8': case '9': case 'C': lowtone_frequency = 852; break;
case '*': case '0': case '#': case 'D': lowtone_frequency = 941; break;
}
switch(digit)
{
case '1': case '4': case '7': case '*': hightone_frequency = 1209; break;
case '2': case '5': case '8': case '0': hightone_frequency = 1336; break;
case '3': case '6': case '9': case '#': hightone_frequency = 1477; break;
case 'A': case 'B': case 'C': case 'D': hightone_frequency = 1633; break;
}
double pi_prod_1 = (2.0 * M_PI * lowtone_frequency)/wSampleRate;
double pi_prod_2 = (2.0 * M_PI * hightone_frequency)/wSampleRate;
for(int i=0; i<m_iPacketLength; i++)
{
m_pTone[i] = 128 + BYTE(63*sin(i*pi_prod_1) + 63*sin(i*pi_prod_2));
}
}
~DTMF() {
if(m_pTone != NULL){
delete[] m_pTone;
m_pTone = NULL;
}
}
public:
PBYTE GetData() const {
return m_pTone;
}
int GetLength() const {
return m_iPacketLength;
}
private:
PBYTE m_pTone;
int m_iPacketLength;
};
</pre><br />
<span style="font-size: large;"><b>Links:</b></span><br />
<ol><li><span style="font-size: small;"><b><a href="http://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling" target="_blank">DTMF Wikipedia</a> </b></span></li>
</ol><a href="http://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling"></a>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-70029536286884500232013-08-09T12:00:00.000+05:302013-08-09T12:01:44.355+05:30Firefox: Get results from your favorite Google country domain<div style="text-align: justify;">
<!--[if gte mso 9]><xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
</o:OfficeDocumentSettings>
</xml><![endif]--></div>
<div style="text-align: justify;">
<!--[if gte mso 9]><xml>
<w:WordDocument>
<w:View>Normal</w:View>
<w:Zoom>0</w:Zoom>
<w:TrackMoves/>
<w:TrackFormatting/>
<w:PunctuationKerning/>
<w:ValidateAgainstSchemas/>
<w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
<w:IgnoreMixedContent>false</w:IgnoreMixedContent>
<w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
<w:DoNotPromoteQF/>
<w:LidThemeOther>EN-IN</w:LidThemeOther>
<w:LidThemeAsian>X-NONE</w:LidThemeAsian>
<w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
<w:DontGrowAutofit/>
<w:SplitPgBreakAndParaMark/>
<w:EnableOpenTypeKerning/>
<w:DontFlipMirrorIndents/>
<w:OverrideTableStyleHps/>
</w:Compatibility>
<m:mathPr>
<m:mathFont m:val="Cambria Math"/>
<m:brkBin m:val="before"/>
<m:brkBinSub m:val="--"/>
<m:smallFrac m:val="off"/>
<m:dispDef/>
<m:lMargin m:val="0"/>
<m:rMargin m:val="0"/>
<m:defJc m:val="centerGroup"/>
<m:wrapIndent m:val="1440"/>
<m:intLim m:val="subSup"/>
<m:naryLim m:val="undOvr"/>
</m:mathPr></w:WordDocument>
</xml><![endif]--><!--[if gte mso 9]><xml>
<w:LatentStyles DefLockedState="false" DefUnhideWhenUsed="true"
DefSemiHidden="true" DefQFormat="false" DefPriority="99"
LatentStyleCount="267">
<w:LsdException Locked="false" Priority="0" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Normal"/>
<w:LsdException Locked="false" Priority="9" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="heading 1"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 2"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 3"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 4"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 5"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 6"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 7"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 8"/>
<w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 9"/>
<w:LsdException Locked="false" Priority="39" Name="toc 1"/>
<w:LsdException Locked="false" Priority="39" Name="toc 2"/>
<w:LsdException Locked="false" Priority="39" Name="toc 3"/>
<w:LsdException Locked="false" Priority="39" Name="toc 4"/>
<w:LsdException Locked="false" Priority="39" Name="toc 5"/>
<w:LsdException Locked="false" Priority="39" Name="toc 6"/>
<w:LsdException Locked="false" Priority="39" Name="toc 7"/>
<w:LsdException Locked="false" Priority="39" Name="toc 8"/>
<w:LsdException Locked="false" Priority="39" Name="toc 9"/>
<w:LsdException Locked="false" Priority="35" QFormat="true" Name="caption"/>
<w:LsdException Locked="false" Priority="10" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Title"/>
<w:LsdException Locked="false" Priority="1" Name="Default Paragraph Font"/>
<w:LsdException Locked="false" Priority="11" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Subtitle"/>
<w:LsdException Locked="false" Priority="22" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Strong"/>
<w:LsdException Locked="false" Priority="20" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Emphasis"/>
<w:LsdException Locked="false" Priority="59" SemiHidden="false"
UnhideWhenUsed="false" Name="Table Grid"/>
<w:LsdException Locked="false" UnhideWhenUsed="false" Name="Placeholder Text"/>
<w:LsdException Locked="false" Priority="1" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="No Spacing"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 1"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 1"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 1"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 1"/>
<w:LsdException Locked="false" UnhideWhenUsed="false" Name="Revision"/>
<w:LsdException Locked="false" Priority="34" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="List Paragraph"/>
<w:LsdException Locked="false" Priority="29" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Quote"/>
<w:LsdException Locked="false" Priority="30" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Intense Quote"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 1"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 1"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 1"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 1"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 1"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 2"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 2"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 2"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 2"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 2"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 2"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 2"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 2"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 2"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 3"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 3"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 3"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 3"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 3"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 3"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 3"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 3"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 3"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 4"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 4"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 4"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 4"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 4"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 4"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 4"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 4"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 4"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 5"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 5"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 5"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 5"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 5"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 5"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 5"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 5"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 5"/>
<w:LsdException Locked="false" Priority="60" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Shading Accent 6"/>
<w:LsdException Locked="false" Priority="61" SemiHidden="false"
UnhideWhenUsed="false" Name="Light List Accent 6"/>
<w:LsdException Locked="false" Priority="62" SemiHidden="false"
UnhideWhenUsed="false" Name="Light Grid Accent 6"/>
<w:LsdException Locked="false" Priority="63" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6"/>
<w:LsdException Locked="false" Priority="64" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6"/>
<w:LsdException Locked="false" Priority="65" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 1 Accent 6"/>
<w:LsdException Locked="false" Priority="66" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium List 2 Accent 6"/>
<w:LsdException Locked="false" Priority="67" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6"/>
<w:LsdException Locked="false" Priority="68" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6"/>
<w:LsdException Locked="false" Priority="69" SemiHidden="false"
UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6"/>
<w:LsdException Locked="false" Priority="70" SemiHidden="false"
UnhideWhenUsed="false" Name="Dark List Accent 6"/>
<w:LsdException Locked="false" Priority="71" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Shading Accent 6"/>
<w:LsdException Locked="false" Priority="72" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful List Accent 6"/>
<w:LsdException Locked="false" Priority="73" SemiHidden="false"
UnhideWhenUsed="false" Name="Colorful Grid Accent 6"/>
<w:LsdException Locked="false" Priority="19" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis"/>
<w:LsdException Locked="false" Priority="21" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis"/>
<w:LsdException Locked="false" Priority="31" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference"/>
<w:LsdException Locked="false" Priority="32" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Intense Reference"/>
<w:LsdException Locked="false" Priority="33" SemiHidden="false"
UnhideWhenUsed="false" QFormat="true" Name="Book Title"/>
<w:LsdException Locked="false" Priority="37" Name="Bibliography"/>
<w:LsdException Locked="false" Priority="39" QFormat="true" Name="TOC Heading"/>
</w:LatentStyles>
</xml><![endif]--><!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin-top:0cm;
mso-para-margin-right:0cm;
mso-para-margin-bottom:10.0pt;
mso-para-margin-left:0cm;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-fareast-language:EN-US;}
</style>
<![endif]-->
</div>
<div class="MsoNormal">
<br /></div>
Firefox's default search bar gets its configuration options
(what search engine to use, what parameters to pass, etc.) from XML files
located in <b>'searchplugins'</b> directory in Firefox’s default directory. If you are
on a Windows system this most probably be <b>'C:\Program Files\Mozilla
Firefox\browser\searchplugins'</b>. There's an XML file for Google called
<span style="color: blue;"><b>'google.xml'</b></span>.To modify it follow the following steps (I am doing it for google.co.in, you can replace it as per your requirement):
<br />
<ol style="text-align: justify;">
<li>The XML tags in this file are self-explanatory. First copy
google.xml and make a new one, let's call it 'google_india.xml' (you should have admin rights on your Windows OS).</li>
<li>Edit <b>'ShortName'</b> tag content and rename it to something else, for
example, Google India.</li>
<li>Then there are two <b>'Url'</b> tags. Leave the first <b>'Url'</b> tag as
it is get search suggestions (though never seen it work as I am behind a firewall). In the second tag change
template attribute to <b>template="https://www.google<span style="color: blue;">.co.in</span>/search"</b> (or
whatever you find useful).</li>
<li>Change <span style="color: #38761d;"><b>https://www.google.com/</b></span> to <b><span style="color: blue;">https://www.google.co.in</span></b>
within <b>'<SearchForm>'</b> tag. This specifies the page to display if you
click on the magnifying glass icon, at the left hand corner of the search bar,
without any search terms.</li>
<li>Now restart your Firefox browser and make the newly added Google
search engine as default.</li>
</ol>
<div style="text-align: justify;">
<span style="font-size: small;"> <b>Credits:</b></span></div>
<div style="text-align: justify;">
<b></b></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-AtN3BCu0kB0/UgSL6fzJMYI/AAAAAAAAAdc/Uv81rbgkaFk/s1600/orig_author_ff_g.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="21" src="http://2.bp.blogspot.com/-AtN3BCu0kB0/UgSL6fzJMYI/AAAAAAAAAdc/Uv81rbgkaFk/s400/orig_author_ff_g.PNG" width="400" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
</div>
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-17521642318300139002013-06-19T23:08:00.000+05:302013-06-19T23:08:10.325+05:30Windows API: The relationship between Process, Handle and Windows<span style="background-color: white;"><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">1)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>HAVE</b>: Process ID, <b>NEED</b>: Process handle</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>Solution</b>: </span></span><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx" target="_blank">OpenProcess()</a><br style="background-color: #fafafa; color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><br style="background-color: #fafafa; color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="background-color: white;"><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">2)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>HAVE</b>: Process handle, <b>NEED</b>: Process ID</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>Solution</b>: </span><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683215(v=vs.85).aspx" target="_blank">GetProcessId()</a><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">3)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>HAVE</b>: Window handle, <b>NEED</b>: Process ID</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>Solution</b>: </span><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633522(v=vs.85).aspx" target="_blank">GetWindowThreadProcessId()</a><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">4)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>HAVE</b>: Window handle, <b>NEED</b>: Process handle</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>Solution</b>: Use 3) and then 1)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">5)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>HAVE</b>: Process ID, NEED: Window handle</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>Solution</b>: </span><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497(v=vs.85).aspx" target="_blank">EnumWindows()</a><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">, then in the callback function do 3) and check if it matches your process ID.</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;">6)</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>HAVE</b>: Process handle, <b>NEED</b>: Window handle</span><br style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;" /><span style="color: #333333; font-family: Verdana, Arial, Tahoma, Calibri, Geneva, sans-serif; font-size: 13px;"><b>Solution</b>: 2) and then 5)</span></span>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-22646794659828371152013-05-21T22:10:00.000+05:302013-05-21T22:15:57.841+05:30What is 'CPoint' : ambiguous symbol atltypes.h?<div style="text-align: justify;">It was a dark and rainy night.. I was trying to do something useful.. what I don't remember right now.. But I was getting this weird problem...</div><div style="text-align: justify;"><br />
</div><div style="text-align: left;"><b><i><span style="color: blue;">Error 1 error C2872: 'CPoint' : ambiguous symbol atltypes.h</span></i></b><br />
<b><i><span style="color: blue;">Error 2 error C2872: 'CRect' : ambiguous symbol atltypes.h</span></i></b><br />
<b><i><span style="color: blue;">Error 3 error C2872: 'CSize' : ambiguous symbol atltypes.h</span></i></b><br />
<b><i><span style="color: blue;">.</span></i></b><br />
<b><i><span style="color: blue;">.</span></i></b><br />
<b><i><span style="color: blue;">Error N error C2872: 'CReality' : ambiguous symbol life.h</span></i></b></div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">Obviously (is it?) I was using ATL and WTL to do something... After scratching my head, googling and going through few WTL headers .. I found the solution. Just include the following, just after you add the <b>#include <windows.h> </b>:</div><pre class="brush:c++">#include <atlbase.h>
#if (_ATL_VER >= 0x0700)
#include <atlstr.h>
#include <atltypes.h>
#endif
#if (_ATL_VER >= 0x0700)
#define _WTL_NO_CSTRING
#define _WTL_NO_WTYPES
#define _WTL_NO_UNION_CLASSES
#endif
#include <atlapp.h>
</pre>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-50094212108524971082013-05-12T08:55:00.000+05:302013-05-12T08:55:00.911+05:30WTL::CRichEditCtrl<div style="text-align: justify;"><span style="background-color: white; color: #555555; font-family: Verdana, 'BitStream vera Sans', Tahoma, Helvetica, sans-serif; font-size: 12px; line-height: 17px;">WTL::CRichEditCtrl needs the following line for initialization, add it in your DllMain or _tWinMain and it resolves the issue:</span><br />
<pre class="brush:c++">HINSTANCE hInstRich = ::LoadLibrary(CRichEditCtrl::GetLibraryName());</pre><div style="text-align: justify;">Unfortunately I forgot that Rich Edit isn’t a common control and is not initialized with <b>InitCommonControlsEx</b>.</div></div>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-87940646265825754612013-02-19T23:55:00.002+05:302013-02-19T23:55:45.169+05:30Some COM Books<br />
Some books on COM. I just keep forgetting the name !!<br />
<br />
<ol>
<li>Inside OLE, 2nd Edition, by Kraig Brockschmidt (Microsoft Press)</li>
<li>Understanding ActiveX and OLE, by David Chappell (Microsoft Press)</li>
<li>Inside COM, by Dale Rogerson (Microsoft Press)</li>
</ol>
<br />
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-31978596153760999362012-10-31T16:27:00.000+05:302012-10-31T16:27:17.345+05:30Print map of India using C I don't know from where I got this code but its amazing ;)<br />
<br />
<pre class="brush:c++">#include <stdio.h>
int main()
{
int a,b,c;
int count = 1;
for (b=c=10;a="- FIGURE?, UMKC,XYZHello Folks,\
TFy!QJu ROo TNn(ROo)SLq SLq ULo+\
UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^\
NBELPeHBFHT}TnALVlBLOFAkHFOuFETp\
HCStHAUFAgcEAelclcn^r^r\\tZvYxXy\
T|S~Pn SPm SOn TNn ULo0ULo#ULo-W\
Hq!WFs XDt!" [b+++21]; )
for(; a-- > 64 ; )
putchar ( ++c=='Z' ? c = c/ 9:33^b&1); return 0;
return 0;
}
</pre>
<h2>
The Output</h2>
<pre> !!!!!!
!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!
!!!!!!!!!!
!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!! !!!!!
!!!!!!!!!!!!!!!!!!! !!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!! ! !!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!
!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !
!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!!!!!
!!!!!!!!
!!!!!!
!!!!
</pre>
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-4310798260375049672012-10-31T16:09:00.000+05:302012-10-31T16:09:15.705+05:30Query system for an environment variable value using C/C++Today one of my colleague asked me how to query an environment variable using C++. The solution is simple, just use <b>getenv()</b> method. See the below code.<br />
<br />
<pre class="brush:c++">#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
#pragma warning(disable: 4996) // disable warning for getenv()
int main()
{
char *pointer = NULL;
string str;
cout<<"Enter the environment variable: ";
while (cin>>str) {
if(str.compare("exit") == 0) break;
if(pointer = getenv(str.c_str())) {
cout<<endl<<"Value of \""<<str<<"\" Variable: "<<pointer<<endl<<endl<<"Enter the environment variable: ";
}else {
cout<<"No such variables defined."<<endl<<"Enter the environment variable: ";
}
}
}
</pre>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-29605450817475438362012-10-09T19:25:00.003+05:302012-10-09T19:33:09.624+05:30HttpServer - The Oracle JDK 1.6 Hidden FeatureI have seen this class many a times, but never encountered a scenario to use it. Recently in one of my application I needed to embedded a HTTP server. So I thought, Why not give this class a try !!<br />
<br />
HTTP server infrastructure/framework is very simple to implement and is bundled only with the Oracle JDK 1.6. Following are the main classes:<br />
<ol><li><a href="http://docs.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpServer.html" target="_blank">HttpServer</a></li>
<li><a href="http://docs.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpContext.html" target="_blank">HttpContext</a></li>
<li><a href="http://docs.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html" target="_blank">HttpExchange</a></li>
</ol>See this <a href="http://stackoverflow.com/a/3732328/373861" target="_blank">link </a>for <b>sun.* </b>package discussions.<br />
<br />
<pre class="brush: java">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.List;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class JavaServer
{
public static final String nl = System.getProperty("line.separator");
public static void main(String[] args) throws Exception
{
if(args.length != 2)
{
printUsage();
System.exit(-1);
}
String strPort = null;
String strAddress = null;
for (int i = 0; i < args.length; i++)
{
if(args[i].startsWith("-p")){
strPort = args[i].substring(2, args[i].length()).trim();
}else if(args[i].startsWith("-a")){
strAddress = args[i].substring(2, args[i].length()).trim();
}else
throw new IllegalArgumentException("Unknown command '" + args[i]+ "'");
}
if(strAddress.length() == 0 || strPort.length() == 0)
throw new IllegalArgumentException("Port = " + strPort + ", IP = " + strAddress);
int port = Integer.parseInt(strPort);
InetSocketAddress address = new InetSocketAddress(strAddress, port);
System.out.println("Going to run server on '" + address + "'");
new JavaServer().start(address);
}
private static void printUsage() {
System.out.println("$JavaServer -p<Port> -a<IP Address>");
}
private HttpServer server;
public void start(InetSocketAddress address) throws IOException
{
server = HttpServer.create(address, 0);
server.setExecutor(Executors.newCachedThreadPool());
server.createContext("/", new RootHandler());
server.start();
}
}
class RootHandler implements HttpHandler
{
private static final int BUFFER_SIZE = 1024;
public void handle(HttpExchange exchange) throws IOException
{
String method = exchange.getRequestMethod();
if(method.equalsIgnoreCase("get"))
{
String request = "";
ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);
InputStream is = exchange.getRequestBody();
byte[] buff = new byte[BUFFER_SIZE];
while (true)
{
int out = is.read(buff);
if(out == -1)
break;
baos.write(buff, 0, out);
}
is.close();
if (baos.size() > 0) {
request = URLDecoder.decode(baos.toByteArray().toString(), "UTF-8");
} else {
request = null;
}
StringBuilder buf = new StringBuilder();
buf.append("<html><head><title>Simple HTTP Server !!</title></head><body>");
buf.append("<p><pre>");
buf.append(exchange.getRequestMethod() + " " + exchange.getRequestURI() + " " + exchange.getProtocol() + JavaServer.nl);
Headers headers = exchange.getRequestHeaders();
for (String name : headers.keySet()) {
List<String> values = headers.get(name);
for (String value : values) {
buf.append(name + " --> " + value + JavaServer.nl);
}
}
if (request != null) {
buf.append(JavaServer.nl);
buf.append(request);
}
buf.append("</pre></p>");
buf.append("</body></html>\n");
String response = buf.toString();
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html");
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
OutputStream res = exchange.getResponseBody();
res.write(response.getBytes());
res.close();
}else
{
String response = "Bad request method !!";
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_METHOD, response.length());
OutputStream res = exchange.getResponseBody();
res.write(response.getBytes());
res.close();
}
exchange.close();
}
}
</pre><h2>Steps to run the above code</h2><ol><li>Compile it using Oracle JDK 1.6</li>
<li>Then execute this command on console (without quotes) 'Java JavaServer -p<port number> -a<ipaddress or localhost>' . For example, java JavaServer -p5463 -a127.0.0.1</li>
<li>Open your browser and type the URL. For example, http://127.0.0.1:5463/</li>
</ol><h2>You should see something like this (depends on the browser):</h2><div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-vsfMqUocks0/UHQsp_5o3FI/AAAAAAAAAcI/tFwcU3h3dKk/s1600/Capture.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="98" src="http://2.bp.blogspot.com/-vsfMqUocks0/UHQsp_5o3FI/AAAAAAAAAcI/tFwcU3h3dKk/s640/Capture.PNG" width="640" /></a></div><div><br />
</div>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-79662613280731089622012-10-01T11:19:00.001+05:302012-10-01T11:22:48.924+05:30How to open a Java file in read-only mode?In one of my eclipse plugin based application I wanted to open Java files in read only mode. One option was to use <i><u>org.eclipse.jface.text.source.SourceViewer</u></i> , where I could have used <i><u>JavaSourceViewerConfiguration</u></i><br />
for providing Java highlighting and all. But there were two problems:<br />
<ol>
<li>Source viewer won't inherit the Java editor settings (and if you have modified eclipse Java editor theme), which means your background and foreground in the SourceViewer gets completely messed up.</li>
<li>Secondly you would lose all the markup and bookmarking facilities available with editors</li>
</ol>
So, I decided to extend the existing Java editor. The steps are extremely simple,<br />
<ol>
<li>Create an editor extension</li>
<li>Extend the extension class with org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor</li>
<li>Override some of the methods</li>
<li>Open your file with this editor</li>
</ol>
<h1>
Code</h1>
<h3>
Editor Code</h3>
<pre class="brush: java">import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
@SuppressWarnings("restriction")
public class ReadonlyEd extends CompilationUnitEditor
{
public static final String ID = "read.only";
public ReadonlyEd() {
}
@Override
public boolean isEditable() {
return false;
}
@Override
public boolean isEditorInputModifiable() {
return false;
}
@Override
public boolean isEditorInputReadOnly() {
return true;
}
@Override
public boolean isDirty() {
return false;
}
}
</pre>
<br />
<div style="font-family: 'Times New Roman'; white-space: normal;">
<h3>
Code for Invoking the Editor</h3>
</div>
<pre class="brush: java">IFile file = ...; // Get the Java file instance
IWorkbenchPage page = ...; // Get the workbench page
FileEditorInput input = new FileEditorInput(file);
try {
IDE.openEditor(window.getActivePage(), input, ReadonlyEd.ID);
} catch (PartInitException e) {
e.printStackTrace();
}
</pre>
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-70133879954313027852012-09-24T14:44:00.004+05:302012-09-24T14:46:25.783+05:30How to hide a window from Win32 Taskbar?<br />
<div style="border: 0px; clear: both; font-size: 14px; line-height: 18px; margin-bottom: 1em; padding: 0px; text-align: left; vertical-align: baseline; word-wrap: break-word;">
<span style="font-family: Verdana, sans-serif;">Argh !!! I don't know why but I keep forgetting the ex-style bit for this... </span></div>
<div style="border: 0px; clear: both; line-height: 18px; margin-bottom: 1em; padding: 0px; text-align: justify; vertical-align: baseline; word-wrap: break-word;">
<i><span style="font-family: Verdana, sans-serif;">To prevent the window button from being placed on the taskbar, create the unowned window with the <b>WS_EX_TOOLWINDOW </b>extended style. <u>As an alternative</u>, you can create a hidden window and make this hidden window the owner of your visible window.</span></i></div>
<div style="border: 0px; clear: both; line-height: 18px; margin-bottom: 1em; padding: 0px; text-align: justify; vertical-align: baseline; word-wrap: break-word;">
<i><span style="font-family: Verdana, sans-serif;">The Shell will remove a window's button from the taskbar only if the window's style supports visible taskbar buttons. If you want to dynamically change a window's style to one that doesn't support visible taskbar buttons, you must hide the window first (by calling ShowWindow with SW_HIDE), change the window style, and then show the window.</span></i></div>
<div style="border: 0px; clear: both; font-size: 14px; line-height: 18px; margin-bottom: 1em; padding: 0px; text-align: left; vertical-align: baseline; word-wrap: break-word;">
<span style="font-family: Verdana, sans-serif;">Taken from here: <a href="http://msdn.microsoft.com/en-us/library/bb776822%28v=vs.85%29.aspx" target="_blank">The Taskbar</a></span></div>
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-607104750625339152012-09-18T16:10:00.000+05:302012-09-18T16:10:29.185+05:303 easy steps to self-sign a Applet Jar file<span style="font-size: small;"><span style="font-family: "Trebuchet MS",sans-serif;">Found this <a href="http://www.narendranaidu.com/2007/11/3-easy-steps-to-self-sign-applet-jar.html" target="_blank">link </a>that explains how to self-sign an applet in 3 easy steps:</span></span><br />
<ol>
<li><span style="font-size: small;"><span style="font-family: "Trebuchet MS",sans-serif;">keytool -genkey -keystore myKeyStore -alias me</span></span></li>
<li><span style="font-size: small;"><span style="font-family: "Trebuchet MS",sans-serif;">keytool -selfcert -keystore myKeyStore -alias me</span></span></li>
<li><span style="font-size: small;"><span style="font-family: "Trebuchet MS",sans-serif;">jarsigner -keystore myKeyStore jarfile.jar me</span></span></li>
</ol>
<span style="font-size: small;"><span style="font-family: "Trebuchet MS",sans-serif;"><br /></span></span>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-53047210780238591142012-08-23T19:08:00.001+05:302012-08-23T19:10:23.394+05:30Firebug Lite for SWT Browser on Windows<div style="text-align: justify;">
Recently I came across this question on stackoverflow <a href="http://stackoverflow.com/questions/12003602/eclipse-swt-browser-and-firebug-lite" target="_blank">'Eclipse swt browser and firebug lite'</a>. The solution seemed very obvious. I <a href="http://stackoverflow.com/a/12092687" target="_blank">answered the question</a> there also, you can always upvote it ;).<br />
<br />
<h3>
The output:</h3>
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-ncqFiOudeto/UDYxCrcmhRI/AAAAAAAAAbw/0azwMi7utJE/s1600/firebug.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="476" src="http://1.bp.blogspot.com/-ncqFiOudeto/UDYxCrcmhRI/AAAAAAAAAbw/0azwMi7utJE/s640/firebug.png" width="640" /> </a></div>
<div class="separator" style="clear: both; text-align: justify;">
</div>
<h3>
The code for the same is as follows:</h3>
<div class="separator" style="clear: both; text-align: justify;">
</div>
<pre class="brush: java">import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class FirebugLite
{
public static void main(String[] args) {
new FirebugLite().start();
}
public void start()
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.widthHint = SWT.DEFAULT;
gridData.heightHint = SWT.DEFAULT;
shell.setLayoutData(gridData);
shell.setText("Firebug Lite for SWT ;)");
final Browser browser = new Browser(shell, SWT.NONE);
GridData gridData2 = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData2.widthHint = SWT.DEFAULT;
gridData2.heightHint = SWT.DEFAULT;
browser.setLayoutData(gridData2);
Button button = new Button(shell, SWT.PUSH);
button.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
button.setText("Install");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
browser.setUrl("javascript:(function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new%20Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','4','firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','https://getfirebug.com/','#startOpened');");
}
});
browser.setUrl("http://stackoverflow.com/questions/12003602/eclipse-swt-browser-and-firebug-lite");
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
</pre>
Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-21972759936190462662012-07-31T14:57:00.001+05:302012-07-31T14:57:29.953+05:30SWT Browser and Image Capture<div style="font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<span style="font-size: small;">Recently I was playing with the SWT-COM bridge and its Win32 APIs. Believe me or not, but the <a href="http://www.eclipse.org/swt/snippets/?sid=e1ae6b1300c65ab1d2aef9ae1e05eb4c" target="_blank">SWT </a>Browser is the best SWT based UI control I have seen (you can argue but without any success). </span></div>
<div style="font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<br /></div>
<div style="font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<span style="font-size: small;">One of the experimental feature I tried accomplishing was to <u style="color: blue;">print the full HTML page as Image</u>, and the result was superb !!</span></div>
<div style="font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<span style="font-size: small;"><br /></span></div>
<div style="font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<span style="font-size: small;">See the below images for the embedded browser control and the output of the image capturing utility !! Cool right ;)</span></div>
<div style="font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<span style="font-size: small;"><br /></span></div>
<div style="color: blue; font-family: "Trebuchet MS",sans-serif; text-align: justify;">
<span style="font-size: small;"><b>Modified Browser Control:</b></span></div>
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-FUnYkMCQvDw/UBejmdiXHHI/AAAAAAAAAbQ/UGxcxEAUMXA/s1600/GUI.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="297" src="http://3.bp.blogspot.com/-FUnYkMCQvDw/UBejmdiXHHI/AAAAAAAAAbQ/UGxcxEAUMXA/s400/GUI.png" width="400" /></a></div>
<div style="text-align: justify;">
</div>
<br />
<br />
<div style="text-align: justify;">
</div>
<br />
<div style="color: blue; font-family: "Trebuchet MS",sans-serif;">
<b>Captured Image:</b></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-sRvic-rWFhw/UBejwaLGeqI/AAAAAAAAAbY/XwXPUiDvDNA/s1600/output.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="http://4.bp.blogspot.com/-sRvic-rWFhw/UBejwaLGeqI/AAAAAAAAAbY/XwXPUiDvDNA/s640/output.png" width="328" /></a></div>
<br />Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-69063242126005547652012-06-05T11:16:00.000+05:302012-07-22T23:24:09.517+05:30Atlapp and secure atl !!<div style="text-align: justify;">
After upgrading to VS2008, I started getting errors for <code>lstrlenA, size_t,</code> and <code>lstrcpynA</code>. My "include directories" settings are exactly the same as my old VS2005, and if I open the project in VS2005, everything compiles just fine. So what is the fix for this problem??</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
And the fix is really simple, before including <code>atlapp.h</code>, just define:</div>
<pre> </pre>
<pre class="brush: c">#define _SECURE_ATL 1
</pre>
<br />
<br />Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-61412165157187083672012-05-01T21:23:00.001+05:302012-07-22T23:23:07.916+05:30SWT - Capturing Control Screen-ShotSWT code for capturing control screen-shot.<br />
<br />
<pre class="brush: java">public class ScreenCaptureTest
{
public static void main(String[] args)
{
String[] names = {"Harry", "Sally", "Jhon", "Tim", "Scott"};
String[] msg = {"Hello World!", "Today is a nice day to walk", "I am bored", "This is how you take widget capture", "Ha Ha Ha!! That's funny !"};
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Screen Capture");
shell.setLayout(new GridLayout(1, true));
final Composite composite = new Composite(shell, SWT.BORDER);
composite.setLayout(new GridLayout(2, true));
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Table table = new Table(composite, SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL|SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TableColumn columnName = new TableColumn(table, SWT.LEFT);
columnName.setText("Name");
columnName.setWidth(100);
TableColumn columnMsg = new TableColumn(table, SWT.LEFT);
columnMsg.setText("Message");
columnMsg.setWidth(200);
for (int i = 0; i < 5; i++)
{
TableItem item = new TableItem(table, SWT.NONE, 0);
item.setText(0, names[i]);
item.setText(1, msg[i]);
}
StyledText text = new StyledText (composite, SWT.BORDER);
text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ");
text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
StyleRange style1 = new StyleRange();
style1.start = 0;
style1.length = 10;
style1.fontStyle = SWT.BOLD;
text.setStyleRange(style1);
StyleRange style2 = new StyleRange();
style2.start = 11;
style2.length = 13;
style2.foreground = display.getSystemColor(SWT.COLOR_RED);
text.setStyleRange(style2);
StyleRange style3 = new StyleRange();
style3.start = 25;
style3.length = 13;
style3.background = display.getSystemColor(SWT.COLOR_BLUE);
text.setStyleRange(style3);
Button button = new Button(shell, SWT.PUSH);
button.setText("Capture");
button.pack();
button.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event event)
{
GC gc = new GC(display);
final Image image = new Image(display, shell.getBounds());
gc.copyArea(image, shell.getBounds().x, shell.getBounds().y);
gc.dispose();
Shell popup = new Shell(shell);
popup.setText("Captured Image");
popup.addListener(SWT.Close, new Listener() {
public void handleEvent(Event e) {
image.dispose();
}
});
Canvas canvas = new Canvas(popup, SWT.NONE);
canvas.setBounds(0,0,image.getImageData().width, image.getImageData().height);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
e.gc.drawImage(image, 0, 0);
}
});
popup.pack();
popup.open();
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}</pre>
<br />
<b>Original Composite:</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-qKI1JCQPx-c/T6AGTAAK0_I/AAAAAAAAAaw/aqNTn3S44y8/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="108" src="http://3.bp.blogspot.com/-qKI1JCQPx-c/T6AGTAAK0_I/AAAAAAAAAaw/aqNTn3S44y8/s320/1.png" width="320" /></a></div>
<br />
<br />
<b>Captured Image:</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-5TdY9VmBjIs/T6AGcZY4_vI/AAAAAAAAAa4/lJr_07gfSbI/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="122" src="http://3.bp.blogspot.com/-5TdY9VmBjIs/T6AGcZY4_vI/AAAAAAAAAa4/lJr_07gfSbI/s320/2.png" width="320" /></a></div>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-30257997374277438232012-04-18T14:27:00.000+05:302012-04-18T14:29:35.438+05:30Programmatically create eclipse Java projectFollowing is a brief code snippet for creating an eclipse Java project using core JDT API.<br />
<br />
<pre class="brush: java">private IJavaProject createProject() throws Exception
{
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
String projName = getProjectName();
if(projName == null || projName.trim().length() == 0)
return null;
//create eclipse project
IProject project = root.getProject(projName);
if(project.exists())
project.delete(true, null);
project.create(null);
project.open(null);
//set the java project nature
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID});
project.setDescription(description, null);
//create java project
IJavaProject javaProject = JavaCore.create(project);
//add bin/ouput folder
IFolder binFolder = project.getFolder("bin");
binFolder.create(false, true, null);
javaProject.setOutputLocation(binFolder.getFullPath(), null);
//add libs to project class path
List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
for (LibraryLocation element : locations) {
entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
}
javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);
//create source folder
IFolder sourceFolder = project.getFolder("src");
sourceFolder.create(false, true, null);
IPackageFragmentRoot srcRoot = project.getPackageFragmentRoot(sourceFolder);
IClasspathEntry[] oldEntries = project.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaCore.newSourceEntry(srcRoot.getPath());
project.setRawClasspath(newEntries, null);
return javaProject;
}
private String getProjectName()
{
String init_value = "project_" + System.currentTimeMillis();
InputDialog dialog = new InputDialog(getShell(), "Java Project", "Provide project name ..", init_value, new IInputValidator() {
public String isValid(String newText)
{
char[] array = newText.toCharArray();
for (int i = 0; i < array.length; i++)
{
if(!Character.isJavaIdentifierPart(array[i]))
return "Cannot contain special characters !!";
}
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject[] projs = root.getProjects();
for (int i = 0; i < projs.length; i++) {
if(projs[i].getName().equalsIgnoreCase(newText))
return "Project already exist !!";
}
/*
Not checking for special Win32 names like con etc.
*/
return null;
}
});
if(dialog.open() == Dialog.CANCEL)
return null;
return dialog.getValue();
}
</pre>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.comtag:blogger.com,1999:blog-2761582418364109373.post-58985925351387415982011-11-25T12:30:00.002+05:302011-11-25T12:44:01.344+05:30Running PostgreSQL From Command Line<div align="justify">This October I enrolled for the online <a href="http://www.db-class.org/" target="_blank">database course</a> offered by Stanford university. I started out with <a href="http://www.sqlite.org/" target="_blank">SQLite</a> as the RDBMS of my choice because it is easy to use, needs no installation and one can use it out of the box. But, in case of SQLite simplicity was the main problem too. So, I downloaded the <a href="http://www.postgresql.org/download/windows" target="_blank">PostgreSQL</a> for windows. Now, as my workstation is normally overloaded (so I can’t afford background services) and also I just wanted to have a no-install distribution; so I downloaded the <strong>Zip Archive</strong>.</div><div align="justify"><br />
</div><div align="justify">The first problem I faced was that when I started to run my <strong>postgres </strong>server then it gave me this long error message:</div><div align="justify"><em><span style="color: blue;">“Execution of PostgreSQL by a user with administrative permissions is not permitted.The server must be started under an unprivileged user ID to prevent possible system security compromises. See the documentation for more information on how to properly start the server.”</span></em> </div><div align="justify"><span style="color: black;"><br />
</span></div><div align="justify"><span style="color: black;">Forums were of no use and mostly people were suggesting to create a non-admin user and use it. But the problem is I can’t do that as I am working a system which doesn’t allow me to do that. So, I read the documentation and found <strong><em>pg_ctl</em></strong> which is a utility to initialize, start, stop, or control a PostgreSQL server. Here are the steps:</span> </div><ol><li> <div align="justify"><strong>CD C:\pgsql\bin</strong> (or where ever your postgres bin folder is)</div></li>
<li> <div align="justify"><strong>set PGDATA=c:/temp/test</strong></div></li>
<li> <div align="justify"><strong>pg_ctl.exe init<br />
</strong>The files belonging to this database system will be owned by user "ABCDXYZ". This user must also own the server process….</div></li>
<li> <div align="justify">Although after the step# 2 it instructs to start your postgres server as "C:/pgsql/bin\postgres" -D "c:/temp/test"; but it is of no use. Instead do this, <strong>pg_ctl.exe start</strong></div></li>
<li> <div align="justify">That it, the server is running and the process is owned by the logged in user.</div></li>
<li> <div align="justify">Now for the admin tool, run the ‘pgAdmin3.exe’ (its inside the <strong>C:\pgsql\bin</strong>)</div></li>
<li> <div align="justify">Now select ‘Add a connection to server’ toolbar button. This will show an image like this and fill in the values as suggested:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-nuQWbhs38uo/Ts8_X43QDbI/AAAAAAAAAZs/RUtAK442lYo/s1600/setting.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="http://4.bp.blogspot.com/-nuQWbhs38uo/Ts8_X43QDbI/AAAAAAAAAZs/RUtAK442lYo/s320/setting.png" width="310" /></a></div><br />
</div></li>
<li> <div align="justify">Finally this page will come:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-4Fx5Nx2x5YQ/Ts8_bwcAv6I/AAAAAAAAAZ0/pLCGNAhnjxw/s1600/output.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="234" src="http://3.bp.blogspot.com/-4Fx5Nx2x5YQ/Ts8_bwcAv6I/AAAAAAAAAZ0/pLCGNAhnjxw/s320/output.png" width="320" /></a></div><br />
</div></li>
</ol>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-84260132935383186162011-09-14T12:43:00.004+05:302011-09-15T01:34:28.479+05:30ANTLR: Global member function in ‘C’ parser & custom error printing<div class="wlWriterEditableSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:cdf6d4f6-b8cc-4cc9-a920-ec6b62718c21" style="display: inline; float: none; margin: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px;">Technorati Tags: <a href="http://technorati.com/tags/antlr" rel="tag">antlr</a>,<a href="http://technorati.com/tags/c" rel="tag">c</a>,<a href="http://technorati.com/tags/parser" rel="tag">parser</a><br />
<br />
Writing a Java parser using <a href="http://www.antlr.org/" target="_blank">ANTLR</a> is a breeze. And why not ! It is written in Java, the default IDE which comes with it is in Java and etc. But recently I needed a tool for writing C/C++ parsers. My first choice was to go ahead with YACC or BISON. But management of the generated parser is hard (at least to people who are new to them), so I started with ANTLR.</div><div align="justify">After few rounds of testing the ANTLR seemed ok to me. But the actual problem came when I have to provide my own custom handler for error processing. After some rounds of googling and diving through the documentation I found the solution.</div><div align="justify"><br />
</div><div align="justify">First create a generic handler:<strong> exceptionhandler.h</strong></div><pre class="brush: c">#pragma once
#include "R2SParser.h"
#ifdef __cplusplus
extern "C" {
#endif
void myDisplayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames);
#ifdef __cplusplus
}
#endif </pre>Its sample implementation: <strong>exceptionhandler.cpp </strong>(taken from <strong>antlr3baserecognizer.c</strong>)<br />
<pre class="brush: c">#include "exceptionhandler.h"
#include <string>
void myDisplayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames)
{
//====================================
pANTLR3_PARSER parser;
pANTLR3_TREE_PARSER tparser;
pANTLR3_INT_STREAM is;
pANTLR3_STRING ttext;
pANTLR3_STRING ftext;
pANTLR3_EXCEPTION ex;
pANTLR3_COMMON_TOKEN theToken;
pANTLR3_BASE_TREE theBaseTree;
pANTLR3_COMMON_TREE theCommonTree;
// Retrieve some info for easy reading.
//
ex = recognizer->state->exception;
ttext = NULL;
std::string error;
// See if there is a 'filename' we can use
//
/*if (ex->streamName == NULL)
{
if (((pANTLR3_COMMON_TOKEN)(ex->token))->type == ANTLR3_TOKEN_EOF)
{
ANTLR3_FPRINTF(stderr, "-end of input-(");
}
else
{
ANTLR3_FPRINTF(stderr, "-unknown source-(");
}
}
else
{
ftext = ex->streamName->to8(ex->streamName);
ANTLR3_FPRINTF(stderr, "%s(", ftext->chars);
}*/
// Next comes the line number
//
ANTLR3_FPRINTF(stderr, "%d) ", recognizer->state->exception->line);
ANTLR3_FPRINTF(stderr, " : error %d : %s",
recognizer->state->exception->type,
(pANTLR3_UINT8) (recognizer->state->exception->message));
// How we determine the next piece is dependent on which thing raised the
// error.
//
switch (recognizer->type)
{
case ANTLR3_TYPE_PARSER:
// Prepare the knowledge we know we have
//
parser = (pANTLR3_PARSER) (recognizer->super);
if(parser->super == NULL)
{
fprintf(stdout, "I think i can use it");
}else
{
fprintf(stdout, "BAD LUCK");
}
tparser = NULL;
is = parser->tstream->istream;
theToken = (pANTLR3_COMMON_TOKEN)(recognizer->state->exception->token);
ttext = theToken->toString(theToken);
ANTLR3_FPRINTF(stderr, ", at offset %d", recognizer->state->exception->charPositionInLine);
if (theToken != NULL)
{
if (theToken->type == ANTLR3_TOKEN_EOF)
{
ANTLR3_FPRINTF(stderr, ", at <EOF>");
}
else
{
// Guard against null text in a token
//
ANTLR3_FPRINTF(stderr, "\n near %s\n ", ttext == NULL ? (pANTLR3_UINT8)"<no text for the token>" : ttext->chars);
}
}
break;
case ANTLR3_TYPE_TREE_PARSER:
tparser = (pANTLR3_TREE_PARSER) (recognizer->super);
parser = NULL;
is = tparser->ctnstream->tnstream->istream;
theBaseTree = (pANTLR3_BASE_TREE)(recognizer->state->exception->token);
ttext = theBaseTree->toStringTree(theBaseTree);
if (theBaseTree != NULL)
{
theCommonTree = (pANTLR3_COMMON_TREE) theBaseTree->super;
if (theCommonTree != NULL)
{
theToken = (pANTLR3_COMMON_TOKEN) theBaseTree->getToken(theBaseTree);
}
ANTLR3_FPRINTF(stderr, ", at offset %d", theBaseTree->getCharPositionInLine(theBaseTree));
ANTLR3_FPRINTF(stderr, ", near %s", ttext->chars);
}
break;
default:
ANTLR3_FPRINTF(stderr, "Base recognizer function displayRecognitionError called by unknown parser type - provide override for this function\n");
return;
break;
}
switch (ex->type)
{
case ANTLR3_UNWANTED_TOKEN_EXCEPTION:
if (tokenNames == NULL)
{
ANTLR3_FPRINTF(stderr, " : Extraneous input...");
}
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
{
ANTLR3_FPRINTF(stderr, " : Extraneous input - expected <EOF>\n");
}
else
{
ANTLR3_FPRINTF(stderr, " : Extraneous input - expected %s ...\n", tokenNames[ex->expecting]);
}
}
break;
case ANTLR3_MISSING_TOKEN_EXCEPTION:
if (tokenNames == NULL)
{
ANTLR3_FPRINTF(stderr, " : Missing token (%d)...\n", ex->expecting);
}
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
{
ANTLR3_FPRINTF(stderr, " : Missing <EOF>\n");
}
else
{
ANTLR3_FPRINTF(stderr, " : Missing %s \n", tokenNames[ex->expecting]);
}
}
break;
case ANTLR3_RECOGNITION_EXCEPTION:
ANTLR3_FPRINTF(stderr, " : syntax error...\n");
break;
case ANTLR3_MISMATCHED_TOKEN_EXCEPTION:
if (tokenNames == NULL)
{
ANTLR3_FPRINTF(stderr, " : syntax error...\n");
}
else
{
if (ex->expecting == ANTLR3_TOKEN_EOF)
{
ANTLR3_FPRINTF(stderr, " : expected <EOF>\n");
}
else
{
ANTLR3_FPRINTF(stderr, " : expected %s ...\n", tokenNames[ex->expecting]);
}
}
break;
case ANTLR3_NO_VIABLE_ALT_EXCEPTION:
ANTLR3_FPRINTF(stderr, " : cannot match to any predicted input...\n");
break;
case ANTLR3_MISMATCHED_SET_EXCEPTION:
{
ANTLR3_UINT32 count;
ANTLR3_UINT32 bit;
ANTLR3_UINT32 size;
ANTLR3_UINT32 numbits;
pANTLR3_BITSET errBits;
ANTLR3_FPRINTF(stderr, " : unexpected input...\n expected one of : ");
count = 0;
errBits = antlr3BitsetLoad (ex->expectingSet);
numbits = errBits->numBits (errBits);
size = errBits->size (errBits);
if (size > 0)
{
for (bit = 1; bit < numbits && count < 8 && count < size; bit++)
{
// TODO: This doesn;t look right - should be asking if the bit is set!!
//
if (tokenNames[bit])
{
ANTLR3_FPRINTF(stderr, "%s%s", count > 0 ? ", " : "", tokenNames[bit]);
count++;
}
}
ANTLR3_FPRINTF(stderr, "\n");
}
else
{
ANTLR3_FPRINTF(stderr, "Actually dude, we didn't seem to be expecting anything here, or at least\n");
ANTLR3_FPRINTF(stderr, "I could not work out what I was expecting, like so many of us these days!\n");
}
}
break;
case ANTLR3_EARLY_EXIT_EXCEPTION:
ANTLR3_FPRINTF(stderr, " : missing elements...\n");
break;
default:
ANTLR3_FPRINTF(stderr, " : syntax not recognized...\n");
break;
}
//====================================
}
</pre>Then create a place holder for error message (this is a trimmed down version): <strong>errorstruct.h</strong> <br />
<pre class="brush: c">#pragma once
#ifndef __ERRORSTRUCT__
#define __ERRORSTRUCT__
struct errormessage_struct
{
char* message;
};
typedef struct errormessage_struct ErrorMessage;
typedef ErrorMessage* pErrorMessage;
#endif
</pre><strong>Now at this point your ANTLR grammar should have this:</strong><br />
<pre class="brush: c">@parser::header {
#include "errorstruct.h"
#include "exceptionhandler.h"
#define ERRORMESSAGE CTX->errorMessage
}
@parser::context
{
ErrorMessage errorMessage;
}
@parser::apifuncs {
RECOGNIZER->displayRecognitionError = myDisplayRecognitionError;
ERRORMESSAGE.message = NULL;
}
</pre><div align="justify">And that’s it. Now you can access your error message any where like this <strong>parser->errorMessage.message</strong>. Similarly, you can add some member function to the structure (in the above example it is <strong>errormessage_struct</strong>) and then can use it anywhere.</div><div align="justify">One point worth noting is that with the above approach you get the free threading, which is built into the code generation and the runtime. Here you get one errorMessage per thread.<br />
<br />
<b><span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">References:</span></b><br />
<ol><li><a href="http://www.antlr.org/pipermail/antlr-interest/2009-May/034567.html">http://www.antlr.org/pipermail/antlr-interest/2009-May/034567.html</a></li>
<li><a href="http://groups.google.com/group/il-antlr-interest/browse_thread/thread/80ec25032e9af7a8?pli=1">http://groups.google.com/group/il-antlr-interest/browse_thread/thread/80ec25032e9af7a8?pli=1</a></li>
</ol></div>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-52003166602711595292011-04-20T11:58:00.010+05:302011-04-20T15:27:19.795+05:30Testing SWT application with SWTBot<div align="justify"><a href="http://www.eclipse.org/swtbot/" target="_blank">SWTBot</a> is open-source Java based UI/functional testing tool for testing <a href="http://eclipse.org/swt">SWT</a> and <a href="http://eclipse.org/">Eclipse</a> based applications.<br />
<br />
</div><div align="justify"><strong>SWTBot </strong>provides APIs that are simple to read and write. The APIs also hide the complexities involved with SWT and Eclipse. This makes it suitable for UI/functional testing by everyone, not just developers. <strong>SWTBot</strong> also provides its own set of assertions that are useful for SWT. You can also use your own assertion framework with <strong>SWTBot</strong>. <br />
<br />
</div><div align="justify">There are many articles present for <strong>SWTBot </strong>for Eclipse Plug-in and RCP applications. Refer the following links for more details: </div><ol><li> <div align="justify"><a href="http://wiki.eclipse.org/SWTBot/Articles_And_Tutorials" target="_blank">Articles and Tutorials</a></div></li>
<li> <div align="justify"><a href="http://wiki.eclipse.org/SWTBot/UsersGuide" target="_blank">Users Guide</a></div></li>
<li> <div align="justify"><a href="http://www.vogella.de/articles/SWTBot/article.html" target="_blank">SWTBot Article</a></div></li>
<li> <div align="justify"><a href="http://swtbot.com/cheat-sheet/" target="_blank">Cheat sheet</a></div></li>
</ol><div align="justify">As the title suggest, the intention of this article to demonstrate the testing of a stand-alone SWT UI. There was a question asked on the <a href="http://stackoverflow.com/questions/5716174/testing-swt-gui-whith-swtbot" target="_blank">Stackoverflow</a> with the same problem. You can checkout <strong>my answer</strong> there also. For completeness purpose I am posting it here too.<br />
<br />
</div>Well it is very much possible to test simple SWT application with <strong>SWTBot</strong>. Follow the step as mentioned below. <br />
<ol><li>Download <a href="http://www.eclipse.org/swtbot/downloads.php">SWTBot for SWT Testing</a><br />
</li>
<li>Put it in the <code><eclipsehome>/dropins</code> folder (although not required for non-plug-in projects)<br />
</li>
<li>Restart your eclipse (not required if you adding the SWTBot jars in a simple Java project)</li>
</ol>Now at this point you are ready to play with <strong>SWTBot</strong>. <br />
<br />
For the demo purpose I have written a small Login dialog for you and it will look like this:<br />
<br />
<div class="separator" style="clear: both; text-align: left;"><a href="http://1.bp.blogspot.com/-XYSCX9GEvSI/Ta59XKGZNbI/AAAAAAAAAXw/g_0sNVTIX24/s1600/login.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-XYSCX9GEvSI/Ta59XKGZNbI/AAAAAAAAAXw/g_0sNVTIX24/s1600/login.png" /></a></div><br />
<strong>>>Code</strong><br />
<pre class="brush: java">import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class SampleSWTUI
{
public Shell showGUI(final Display display)
{
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(3,true));
shell.setText("Sample SWT UI");
new Label(shell, SWT.NONE).setText("User Name: ");
final Text nameText = new Text(shell, SWT.BORDER);
nameText.setText ("");
GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.horizontalSpan = 2;
nameText.setLayoutData(data);
new Label(shell, SWT.NONE).setText("Password: ");
final Text passwordText = new Text(shell, SWT.BORDER|SWT.PASSWORD);
passwordText.setText ("");
data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.horizontalSpan = 2;
passwordText.setLayoutData(data);
Button loginButton = new Button (shell, SWT.PUSH);
loginButton.setText ("Login");
data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.horizontalSpan = 3;
loginButton.setLayoutData(data);
loginButton.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
String user = nameText.getText();
String password = passwordText.getText();
System.out.println("\n\n\n");
if(user.equals("Favonius") && password.equals("abcd123")){
System.out.println("Success !!!");
}else {
System.err.println("What the .. !! Anyway it is just a demo !!");
}
}
});
shell.pack();
shell.open();
return shell;
}
public static void main(String [] args)
{
Display display = new Display();
Shell shell = new SampleSWTUI().showGUI(display);
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}</pre>Now create a JUnit test case (google for it if you are new to it) . Also <strong>add all the jar files</strong> present in SWTBot <em>(the one you have downloaded)</em> <strong>in your classpath</strong>. <br />
<br />
Now first create a display (because application needs one). Also get the handle of <strong>container</strong> in which your widgets/controls are present. In my case it is the <strong>Shell</strong>. Although the below code is self descriptive, still, I will suggest you to refer its Javadoc. <br />
<br />
<strong>>>SWTBot Code</strong><br />
<pre class="brush: java">import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.utils.SWTBotPreferences;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotText;
import org.junit.Test;
import junit.framework.Assert;
public class SWTBotDemo
{
@Test
public void test()
{
SWTBotPreferences.PLAYBACK_DELAY = 100; // slow down tests...Otherwise we won't see anything
Display display = new Display();
Shell shell = new SampleSWTUI().showGUI(display);
SWTBot bot = new SWTBot(shell);
SWTBotButton loginButton = bot.button("Login");
SWTBotText userText = bot.textWithLabel("User Name: ");
SWTBotText passwordText = bot.textWithLabel("Password: ");
userText.setFocus();
userText.setText("Superman");
Assert.assertEquals(userText.getText(),"Superman");
passwordText.setFocus();
passwordText.setText("test123");
Assert.assertEquals(passwordText.getText(),"test123");
loginButton.setFocus();
loginButton.click();
userText.setFocus();
userText.setText("Favonius");
Assert.assertEquals(userText.getText(), "Favonius");
passwordText.setFocus();
passwordText.setText("abcd123");
Assert.assertEquals(passwordText.getText(), "abcd123");
loginButton.setFocus();
loginButton.click();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}</pre>Now all the <strong>SWTBot</strong> methods and variables are well defined in the source <strong>and</strong> the source is bundled within the SWTBot jars. So you can always go ahead and hack its source code.<br />
<br />
<strong>>>Further Reading</strong> <br />
<ol><li><a href="http://wiki.eclipse.org/SWTBot/FAQ">SWTBot FAQ</a></li>
</ol>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-85603171793071976342011-04-18T16:16:00.007+05:302011-04-18T16:28:00.255+05:30Detecting change in SWT Table's scrollbar visibility<div align="justify">Recently on <a href="http://stackoverflow.com/" target="_blank">stackoverflow</a> there was a question asked related to this. The requirement was simple <i>‘resize all the columns as soon as scrollbar appears or disappears’</i>. Now, if you look deep into the SWT table API then you will notice that there is no direct solution for this because:</div><ol><li> <div align="justify">There is no way to get the scrollbar handle</div></li>
<li> <div align="justify">Scrollbar does not support any event related to visibility</div></li>
</ol><div align="justify">One can solve this problem by implementing a simple hack. I am using the concept presented in this SWT snippet <a href="http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet253.java?view=co" target="_blank">compute the visible rows in a table</a>. Along with that I am also using <strong>SWT Paint Event</strong>. <br />
<br />
</div><div align="justify">The basic concept is as follows: </div><ol><li> <div align="justify">Calculate the number of visible rows (items).</div></li>
<li> <div align="justify">Compare it with total number of rows (items).</div></li>
<li> <div align="justify">Do all this in some event which occurs with the addition of rows (items). I have chosen the <strong>SWT Paint Event</strong></div></li>
</ol><strong>>> Code</strong><br />
<pre class="brush: java">import org.eclipse.swt.*;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class TableScrollVisibilityTest
{
private static int count;
public static void main(String [] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setBounds(10,10,300,300);
shell.setLayout(new GridLayout(2,true));
final Table table = new Table(shell, SWT.NONE);
GridData data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 2;
table.setLayoutData(data);
count = 0;
final Button addItem = new Button (shell, SWT.PUSH);
addItem.setText ("Add Row");
data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.horizontalSpan = 2;
addItem.setLayoutData(data);
final Text text = new Text(shell, SWT.BORDER);
text.setText ("Vertical Scroll Visible - ");
data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.horizontalSpan = 2;
text.setLayoutData(data);
addItem.addListener (SWT.Selection, new Listener ()
{
public void handleEvent (Event e)
{
new TableItem(table, SWT.NONE).setText("item " + count);
count++;
}
});
table.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Rectangle rect = table.getClientArea ();
int itemHeight = table.getItemHeight ();
int headerHeight = table.getHeaderHeight ();
int visibleCount = (rect.height - headerHeight + itemHeight - 1) / itemHeight;
text.setText ("Vertical Scroll Visible - [" + (table.getItemCount()>= visibleCount)+"]");
// YOUR CODE HERE
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}</pre><br />
<div align="justify"><strong>>> Output</strong></div><div align="justify">For <strong>itemcount < numberofvisible</strong> rows<br />
<div class="separator" style="clear: both; text-align: left;"><a href="http://2.bp.blogspot.com/-jSpd8KTECns/TawYS91Ft9I/AAAAAAAAAXk/oYfaS8BAS2g/s1600/sample1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-jSpd8KTECns/TawYS91Ft9I/AAAAAAAAAXk/oYfaS8BAS2g/s1600/sample1.png" /></a></div><br />
<div class="separator" style="clear: both; text-align: center;"></div><br />
</div><div align="justify">For <strong>itemcount >= numberofvisible</strong> rows<br />
<div class="separator" style="clear: both; text-align: left;"><a href="http://1.bp.blogspot.com/-sIEeLqTPKaE/TawYTfohouI/AAAAAAAAAXo/5BHv_Ss0pbY/s1600/Sample2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-sIEeLqTPKaE/TawYTfohouI/AAAAAAAAAXo/5BHv_Ss0pbY/s1600/Sample2.png" /></a></div><br />
</div><br />
<div align="justify"><strong><span class="Apple-style-span" style="color: red;">Note </span>-</strong> If you are going to use the <b>paint event</b> then try keep the calculations minimum as it is called frequently.</div><div align="justify"><span style="color: blue;"><strong>Link to the actual problem: <a href="http://stackoverflow.com/questions/5674207/how-to-detect-swt-tables-scroll-bar-visibility-changes/5699018#5699018" target="_blank">Stackoverflow - How to detect SWT Table's scroll bar visibility changes</a></strong></span></div>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0tag:blogger.com,1999:blog-2761582418364109373.post-3033183636357946282011-04-16T10:09:00.001+05:302011-04-16T10:27:15.863+05:30SWT Browser and Javascript<div align="justify">Sometime we feel the need of modifying SWT browser content dynamically. Using <code>getText</code> and modifying it is not the advisable way of changing HTML content. I will suggest you to use <code>execute()</code> method of <code>org.eclipse.swt.browser.Browser</code>. It allows you to fire javascripts on the DOM object of the page. <br />
<br />
</div><div align="justify"><strong>>> Example</strong> </div><div align="justify">Here in this code I am allowing the page to fully load and then looking for all the links item and then creating a <code>red border</code> around them. <br />
<br />
</div><pre class="brush: java">import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class BrowserTest
{
private static Browser browser;
public static void main(String [] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
shell.setLayout(gridLayout);
createBrowser(shell);
browser.addProgressListener(new ProgressListener()
{
public void changed(ProgressEvent event) {
}
public void completed(ProgressEvent event) {
changeSomething();
}
});
shell.open();
browser.setUrl("http://google.com");
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
protected static void changeSomething()
{
String s = "var allLinks = document.getElementsByTagName('a'); " +
"for (var i=0, il=allLinks.length; i<il; i++) { " +
"elm = allLinks[i]; elm.style.border = 'thin solid red';" +
"}";
System.out.println(browser.execute(s));
}
private static void createBrowser(Shell shell)
{
ToolBar toolbar = new ToolBar(shell, SWT.NONE);
ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
itemGo.setText("Go");
GridData data = new GridData();
data.horizontalSpan = 3;
toolbar.setLayoutData(data);
Label labelAddress = new Label(shell, SWT.NONE);
labelAddress.setText("Address");
final Text location = new Text(shell, SWT.BORDER);
data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.horizontalSpan = 2;
data.grabExcessHorizontalSpace = true;
location.setLayoutData(data);
try {
browser = new Browser(shell, SWT.NONE);
} catch (SWTError e) {
System.out.println("Could not instantiate Browser: " + e.getMessage());
//display.dispose();
return;
}
data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.horizontalSpan = 3;
browser.setLayoutData(data);
/* event handling */
Listener listener = new Listener()
{
public void handleEvent(Event event)
{
ToolItem item = (ToolItem)event.widget;
String string = item.getText();
if (string.equals("Go")) browser.setUrl(location.getText());
}
};
browser.addLocationListener(new LocationListener() {
public void changed(LocationEvent event) {
if (event.top) location.setText(event.location);
}
public void changing(LocationEvent event) {
}
});
itemGo.addListener(SWT.Selection, listener);
location.addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
browser.setUrl(location.getText());
}
});
}
}
</pre><div><strong>>>Output</strong></div><div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-GCOAfR_yQKc/Takd2xKb8yI/AAAAAAAAAXg/as1PsW7aTgc/s1600/Capture.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="319" src="http://1.bp.blogspot.com/-GCOAfR_yQKc/Takd2xKb8yI/AAAAAAAAAXg/as1PsW7aTgc/s640/Capture.PNG" width="640" /></a></div><div align="justify"><strong><br />
</strong></div><div align="justify"><strong><br />
</strong></div><strong>>> Further Reading</strong> <br />
<ol><li><a href="http://www.eclipse.org/articles/Article-SWT-browser-widget/browser.html">Eclipse Article</a><br />
</li>
<li><a href="http://www.eclipse.org/swt/snippets/">SWT Snippets</a></li>
</ol>Manishhttp://www.blogger.com/profile/17308795203282864587noreply@blogger.com0