Jump to content

Check out our Community Blogs


Member Since 18 Aug 2010
Offline Last Active Jun 29 2011 09:07 PM

Topics I've Started

[PHP] Display Google Map based on user location

27 August 2010 - 01:03 PM

//Code for getting users IP address
* Function to get the users IP address. We "attempt"
* to determine if the user is coming through a proxy server
* by checking if HTTP_X_FORWARDED_FOR is set, then we
* use a regular expression to ensure the IP address
* found is in the proper format
function getIP()
// here we check if the user is coming through a proxy
// NOTE: Does not always work as proxies are not required
// to provide this information
//reg ex pattern
$pattern = "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/"
// now we need to check for a valid format
if(preg_match($pattern, $_SERVER["HTTP_X_FORWARDED_FOR"]))
//valid format so grab it
//invalid (proxy provided some bogus value
//so just use REMOTE_ADDR and hope for the best
//not coming through a proxy (or the proxy
//didnt provide the original IP)
//grab the IP

//return the IP address
return $userIP;

* Function for displaying a Google Map based on the users
* location, which we get from their IP address then use
* HostInfo.info to get their location. Function expects
* 4 parameters:
* 1) Your Google Maps API key
* * Can be obtained here http://code.google.c...aps/signup.html
* 2) Width you want the returned image
* 3) Height you want the returned image
* 4) Zoom value
* Returns an image source, either one for the Google Map
* or the default image specified
function ShowGoogleMap($api_key, $width, $height, $zoom)
$user_ip = getIP();
$meta_tags = get_meta_tags('http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=' . $user_ip) or die('Error getting meta tags');

$city = $meta_tags['city'];
$state = $meta_tags['regioncode'];
$country = $meta_tags['fips104'];
$lat = $meta_tags['latitude'];
$long = $meta_tags['longitude'];

//encode the city & country into $address variable
//for use in the Google Map API url
$address = urlencode($city . ', ' . $state . ', ' . $country);

//create the image course for displaying the Google map
$img_source = 'http://maps.google.com/staticmap?key=' . $api_key . '&size=' . $width . 'x' . $height . '&markers=' . $lat . ',' . $long . '&zoom=' . $zoom;

//return the image source
return $img_source;

//Sample usage
<img src='<? echo(ShowGoogleMap('YourKey', 555, 280, 4));?>' />

Disable an applications close button (The X)

26 August 2010 - 10:07 PM

In this entry we will look at how to disable the close button (The x in the upper right hand corner of the application) of an application in C#. This can come in handy when you need to do some processing when an application is being closed, and you need to control how/when it's being closed. If you read around on the internet you will undoubtedly find many solutions, the problem is most dont account for more than one way to closing an application.

If you were to just simply disable the close button (The x in the upper right hand corner of the application), that leaves several other ways for the user to close the application. When you right-click on the title bar of an application they all have a System Menu that also has a close option, so we need to remove that option as well.

Doing all this still leaves one option available for closing the application, and that is if the user presses Alt + F4, this will close the application immediately. This is probably the easiest thing to account for, simply using the Forms FormClosing event to capture this.

To disable the close button, and remove the close option from the applications System Menu, we will have to use P/Invoke, a low level access to a Windows system, to capture several events. When using P/Invoke, I prefer to keep all of that code in a separate class file, I usually name this class Base (Since we are dealing with base level events). We will be using 4 Win32 API's:

  • RemoveMenuItem: RemoveMenu is used to remove an item from a menu. If the item being removed is a sub-menu, the sub-menu is not actually destroyed by this function, instead, the close option is simply removed from the menu.
  • GetSystemMenu: GetSystemMenu is used to obtains a handle to a window's system menu. This menu is what appears when the application icon on the title bar is clicked, or when the title bar itself is right-clicked.
  • GetMenuItemCount: GetMenuItemCount counts the number of items in a menu. Remember, the position indexes of menu items are zero based. This means that if there are n items in the menu, their position indexes go from 0 to n - 1.
  • DrawMenuBar: DrawMenuBar is used to redraw the system menu so the user can see & use it.

public class Base
    public static extern int RemoveMenu(IntPtr systemMenu, int itemPosition, int flag);

    public static extern IntPtr GetSystemMenu(IntPtr systemMenu, int revert);

    public static extern int GetMenuItemCount(IntPtr systemMenu);

    public static extern int DrawMenuBar(IntPtr currentWindow);

Now that we have our Base class defined with the API Calls we need, we can concentrate on the methods for removing the Close option from the system menu. This method, we'll name it DisableClose, will use the 4 API methods we declared in the Base class to retrieve the system menu, get a count of all the items in the system menu, remove the items we specify, then redraw the menu. Remember, Close is always the last item in the system menu, and thats the one we want to remove.

private void DisableClose(IntPtr window)
    //get the system menu of the application
    IntPtr menu = Base.GetSystemMenu(window, 0);

    //get the count of menu items in the system menu
    int count = Base.GetMenuItemCount(menu);

    //disable the "Close" command in the menu
    Base.RemoveMenu(menu, count - 1, MF_DISABLED | MF_BYPOSITION);

    //now draw the menu bar on the application

To remove only the "Close" option we get the count of all items in the menu, then we go to the last one, back up one (the count is zero based, so its always n-1 for the one you want) then we call the RemoveMenu API method to remove that specific item. Now when your application runs, if you right-click on the title bar to bring up the system menu, the Close option is now gone.

We have no tackled 2 of the 3 ways to close an application, the last way is if the user presses Alt + F4. To do this we will capture this in the FormClosing event of the form. We will also give them an option to either let the application close or keep it open in case they have changes they wish to save before exiting.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    //set the variable to the messagebox results
    DialogResult result = 
        MessageBox.Show("Are you sure you want to exit this application", 
        "Exit Application?", 

    e.Cancel = (result == DialogResult.OK) ? false : true;

We then call DisableClose in the form's Load Event, passing it the Handle of the form like so:

private void Form1_Load(object sender, EventArgs e)

That's it, that's how you can disable the close button (the X) and remove the close option from the applications system menu.

Use the Luhn Algorithm to validate a credit card number

26 August 2010 - 09:53 PM

//using System.Text

/// <summary>

///method utilizing the Luhn algorithm (or Luhn formula) to 

///validate the provided credit card number

/// </summary>

/// <param name="value">number we're validating</param>

/// <returns>True, if valid, otherwise false</returns>

public bool DoesPassLuhnAlgorithmCheck(string value)


    int sum = 0;

    int end = 0;



        if (string.IsNullOrEmpty(value))

            throw new ArgumentException("The input value cannot be null or empty", value);


        StringBuilder sb = new StringBuilder(value.Length);

        //perform Luhn algorithm to determine if the value

        //provided is a valid cc number

        for (int i = 0; i < value.Length; i++)


            //here we want only the numbers in the value being checked

            if (Char.IsDigit(value[i]))



        if (sb.Length > 18 || sb.Length < 15)

            return false;

        //determines whether the end digit will be multiplies by 2

        bool multiplyByTwo = false;

        //now loop through what we have, looping backwards

        for (int i = sb.Length - 1; i >= 0; i--)


            //get each digit one at a time

            int digit = Int32.Parse(sb.ToString(i, 1));

            //if multiplyByTwo then we need to

            //multiple digit by 2

            if (multiplyByTwo)


                end = digit * 2;

                if (end > 9)

                    end -= 9;



                //otherwise end is given the value of the end digit

                end = digit;

            //keep a running total

            sum += end;

            //change the value of multiplyByTwo

            multiplyByTwo = !multiplyByTwo;


        //use mod 10 on the sum value

        int remainder = sum % 10;

        //if it's 0 (zero) then we got a valid value

        //otherwise we dont

        return (remainder == 0);


    catch (ArgumentException ex)


        return false;



The effectiveness of code reviews

26 August 2010 - 04:47 PM

Do you utilize code reviews in your development process? Do they improve the quality of code that makes it into a production environment?

Before I get into my spiel I would have to say, according to experience, that the answer to both of these questions is a resounding yes. The last Fortune 500 company I worked for it was me who as responsible for writing the departments code review standards (and the coding standards document but that's for a different discussion).

This took me several weeks of reviewing other formats used by various companies and what was currently happening at said company (that was the research part), then a couple more weeks of actual writing and revising. Once it was done, then came the hard part of implementing the process. Change is a hard thing to get some seasoned developers to accept, and I knew the ones who would fight it tooth & nail.

I did a meeting with the entire development team/department and explained how it's been proven time and time again that code reviews do indeed lead to less defects in your software. Core reviews are viewed by a lot of developers, and probably for good reason (I've seen some bad policies before as well) as a painful experience to have to endure, to survive. Everyone knows what the purpose of a code review is, so when I wrote up the guidelines I focused more on what a code review is not:

  • A code review is not a way to try and show the reviewee that you are superior to them and that their skills are dwarfed by yours. This will do nothing but create instant animosity and you will accomplish nothing.
  • A code review is not your chance to take a shot at the reviewee. It's not the developer that is being reviewed it's the code that was written.
  • A code review is not a chance to belittle another developer because they don't write code the same way you do

An effective code review can actually be a non-painful (some would say informative, relaxing) experience if done properly. I'm currently looking for my copy I saved when I left the company and will post it as soon as I find it. Within 4 months of implementing my code review guidelines we seen a 55% decrease in bugs & flaws that made it as far as QA, and a 65% drop in ones that made it into production.

I've worked for companies before that had no kind of standardized code review standards/guidelines in place and let me say it would never happen again. I'd say that at least 90%+ of all bugs made it as far as QA and I bet 80%+ of those made it into production, and it always went downhill from there.

So let's get y'alls take on an effective code review, do you think it helps improve the quality of code that makes it to QA and then into production. I know I've seen both sides of the coin and the differences were staggering in experience.

[C#] Write text to the beginning of a file

26 August 2010 - 03:21 PM

/// <summary>

/// method for adding new data to the beginning of a file

/// </summary>

/// <param name="file">the file we're adding to</param>

/// <param name="newValue">the value we want to write</param>

private void WriteToStartOfFile(string file, string newValue)


    char[] buffer = new char[2048];

    string tempFile = file + ".tmp";

    File.Move(file, tempFile);

    using (StreamReader reader = new StreamReader(tempFile))


        using (StreamWriter writer = new StreamWriter(file, false))



            int totalRead;

            while ((totalRead = reader.Read(buffer, 0, buffer.Length)) > 0)

                writer.Write(buffer, 0, totalRead);





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download