Tuesday, March 4, 2014

Windows 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.

Links:
  1. C++ Resource Leaks
  2. C++ Stack Corruption
  3. C++ Stack Overflow
  4. C++ Heap Corruption
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.

Enjoy !




Friday, September 20, 2013

Generate Lib From DLL

Introduction
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.

Open Visual Studio Command Prompt
It can be found within the Visual Studio Tools menu entry:
Start / Program Files / Microsoft Visual Studio / Visual Studio Tools / Visual Studio Command Prompt.

Extract Symbols
Within the command prompt type:
dumpbin /exports "C:\Program Files\VideoLAN\VLC\libvlc.dll" > "C:\Program Files\VideoLAN\VLC\libvlc.def"
Edit the libvlc.def file and modify it to get something like this:
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
...
Generate the .lib
Still within the command prompt type:
lib /def:"C:\Program Files\VideoLAN\VLC\libvlc.def" /out:"C:\Program Files\VideoLAN\VLC\libvlc.lib" /machine:x86
Of course, you'll need to adapt the path according to your configuration.

Source
Generate Lib From DLL

Saturday, September 7, 2013

Generating DTMF tones using C++

What are DTMF tones ?

DTMF tones are the tones used in telephones for tone dialing. The DTMF tones are sums of two sine wave tones at following frequencies:
                 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

How to generate DTMF tone samples
Generating sine wave samples is easy using the following formula:
sample=sin(n*2*pi*f/samplerate)
Where
  • n is the sample number (starting from 0)
  • f is the frequency you wan to generate
  • samplerate is the rate you are playing the samples through your sound card
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:
sample(n) = 128 + 63*sin(n*2*pi*f1/8000) + 63*sin(n*2*pi*f2/8000)
Where f1 and f2 are the frequencies of the sine waves in DTMF tone.

C++ Code (For 8 KHz Sampling Rate)
#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;
};

Links:
  1. DTMF Wikipedia 

Friday, August 9, 2013

Firefox: Get results from your favorite Google country domain


Firefox's default search bar gets its configuration options (what search engine to use, what parameters to pass, etc.) from XML files located in 'searchplugins' directory in Firefox’s default directory. If you are on a Windows system this most probably be 'C:\Program Files\Mozilla Firefox\browser\searchplugins'. There's an XML file for Google called 'google.xml'.To modify it follow the following steps (I am doing it for google.co.in, you can replace it as per your requirement): 
  1. 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).
  2. Edit 'ShortName' tag content and rename it to something else, for example, Google India.
  3. Then there are two 'Url' tags. Leave the first 'Url' 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 template="https://www.google.co.in/search" (or whatever you find useful).
  4. Change https://www.google.com/ to https://www.google.co.in within '<SearchForm>' 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.
  5. Now restart your Firefox browser and make the newly added Google search engine as default.
 Credits:
 

Wednesday, June 19, 2013

Windows API: The relationship between Process, Handle and Windows

1)
HAVE: Process ID, NEED: Process handle
Solution
OpenProcess()

2)
HAVE: Process handle, NEED: Process ID
SolutionGetProcessId()

3)
HAVE: Window handle, NEED: Process ID
SolutionGetWindowThreadProcessId()

4)
HAVE: Window handle, NEED: Process handle
Solution: Use 3) and then 1)

5)
HAVE: Process ID, NEED: Window handle
SolutionEnumWindows(), then in the callback function do 3) and check if it matches your process ID.

6)
HAVE: Process handle, NEED: Window handle
Solution: 2) and then 5)

Tuesday, May 21, 2013

What is 'CPoint' : ambiguous symbol atltypes.h?

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...

Error 1 error C2872: 'CPoint' : ambiguous symbol atltypes.h
Error 2 error C2872: 'CRect' : ambiguous symbol atltypes.h
Error 3 error C2872: 'CSize' : ambiguous symbol atltypes.h
.
.
Error N error C2872: 'CReality' : ambiguous symbol life.h

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 #include <windows.h> :
#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>

Sunday, May 12, 2013

WTL::CRichEditCtrl

WTL::CRichEditCtrl needs the following line for initialization, add it in your DllMain or _tWinMain and it resolves the issue:
HINSTANCE hInstRich = ::LoadLibrary(CRichEditCtrl::GetLibraryName());
Unfortunately I forgot that Rich Edit isn’t a common control and is not initialized with InitCommonControlsEx.

Tuesday, February 19, 2013

Some COM Books


Some books on COM. I just keep forgetting the name !!

  1. Inside OLE, 2nd Edition, by Kraig Brockschmidt (Microsoft Press)
  2. Understanding ActiveX and OLE, by David Chappell (Microsoft Press)
  3. Inside COM, by Dale Rogerson (Microsoft Press)

Wednesday, October 31, 2012

Print map of India using C

I don't know from where I got this code but its amazing ;)

#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;
}

The Output

                    !!!!!!                                                     
                    !!!!!!!!!!                                                 
                     !!!!!!!!!!!!!!!                                           
                       !!!!!!!!!!!!!!                                          
                     !!!!!!!!!!!!!!!                                           
                      !!!!!!!!!!!!                                             
                      !!!!!!!!!!!!                                             
                        !!!!!!!!!!!!                                           
                        !!!!!!!!                                               
                        !!!!!!!!!!                                             
                       !!!!!!!!!!!!!!                                          
                     !!!!!!!!!!!!!!!!                                          
                    !!!!!!!!!!!!!!!!                                  !!!!!    
                  !!!!!!!!!!!!!!!!!!!                               !!!!!!!!!! 
                 !!!!!!!!!!!!!!!!!!!!!!!                 !         !!!!!!!!!!  
            !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!              !!     !!!!!!!!!!!!    
           !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!        !!      !!!!!!!!       
            !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!      
             !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!       
              !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!  !!!!!!!!!!!!       
       !!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!        !!!!!!        
      !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!      !!!!!         
          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!        !!!          
        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!        !          
          !!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                       
           !!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                         
                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                          
                 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                           
                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                               
                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                               
                  !!!!!!!!!!!!!!!!!!!!!!!!!!!!                                 
                  !!!!!!!!!!!!!!!!!!!!!!!!!!                                   
                  !!!!!!!!!!!!!!!!!!!!!!!!!                                    
                   !!!!!!!!!!!!!!!!!!!!!!!!                                    
                    !!!!!!!!!!!!!!!!!!!!                                       
                    !!!!!!!!!!!!!!!!!!!                                        
                     !!!!!!!!!!!!!!!!                                          
                      !!!!!!!!!!!!!!!!                                         
                      !!!!!!!!!!!!!!!                                          
                       !!!!!!!!!!!!!!                                          
                        !!!!!!!!!!!!                                           
                        !!!!!!!!!!!!                                           
                        !!!!!!!!!!!!                                           
                          !!!!!!!!                                             
                          !!!!!!                                               
                           !!!!                                                
   

Query 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 getenv() method. See the below code.

#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: ";
  }
 }
}

Tuesday, October 9, 2012

HttpServer - The Oracle JDK 1.6 Hidden Feature

I 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 !!

HTTP server infrastructure/framework is very simple to implement and is bundled only with the Oracle JDK 1.6. Following are the main classes:
  1. HttpServer
  2. HttpContext
  3. HttpExchange
See this link for sun.* package discussions.

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();
 }
}

Steps to run the above code

  1. Compile it using Oracle JDK 1.6
  2. 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
  3. Open your browser and type the URL. For example, http://127.0.0.1:5463/

You should see something like this (depends on the browser):


Monday, October 1, 2012

How 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 org.eclipse.jface.text.source.SourceViewer , where I could have used JavaSourceViewerConfiguration
for providing Java highlighting and all. But there were two problems:
  1. 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.
  2. Secondly you would lose all the markup and bookmarking facilities available with editors
So, I decided to extend the existing Java editor. The steps are extremely simple,
  1. Create an editor extension
  2. Extend the extension class with org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor
  3. Override some of the methods
  4. Open your file with this editor

Code

Editor Code

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;
 }
}

Code for Invoking the Editor

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();
}

Monday, September 24, 2012

How to hide a window from Win32 Taskbar?


Argh !!! I don't know why but I keep forgetting the ex-style bit for this... 
To prevent the window button from being placed on the taskbar, create the unowned window with the WS_EX_TOOLWINDOW extended style. As an alternative, you can create a hidden window and make this hidden window the owner of your visible window.
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.
Taken from here: The Taskbar

Tuesday, September 18, 2012

3 easy steps to self-sign a Applet Jar file

Found this link that explains how to self-sign an applet in 3 easy steps:
  1. keytool -genkey -keystore myKeyStore -alias me
  2. keytool -selfcert -keystore myKeyStore -alias me
  3. jarsigner -keystore myKeyStore jarfile.jar me

Thursday, August 23, 2012

Firebug Lite for SWT Browser on Windows

Recently I came across this question on stackoverflow 'Eclipse swt browser and firebug lite'. The solution seemed very obvious. I answered the question there also, you can always upvote it ;).

The output:


The code for the same is as follows:

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();
 }
}

Tuesday, July 31, 2012

SWT Browser and Image Capture

Recently I was playing with the SWT-COM bridge and its Win32 APIs. Believe me or not, but the SWT Browser is the best SWT based UI control I have seen (you can argue but without any success). 

One of the experimental feature I tried accomplishing was to print the full HTML page as Image, and the result was superb !!

See the below images for the embedded browser control and the output of the image capturing utility !! Cool right ;)

Modified Browser Control:




Captured Image:


Tuesday, June 5, 2012

Atlapp and secure atl !!

After upgrading to VS2008, I started getting errors for lstrlenA, size_t, and lstrcpynA. 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??

And the fix is really simple, before including atlapp.h, just define:
 
#define _SECURE_ATL 1 


Tuesday, May 1, 2012

SWT - Capturing Control Screen-Shot

SWT code for capturing control screen-shot.

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();
 }
}

Original Composite:


Captured Image:

Wednesday, April 18, 2012

Programmatically create eclipse Java project

Following is a brief code snippet for creating an eclipse Java project using core JDT API.

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();
}

Friday, November 25, 2011

Running PostgreSQL From Command Line

This October I enrolled for the online database course offered by Stanford university. I started out with SQLite 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 PostgreSQL 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 Zip Archive.

The first problem I faced was that when I started to run my postgres server then it gave me this long error message:
“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.”

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 pg_ctl which is a utility to initialize, start, stop, or control a PostgreSQL server. Here are the steps:
  1. CD C:\pgsql\bin (or where ever your postgres bin folder is)
  2. set PGDATA=c:/temp/test
  3. pg_ctl.exe init
    The files belonging to this database system will be owned by user "ABCDXYZ". This user must also own the server process….
  4. 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, pg_ctl.exe start
  5. That it, the server is running and the process is owned by the logged in user.
  6. Now for the admin tool, run the ‘pgAdmin3.exe’ (its inside the C:\pgsql\bin)
  7. Now select ‘Add a connection to server’ toolbar button. This will show an image like this and fill in the values as suggested:

  8. Finally this page will come: