Monday, August 13, 2007

PHP: Force a page to https

Here is some php code which forces a page to redirect to the same page for https at port 443.

<?php
function die_force_page_to_https()
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='off')
{
$u='https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
$t='';
$t.='<html>';
$t.= '<head>';
$t.= '<meta http-equiv="Refresh" content="0;url='.$u.'>';
$t.= '</meta>';
$t.= '</head>';
$t.= '<body>';
$t.= '</body>';
$t.='</html>';
die($t);
}
}
?>

Monday, August 06, 2007

APACHE: Problem with mod_rewrite setup

One way to see if mod_rewrite is installed is to create a file called info.php with the following contents

 <?php echo phpinfo(); ?> 


Put the file in your server root and view it at http://localhost/info.php. Go to the apache section and look at Loaded Modules. If you see mod_rewrite listed there, you can start using the mod_rewrite commands. If not, you have to play with the apache config file: http.conf, add the following (a website told me to do this):

LoadModule rewrite_module modules/mod_rewrite.so
AddModule mod_rewrite.c


... and make sure the mod_rewrite.so file is in the right place. Then restart your web server. (suse linux: "rcapache2 restart", or windows: Control Panel->Administrative Tools->Services, right click on Apache and select restart)

PROBLEM:
Apache fails to restart.

In windows you can discover the reason using the Event Viewer (Control Panel->Administrative Tools->Services->Event Viewer). It gives the error for Apache:
Invalid command 'AddModule', perhaps mis-spelled or defined by a module not included in the server configuration

REASON:
AddModule for mod_rewrite is for apache 1.2 to 1.3x, but not apache2. I was running Apache2, so instead, the following worked for me in the apache config file:

LoadModule rewrite_module modules/mod_rewrite.so


Now restart apache, and check your http://localhost/info.php file and Voila! mod_rewrite is there, listed as a Loaded Module.

Now as for how to actually use mod_rewrite there are a lot of examples out there,
thats what google is for, right?

http://hypermail.linklord.com/new-httpd.old/2001/Jul/0863.html

Friday, August 03, 2007

CSS: Irritating IE FORM tags act like BR tag

One of the irritating things about IE is that the form start tag is automatically treated like a line-break tag.

Add this to your stylesheet to solve the problem:
form {margin: 0px 0px 0px 0px; }


source(s): http://weblogs.macromedia.com/cantrell/archives/2003/05/
git_rid_of_anno.cfm

Wednesday, August 01, 2007

C++: Set Registry Key Values

This piece of example code writes a key to the windows registry.

#include <windows.h>

int SetRegValue(char *key_name,char *key_word,char *b,int dwType,int s)
{
int j=0;

DWORD lpdwDisposition;
HKEY hKey;

j=RegCreateKeyEx(
HKEY_CURRENT_USER,
key_name,
0, /* reserved */
NULL, /* address of class string */
REG_OPTION_NON_VOLATILE, /* special options flag */
KEY_WRITE, /* desired security access */
NULL, /* address of key security structure */
&
hKey, /* address of buffer for opened handle */
&
lpdwDisposition /* address of disposition value buffer */
);

if (j==ERROR_SUCCESS)
{
RegSetValueEx(hKey, key_word, 0, dwType, (unsigned char *)b, s);
RegCloseKey(hKey);
}
return(j);
}

int main(int argc, char* argv[])
{
char val[100]="myusername";
SetRegValue("Software\\MySoft\\Settings","Username", val, REG_SZ, 100);
return 0;
}



source(s): http://msdn2.microsoft.com/en-us/library/ms724923.aspx
http://msdn2.microsoft.com/en-us/library/ms724875.aspx

Wednesday, July 25, 2007

C++: Check a valid date

C++ has no checkdate, like php does. so i wrote this to filter out bad dates and feb29ths.

bool isValidDate(int m, int d, int y)
{
//
checks Gregorian date
if
(! (1582<= y ) )
return false;
if (! (1<= m && m<=12) )
return false;
if (! (1<= d && d<=31) )
return false;
if ( (d==31) && (m==2 || m==4 || m==6 || m==9 || m==11) )
return false;
if ( (d==30) && (m==2) )
return false;
if ( (m==2) && (d==29) && (y%4!=0) )
return false;
if ( (m==2) && (d==29) && (y%400==0) )
return true;
if ( (m==2) && (d==29) && (y%100==0) )
return false;
if ( (m==2) && (d==29) && (y%4==0) )
return true;

return true;
}


source(s): http://en.wikipedia.org/wiki/Leap_year

Monday, July 23, 2007

C++: Hide an Application from the Taskbar

(This solution is specific to Borland C++ Builder)

Use this code as your project source to prevent the window from showing up in your windows taskbar.

WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(TForm1), &Form1);
SetWindowLong(Application->Handle,
GWL_EXSTYLE,
GetWindowLong(Application->Handle, GWL_EXSTYLE)
|
WS_EX_TOOLWINDOW) ;
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}


source(s): http://delphi.about.com/od/adptips1999/qt/hidefromtaskbar.htm

Friday, July 20, 2007

C++: Redirect command-line output

I've always wondered how to capture output from a command line program in windows, and the record it into a file.

while you can always just the greater-than-sign to output text into a file at the windows command prompt, sometimes it just isn't good enough.
"echo abc>hi.txt"

I ran into this once with mysqldump.exe.

Well I finally found the code that works. In this example I call 'dir'.

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

int main(int argc, char* argv[])
{
char psBuffer[128];
FILE *iopipe;

if( (iopipe = _popen( "dir", "rt" )) == NULL )
exit( 1 );

while( !feof( iopipe ) )
{
if( fgets( psBuffer, 128, iopipe ) != NULL )
printf( psBuffer );
}

printf( "\nProcess returned %d\n", _pclose( iopipe ) );

return 0;
}





source(s): www.daniweb.com/forums/thread5755.html

Thursday, July 05, 2007

SVN: Command-line SVN

Just a couple examples.

Use svn checkout help or svn update help for more details.
//you do the initial checkout like this:
svn checkout [svn path] [destination path]
//svn path: svn://192.168.0.93/srv/svn/src/trunk/proj
//dest path: /srv/www/htdocs/dest_path
//user note: it may prompt for a username and password

//this will update to the most recent revision
svn update [destination path]

//for more details call
svn checkout help
// or
svn update help

Thursday, May 10, 2007

Recruiting: High-tech companies go virtual

I am about to graduate from BYU with a bachelor's degree in CS, and have began my job search. I signed up for an erecruiting account where my school has an account with Experience Inc. The system is set up so that interested companies can view my resume and send me job opportunities while I finish up my last segment of schooling.

I received this email this morning.

Dear Students:

Representatives from Hewlett Packard have released the following opportunity.

HP will be interviewing in the virtual world for real-world jobs! This is a first for HP and encourage BYU students to try it out, especially if they are already Second Life players. Those interested can go to the following web address:

http://www.networkinworld.jobs/hp_profile.aspx

Good Luck!
Career Placement Services


Second life is virtual world where "Residents can explore, meet other Residents, socialize, participate in individual and group activities, create and trade items (virtual property) and services from one another." [wikipedia.org]

Most companies have an multiple-contact interview process. Its kind of like tryouts on a high school sports team with multiple cuts. After each interview you sit around waiting to know "Did I make the cut?". For technical positions the first interview is usually with a non-technical person who weeds out their stack of candidates. If you made the cut, you reach the second interview with a more technical person, sometimes as a phone interview depending on your location. After 4-6 contacts they have weeded their candidate pool down to the point they often invite you to their facilities and make you an offer.



Human Resource managers who are involved in the hiring process try to make the best decisions they can based on how you will fit into the company culture, your goals, your passions, and your technical abilities. But how they are trying to measure this using Second Life I just don't know. I mean they may as well have an HP LiveChat operator waiting to assist you and you can sign up for an interview.

For my job I've had to interview before, and I don't understand how an interviewer could adequately determine how someone could work in the real world at HP with a virtual interview. In an interview you are trying to make use of every piece of information available to you to learn about the individual and make the best decision you can.



I guess it makes sense though, if you're being interviewed for a satellite job or a job like HP Second Life Advertising, where you'll never talk to you boss face to face in real life anyway.

While I do respect HP as a company, do they really think they make good decision using Second Life? Or are they just using this as a marketing tactic to lure people into their potential candidate pool who would otherwise not be included? Are they just doing this for the first interview? Or are they trying to use Second Life for every interview?

Thursday, April 19, 2007

Windows: Nightly Defrag

It isn't that hard to set up a nightly defragmentation routine.

In Windows XP, go to Start Menu > Settings > Control Panel > Scheduled Tasks go through the wizard, selecting C:\Windows\System32\defrag.exe to run. At the end, in the advanced options make it run
C:\Windows\System32\defrag.exe c: -f
or D: or whatever your drive name is.

Microsoft provides documentation on the command line defrag:
defrag volume [-a] [-f][-v] [-?]
volume: The drive letter or a mount point of the volume to be defragmented
-a: Analyze only
-f: Forces defragmentation of the volume regardless of whether it needs to be defragmented or even if free space is low
-v: Verbose output
-?: Display the help text


source(s): http://support.microsoft.com/kb/283080

Wednesday, April 18, 2007

PHP: PHP 5 Deployment Error

I've written some code for PHP5, and deployed it to a production server and I saw an error that I'd never seen before.

PHP 5 Code:
<?php

class form
{
    public $name;
    public $fields;
}
?>


Error:
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in C:\x\y\page.php on line z


The problem is that PHP 4 has a different syntax for classes. The code above is PHP 5 valid, but not PHP 4. A valid version of its PHP 4 equivalent is this:

PHP 4 Code:
<?php

class form
{
    var $name;
    var $fields;
}
?>

Tuesday, April 10, 2007

WINDOWS: Skip 'Open With Web Service' Window

When you try to open a file and you haven't set a handler for a file extension, a window pops up in XP saying:

"Windows cannot open this file:"
To open this file, Windows needs to know what program created it. Windows can go online to look it up automatically, or you can manually select from a list of programs on your computer.
What do you want to do?
- Use the Web service to find the appropriate program
- Select the program from a list


This is really irritating because no one would ever want to use 'the Web Service' anyway. BTW Microsoft, look up Web Service at wikipedia.

To skip that step, make a file with the following contents, and open it and the registry setting will be automatically imported into your system.

skipOpenWithWebService.reg
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer]
"InternetOpenWith"=dword:00000000


source(s): http://www.pctools.com/guides/registry/detail/1314/

Monday, April 09, 2007

C++: Associative Arrays

#include <map>
#include <string>


using namespace std;

int main()
{
std::map<std::string, std::string> m;
m["ENG"] = "English";
m["FRA"] = "France";
m["CAN"] = "Canada";
m["AUS"] = "Australia";

//does print empty string
cout<<m["Germany"]<<endl;

//iterate through all elements of array
std::map<string, string>::iterator curr,end;
for( curr = m.begin(), end = m.end(); curr != end; curr++ )
cout << curr->first + " = " + curr->second << endl;
return 0;
}


C++ maps or associative arrays are implemented as self-balancing binary search tree. This means that when you iterate through your map it will not be in the order you added them like in PHP but instead will be in sorted order.

source(s):
http://www.webmasterworld.com/html/3249762.htm

Sunday, April 08, 2007

HTML: Website blank in IE, fine in Firefox

I coded up a website in firefox but it wouldn't show in IE. I was trying to make it xHTML-ish, and had the script tag looking like this:

<script language='JavaScript' type='text/JavaScript' 
src='script.js'/>


For some idiot reason, IE chokes on the whole page, unless it looks like this:

<script language='JavaScript' type='text/JavaScript' 
src='script.js'></script>


source:
http://www.webmasterworld.com/html/3249762.htm

Tuesday, April 03, 2007

LINUX : C++ Hello World Compile Errors

A simple hello world using cout and string yields this.

main.cpp
#include <string>
#include <iostream>

using namespace std;

int main ( int argc, int argv[] )
{
cout << "running....\n";

cout<<"finished"<<endl;
return 0;
}


compile.sh
#compile
CFG=/usr/bin/mysql_config
sh -c "gcc -o mysqltest `$CFG --cflags` main.cpp `$CFG --libs`"


errors
abc@localhost:~/Projects/mysqltest> ./compile.sh
/tmp/ccpF755X.o: In function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0x23): undefined reference to `std::ios_base::Init::Init()'
/tmp/ccpF755X.o: In function `__tcf_0':
main.cpp:(.text+0x66): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccpF755X.o: In function `main':
main.cpp:(.text+0x81): undefined reference to `std::cout'
main.cpp:(.text+0x86): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
main.cpp:(.text+0x90): undefined reference to `std::cout'
main.cpp:(.text+0x95): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
main.cpp:(.text+0x9d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
main.cpp:(.text+0xa2): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
/tmp/ccpF755X.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'


The problem is that I was compiling with gcc instead of g++

Monday, April 02, 2007

LINUX: Weird characters when you compile

Why are there weird characters when I compile:

test.cpp: In function âint main()â:
test.cpp:7: error: âcoutâ was not declared in this scope
test.cpp:7: error: âendlâ was not declared in this scope


It's normal if you don't set the environment variable e.g.
export LANG=C


source(s):
http://gcc.gnu.org/ml/gcc-help/2006-08/msg00179.html

Friday, March 02, 2007

VISTA: Install Multiple Updates at Once

I just got a free copy of Windows Vista. But I installed it on a computer without internet access. So to install updates I have to DL them manually.

I just discovered that you can type execute multiple updates at once. Create a and execute a batch file (text file named .bat) containing something like the following:
Windows6.0-KB929451-x86.msu /quiet /norestart
Windows6.0-KB929735-x86.msu /quiet /norestart

/quiet makes it so the update requires no user interaction
/norestart makes it so it won't keep prompting you to restart the machine
Don't forget to restart when you're done.

UPDATE:
As of March 7, I uninstalled vista. I couldn't take it. I couldn't even make it one week. Wait for SP1.

Wednesday, February 21, 2007

JAVASCRIPT: Associative Arrays

I've been programming in javascript for years. Sometimes I borrow other people's javascript code, other times I write my own. Whenever I borrow other people's code there often is a lot of browser independent stuff, like 'if (ie) or if (nn6)...' and I always wondered how they did it. I knew I could do this as well if I had a way to list all of a DHTML element's properties and functions. I could do this in different browsers and then learn when functions and properties to use in each browser.

Now I know how. Every HTML tag or page element can be accessed in javascript. Just tag your element with an id:
<div id='abc'></div>

to access the element, use this javascript
var element = document.getElementById('abc');

each object in javascript can have functions or properties, but all of these can be accessed as an associative array,
so to list all of the element's properties and functions you can do this:

var str = '';
for(var property in myObject) {
var value = myObject[property];
str+= "\n" + "myObject[" + property + "] = " + value;
}
alert(str);


You will notice a different set of properties displayed in IE, Safari, Firefox, etc.

http://en.wikipedia.org/wiki/Associative_arrays

Thursday, February 01, 2007

PHP: Regular Expressions


^ Start of line
$ End of line
n? Zero or only one single occurrence of character 'n'
n* Zero or more occurrences of character 'n'
n+ At least one or more occurrences of character 'n'
n{2} Exactly two occurrences of 'n'
n{2,} At least 2 or more occurrences of 'n'
n{2,4} From 2 to 4 occurrences of 'n'
. Any single character
() Parenthesis to group expressions
(.*) 0 or more occurrences of a single character (anything)
(n|a) Either 'n' or 'a'
[1-6] Any single digit in the range between 1 and 6
[c-h] Any single lower case letter between c and h
[D-M] Any single upper case letter between D and M
[^a-z] Any single char EXCEPT lower case letter from a to z.

Pitfall: the ^ symbol only acts as an EXCEPT rule if it is
thevery first character inside a range, and it denies the
entire range including the ^ symbol itself if it appears
again later in the range. Also remember that if it is the
first character in the entire expression, it means "start
of line". In any other place, it is always treated as a
regular ^ symbol. In other words, you cannot deny a word
with ^undesired_word or a group with ^(undesired_phrase).

Read more detailed regex documentation to find out what is
necessary to achieve this.

[_4^a-zA-Z]
Any single character which can be the underscore or the
number 4 or the ^ symbol or any letter, lower or upper case

?, +, * and the {}
count parameters can be appended not only to a single
character, but also to a group() or a range[].

therefore,
^.{2}[a-z]{1,2}_?[0-9]*([1-6]|[a-f])[^1-9]{2}a+$
would mean:

^.{2} = A line beginning with any two characters,
[a-z]{1,2}= followed by either 1 or 2 lower case letters,
_? = followed by an optional underscore,
[0-9]* = followed by zero or more digits,
([1-6]|[a-f]) = followed by either a digit between 1 and
6 OR a lower case letter between a and f,
[^1-9]{2} = followed by any two characters
except digits between 1 and 9 (0 is possible),
a+$ = followed by at least one or more occurrences
of 'a' at the end of a line.


I used what i knew of regular expressions to create this for form checking.

//mm/dd/yyyy date checking
if (!ereg("^[0-1]{0,1}[0-9]{1}/[0-9]{1,2}/[19|20]{2}[0-9]{2}$", $date))
die('invalid date format, use mm/dd/yyyy');
$mdy = explode("/",$date);
//checkdate() will check things like feb29th in the wrong year etc.
if (!checkdate( $mdy[0], $mdy[1], $mdy[2] ))
die('invalid date format, use mm/dd/yyyy');

//phone format checking
if (!ereg("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", $phone))
die('invalid phone format, use xxx-xxx-xxxx');

//ssn format checking
if (!ereg("^[0-9]{3}-[0-9]{2}-[0-9]{4}$", $ssn))
die('invalid ssn format, use xxx-xx-xxxx');

//zip code format checking
if (!ereg("^[0-9]{5,5}$", $zip) && !ereg("^[0-9]{5,5}-[0-9]{4,4}$", $zip))
die('invalid zipcode format, use xxxxx-xxxx (last 4 digits are optional)');

//email address checking (i got this from somewhere on the net.
//First, check that there's one @ symbol, and that lengths are right
if (!ereg("[^@]{1,64}@[^@]{1,255}", $email))
die('invalid email');

$email_array = explode("@", $email);
// Split it into sections to make life easier
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
if(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
die('invalid email');


// Check if domain is IP. If not, it should be valid domain name

if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)// Not enough parts to domain
die('invalid email');

for ($i = 0; $i < sizeof($domain_array); $i++)
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
die('invalid email');
}


source: http://us2.php.net/manual/en/ref.regex.php

Friday, January 19, 2007

C++: LibXML in Borland C++ Builder 5

The key to this solution is using a command-line utility that comes with BCB5 called implib.exe which creates a borland-type .lib file from a win32 .dll

Goal:
Get a simple C++ libxml code example to work (from http://xmlsoft.org/examples/index.html)

What to do:
Okay the first thing you need to do is download win32 libxml from http://www.zlatkovic.com/libxml.en.html

but it has certain dependencies so you will want to fetch the binaries:
* libxml2, the XML parser and processor.
* libxslt, the XSL and EXSL Transformations processor.
* xmlsec, the XMLSec and XMLDSig processor.
* xsldbg, the XSL Transformations debugger.
* openssl, the general crypto toolkit.
* iconv, the character encoding toolkit.
* zlib, the compression toolkit.

Then you three types of files in each project, .dll .lib and .h. The problem with these .lib files is that these .lib files are compiled for Microsoft Visual Studio. But in borland the way to create lib files is using implib.exe included in all distributions of borland c++ builder. I run

implib.exe -a zlib.lib zlib.dll

to create a zlib.lib for borland. Then I do the same thing for the other dlls.

Then add the .lib into the borland project and then source code examples will work.

Hooray for implib!

source(s)
http://www.gantless.com/borland.html (implib)
http://www.zlatkovic.com/libxml.en.html (libxml)
http://xmlsoft.org/examples/index.html (libxml examples)

Thursday, January 04, 2007

PHP: SQL Injection Best Practice in MySQL

It is important to avoid SQL injection when working with mysql, and so it is common to use a function like mysql_real_escape_string() in PHP.

At php.net, they suggest using sprintf and a function called quote_smart as described on their mysql_real_escape_string documentation page as a "best practice" method.

php.net [good]:
$query = sprintf(
"SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));


php.net [better]:
$query = sprintf(
"SELECT * FROM users WHERE user=%s AND password=%s",
quote_smart($user),
quote_smart($password));


qsprintf [best]:
$query = qsprintf(
"SELECT * FROM users WHERE user=%s AND password=%s",
$user,
$password);

correction: Of the 3 examples above, the 2 previous used to have single quotes around %s, but this is incorrect as quote_smart or myquote will add single quotes.

note: using sprintf either qsprintf functions will get screwed up when you have a " like 's%' " statement in sql or similar 'like' statements using % (the percentage character).

<?php
function myquote($value)
{
if (get_magic_quotes_gpc())
$value = stripslashes($value);
if (is_numeric($value))
return "'$value'";
return "'".mysql_real_escape_string($value)."'";
}

function qsprintf()
{
$numargs = func_num_args();
$arg_list = func_get_args();
$format = $arg_list[0];
$next_arg_list = array();
for ($i = 1; $i < $numargs; $i++)
$next_arg_list[] = myquote($arg_list[$i]);
return vsprintf($format, $next_arg_list);
}
?>


notes: I modified their quote_smart function and renamed it to myquote in my code sample below because mysql doesn't care if you try to insert '123' into a numeric field (including single quotes) and that way I wouldn't lose leading zeros when inserting something like '01234' into a character field.

Thursday, December 07, 2006

C++: Visual C++ 2005 Express Edition x64

Visual C++ 2005 Express Edition is a free 32 bit IDE and compiler offered by microsoft. It has limitations (no resource editor, no MFC) but you can build command line apps with it ok, and if you set it up properly you can build apps for x64. This is helpful particularly if you have an x64 system, and don't want to pay for Visual Studio 2005 which has support for x64 compilation. To enable x64 install the free Microsoft Platform SDK. Then depending on what you're programming you may want the .NET Framework SDK 2.0 (x64).

download links


After installing these, you need to configure Visual C++ Express to compile with the Platform SDK libraries.
go to Tools > Options > Projects and Solutions > VC++ Directories and set the following:
Executable files: C:\Program Files\MS_Platform_SDK\Bin
Include files: C:\Program Files\MS_Platform_SDK\Include
Library files: C:\Program Files\MS_Platform_SDK\Lib
Note: depending on where you installed the platform sdk you may have to use "Microsoft Platform SDK for Windows Server 2003 R2" as "MS_Platform_SDK" above.


Now, open up the x64 open build debug/retail environment window (came with Platform SDK). It will look like a command-line interface. From that command-line go to the folder where "VCExpress.exe" is located and call it. Now when you build apps it will build with the x64 libraries.

Then, you need to modify some default settings in your projects.

To compile for x64, create 'x64' in the configuration manager for x64 (copy settings from win32), then verify and set the following project settings:
* /MACHINE (Specify Target Platform) is set to /MACHINE:AMD64.
* Register Output is turned OFF.
* If Debug Information Format was set to /ZI in the Win32 project configuration, then it is set to /Zi in the 64-bit project configuration. For more information, see /Z7, /Zi, /ZI (Debug Information Format).
* Values of WIN32 are replaced by WIN64 for /D (Preprocessor Definitions).


When linking, if you get errors like:
"error LNK2001: unresolved external symbol _RTC_Shutdown"
then set "Basic Runtime Checks" to Default in the project settings.

When linking, if you get errors like:
fatal error LNK1112: module machine type 'AMD64' conflicts with target machine type 'x64', you need to make sure you use /MACHINE:AMD64 and not /MACHINE:x64. If it won't let you, change to "Not Set", then add it explicitly under Additional Linker Options.

When running your app you may get an error saying msvcrtd.dll not found. Go to your platform SDK folder, and go to noredist/win64/amd64 and you will find it there, copy it into your system32 folder. Don't use the one in noredist/win64/ like i did at first, it doesn't help.

sources:
http://msdn2.microsoft.com/en-us/library/9yb4317s(VS.80).aspx
http://www.planetamd64.com/lofiversion/index.php/t18796.html
http://www.planetamd64.com/lofiversion/index.php/t5934.html

CSS: Block IE 'active content' bar

I don't know what implications this has, the IE 'warning active content' bar pops up on safe CSS using ActiveX, but the message may be coming up legitimately.

Problem: I wanted to have a fancy gradient in the background of a button for IE users only. I found css code supposedly uses activeX to achieve this.
CSS code:
.btn { filter:progid:DXImageTransform.Microsoft.Gradient(
GradientType=0,StartColorStr='#ffD3D7E0',EndColorStr='#ff8C939B');}


But when I view the HTML page on my local computer I see:
"To help protect you security, Internet Explorer has restricted this file from showing active content that could access your computer"

Solution: I found a forum that said when you deploy it to HTTP this message goes away. Another alternative is to include the following code.

<!-- Start Information Bar Blocking Code -->
<!-- saved from url=(0027)http://www.blockingspoof.com/dumbie.html -->
<!-- End Information Bar Blocking Code -->


However I noticed that while the IE-Bar goes away, I don't think it addresses this issue: (an IE security flaw which I also found) which leads me to think the IE Bar is legitimately popping up (because of insecure code).
see: http://osvdb.org/27109

Thursday, November 30, 2006

C++: Visual C++ 2005 Express Edition

Visual C++ 2005 Express Edition is a free IDE and compiler offered by microsoft. It has limitations (no resource editor, no MFC) but you can build command line apps with it ok. They strip out a lot of stuff but you can install the free Microsoft Platform SDK to enable more features for Visual C++ 2005 Express. Then depending on what you're programming you may want the .NET Framework SDK 2.0 (x86).

download links


After installing these, you need to make the Visual C++ Express able to see the Platform SDK libraries.
go to Tools > Options > Projects and Solutions > VC++ Directories and set the following:
Executable files: C:\Program Files\MS_Platform_SDK\Bin
Include files: C:\Program Files\MS_Platform_SDK\Include
Library files: C:\Program Files\MS_Platform_SDK\Lib
Note: depending on where you installed the platform sdk you may have to use "Microsoft Platform SDK for Windows Server 2003 R2" as "MS_Platform_SDK" above.

Then, you need to modify some default settings in your projects. Edit the corewin_express.vsprops file in
C:\Program Files\Microsoft Visual Studio 8\VC\VCProjectDefaults and add the following to AdditionalDependencies: " user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib"

You can enable a windowed template in the Visual Studio Express:
Edit the file AppSettings.htm in
C:\Program Files\Microsoft Visual Studio 8\
in subfolder \VC\VCWizards\AppWiz\Generic\Application\html\1033\ and comment out the following 4 lines (approx line 440)
// WIN_APP.disabled = true;
// WIN_APP_LABEL.disabled = true;
// DLL_APP.disabled = true;
// DLL_APP_LABEL.disabled = true;


Then when go to build an application choose a Win32 Console Application. In the Win32 Application Wizard dialog box, make sure that Windows application is selected as the Application type and the ATL is not selected. (before you edited the AppSettings.htm file, this was disabled. Click the Finish button to generate the project.

This post is pretty much a regurgitation of the following link. So for more information go check it out. I originally had this post for x64 and x86 but decided to split. This one was the x86 so go check out my other x64 post.

source: http://msdn.microsoft.com/vstudio/express/visualc/usingpsdk/

Tuesday, November 28, 2006

C++: Read-only member function

class MyClass
{
private:
int _AsInteger;
public:
const int &AsInteger;

MyClass() : _AsInteger(0), AsInteger(_AsInteger)
{
}

void SetDefault()
{
_AsInteger= 17;
}
};


MyClass obj1;
int a = obj1.AsInteger; //success
obj1.AsInteger= 1337; //compiler error
This way, you have a member that appears public but really isn't.

Monday, November 20, 2006

XML: Embed tags (other XML or HTML) in XML

Use CData to embed html or other xml in your xml
<doc_root>
<
data>
<![CDATA[
<b>text</b>
]]>
</data>
</
doc_root>

Friday, October 27, 2006

WIN32: Build a basic Windows installer with NSIS

Its not that hard to write a program that copies a bunch of files to another folder, but sometimes it is nice to have a program that takes care of the license agreement, registry keys, start menu creation, copying to a program files folder and uninstaller all in one self-extracting archive.

There are many installers available, I decided to go with the Nullsoft Scriptable Install System (NSIS) as it is open source. I used the following settings in my script, I should have provided enough that you should do find-replaces on the provided script to customize for your basic needs. For anything else go look at the NSIS documentation, its pretty good.

Settings-
Language: English
Program Name: Popcorn Maker
Program .EXE: popcorn.exe
Program .DLLs: popcorn1.dll, popcorn2.dll
EULA File (for installer): TermsOfUse.txt
Installer .EXE: pm_installer.exe
Splash bitmap: res/splash3.bmp (res is relative to your NSIS script)
Installer Icon: res/installer.ico
Uninstaller Icon: res/uninstaller.ico

[1] Go to http://nsis.sourceforge.net, download and install the Nullsoft Scriptable install system.

[2] Look at their example scripts and get a feel for how you want to design your installer. They provide 20+ example scripts from basic, to complex, even including the source for the installer that they used to install the NSIS that you downloaded.

[3] Use the following script. Save it as a .NSI filetype and put it in the same folder as your .EXE file and res folder (setup as shown above).

;--------------------------------
;Include Modern UI

  !
include "MUI.nsh"

;--------------------------------
;Splash screen
XPStyle on

Function .onInit
  ; the plugins dir is automatically deleted when the installer exits
  
InitPluginsDir
  File /oname=$PLUGINSDIR\splash3.bmp ".\res\splash3.bmp"

  
advsplash::show 1500 600 0 -1 $PLUGINSDIR\splash3
  ;splash3.bmp is a splash screen that fades in for
  ;1500 ms holds for 600 ms and fades out for 0 ms

  
Pop $0
  
; $0 has '1' if the user closed the splash screen early,
  ; '0' if everything closed normally, and '-1' if some error occurred.
FunctionEnd

;--------------------------------
;General

  ;Name and file
  
Name "Popcorn Maker"
  
OutFile "pm_installer.exe"

  
;Default installation folder
  
InstallDir "$PROGRAMFILES\Popcorn Maker"

  
!define MUI_ICON ".\res\installer.ico"
  
!define MUI_UNICON ".\res\uninstaller.ico"

  
!define MUI_FINISHPAGE_NOAUTOCLOSE
  !define MUI_UNFINISHPAGE_NOAUTOCLOSE
;--------------------------------
;Variables
  
Var STARTMENU_FOLDER
  Var MUI_TEMP
;--------------------------------
;Interface Settings
  !
define MUI_ABORTWARNING
  !define MUI_STARTMENUPAGE_DEFAULTFOLDER "Popcorn Maker"
;--------------------------------
;Pages
  !
insertmacro MUI_PAGE_LICENSE ".\TermsOfUse.txt"
  
!insertmacro MUI_PAGE_COMPONENTS
  !insertmacro MUI_PAGE_DIRECTORY

  ;Start Menu Folder Page Configuration
  !
define MUI_STARTMENUPAGE_REGISTRY_ROOT "HKCU"
  
!define MUI_STARTMENUPAGE_REGISTRY_KEY "Software\Popcorn Maker"
  
!define MUI_STARTMENUPAGE_REGISTRY_VALUENAME "Start Menu Folder"
  
!define MUI_UN_REG "Software\Microsoft\Windows\CurrentVersion\Uninstall"

  
!define MUI_FINISHPAGE_RUN "$INSTDIR\popcorn.exe"
  
!define MUI_FINISHPAGE_NOREBOOTSUPPORT

  !insertmacro MUI_PAGE_STARTMENU Application $STARTMENU_FOLDER

  !insertmacro MUI_PAGE_INSTFILES

  !insertmacro MUI_PAGE_FINISH

  !insertmacro MUI_UNPAGE_CONFIRM
  !insertmacro MUI_UNPAGE_INSTFILES

;--------------------------------
;Languages

  !
insertmacro MUI_LANGUAGE "English"

;--------------------------------
;Installer Sections

Section "Popcorn Maker (Core)" SecMain
  SectionIn RO

  SetOutPath "$INSTDIR"

  
!insertmacro MUI_STARTMENU_WRITE_BEGIN Application

  File .\popcorn.exe
  File .\popcorn1.dll
  File .\popcorn2.dll

  ; Write the installation path into the registry
  
WriteRegStr HKCU "Software\Popcorn" "Install_Dir" "$INSTDIR"

  
; Write the uninstall keys for Windows
  
WriteRegStr HKCU "MUI_UN_REG\Popcorn" "DisplayName" "Popcorn Uninstaller"
  
WriteRegStr HKCU "MUI_UN_REG\Popcorn" "UninstallString" '"$INSTDIR\un.exe"'
  
WriteRegDWORD HKCU "MUI_UN_REG\Popcorn" "NoModify" 1
  
WriteRegDWORD HKCU "MUI_UN_REG\Popcorn" "NoRepair" 1
  
WriteUninstaller "un.exe"

  
;Create shortcuts
  
CreateDirectory "$SMPROGRAMS\$STARTMENU_FOLDER"
  
CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER\Popcorn Maker.lnk" "$INSTDIR\Popcorn.exe"
  
CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER\Uninstall.lnk" "$INSTDIR\Un.exe"

  
!insertmacro MUI_STARTMENU_WRITE_END

SectionEnd

;--------------------------------
;Descriptions

  ;Language strings
  
LangString DESC_SecMain ${LANG_ENGLISH} "Popcorn Maker, a program"

  
;Assign language strings to sections
  !
insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
    !insertmacro MUI_DESCRIPTION_TEXT ${SecMain} $(DESC_SecMain)
  !
insertmacro MUI_FUNCTION_DESCRIPTION_END

;--------------------------------
;Uninstaller Section
Section "Uninstall"

  
!insertmacro MUI_STARTMENU_GETFOLDER Application $MUI_TEMP

  Delete "$SMPROGRAMS\$MUI_TEMP\Popcorn Maker.lnk"
  
Delete "$SMPROGRAMS\$MUI_TEMP\Uninstall.lnk"

  
;Delete empty start menu parent diretories
  
StrCpy $MUI_TEMP "$SMPROGRAMS\$MUI_TEMP"

  
smDeleteLoop:
    
ClearErrors
    RMDir $MUI_TEMP
    GetFullPathName $MUI_TEMP "$MUI_TEMP\.."

    
IfErrors smDeleteLoopDone

    StrCmp $MUI_TEMP $SMPROGRAMS smDeleteLoopDone smDeleteLoop
  smDeleteLoopDone:

  
Delete "$INSTDIR\popcorn.exe"
  
Delete "$INSTDIR\popcorn1.dll"
  
Delete "$INSTDIR\popcorn1.dll"
  
Delete "$INSTDIR\Un.exe"
  
RMDir "$INSTDIR"

  
DeleteRegValue HKCU "MUI_UN_REG\Popcorn" "DisplayName"
  
DeleteRegValue HKCU "MUI_UN_REG\Popcorn" "UninstallString"
  
DeleteRegValue HKCU "MUI_UN_REG\Popcorn" "NoModify"
  
DeleteRegValue HKCU "MUI_UN_REG\Popcorn" "NoRepair"
  
DeleteRegKey   HKCU "MUI_UN_REG\Popcorn"
  
DeleteRegValue HKCU "Software\Popcorn" "Install_Dir"
  
DeleteRegKey   HKCU "Software\Popcorn"

SectionEnd




Note: I'm always fighting with the width of blogspot, so i changed the font to Arial to fit more in. Sometimes the commands wrapped to the next line, but you can kind of tell. When you actually run it you'll have to put the wrapped text back on the original line.

Monday, September 18, 2006

FTP: Automated sessions via script

So you know how to use command line ftp clients, but you're not sure how to automate them with scripts.

WINDOWS (command-line)

ftp -s:script1.txt 11.11.11.11

script1.txt
username
password
ftp command1
ftp command2
quit

where username is the ftp username, password is their password. ftp command1 is any command line ftp commands like "get filename.zip" (download) or "put filename.rar" (upload).

Now its less important what the contents of the script are, and more important how to execute the script because once you know how, you can go use the commandline ftp client to run through whatever you want to automate, and make sure you have one command per line.

The only differences with the next command are that the hostname is embedded inside the script, and I replaced hostnames, usernames and passwords (etc) with more real examples.

ftp -s:script2.txt

script2.txt
open 192.168.0.123
gus
secretp123
put magicfile.zip
quit


LINUX

At the linux shell (command-line) type this command.
ftp < script2.txt

Because linux just uses i/o redirection, with the < symbol, one should use the format of script2 where the first line of the file is 'open [hostname]'.

USEFUL FTP COMMANDS
SERVER COMMANDS
# cd change directory on the remote SERVER
# cd .. change directory up one level on the remote SERVER
# pwd print the current directory you are within on the remote SERVER
# ls list files within the current directory on the remote SERVER
# binary prepare FTP to transfer binary files such as apps or images
# ascii prepare FTP to transfer ascii or text files such as .html files
# put copy a specific file from the local machine to the remote SERVER
# get copy a specific file from the remote SERVER to the local PC
# chmod change file permissions on a remote SERVER if you have access
# del delete a specific file on the remote SERVER
# bye end your FTP connection

LOCAL MACHINE
# lcd change directory on your local PC
# lcd .. change directory up one level on your local PC
# lpwd print the current directory you are within on your local PC


sources: http://support.microsoft.com/?kbid=96269 and http://www.reallylinux.com/docs/autoftp.shtml

Tuesday, September 12, 2006

DOS: Using winzip for command line

You want to automate compression and you remember pkunzip.exe and pkzip.exe of yesteryear. It turns out winzip can be used from the command line and embedded into a batch (.BAT) file for automation. (oooh automated backups).

The command format is:

 winzip32 [-min] action [options] filename[.zip] file(s)


-min this specifies that WinZip should run minimized. If -min is specified, it must be the first command line parameter.

action
-a for add, -f for freshen, -u for update, and -m for move. You must specify one (and only one) of these actions. The actions correspond to the actions described in the section titled "Add dialog box options" in the online manual.

options
-r corresponds to the Include subfolders checkbox in the Add dialog and causes WinZip to add files from subfolders. Folder information is stored for files added from subfolders. If you add -p, WinZip will store folder information for all files added, not just for files from subfolders; the folder information will begin with the folder specified on the command line.

-ex, -en, -ef, -es, and -e0 determine the compression method: eXtra, Normal, Fast, Super fast, and no compression. The default is "Normal". -hs includes hidden and system files. Use -sPassword to specify a case-sensitive password. The password can be enclosed in quotes, for example, -s"Secret Password".

filename.zip
Specifies the name of the Zip file involved. Be sure to use the full filename (including the folder).

files
Is a list of one or more files, or the @ character followed by the filename containing a list of files to add, one filename per line. Wildcards (e.g. *.bak) are allowed.

examples:

 winzip32.exe -min -a -r c:\myfiles\ c:\output.zip


this creates an output.zip with all the files in the c:\myfiles\ folder. if winzip isn't in your path, you may have to use "c:\program files\winzip32.exe" instead of winzip32.exe above,

 winzip32 -a "c:\My Documents\file1.doc" c:\output2.zip


this creates an output2.zip but note how the path must be enclosed in quotation marks because there is a space in it. Also winzip32.exe and winzip32 in the 2 examples are equivalent.

source: http://www.memecode.com/docs/winzip.html

Saturday, September 09, 2006

JBOSS: Deploying a win32 project on linux

When you copy a jboss project from a windows (eclipse) programming environment there are two important things to remember.

Modify permissions
1. chmod 775 $JBOSS_HOME/server/default/deploy/ProjectName.war

Fix WEB-INF
2. Change web-inf folder to uppercase WEB-INF

JBOSS: Running JBoss as a Service

Starting JBoss as a service:
http://wiki.jboss.org/wiki/Wiki.jsp?page=StartJBossOnBootWithLinux

More Linux tutorials (relative to startups)
http://yolinux.com/TUTORIALS/LinuxTutorialInitProcess.html

LINUX: Useful commands

ps -aux|grep java //show processes containing 'java'
top //display processes list
passwd //change current users password
passwd gus123 //change password user gus123
service iptables stop //stops firewall from running
chkconfig iptables off//firewall won't start on boot

tail -f textfile//turns a log file thats being
//generated into a console
netstat -a //shows port usage
touch <file> //update timestamp of file
dd if=/dev/zero of=/dev/hda/ bs=512 count=1//wipe mbr
free -m //check mem usage
du -x --block-size=1024K | sort -nr | head -10
//10 biggest folders in current path
wc -l gives linecount


Memory Usage Tools useful
http://www.ss64.com/bash/ also useful

J2EE: Linux J2EE Server Setup

I ran the j2ee for linux installer and had issues:

[root@cs462-2-1 src]#./java_ee_sdk-5-linux.bin
Checking available disk space...
Checking Java(TM) 2 Runtime Environment...
Launching Java(TM) 2 Runtime Environment...
Deleting temporary files...


But then it would appear to hang. Well it wasn't really hanging. I've installed j2ee sdk before in linux on suse where there was a gui available, but this time I needed to do it via linux terminal (command line).

Solution: use the -console flag
[root@cs462-2-1 src]#./java_ee_sdk-5-linux.bin -console


Once we used the -console flag we were able to get past the "Deleting temporary files" output, and were give a console based installer UI that made us say yes to a license agreement, and choose the install path etc.