Pages

Tuesday, March 11, 2014

Preprocessor to control printf debugging

A fundamental way of debugging an application, especially developed using  C / C++ programming languages is "printf debugging". i.e. To dump a message on to console output with some variables.

However, including too many "printf debugging" statements can hinder the performance of an application. Therefore, it is important to include a mechanism to automatically remove all such debugging statements. The easiest way to achieve this is through conditional compilations.

One straight forward way is to wrap the printf statements within a preprocessor directive as follows.


#ifdef _DEBUG
    printf("Debug message\n");
#endif


This approach adds too much clutter into the source code. Therefore, I was looking for a elegant solution to this fundamental problem and came across the following code block.

Friday, January 24, 2014

Play WAV files with Java


The following simple application demonstrates how to play back a WAV audio file with Java APIs.
The key step is to specify the correct parameters and create an AudioFormat object.


Wednesday, January 15, 2014

Playing with Big Integers using Java BigInteger

The BigInteger class in java.math package allows to perform arithmetic operations on large numbers which do not fit into the Java primitive data types. The BigInteger class is particularly useful in cryptography operations where large prime numbers play a pivotal role.

The following snippet, which calculates the smallest factor of an integer (not in the most efficient way) gives a simple demonstration of fundamentals of using BitInteger instances in a program.

A key point to remember is the immutable nature of BitInteger instances.

Monday, January 13, 2014

Inter Process Communication: Windows NamedPipes & Java Applications

A Named Pipe is a mechanism for communication between processes. One process has to create the Named Pipe (termed as pipe server) and one or more processes can connect to this Named Pipe (pipe clients) using the unique name given to it, when it was created. 

Saturday, January 11, 2014

HTML iframe without src attribute



The HTML <iframe> tag denotes an inline frame within the HTML document. The primary usage of the inline frame is to embed another document within the current HTML document. In order to embed the intended document within the <iframe>, the address of the target document should be specified as src attribute value.

The following simple code snippet shows how to embed this page within another HTML document.

<!DOCTYPE html> <html> <body> <iframe src="http://www.duleekag.blogspot.com" width="200" height="200"> <p>iframes are not supported.</p> </iframe> </body> </html>

The paragraph tag (<p>) is used to indicate the browsers that do not support this tag. 

The intended purpose of <iframe> is to embed another document within the current HTML document. But sometimes, we all get the urge to tryout unorthodox stuff within our code. This is one such scenario where hard coded HTML content is embedded within an <iframe>. The obvious question is "why bother to add it within an <iframe>, if the content can be hard coded". Well.. this is just out of curiosity. 


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>iframe without src attribute</title>

<script type="text/javascript">
    function onTryItClick() {
        var content = document.getElementById("iframecontent").innerHTML;
        var iframe = document.getElementById("myiframeid");

        var frameDoc = iframe.document;
        if (iframe.contentWindow)
            frameDoc = iframe.contentWindow.document;

        frameDoc.open();
        frameDoc.writeln(content);
        frameDoc.close();
    }
</script>
</head>
<body>
    <div id="iframecontent" style="display: none;">
        <b>Hello World!</b> <br /> <i>Hello Again !</i>
    </div>

    <div style="margin: auto; width: 80%;">
        <iframe height="100" width="100%" src="about:blank" name="myiframe"
         id="myiframeid"> </iframe>
        <br />
        <button id="tryIt" onclick="onTryItClick()">Try It</button>
    </div>
</body>
</html>



Friday, December 27, 2013

OPOS (OLE for Retail POS) with JavaScript

The following simple JavaScript / HTML document demonstrates the fundamentals of establishing connectivity with the selected POS hardware device, through device dependent OPOS service object adhering to the UnifiedPOS device management architecture and specification. 


The detailed UnifiedPOS Retail Peripheral Architecture specification is available here.

This example uses a Magnetic Stripe Reader (MSR) as the hardware unit to demonstrate the basic device initialization process.

  1. Open : Opens a selected device for subsequent input / output operations.
  2. Claim: Requests exclusive access to the device.
  3. Enable Device: Bring the device to an operational state.
  4. Enable Data Events: Enable delivery of notifications when input data is available. The application should subscribe to notification events by registering a Data Event handler.
  5. Release: Releases exclusive access to the device.
  6. Close: Release the device and allocated resources.

 

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>POS Test Application</title>



<script type="text/javascript">

    //OPOS Data Event handler function

    function onDataEvent(status) {

        //Retrieve and demonstrate available MSR track data.

        document.getElementById("track1").innerHTML = OPOSMsr.Track1Data;

        document.getElementById("track2").innerHTML = OPOSMsr.Track2Data;

        document.getElementById("track3").innerHTML = OPOSMsr.Track3Data;

    }



    function onOpenClick() {

        //Subsribe for UPOS Data Events

        OPOSMsr.attachEvent('dataevent', onDataEvent);



        var result = OPOSMsr.Open("MSR-Device");

        if (result != 0) {

            //Failed to open MSR device with given device name.

            alert(result.toString());

        }

    }



    function onCloseClick() {

        var result = OPOSMsr.Close();

        if (result != 0) {

            //Close function invocation failed.

            alert(result.toString());

        }

    }



    function onClaimClick() {

        var result = OPOSMsr.Claim(1000);

        if (result == 0) {

            //If exclusive access is granted, bring the device to operational state.

            OPOSMsr.DeviceEnabled = 1;

            OPOSMsr.DataEventEnabled = 1;

        } else {

            alert(result.toString());

        }

    }



    function onReleaseClick() {

        //Relese exclusive access for the device.

        var result = OPOSMsr.Relese();

        if (result != 0) {

            alert(result.toString());

        }

    }



    function enableDataEvents() {

        //Retrieve number of data events queued by the device / service object.

        var eventCount = OPOSMsr.DataCount;

        document.getElementById("dataEventCount").innerHTML = eventCount.toString();



        //The DataEventEnabled property is automatically disabled for each Data

        //Event notification. The application should indicate its readiness to

        //handle the next Data Event by enabling this property.

        OPOSMsr.DataEventEnabled = 1;

    }

</script>

</head>

<body>



    <object id="OPOSMsr"

      classid="clsid:CCB90122-B81E-11D2-AB74-0040054C3719" height="36"

     width="36"> </object>

    <br />

    <button id="openButton" onclick="onOpenClick()">Open</button>

    <button id="claimButton" onclick="onClaimClick()">Claim</button>

    <br />

    <button id="closeButton" onclick="onCloseClick()">Close</button>

    <button id="releaseButton" onclick="onReleaseClick()">Release</button>

    <br />

    <button id="dataEventEnableButton" onclick="enableDataEvents()">Enable

  Data Events</button>

    <div></div>

    <div id="dataEventCount"></div>

    <div id="track1"></div>

    <div id="track2"></div>

    <div id="track3"></div>


</body>

</html>




This example uses the <object> tag to embed the device specific UnifiedPOS compliant control object as an ActiveX control. The relevant ActiveX control is located through the specified Class ID.

When the OPOS MSR ActiveX control object is registered using the "Regsvr32" command line tool, the relevant Class ID is added to the following location in the Microsoft Windows registry.
[HKEY_CLASSES_ROOT\OPOS.MSR\CLSID]

When the above HTML document is loaded on Internet Explorer web browser, a frequent browser crash problem may occur. This is caused by a mismatch in threading models used by different components loaded during operation. Detailed information on Processes, Threads and Apartments is available here.

The following registry entry is created when the control object is registered, which indicates the location of the object in the file system and its threading model. The ThreadingModel value should be set to Apartment.

Windows 32 bit
[HKEY_CLASSES_ROOT\CLSID\{Class ID}\InprocServer32]

Windows 64 bit
[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{Class ID}\InprocServer32]


The OPOS MSR control object depends on the services provided by the device specific service object to form its input output operations. The service object is registered as a seperate object using "Regsvr32" command line tool. During the registration process, a separate registry entry is created with its own class ID in [HKEY_CLASSES_ROOT\CLSID]. The ThreadingModel value of service object should be set to Apartment.  

Monday, December 23, 2013

Catching Linux signals - Example C program

Did a quick test on a strip down Linux machine to make sure the basics are in tact before troubleshooting a C program with signal handlers. This simple program triggers an alarm signal at a predetermined time. Just to make sure it has not stalled, a while loop is used to print the remaining time for the signal to trigger.    

 

#include <stdio.h>

#include <signal.h>

void handle(int sig)

{

   switch (sig)

   {

      case SIGALRM:

         printf("\nAlarm triggered\n");

         break;

      default:

         break;

   }

}



int main(int argc, char * argv[]) {

   int ticks = 10;

   signal(SIGALRM, handle);

   if (argc == 1)

   {

      printf("Using default alarm time: 10 seconds\n");

   }

   else

   {

      ticks = strtol(argv[1], NULL, 10);

      printf("Using alarm time: %d second(s)\n", ticks);

   }

   //Schedule alarm

   alarm(ticks);

   //Print remaining time

   while(ticks > 0)

   {

       printf("\r%02d", ticks);

   

       //Should call this function to display tick before sleeping.

       //Otherwise the request is buffered.

       fflush(stdout);

       ticks--;

       sleep(1);

   }

 

   //Cancel pending alarm requests, if any.

   alarm(0);

   printf("\ndone\n");



   return 0;

}