Archive

Archive for the ‘C/C++’ Category

Importance of Structure and Coding Etiquette

August 7th, 2009 admin No comments

Well, it’s been a very long time since I last updated and I’d like to apologize to all my subscribers for that. I’ve been very busy, but it seems the work load is going down and I’ll have more time to continue writing! Now, on with the article.

So recently, I have just finished a project where one developer had started and then decided he could not finish the work, so I was hired to finish it. The natural thought to one who is inexperienced is, “This will be a cakewalk. Most of the programming is already done!” – wrong. The first thing that went through my mind was, “I wonder how bad this really is.” So, I accept the project (as I had only a few projects at the time) and take a look.

The code was atrocious to say the least. I felt as if this other developer had never learned how to use comments or his tab key/space bar to format. Most of the time on the project was bent around figuring out what the original developer had tried to do. It was a nightmare.

As I started digging through files and files of unnecessary sloppy code, I thought to myself, “I need to write something about this. This kind of work needs to stop.” I was not upset because of the amateur programming, nor the fact that it was undocumented and poorly written. What bugs me is the fact that someone paid for that kind of work. It looked like the developer copy/pasted everything from snippets he or she found online. That being said, one must learn the importance of structure and coding etiquette.

Structure is important for general organization. It keeps code neat and clean looking and much easier for anyone, to include yourself, to go back and fix errors/security holes. Most people see structural formatting as a simple aesthetic quality when in reality it is like formatting a letter. The structure keeps things organized and understandable on a more universal level.

Coding etiquette, on the other hand, is something learned over a long period of time. No new developer can simply logon and expect to program to the standards set right now, but at the same time should begin mimicking the styles of major developers. Examining the work of others is one of the best ways for any developer to learn, so studying (yes, just like in school) the work of past developers, and prominent works of today, one can easily understand how to program professionally. A simple example would be to write functions rather than hardcode functions multiple times. Or rather than using raw MySQL functions, create an SQL wrapper to execute the functions.

There are many resources on learning how to program professionally, and be neat, but it’s up to developers to use the tools. The vast majority of developers, I would say, hold to the standards. However, for those who do not, they are just ripping off their client in the long-run.

Regards,
Dennis M.

Importance of a Portfolio

June 10th, 2009 admin 1 comment

Portfolio. The word sometimes lingers in one’s mind, but usually is associated with artwork, or a collection of works from your high school English class. But really, an online portfolio (whether it’s only artwork/graphics or programming) is very important when trying to find interested clients.

Generally, most people can only establish their names by doing quality work at a great price (or in a few cases, great work and advertising at a high price pays off too – but those are the few giants of the web today). Word of mouth is good, but when you have a website, you should be showing off more than that to your potential clients. When a client visits your site (no matter which way – browsing, by accident, referal, etc.) their first opinion is your site itself. From there, they are looking for a giant link or button that says “Portfolio.”

When the user goes to this link, they don’t want to see just links, but they want a thumbnail shot of what to expect, a link to a working example, and a description of the purpose of the work. Now I know I do not have all of those things right now (just yet, anyway), but they are well worth it. Since most users see other works I’ve done (and after speaking to me on MSN) they are always satisfied with what I have to offer, but I am working on my designing skills and a portfolio script which I shall be launching very soon so I can practice what I preach.

So now that everyone understands that a portfolio should be more than just a collection of works you done, everyone can start really presenting themselves effectively. Like I said, soon I will be finishing my portfolio script and perhaps releasing it to the public, so if you are unsure about how to get yours started, that may be a great starting point for you!

Regards,
Dennis M.

The For(); Loop

May 13th, 2009 admin No comments

Many new programmers are perplexed by the “for” loop. However, it is one of the most essential and powerful tools in any developer’s arsenal. Without it, efficient and clean programming would not be as possible. Early on, most developers seem to stick to the while(); loop. I mean sure, while(); is great for some things, but may not exist in some programming languages and not to mention won’t work for everything you need.

Let’s begin by going into the basics about the for(); loop. Well really, a lot depends on the programming language (I will provide both PHP and C++ examples in the source file). But more or less, the for(); loop is simply iteration. It will run until its defined limit is hit providing whatever results you wish. We’re going to do this in more standard languages (e.g.: C/C++ and Java) instead of PHP for mass compatibility. Just note, if you’re looking to do this for php, you do not need to define the type of variable, and your variable will just start with the “$” symbol. So for example, PHP would be for($i=0;…;…){}.

Now we’re going to write a sample program and break it down:

for(int i=0;i<=5;i++){
std::cout<< "This is line number "<< i << std::endl;
}

Now as most of you may have noticed, this is a C++ example, but will effectively explain how the loop works for ALL programming languages!

int i=0; – This simply defines the variable and starting place (0 in this case). In PHP you would simply use $i=0; and so on for the rest of the statements.
i<=5 – This tells the loop when to stop (This <= symbol means less than or equal to). When i>5, the loop will stop and proceed on to the rest of the code.
i++ – This tells what the loop should do after every time it is run. In this case, we’re using i++ which means to add 1 each time around.

Now those are the basics to the loop. What lies within is just simply the code to be executed, which could of course have conditionals and such within it as well (e.g.: if(), etc.). So now we’ll move on to a more complex example.

unsigned int choices=5;
char* choice = new char[choices];
for(int i=0;i<=choices;i++){
std::cout<<"Please enter a value: ";
std::cin>>choice[i];

if(!choice[i]){
std::cout<<"No value for choice "<< i<< std::endl;
}
}
for(int i=0;i<=choices;i++){
std::cout<<"Choice "<< i<<" was "<< choice[i] << std::endl;
}

This will store an array of choices and then after entering them, they will be printed back!

In the source below, all working examples will be provided!
For(); Loop Tutorial

So, that basically wraps everything up! If you need anymore clarification, just let me know.

Regards,
Dennis M.

Categories: C/C++, Java, Other, PHP Tags: , , , , , ,

C++ Programming: Visual Windows

April 24th, 2009 admin No comments

I am primarily a programmer for *nix platforms and some cross compatibility for the DOS command prompt as many of you know. However, I also program Windows in the visual sense (how most end-users envision their product). So I’m going to write up a quick tutorial for you guys today!

I am compiling the example with Microsoft’s Visual C++. I am not normally an advocate for most things made by Microsoft, but in this case there is no doubt that this is the best compiler for compiling Windows programs. The best part about it is (unexpected, I know; it is Microsoft after all) that the compiler is FREE and comes with a very nice and clean GUI.

Now be mindful, the example has small functionality, but it is more or less the basis to ALL Windows programs! As we go through, we’ll explain the importance of each part. So let’s begin with the main file so you can see what’s going on.

main.cpp

/**
* Windows Programming Tutorial by Dennis M.
*
* main.cpp
*
*/

// Basic includes :D
#include <windows.h> // Win32 Lib
#include “menu.h” // Our menu – we’ll explain this later ;)
// more commonly named “resource.h,” but for
// explanation purposes this is easier :)

// Main WindowProcedure Definition
LRESULT CALLBACK WindowProcedure(HWND,UINT,WPARAM,LPARAM);
const char szClassName[] = “MicrosonicTestProgram”; // Our program’s name

int WINAPI
// Our main class to make the Window
WinMain(HINSTANCE hThisInstance,HINSTANCE hPrevInstance,LPSTR lpszArg,int WindowStyle)
{
// Pointer definitons
HWND hwnd;
MSG msgs;
WNDCLASSEX wcl;

// Standard window properties
wcl.hInstance = hThisInstance;
wcl.lpszClassName = szClassName;
wcl.lpfnWndProc = WindowProcedure;
wcl.style = CS_DBLCLKS;
wcl.cbSize = sizeof(WNDCLASSEX);
wcl.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wcl.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
wcl.hCursor = LoadCursor(NULL,IDC_ARROW);
wcl.lpszMenuName = “MAIN_MENU”;
wcl.cbClsExtra = 0;
wcl.cbWndExtra = 0;
wcl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

if(!RegisterClassEx(&wcl)){
return 0;
}

hwnd = CreateWindowEx(
0,
szClassName,
“Microsonic.org Test Program”,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
640,
480,
HWND_DESKTOP,
LoadMenu(hThisInstance,”MAIN_MENU”),
hThisInstance,
NULL
);

// This is where we see the window.. ShowWindow()… duh!
ShowWindow(hwnd,WindowStyle);
while(GetMessage(&msgs,NULL,0,0)){
TranslateMessage(&msgs);
DispatchMessage(&msgs);
}
return msgs.wParam;
}

// Here we process all the commands etc.
LRESULT CALLBACK WindowProcedure(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam){
switch(msg){
// Process commands sent to the program
// In this case, from the menu items
case WM_COMMAND:
switch(wParam){
case MM_FILE_NEW:
MessageBox(hwnd,”MDI is more complex! Another tutorial soon perhaps on it! This is just the basics to Windows programming!\r\nSorry!”,
“Feature Not Available”,MB_OK);
return 0;
break;
case MM_FILE_EXIT:
PostQuitMessage(0);
return 0;
break;
case MM_HELP_ABOUT:
MessageBox(hwnd,”\tMicrosonic.org test program!\r\n\r\n\tFor more tutorials visit:\r\n\r\n\thttp://microsonic.org! \r\n”,
“Microsonic.org Test Program”,MB_OK);
return 0;
break;
case MM_HELP_VISIT:
ShellExecute(hwnd,”open”,”http://microsonic.org”,NULL,NULL,0);
return 0;
break;
}
break;
// If they hit the “X” button
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
// Default loop
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
break;
}
return 0;
}

Some basic points I’d like to touch upon. Since this is just the basics to the Window, I have not included MDI (allowing text, etc. through the new button) but, this is important for the generalization of the program. If you understand how this works, Windows programming becomes very similar to all other sorts of programming with the assistance of the MSDN Library. Now, realize that the structure file for the menu is never directly included into any C++ file, but rather automatically linked. Make sure you keep it this way and don’t make the mistake of including a .rc file. Also, as I peer through the code, it is important to realize that many of the function names are static. For the basics, all Windows programs should look as some sort of variation to this code simply by definition of a Windows program.

Now, let’s continue to see the header file. This purely holds definitions for the resource file holding the menu structure. If they are not defined, they will not work properly.

menu.h

/**
* Windows Programming Tutorial by Dennis M.
*
* menu.h
*
* Contains all our menu definitions
*
*/

// Give values to menu items
#define MM_FILE_NEW 2001
#define MM_FILE_EXIT 2002
#define MM_HELP_ABOUT 3001
#define MM_HELP_VISIT 3002

As you can see, each menu item is defined. These numbers are more or less arbitrary, you just want to make sure their definitions don’t conflict with each other or any other aspect of your program. I personally like to keep menu items grouped together, so I defined the “File” items in the 2000‘s and the “Help” items in the 3000‘s.

Finally, the structure of our menu. A resource file that is never really included.

menu.rc

/**
* Windows Programming Tutorial by Dennis M.
*
* menu.rc
*
* Resource file which contains the menu structure!
* To edit the file with Free Visual C++
* Right click and “View Code”
* Again, more commonly named “resource.rc”
*
*/
// Menu definitions
#include “menu.h”

// Should be able to get the hang of the menu ;)
MAIN_MENU MENU
BEGIN
POPUP “&File”,
BEGIN
// Format: MENUITEM “Title”, COMMAND_TO_SEND
MENUITEM “N&ew”, MM_FILE_NEW
MENUITEM SEPARATOR
MENUITEM “E&xit”, MM_FILE_EXIT
END
POPUP “&Help”
BEGIN
MENUITEM “A&bout”, MM_HELP_ABOUT
MENUITEM SEPARATOR
MENUITEM “G&oto Microsonic.org”, MM_HELP_VISIT
END
END

The structure is fairly straight forward, so I can probably leave it without much explanation. The only thing I would like to say is that you should realize how usable menu items are presented.
MENUITEM “Display Text”, DEFINED_FUNCTION.
The defined function is what is sent to the main loop of the program and is processed in the “switch.” Just remember this when you’re creating your programs!

As usual, I will provide complete source WITH the VC++9 Project file!

If you choose to make your own project, please make sure you go to the “General” tab and create an empty project. Compiler options in other Visual C++ presets do not work properly for many reasons. A major error one could run into (if using another setting) is compiling UNICODE which would break “const char szClassName[]” by definiton. You would then have to declare it as _T string.

Simple Win32 API Tutorial

Regards,
Dennis M.

What is CGI and How Can It Be Useful?

April 17th, 2009 admin 2 comments

Well, to be honest, in the present day the CGI wrapper is used much less commonly with all the new web programming languages such as: PHP, Ruby, etc. However, CGI, to put it simply, is a kind of C wrapper for websites. The concept sounds confusing and the truth is, it is just like any other programming language.

Let’s begin discussing the uses of it. The most important use of it today is for hosts that are not PHP (or any other language) enabled. Most hosts allow CGI (even though if programmed wrong can make the system vulnerable) if they don’t allow PHP or some other advanced server-side scripting. Normally, these files need to be placed in the “cgi-bin” to execute. Hosts do this as a sort of precaution, trying to confine the areas of break-ins due to poor programming.

Actually using it is different now. If you’re writing a Perl script, there is no compilation needed, you write like normal. However, if you are a C programmer, such as myself, and wish to use C, compile the source as program.cgi. Now, I’ve dabbled with Perl and can program in it fairly decently, but I’d much rather use C. It’s much easier for me. So, I’ll provide source examples for both styles here!

Now, let’s look at an example script:
The first and most basic script to any sort of programming is “Hello World” so I’ll provide the source for each (and the compiled binaries in the package below for the C-version scripts)

hello_world.pl (This will run properly as is)

#!/usr/bin/perl
# Hello World CGI Script (Perl Version) by Dennis M.
#
# Remember now, comments in Perl must begin with the '#' character

## Our content type ##
print "Content-type: text/html\n\n";

## Now print the page! ##
print "<html>\n
<head><title>Hello World! :D </title></head>\n
<body>\n
<h1>Hello World!</h1>\n
Hello World Script!\n
</body>\n
</html>";

and here is the C source (which, again, needs to be compiled)
hello_world.c

/**
 * Hello World CGI Script (C Version) by Dennis M.
 *
 * I prefer this (although it needs to be compiled) because
 * I'm a C programmer ;)
 *
 * oh yeah, and because we're compiling it with GCC or whatever
 * you use, we can use normal comments ;)
 *
 */

#include <stdio.h>

int main(){
  // Our content type
  printf("Content-Type: text/html;charset=us-ascii\n\n");

  // Our page!
  // We're going to break it up line by line so you can
  // see what's going on here.
  printf("<html>\n");
  printf("<head><title>Hello World! :D </title></head>\n");
  printf("<body>\n");
  printf("<h1>Hello World!</h1>\n");
  printf("Hello world! C style ;) \n");
  printf("</body>\n");
  printf("</html>\n\n");

  // Let's terminate the program now :)
  return 0;
}

Now, we won’t go too deep into the code because simply, they are two completely different languages. But, it’s important to point out that both send headers (Content-type: text/html). You can Google content-type’s and figure what does what, but there are many different types. Another commonly used type is Content-type: text/plain. Notice, if this had been the case, no HTML would have been parsed by the server and everything would have been displayed as plain-text!

So that’s basically it :) CGI is just a wrapper to run Perl and C programming on the web!

Here you can download the sources AND binaries:
CGI Tutorial – Hello World

One more tutorial left in the series! Keep sending in the questions so I have a few more topics to write about! ;)

Regards,
Dennis M.

Categories: C/C++, Other Tags: , , , ,