Saturday, November 28, 2009

Computer Graphics vs Image Processing

There is always a confusion among the newbies about the difference between Image Processing and Computer Graphics. Unless specifically mentioned , Computer Graphics is all about Synthesizing a new image from Geometry , Lighting parameters , Materials and Textures . The Emphasis is on Digital Image Synthesis.

Image Processing is the process of manipulating an image acquired through some device . The image too often will be acquired from photographs,scanners , medical equipments. The emphasis is on Analysis and Enhancement of the image. Computer Vision is an area where Image Analysis is used a lot. Raster Operations dominate in the case of image processing. In the case of Computer Graphics , you will mix vector and raster operations to generate the final image.

Friday, November 27, 2009

what are Pixels ?

Pixel or a Picture Element can be interpreted as a dot on the screen. Actually , it is the code for the color to be shown at a particular discrete ( with x, y position ) co-ordinates on the screen. Bitmaps or Pixmaps ( in Linux Parlance ) stores the information regarding the color of an image as sequence of bytes. I have blogged about this here in the past..! . In that particular page there is a code snippet which shows how one can store pixel values.

What is real time Rendering ?

Rendering is the process of converting Geometric description of Objects to picture. To do computations regarding lighting of a scene , it takes a while to finish the process. A Physically based Photorealistic computation will some time takes a day and more for rendering even a frame of graphics. ( you require 24 frames to show one second of a movie ...! ).

People came up with much cheaper lighting calculation which gives good visual fidelity( Phong illumination model [Ambient , Diffuse , Specular etc] was the dominant one till hardware accelerated graphics came. Now , using GPU you can have other lighting models in real time ). This helped to render scenes in milli seconds time per frame. Coupled with hardware acceleration , good interactivity was achieved. if you are rendering a scene at least 16 frame per second , it is called real time rendering. This is essential for Games , CAD and other scientific applications.

The cheaper lighting calculation is called Local illumination model. To have physically correct rendering , we require Global illumination calculation like Radiosity , Photon mapping etc.

what is a GPU ?

GPU ( Graphics Processing Unit ) was coined by NVIDIA to distinguish itself from others who were providing hardware acceleration support for 3D graphics (at that point of time ). NVIDIA was hinting that their Hardware accelerator was programmable. The name rhymed with the CPU. At one point of time , CPU was doing all the rendering work. Then Hardware accelerator began to appear to speed up the graphics processing by taking some of the load from the CPU. From circa 2001 onwards , GPU became programmable. NVIDIA , ATI/AMD and Intel are leading GPU vendors

HLSL ( Microsoft Direct3D ) , Cg ( Direct3D & OpenGL ) and GLSL are the programming languages meant to program the GPU.

Before 2002, there was a graphics pipeline ( meant for processing graphical elements ) which was fixed. Advent of programmable GPUs helped people by giving provision to inject one's own code to customize the Graphics Processing. The small snippet of code is called a Shader. Direct3D and OpenGL allowed two shaders viz Vertex Shader ( Per vertex processing before primitive assembly ) and Pixel Shader ( Per fragment [ almost pixel ] processing ). Now, there is provision to add a new beast called Geometry Shader ( works after vertex shader ) to the pipeline. Refer to OpenGL ( www.opengl.org ) , NVIDIA , ATI/AMD and Micrsofot DirectX documentation for more details regarding this.

Now a days , GPUs are used for things other than Graphics. They are massively parallel processors which can be used for Science and Engineering Computation as well. NVIDIA has got CUDA and Microsoft has got DirectCompute ( available with DirectX 11 ) for exploiting this facility. ATI has got CTM ( close to the metal ).

Khronos group ( who standardizes OpenGL ) is coming up with OpenCL as a cross platform standard for GPU/co-processor computation.

Read about GPU in wikipedia and other site. Other keywords to look are CUDA, DirectCompute , OPENCL etc..!

Thursday, November 26, 2009

Books on Graphics Programming Math

F.S. Hill's (co-authored with stephen Kelley ) Computer Graphics Using Opengl, 3rd Ed is an excellent book which covers all the math and has got good OpenGL sample code. Incidentally,I am having all the three editions with me. The book costs around Rs. 500.

"Foley & Van dam" and "Hearn & Baker" has got good coverage of Math as well.

Books on Graphics Programming Theory

There is no one single book which covers a huge area like Computer Graphics Programming. It is impossible to do justice to any of the topics , if one attempts to do so. My current favorite meant for the beginner is Hearn and Baker's book on Computer Graphics. Pls. try to buy OpenGL edition which is available as international edition (Rs. 550 ) .

I have blogged about that book in the past @ here and here as well.

To understand the underlying theory , Foley and Van dam is a good book.

Computer Graphics - James Foley and Adries Van Dam ( available as low priced asian edition
@ rs. 350 or so )

Rogers "Procedural Elements of Computer Graphics" is good at giving insights into Clipping , Hidden Surface Removal ( Visible Surface determination ) , Scan conversion and Rendering.

How do i start Graphics Programming ?

To learn Computer Graphics Programming , one has to Program in a platform like Windows , Linux or even Java. Technically speaking , Java is a virtual machine platform.

1 ) Since installed base of Windows is more than any other Operating system, first one
should learn

a) Windows API Programming

C/C++ is the primary programming language for programming Windows. Even though Programming model is bit dated , still at the metal level Windows works this way.

There are other GUI libraries like MFC ( Microsoft Foundation class ) , Qt ( from Nokia ) or
WxWidgets for programming Windows.


2) if GNU Linux is the primary platform of your choice , you should start
with

a) XLib Programming

C is the primary programming language for programming X. There are libraries like
Gtk ( C ) , Qt ( C/C++ ) and WxWidgets to ease the programming effort.

3) if Java is the primary platform of your choice , you should learn

a) AWT or Swing Interface.

Once you have chosen the platform , one should choose a 2D graphics API.

2D graphics APIs for Windows
=====================

GDI (Graphical Device Interface) is the standard interface for interacting with display , hardcopy and plotter devices. GDI+ has added some extensions like Alpha channel , better Imaging support etc... OpenGL (a 3D graphics API ) can be tricked into providing a 2D surface to draw up on. Coercing a 3D API to do 2D programming is bit advanced.


2D graphics APIs for Linux
===================
XLib has got extensive support for 2D graphics. Qt and Wxwidgets nicely wraps XLib graphics.
OpenGL (a 3D graphics API ) can be tricked into providing a 2D surface to draw up on. Coercing a 3D API to do 2D programming is bit advanced.

2D graphics API for Java
==================
Java2D is an excellent API for doing 2D graphics programming under Java.


After fiddling with 2D , one can choose a 3D graphics API

3D graphics API for Windows
=====================
DirectX has got Direct3D which meant for Graphics Programming. You can also choose
OpenGL for programming 3D under windows. Mesa3D ( @ www.mesa3d.org ) is a OpenGL
like API for doing 3D graphics.

3D graphics API for Linux
===================
OpenGL is well supported under Linux. Mesa3D ( @ www.mesa3d.org ) is a OpenGL
like API for doing 3D graphics under Linux as well.

3D graphics API for Java
===================
JOGL is an API which gives access to underlying OpenGL driver under java. To program at a higher level , one can use Java3D ( a scene graph API ) for programming 3D under java.

Can we do Graphics Programming under C# ?
Of course, one can use GDI+ for doing 2D graphics programming. XNA and now deprecated Managed DirectX is a way to program 3D. To Program at a higher level , one has got WPF 3D.

Computer Graphics Programming - BarCamp 7

I am planning to present a session on 3D computer graphics programming @ the BarCamp Kerala 7 event to be held at Kristu Jyoti College of Management and Technology (Kottayam/Changanassery).

The synopsis of the talk from the site is as follows

"The Visual Computing Paradigm is in vogue for the past ten to fifteen years. In Kerala, we have got plenty of talent in the Computer Graphics content (designers,media animators etc ) space. There are only a few people who have chosen Computer Graphics Programming as a career in Kerala ( for that matter whole of India ). The Session will give a detailed introduction to Computer Graphics Programming Concepts like Mathematics of Co-ordinate System/Geometric Transformations,Viewing,Lighting Techniques,Texture and Special Effects to name a few. I will be demonstrating Procedural Techniques using Cg (NVIDIA) , GLSL (OpenGL) and HLSL (from Microsoft ). These are languages meant for programming the GPU (Graphics Processing units). The Presenter has (in the past ) spent considerable amount of time on Real Time Computer Graphcis as applied to CAD and Visualization industry. The samples will be shown using Direct3D,OpenGL and even Software Rendering. The stuff like Ray Tracing will also be discussed."

Aim of the Session
=============
Statistically speaking , if some one is a programmer in Kerala , he will be working with Databases using C# or Java as the primary programming language. The services industry in kerala is skewed towards these kind of stuff. There are only a few companies in the science and the engineering space. As far as i know , even these companies started very late in the 3D vector graphics arena. The session is for motivating youngsters to take Computer Graphics Programming as a career option.

What is wrong with database Programming ?

There is nothing inherently wrong with database programming. After learning Engineering for four years , programming for a investment bank or a insurance company is waste of one's time.
There are commerce graduates ( with little training ) who can do a better job than these engineers. So,Plenty of talent is wasted this way.

IF-ELSE-WHILE LOOP-SELECT-UPDATE-DELETE Programming can be done by anyone who has bothered to learn it.

why computer graphics programming ?

This is an area where multi disciplinary skills are necessary. A career in computer graphics is a rewarding experience both intellectually and from a bottom line perspective. You will use things
like Linear Algebra , Numerical Methods , Signal Processing and Sound Object Oriented Programming principles while developing Graphics intensive applications.

In the coming days , I will blog about Computer Graphics Programming and choosing it as a career option. Feel free to write to me with questions @ praseedp@yahoo.com

BarCamp Kerala Edition #7

The Next edition of the BarCamp Kerala will be held at Kristu Jyoti College of Management and Technology, Kottayam (Changanassery).

You can register to participate in the events by going to the url @

http://www.barcampkerala.org/blog/register/

I am planning to take a session on Computer Graphics Programming there.

Thursday, November 19, 2009

A strategy to port VB.net code to C#

I was flipping through a game programming book which i purchased long back. The title of the book is .NET game programming with DirectX 9 . The code is written in VB.net. I happen to see a chapter which gives a newbie how to get into 3D programming. There is a walk cycle demo. The value of the book is questionable ( at this point of time ) as Microsoft is focusing on XNA as opposed to Managed DirectX. The first two games ( A tetrix clone and a snake game ) is using GDI+ for rendering.

I chose the Tetrix clone as a vehichle to teach Graphics programming concept to a friend of mine.

There are four modules in the project

a) clsSquare
b) clsBlock
c) clsGameField
d) Gamefield class..

The person in question is not familiar with VB.net much. So, i had to help him out.

What we did was

a) Created a DLL Project in C#
b) Ported clsBlock to C# (from VB)
c) Generated the DLL
c) Removed clsSquare.vb from the applcation project
d) Added a reference to the TetrisEngine.dll
e) use clsSquare type in the VB project.

Followed the same strategy for clsBlock , clsGameField. Only thing remained was the form. For that created a new executable project. Added the form to the new project. Linked TetrisEngine.dll (assembly) to this Application. The whole game was ported to C#.

Mixed Language programming is a boon...!

Wednesday, November 18, 2009

Hearn and Baker - The best academic book on computer graphics

For the past couple of days , i was using Hearn and Baker ( OpenGL edition ) to teach computer graphics programming to be a newbie. The feature of this book is availability of some twenty computer programs which uses OpenGL as it's physical renderer. The book uses only basic primitives from OpenGL API like GL_POINTS , GL_LINE_STRIP , GL_POLYGON for it's
2D graphics programming part. The explanation of co-ordinate transformation is one of the best available. The author has taken care to use Column format for Vector and Matrix. This matrix format is compatible with OpenGL and Java3D. The math in this book is written in such a way that one will emerge out with clear idea of how things in a typical (OpenGL like ) graphics pipe line works ( At least the Vertex Processing part ). I recommend this book to anyone who want to start Graphics programming.

OpenGL uses Column Vector Format . This means a new Transformation Matrix is Pre-multiplied with Current Transformation Matrix.

Imagine that we want to Scale a Polygon and Translate it ...

S = <scale Matrix>
T = <translation Matrix>
I - Identity Transformation Matrix

you have to give glTranslate followed with glScale

CTM => I (identity Matrix )
CTM => T*CTM
CTM => S*CTM

Transformed Vertex = CTM*Vertex

This is bit confusing for a newbie.

This is what really happens => Transformed Vertex = T*S*vertex ( Scale is applied first and
then the effect of Translation..this is what was intended )


I used Brian Paul's Mesa3D as the opengl implementation of the book. The book can even work with Microsoft's Generic OpenGL implementation.

Monday, November 16, 2009

Ankit Fadia Story- Now the people are striking back..!

It was at the turn of this millennium, Ankit Fadia made his presence felt in the Indian media. Moment we (Indians) hear about Ethical hacking,his name really pops up in any case. For some , he is synonymous with ethical hacking and for others a nuisance created by the media. They fear this lad has hijacked Ethical hacking movement. ( He is bit hyped by reporters ..i have not heard Ankit boasting )

Over the years , where-ever i go there will be at least one geeky engineer in the crowd who question his (Ankit's) credentials. The first time i came across this was from a group of (young ) software professionals who were two years into their career and working with Microsoft and Yahoo in India. These youngsters were pissed off when Ankit's name pops up everywhere. This is understandable as these young professionals were working with equally geeky stuff as Ankit's exploits.

The latest tirade is from some guy by the name Sandeep. The blog post is available here.

My observations on him is as follows

a) His first book was really amusing to read from a programmer's perspective. The book contained good introduction to Perl , C/C++ socket programming. ( Teaching Perl or C/C++ network programming is not the stated goal of the book though )

b) His series ( of books ) is generally informative.

c) I happen to find a network hacking book authored by him which contains good technical information useful for a budding network programmer.

d) The book on crytography ( co-authored ) with Jayasree Battacharjee is good as an example for coding bit level stuff in C/C++. I liked the book. ( Here again , i liked the book not for it's stated goal)

In the last BarCamp when security was discussed , Ankit's issue popped up again.
This time Manu Zacharia ( who has co-authored a book with Ankit - on IDS ) gave a different perspective. "His managerial skills and time management skills are really good. Moreover , in India most people cannot afford Rs. 40,000 ( $1000 ) course for security. His courses gave masses an opportunity to learn security topics for Rs. 6000 ($120 ). ". So, the guy has a business model which has got takers. ( Economics favor the existence of Ankit Fadia. )

I think , (some times unusual ) Media projection he gets is responsible for this anger. Anyway , i respect this guy for his over all quality. The best strategy is to ignore the media projection and carry on with our life as usual. There are other things beyond hacking in Computer Programming.

Sunday, November 15, 2009

Installing OpenGL 3.2

OpenGL API is a cross platform API for graphics Programming. It's Ancestor is Silcon Graphic's GL API. I started using OpenGL in the year 1996. It was an add on for Microsoft Windows 95 operating system back then (Though, It was part of Windows NT Operating System). I started with OpenGL after gaining reasonable competence in GDI Programming. I could not understand anything at first.


Later two books helped me to get a grip on the OpenGL API....

a) OpenGL Programming in Windows 95 and Windows NT by Ron fosner
b) Interactive Computer Graphics - A top down approach - by Edward Angel.

Last , but not the least i learned a lot from

c) 3D Graphics File Formats: A Programmer's Reference by kieth rule.

Kieth rule's book ( which had a OpenGL based rendering Engine ) along with VRML in 21 days made me competant to work with 3D graphics. The information was hard to come by as there was no Google around or access to internet was costly (for me !).

Later , i started using SceneGraph based APIs like Java3D , HOOPS etc in my projects. These APIs give a higer level view of the Graphics pipeline. We can produce surprising amount of good Graphics in a matter of days. using OpenGL's low level API,it my take a year or so to get a good grip on the subject.

So, if you are a Graphics Application developer , go for

A) OpenSceneGraph
B) HOOPS ( it is commercial..but..worth it )
C) Java3D
D) WPF 3D

These APIs isolate the underlying physical renderer from you. This is convenient for a programmer who is working with CAD applications.

But, modern GPUs (Graphics Processing Units ) are programmable. if you want high fidelity
visual effects, one needs to touch the metal. Then , one should directly program at the Direct3D or OpenGL level. Direct3D has evolved keeping up with the trends in the graphics hardware (moore's law applies here too ) and OpenGL was lagging behind as it is controlled by a consortium ( ARB / Khornos grpup ). In the past couple of years , they have made sweeping changes to the API to give developer all the feature of the underlying graphics hardware ( Earlier these were exposed through Vendor Extensions ).


My graphics card is GeForce 9400 GT. It is a Direct3D 10 class hardware ( that means it can support Geometry Shader , Vertex Shader and Pixel Shader ). I went to the NVIDIA site and did download the drivers necessary for writing OpenGL 3.2 programs. The drivers available with Cg 2.1 is only OpenGL 3.0 compatible.

I could run a GLSL 1.5 sample tutorial found on the net.

Hearn and Baker - OpenGL edition

I purchased the third edition of Celebrated Computer Graphics Programming book authored by Donald Hearn and Pauline Baker. I had purchased the first edition of their book back in the year 1995. It was my fifth book (back then ) on Graphics. ( Now, i might be having some fifty books on Graphics Programming alone ..!)

The Previous books before Hearn and Baker were

a) Zen of Graphics Programming by Michael Abrash
b) Graphics Programming in C by Roger Stevens
c) Computer Graphics - Steve Harrington
d) Procedural Elements of Computer Graphics - Rogers

When the C version of the book was published , i purchased that as well. The OpenGL edition contains some 20 odd executable programs (source is available in the print form ) which one can run using Generic OpenGL from MS , Mesa By Brian Paul or using any Hardware vendor provided OpenGL implementation.

The book uses only a small subset of OpenGL calls to teach the concepts of computer graphics. The C/C++ code will give a student of Computer Graphics good insight into how theory is put into practice. It is done really well.

The only problem i see with the book is some of the calls are deprecated by OpenGL 3.2. There is no mention of Shader Programming or Programmable pipeline.

Wednesday, November 11, 2009

Armchair Musing about "GO" Programming language

Through tweets , i came to know that Google has released GO, a new Programming language. I happen to see tweets about trying the language out. Personally , i feel it is going to be YAPL ( Yet Another Programming Language ). I think Google might be going the Microsoft way in releasing non standard stuff which is going to be de-facto stuff. Since Google developer products are becoming ubiquitous , the language will make it presence felt in the coming days.

I went to the Lambda the ultimate site to see the news and comments on that. The biggest resistance is from the python camp. The other day , i had blogged about MIT replacing scheme with python for their freshmen course. From a link , i went to the GO Language design FAQ page.
Oh, the people behind the project are former AT&T guys. Ken Thompson and Rob Pike are
old unix gurus ( Ken thompson is the father of Unix ). Rob Pike is famous for his BitBlt (Binary Block transfer for Graphics image ) algorithm. Last time they were heard in the context of
Plan 9 OS, which is supposed to be a successor of Unix.

Rob Pike is the author of Unix Programming Environment and co-author (along with Brian Kernighan ) of Practice of Programming. Both books are really good.

I will wait for a while , before taking a look at this new programming language. The day before ytd , i decided to learn Python to port some programs in python to C#.

Tuesday, November 10, 2009

GLSL shaders under MESA

The Mesa Project started by Brian Paul is a Software Renderer with OpenGL API interface. This Project even forms the basis of some OpenGL drivers. Today , i wrote some Cg Programs to refresh my skills in Shader Programming. After porting couple of programs from Orange Book ( OpenGL shading language 2nd Edition ) , out of curiosity , i tried to run GLSL programs on Mesa.

The steps were as follows ( It took two hours for me to get a sample shader up and running )

a) DownLoad MesaLib.zip , MesaGlut.zip and MesaSamples.zip from Mesa3D.org.
b) Unzip all the files ( i used winzip )
c) open in the visual studio [MesaHome]\windows\VC8\mesa\mesa.sln and build it
d) go to [MesaHome]\windows\VC8\progs
e) open progs.sln to build the MesaGlut library

By now , i got Mesa Binaries and Mesa Glut binaries. This did not help me to run the shaders.

I went to the Glew Library project site and downloaded the latest glew library.

Copied all the libraries ( LIB and DLL ) to \progs\glsl. I could not run the makefile. The files were showing errors. I tried command line approach

To compile brick shader

\progs\glsl> cl -I..\..\include -L..\..\Lib brick.c opengl32.lib glut.lib glew32.lib glew32s.lib
shaderutil.obj

To compile trirast shader

\progs\glsl> cl -I..\..\include -L..\..\Lib brick.c opengl32.lib glut.lib glew32.lib glew32s.lib
shaderutil.obj


shaderutil.h and shaderutil.c are available in the \progs\util directory. I copied the stuff into
\progs\glsl folder and compiled using cl.exe

command : - cl /c shaderutil.c ( this produced shadertutil.obj )

Even though the performance of a software shader is questionable , we can test the correctness of our program.

Scheme vs Python @ MIT

I got introduced to the scheme programming language through (Essentials of Programming Languages ) EOPL book. I happen to get an indian edition of the book from a book stall (MindStorm ) in Kochi. After completing my first full blown interpreter for a circuit simulation language in 1998 , i got this book. When i got the book , i did not have a scheme interpreter with me. Neverthless , it was amusing to go through the book.


The first statement from the foreword is as follows

"INTERPRETER for a Computer Program is just another Program ...!"

For a person who just finished an interpreter project for a Domain Specific Language , it is music. The foreword is written by Harold Abelson. Harold Abelson is a co-author of venerable Structure and interpretation of Computer Programs (SICP). In the year 2001, i downloaded the MIT scheme interpreter and keyed in some of the programs. The Electronic version of the
SICP is available @ the following site.

In the year 2005, i got the hardcopy of SICP. To this day , once in a while , i still flip through the pages to find something amusing. This helped me to master LINQ very easily. Now a days , ideas from functional programming are percolating into mainstream languages like C# , Java and
Python.

In the last two days , i have watched at least eight videos from MIT course 6.00. I told about this to my friend , Sanjay. He gave me the information that this new course is a replacement for
6.001. MIT has dropped scheme in favor of python. Any way 6.00 is a really cool course. Even
experienced programmers will gain a lot. I am really enjoying it.

Sunday, November 08, 2009

OWASP meet up at Kochi - Nov 8. ,2009

The OWASP Kerala's meet-up was held ( on Nov.8 ) at Cyber Prism Technologies , Eranakulam. The Turnout doubled this time. In the first meet-up organized at Some-where-Else cafe had fifteen participants. This time it was more than thirty.

Myself and a friend ( Dilip varma ) of mine started from Aluva around 2.45 pm. It was raining heavily in Aluva at that point of time. But,once we crossed Kalamassery , it was sunny once again. So,we reached the venue at least 55 minutes earlier. After another half an hour , Daniel and Deepu arrived at the scene. Later we learned that the chief resource person of the day , Manu Zacharia had arrived earlier busy setting up a lab for his demo.

We got roughly 30 minutes for chit chat with other attendees. The discussion drifted to OSS solutions and it's merit. To Act as a devil's advocate , i pointed some of the weaknesses of OSS
strategy. The discussion was lively and was cut short as the time for presentation was up.

Deepu Joseph made a welcome speech and asked audience to introduce themselves. The audience comprised software developers, network administrators , representatives from City Police Cybe crime dept. , students and some enterprueners ( i could count four !) .

Then for the next two and half hours , Manu Zacharia gave a detailed walkthrough of Security Principles and Security Lingo ( They have got their own terms for every phenomena under the sun !). Most specialized professions do have that ..!

He started with CIA triad , Confidentiality , Integrity , and Availability. He gave defenition of
each of the term in an unambiguous manner with examples. His attempt to reach the audience is clearly laudable. By asking Questions , he made the session very interactive.

The most fascinating part was the discussion of Web Shells. He demonstrated how C99 shell can be used to peek ( and even poke ) sensitive information on the web server of public sites.
Then the discussion shifted to technicalities of how one can inject a php page on to a server. There were questions regarding the availability of such shells for ASP.net etc..

He demonstrated a vulnerability in the new Windows 7 OS. He crashed a running Windows Machine by running a Python Script from a remote machine. The script exploited the vulnerability in the implementation of SMB Protocol. SMB protocol is the standard protcol
used by windows explorer for file sharing. Most OS's support it. (This reminded me of a project
which i worked at Nest for a Storage device. We took then new 2.4 kernel and added support
for USB mass storage device so that this storage device can be accessed from Windows. we tweaked some SAMBA code to enable that.) He showed another vulnerability with Windows 2003 R2 server. This also exploited a SMB hole. The content of the file ( smb_BSOD.py or so )
is an array of x86 instruction code ( Shell code ) which is thrown to the port
445 ( if my memory is correct ) ....bing...you have got a BSOD ( Blue Screen Of Death - I asked
about this acronym. ). BSOD is a daily story for device driver writers who play with DDK.

There was lively discussion about the Security / Usability as well. Theoretically , any system can be made secure. But , There should be justification from an Economic Perspective as well. More secure you system , performance (most often ) has got a inverse co-relation with it. One needs to balance that.

He did show a slide on AT&T security monitoring infrastructure. The place looked like a huge theatre. There was discussion on Protocol vulnerabilities , OS specific gotchas , AKAMAI (
it was a long one ) etc to name a few.

All together it was enough food for thought for all the people who were present over there. Almost all the people from the audience participated in the discussion.

Saturday, November 07, 2009

A Program to generate Palindrome Number in C#

I was flipping through Java Cook book published by Orielly. In the Number chapter , there is a recipe to generate Palindrome Number.

The idea is as follows... Take a number ...say 54

Algorithm ...

Add <num> + Reverse(<num> ) ... should converge to a palindrome !

54 + 45 .... 99 is a palindrome

132 + 231 => 363 .. is a palindrome...

Some times..we need to continue this process untill we reach a palindrome..

The source code will tell the rest of the story..

//////////////////////////////////////////// 
//
// A C# Program to generate a Palindrome Number from
// a number... Adapted from Java CookBook...
//
// Recipe 5.21 Program:Number Palindrome...page 151
//
//
using System;


namespace Test
{


public class Caller {

////////////////////////////////////////////
//
// This will reverse a Long number
//

public static long Reverse( long a )
{
long rev = 0;

while ( a != 0 ) {

rev = rev*10 + a%10;

a=a/10;

}

return rev;
}
/////////////////////////////////////////////////////
//
//
// This will determine whether a number
// is palindrome or not
//
public static bool isPalindrome( long a ) {
if ( a.ToString() ==
Reverse(a).ToString() )
return true;

return false;
}

/////////////////////////////////////////////////////////
//
// Actual routine to Generate a Palindrome... it will converge !
//
//

public static long FindPalindrome( long a ) {

if ( isPalindrome(a) )
return a;

return FindPalindrome(
a + Reverse(a));
}

//////////////////////////////////////////
//
// entry Point ...
//
//

public static void Main(String [] args ) {


if ( args.Length != 1 ) {
Console.WriteLine("FindPalindrome <num>\n");
return;
}



long rs = 0;

try {
rs = Int64.Parse(args[0]);
}
catch( Exception e ) {
e.ToString();
}

if ( rs <= 0 ) {
Console.WriteLine("Invalid number\n");
return;
}
rs = FindPalindrome(rs);
Console.WriteLine(rs.ToString());
}

}

}

Friday, November 06, 2009

Bit Wise Operations and Enums in C#

I was helping a friend of mine implement a form in C#. The form has three buttons for ADD,UPDATE and DELETE. There were five text fields in the form. Depending on the state of the text field controls and application context, i need to enable or disable the buttons. This is a common design problem in C#.

I declared an Enum

enum BUTTON_STATE
{
NONE=0, // None of the buttons are active
ADD = 1, // ADD button is active
UPDATE = 2, // UPDATE button is active

ADD_OR_UPDATE = ADD | UPDATE, // 1 | 2 = 3
DELETE = 4, // Delete Button is active
UPDATE_OR_DELETE = UPDATE | DELETE // 4 | 2 = 6

};

////////////////////////////////
//
// i am pasting a code snippet culled from the source code
//

public partial class ContactPlace : Form
{

///////////////////////////////////
//
// Current state of the buttons...

BUTTON_STATE curr_state = BUTTON_STATE.NONE;

////////////////////////////////////////////////
// Here a property would have been better... returns the
// current button state

private BUTTON_STATE GetButtonState()
{
return curr_state;
}

/////////////////////////////////////////////////////
//
// Set the button state and take necessary actions..

private void SetButtonState(BUTTON_STATE btn )
{
this.addbtn.Enabled = false;
this.deletebtn.Enabled = false;
this.updatebtn.Enabled = false;

if ((btn&BUTTON_STATE.ADD) > 0 )
{
this.addbtn.Enabled = true;
}

if ((btn & BUTTON_STATE.DELETE) > 0)
{
this.deletebtn.Enabled = true;
}

if ((btn & BUTTON_STATE.UPDATE) > 0)
{
this.updatebtn.Enabled = true;
}

curr_state = btn;


}

///////////////////////////////////////////////
// In the constructor , i am enabling all the button first
//
public ContactPlace()
{
InitializeComponent();

////////////////////////////////////////////////////
//
// Switch on all the buttons.... 4 | 2 | 1 ...... 7
//

SetButtonState(BUTTON_STATE.UPDATE_OR_DELETE | BUTTON_STATE.ADD );


///////////////////////////////////////////////////////
// Get the current state ( that is 7 ) and clear the Update and Delete Flag
// This will only enable ADD
//
SetButtonState(GetButtonState() & (~BUTTON_STATE.UPDATE_OR_DELETE));


}

//-------------------- Rest of the code
}

In short , we can enable the requisite bits to control the buttons....

///////////////////////
// Only enable Update and Delete Button ...
//
SetButtonState(BUTTON_STATE.UPDATE | BUTTON_STATE.DELETE);

//////////////////////////////////////////////
//
// Only Enable Delete Button.....
//
SetButtonState(BUTTON_STATE.UPDATE_OR_DELETE);


This is nothing but implementation of a Finite State Machine using Enums and Bit Operators.

Thursday, November 05, 2009

OpenGL Programming with C#

To run a piece of code from a C# Geometry and Graphics Book , i required an OpenGL adapter(wrapper) used by the book. The Library csgL is a wrapper over OpenGL Graphics Library. This will help one to write OpenGL programs in C#. I did download a tutorial from Nehe Productions site. The sample source file contained csGL assembly. Unfortunately , the program was breaking. Later , I went to the Sourceforge site to download the Library. It had a batch file whichwill setup the library so that we can use it from Visual Studio. They put the library into the GAC so that it can be shared from all C# programs. After the install , i could run the sample programs. I am planning to port some C/C++ code to C# .

Tuesday, November 03, 2009

Web Site of Simon Singh

One of my friend called me to know about an algorithm to find Prime numbers. The text book
sieve of Eratosthenes is the first one which came to his mind. Since it was for his nephew's home
work , that naive algorithm was enough for the task.

This algorithm is not suitable for industrial strength Prime number mathematics. The discussion drifted to Number Theory and it's application to Cryptography. The discussion did not go far before it reached the celebrated Fermat's Last Theorem. Suddenly , i remembered about Simon Singh's book on Fermat's Last Theorom. Incidently, i started my professional career the day Andrew Wiles proved Tanyama-Shimura Conjecture which implies a positive proof of Fermat's Theorom. But, The proof of Wiles seems not connected with alleged proof of Fermat. The Search is still on for Fermat's Proof ( if at all , any ).

The Wiki page of Andrew Wiles is available here. I went to the Web site of Simon Singh. I read his book on Cryptography before i read his Fermat's Last theorem book. His site is a very interesting read.

A File Filter in C/C++ - Part 2

In a previous post , i wrote a C/C++ program to convert a file into upper case. Since most operating systems support I/O redirection ( > , < and | operator ) at the command line , we
can write the program in a much simpler manner.

/////////////////////////////////
//
// FileFilter.cpp
// usage
// FileFilter < test.cpp
// FileFilter < test.cpp > tupper.cpp


#include <stdio.h>
#include <ctype.h>

int main()
{
int c = 0;

while ( ( c = getchar() ) != EOF )
putchar(toupper(c));
}

A File Filter in C/C++ - Part 1

C/C++ language is good for Writing File Filters. The Standard I/O library gives a cross platform solution to access text and binary files. using fopen family of function
and output to the console , we can write useful utilities. Here is a program which will
convert a file into upper case. The output will be sent to the console. One can use I/O
redirection to capture the output on to file of your choice.

TOUPPER.cpp => Compile ( cl TOUPPER.cpp ) and link to create TOUPPER.exe

usage
TOUPPER test.cpp
TOUPPER test.cpp > tupper.cpp // will send the output to tupper.cpp


///////////////////////////////////////////
//
// Compile @ Visual Studio command prompt using
// cl TOUPPER.cpp
// Written by Praseed Pai
// praseedp@yahoo.com
// http://praseedp.blogspot.com
#include <stdio.h>
#include <ctype.h>

void main(int argc , char **argv )
{
FILE *fp = 0;


///////////////////////////////////////
// argc will be at least one in C/C++
// argv[0] -> ExeName
//
//
if ( argc == 1 ) {

printf("No file is given as argument");
return;
}



if ((fp = fopen(argv[1] ,"rt"))== 0 )
{
printf("Failed to Open input file");
return;

}

//////////////////////////////////////////////
//
// Read a character at a time ( getc(fp ) convert
// it into upper case ( toupper(char) ..ctype ) and emit
// to the console (putchar)
//

while (!feof(fp) )
{
putchar(toupper(getc(fp)));

}

fclose(fp);




}

const_cast in C++

const_cast is a handy operator to remove the constness of a variable. The following Template function will demonstrate the usage of it.

///////////////////////////////////////////
// test.cpp
//
// Compile at the Visual C++ command prompt by giving
//
// cl test.cpp
//
//

#include <stdio.h>

/////////////////////////////////
// Following Template function demonstrates
// the use of const_cast. The function takes
// two references to T and returns the reference
// of the maximum. The Advantage of returning the
// reference is you can assign to the return value
// of this function as
// int a=10;
// int b=9;
// MAX_REF(a,b) = 100 will make a = 100
//

template <class T >
T& MAX_REF(const T& a ,const T&b )
{
return ( a > b ) ? const_cast<T&>(a) :
const_cast<T&>(b);
}

///////////////////////////////////////////
//
// Entry point.
//
//
int main()
{
int a = 10;
int b = 6;
///////////////////////////////////
//
// Assign 20 to the return value of the method
// this will make a = 20;

int r = (MAX_REF(a,b) = 20);
//////////////////////////////////
// This should print 20
//
printf("%d\n",a);
getchar();
}

Monday, November 02, 2009

A C# program to List files with specific extension

I was going through some of the C# code which i wrote when i started programming with C#. I saw a directory traversal routine which i wrote to search for Excel files in a particular folder. I tweaked a bit and here is how it looks now.

//////////////////////////////////////////////////
//
// A C# program to list files with a specific extension in a folder given
// as parameter.
// DirWalk.cs
//
// At Visual studio command prompt compile with csc DirWalk.cs
//

using System;
using System.IO;
using System.Collections;

namespace ForeCastWatcher
{

public class CDirectoryWalker
{
public CDirectoryWalker()
{

}

public void Reset()
{

}

public void Visit(String Path , String Filter , bool first_time)
{

DirectoryInfo di = new DirectoryInfo(Path);

DirectoryInfo[] dirs = di.GetDirectories("*.*");


if ( first_time )
{
System.IO.FileInfo[] nts = di.GetFiles(Filter);
foreach(FileInfo ns in nts )
{
Console.WriteLine(ns.FullName);
}
first_time = false;
}

foreach (DirectoryInfo diNext in dirs)
{

System.IO.FileInfo[] nts = diNext.GetFiles(Filter);

foreach(FileInfo ns in nts )
{

Console.WriteLine(ns.FullName);
}

////
/// Recurse the subdirectories
///
Visit(diNext.FullName+"\\",Filter,first_time);

}

}

public static void Main(String[] ar )
{

if ( ar.Length != 2 )
{
Console.WriteLine("Pls. pass a foldername and file extension without .");
Console.WriteLine("Examples are DirWalk d:\\test cs ");
Console.WriteLine(" DirWalk c:\\windows hlp");
Console.WriteLine(" DirWalk d:\\test exe");
return;
}
CDirectoryWalker v = new CDirectoryWalker();
v.Visit(ar[0],"*."+ar[1],true);

}

}

}

A simple CGI Program in Visual C/C++

I am just pasting a C/C++ program which wrote long back to demonstrate Web Programming model to a group of ASP.net developers.

/////////////////////////////////////////////////
// A simple CGI program
// This will retrieve the Browser name and spit it
// to the browser
//
//

#include <stdio.h>
#include <stdlib.h>

void EmitHTTPHeader()
{
printf("HTTP/1.0 200 OK\n");
printf("Content-type: text/html\n\n\n");

}

void main( int argc , char **argv )
{
char *lpstrBrowser = getenv("HTTP_USER_AGENT");

EmitHTTPHeader();
printf("<HTML><BODY>\n");
printf("<TITLE>");
printf("CGI sample program");
printf("</TITLE>");
printf("<H1>%s</H1>\n",lpstrBrowser);
printf("</BODY></HTML>\n");
return ;

}

How to Programmatically create a Datatable in ASP.net ?

We can create a DataTable programmatically by creating Columns by giving their types and other attributes. This can be handy some times. Here is how you can do it .

DataTable dt_table = new DataTable();
DataColumn dt_column;
dt_column = new DataColumn();
dt_column.DataType = System.Type.GetType("System.Int32");
dt_column.ColumnName = " X ";
dt_column.ReadOnly = false;
dt_column.Unique = true;
dt_table.Columns.Add(dt_column);
dt_column = new DataColumn();
dt_column.DataType = System.Type.GetType("System.Int32");
dt_column.ColumnName = " Y ";
dt_column.ReadOnly = false;
dt_column.Unique = false;
dt_table.Columns.Add(dt_column);
dt_column = new DataColumn();
dt_column.DataType = System.Type.GetType("System.Int32");
dt_column.ColumnName = " X*Y ";
dt_column.ReadOnly = false;
dt_column.Unique = true;
dt_table.Columns.Add(dt_column);

for (int i = 1; i < 100; ++i)
{
DataRow dr = dt_table.NewRow();
dr[0] = i;
dr[1] = 16;
dr[2] = i * 16;
dt_table.Rows.Add(dr);
}

////////////////////////////////
//
// Instantiate a DataGrid
DataGrid dgrdMenu = new DataGrid();
dgrdMenu.DataSource = dt_table;
dgrdMenu.DataBind();

/////////////////////////////////////
// Add to the control collection...and you are done
//
this.Controls.Add(dgrdMenu);

How to Load an XML file into DataGrid in ASP.net ?

I just wrote a piece of code which will load an XML file to a DataSet in ASP.net.


DataSet dstMenu = new DataSet();

////////////////////////////////////////
// In ASP.net , you need to call Server.MapPath
// to get the Windows File Path

string s = Server.MapPath("Test.xml");
dstMenu.ReadXml( s);

////////////////////////////////
//
// Instantiate a DataGrid
DataGrid dgrdMenu = new DataGrid();
dgrdMenu.DataSource = dstMenu;
dgrdMenu.DataBind();

/////////////////////////////////////
// Add to the control collection...and you are done
//
this.Controls.Add(dgrdMenu);

Chimp vs Tiger

Prem was consoling his friend Jerry because the latter was tensed about attending an interview the next day.

Prem => "Jerry,if you do not qualify ,who else will yaar ?"

Jerry =>"It all depends on the interviewer ?"

Prem =>"Why did u say so ?"

Jerry =>" I am confident about my skills. But,if interviewer do not know much..i will
be in trouble."

Prem =>"?????...Let us ask Guruji..."

Guru =>"It seems , Jerry has a point there. A Tiger cannot qualify an interview conducted by a Chimp...!"

A Mini File Searcher ( Mini GREP ? )

I was explaining Boyer Moore string searching algorithm to a friend of mine. In order to explain the algorithm , i initially wrote a naive algorithm to search a string ( like strstr in C/C++ ). To give a completion to the theme , i implemented a file searching program. The Program expects two
command line arguments

argv[0] - By default the exe name
argv[1] - File in which search has to be performed
argv[2] - search string

One can use GCC or Visual C/C++ command line compiler to compile the program. Here is the
complete program (albiet a naive one ).


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char * string_in_string( char *target , char *searchkey )
{
char *temp = target;

int len = strlen(searchkey);

while (*temp != 0 )
{
if ( strncmp(temp,searchkey,len) == 0)
return temp;
temp++;
}

return 0;

}


void main( int argc , char **argv )
{
if ( argc != 3 ) {
fprintf(stdout,"Usage: FileSearch <filename> <whattosearch>\n");
return;
}

FILE *fp = fopen(argv[1],"rt");

if ( fp == 0 )
{
fprintf(stdout,"Failed to open %s\n",argv[1]);
return;

}

char buffer[512];

while (!feof(fp)) {
buffer[0]=0;
fgets(buffer,511,fp);
if ( string_in_string(buffer,argv[2]) != 0 )
fprintf(stdout,"%s",buffer);
}

fclose(fp);
}



Sunday, November 01, 2009

A Brief introduction to Function Pointers

One of the biggest strength of C/C++ language is Pointer Arithmetic. We can have variables which
can hold address of functions. we can de-reference these pointers to invoke the function. Here
is a small C/C++ program which demonstrates the use of Function Pointers.

/////////////////////////////////////
//
// This is a simple example of function
// pointer. Function Pointers are like data
// pointers. Only difference is that we store
// Addresses of Functions
//
//
// Written By : Praseed Pai K.T
// http://praseedp.blogspot.com
// praseedp@yahoo.com
//
//

#include <stdio.h>

/////////////////////////////////
//
// I am creating a new data type which
// can store address of a function which
// takes two integers as parameter and returns
// an integer as result
//


typedef int (*FUNC)( int ax , int ay );


/////////////////////////////////////
//
// Let us declare two functions which
// takes two integers as parameter and
// returns an integer as result
//
//

int Add( int x, int y )
{
return x+y;
}

int Mul( int x, int y )
{
return x*y;
}


//////////////////////////////////
//
// Entry Point of a function
//
//

void main()
{

FUNC fp = Add;

//////////////////////////////////
// Invoke the function through the
// pointer
//
//

int rs = (*fp)(20,20); // fp(20,20);
printf("%d\n",rs);

/////////////////////////////////////////
//
//
//
fp = Mul;
rs = fp(20,20); // (*fp)(20,20);
printf("%d\n",rs);

}