Jump to content


Check out our Community Blogs

PsychoCoder

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

#571528 [PHP] Display Google Map based on user location

Posted by PsychoCoder on 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
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
//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
$userIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else
{
//invalid (proxy provided some bogus value
//so just use REMOTE_ADDR and hope for the best
$userIP = $_SERVER["REMOTE_ADDR"];
}
}
//not coming through a proxy (or the proxy
//didnt provide the original IP)
else
{
//grab the IP
$userIP = $_SERVER["REMOTE_ADDR"];
}

//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));?>' />

  • 1


#571401 Saving to Text file question

Posted by PsychoCoder on 26 August 2010 - 03:19 PM

Here's one option. You can read the content of your file into a generic list, add your new data to the start of the generic list then write the data back to the file

/// <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)
{
    //generic list to hold the contents of the file
    List<string> fileContents = new List<string>();

    //add the content of the file to our list
    fileContents.AddRange(File.ReadAllLines(file));

    //add the new data to the beginning of the list
    fileContents.Insert(0, newValue);  
 
    //now write everything back to the file        
    File.WriteAllLines(file, fileContents.ToArray());

}

The downfall to this is it requires you to read the entire file into memory each time something is added, which can be inefficient with very large files.

Another option you have is:

  • Open a temp file (for writing to)
  • Write the new data to the temp file
  • Open the current file for reading
  • write all the data in the original file to the temp file

Here's an example of that

/// <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[10000];

    string tempFile = file + ".tmp";
    File.Move(file, tempFile);

    using (StreamReader reader = new StreamReader(tempFile))
    {
        using (StreamWriter writer = new StreamWriter(file, false))
        {
            writer.Write(newValue);

            int totalRead;
            while ((totalRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                writer.Write(buffer, 0, totalRead);
        }

        File.Delete(tempFile);
    }
}

Hope that helps :)
  • 0


#571246 Your take on piracy

Posted by PsychoCoder on 25 August 2010 - 09:50 AM

On other forums there have been long, in-depth discussion about software/music piracy. I take a very hard line view on this, it's stealing no matter how you look at it or try to rationalize it. As someone who makes my living from developing software it just irks me when people say they think it's ok to pirate something because it's so expensive.

Others have said they dont consider it stealing because you're not taking anything physical. My take is this, pirating software/movies/music is no different in my eyes than walking into a store and taking a CD. The whole "But it's so much money" argument for supporting piracy is, well it's just plain ** in my option. I dont care how much Photoshop costs, that doesn't mean it's ok to pirate it.

Still others say it's ok as long as you end up purchasing the software after evaluating it. Once you pirate a piece of software what incentive do you have to actually purchase it? I'll tell you, none. If you're already using it for free from piracy then why would you go a head and spend money on it?

I've seen others even go as far as saying that piracy is good because it gets your product out there and will eventually prompt people to purchase it. I disagree with this as well. Still others say that companies aren't losing any money from pirating, it's called ROI people. When a company spends millions on R & D and developing a product they count on purchases to recoup as much of that investment as possible, so when you piracy a piece of software and make it available to the masses via piracy you are, in reality, taking money out of said companies pockets because that's profits they're not getting from their investment.

You wont find a single piece of pirated software/movie/music on my network. I just cannot bring myself to steal from developers like that. It's software people, you do not have a right to own something just because you want it. Software is a privileged, not a right.

So, let's discuss this issue, and please keep it professional. There's no need to name call and such just because someone disagrees with you :)
  • 1


#570993 A look at Delegates, Events & Event Driven Design in C#

Posted by PsychoCoder on 23 August 2010 - 10:31 PM

At one point in our careers we've all been introduced to, or at least heard of, event driven programming, programming where the overall flow of the application is controlled by user generated events. In C# event driven programming is made much easier with the offering of Delegates & Events.

So today we're going to look at event driven programming in C#. Before we get into the meat of event driven programming we need to set a couple definitions for terms we will be using in this article:

Delegate:

A delegate is very similar to a function pointer in C++. It is a reference type that encapsulates a method which has a specific signature and a return type.


Events:

An event allows a class (or other object) to send notifications to other classes (or objects) that something has occurred. In simple terms an event is the outcome of a specific action.


In the old days all programs were very linear, they followed a set of commands/paths and user interaction was merely an after-thought, or limited to filling in forms or providing data. Over time things have changed drastically, today's programs are more user driven than ever, and as developers we need to change & adapt to this.

In today's environment we as developers know that actions are going to need to be taken, but at design-time we do not know what order these actions are going to occur, because it's all dependent on what actions the users take. We know we're going to have to execute ana ction, but until the user makes their action we dont know which method (or event) is supposed to be executed. That's where event driven programming comes into play. With events & delegates we can make these decisions on the fly.

So how exactly do delegates & events help with event driven programming you may ask? Well I have an answer. In event driven programmer you have a publisher, a class that exposes the event) and at least one subscriber, a class that subscribes to your event through the use of a delegate. So, given that context your publisher raises an event, more than likely through some user interaction or user choice, and your subscriber makes a decision on what to execute based on what event was raised, thus the term event driven programming.

To demonstrate the use of delegates & events in C# we're going to create an alarm clock application that is driven by events from user interaction. In our alarm clock we will have 2 classes that inherit from System.EventArgs, which will hold the data for our events. We will have SetAlarmEventArgs and AlarmTriggerEventArgs and here's the code for them

using System;

namespace PC.EventsAndDelegatesExample
{
    public class SetAlarmEventArgs : EventArgs
    {
        public DateTime SetTime { get; set; }        
        public bool AlarmEnabled { get; set; }
    }
}

using System;

namespace PC.EventsAndDelegatesExample
{
    public class AlarmTriggerEventArgs : EventArgs
    {
        public bool AlarmTurnedOff { get; set; }
    }
}
We will implement an interface based design into our example as well, we will name it IAlarmClock and it will handle the methods for working with the alarm clock that AlarmClock.cs will implement

using System;

namespace PC.EventsAndDelegatesExample
{
    public interface IAlarmClock
    {
        void AlarmClockSet(object sender, SetAlarmEventArgs e);
        void AlarmTurnedOff(object sender, AlarmTriggerEventArgs e);
        void TriggerAlarm(object sender, AlarmTriggerEventArgs e);
    }
}

In our AlarmClock.cs we will implement the above interface, and have properties that will be accessible in AlarmClockService.cs, which will do all the controlling of our alarm clock example

using System;

namespace PC.EventsAndDelegatesExample
{
    public class AlarmClock : IAlarmClock
    {
        public DateTime AlarmSetTime { get; set; }
        public bool AlarmEnabled { get; set; }
        public bool HitSnooze { get; set; }
        public int SnoozeTime { get; set; }

        public AlarmClock(DateTime setValue, bool enabled, bool snooze)
        {
            this.AlarmSetTime = setValue;
            this.AlarmEnabled = enabled;
            this.HitSnooze = snooze;
        }

        void IAlarmClock.AlarmClockSet(object sender, SetAlarmEventArgs e)
        {
            e.AlarmEnabled = this.AlarmEnabled;
        }

        void IAlarmClock.TriggerAlarm(object sender, AlarmTriggerEventArgs e)
        {
            //put your code here you want executed when the alarm is triggered\
            e.AlarmTurnedOff = this.AlarmEnabled;
        }

        void IAlarmClock.AlarmTurnedOff(object sender, AlarmTriggerEventArgs e)
        {
            e.AlarmTurnedOff = true;
        }
    }
}

Now for our alarm clock service. This is where all the events will be handled and triggered. We have two delegates and events derived from these delegates

public delegate void AlarmSetEventHandler(object sender, SetAlarmEventArgs e);
public delegate void AlarmTriggerEvenHandler(object sender, AlarmTriggerEventArgs e);

public event AlarmSetEventHandler AlarmSetEvent;
public event AlarmTriggerEvenHandler AlarmTriggerEvent;

That will handle the meat of our event driven alarm clock example. We will ask the user for a value to set the alarm clock to, then monitor this with a timer in our client application. Once the proper date & time are reached we will call our TriggerAlarm method, which will then set out AlarmTriggerEvent. Once the user gives the command to turn the alarm off we will unregister the AlarmTriggerEvent to shut the alarm down, here's the code for our AlarmClockService class

using System;

namespace PC.EventsAndDelegatesExample
{
    public class AlarmClockService
    {
        public delegate void AlarmSetEventHandler(object sender, SetAlarmEventArgs e);
        public delegate void AlarmTriggerEvenHandler(object sender, AlarmTriggerEventArgs e);

        public event AlarmSetEventHandler AlarmSetEvent;
        public event AlarmTriggerEvenHandler AlarmTriggerEvent;

        private AlarmClock clock { get; set; }

        public bool IsAlarmTriggered { get; set; }
        public bool IsAlarmEnabled { get; set; }

        public AlarmClockService(AlarmClock c)
        {
            this.clock = c;
        }

        public void SetAlarm(DateTime setValue)
        {
            try
            {
                if (clock == null)
                {
                    throw new ArgumentException("An AlarmClock instance much be provided");
                }
                else
                {
                    if (DateTime.Compare(setValue.Date, System.DateTime.Now.Date) >= 0 && (!(TimeSpan.Parse(setValue.ToShortTimeString()) < System.DateTime.Now.TimeOfDay)))
                    {
                        if(this.IsAlarmTriggered)
                            OnAlarmTimeSet(setValue);
                    }
                    else
                    {
                        throw new Exception("A date & time value before the current date & time isnt valid");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        protected void OnAlarmTimeSet(DateTime setValue)
        {
            if (AlarmSetEvent != null)
            {
                SetAlarmEventArgs args = new SetAlarmEventArgs();
                args.SetTime = setValue;
                args.AlarmEnabled = true;
                AlarmSetEvent(this, args);
            }
        }

        public void TriggerAlarm()
        {
            while ((clock.AlarmEnabled) && (!clock.HitSnooze))
            {
                OnAlarmTrigger();
            } 
        }

        protected void OnAlarmTrigger()
        {
            if (AlarmTriggerEvent != null)
            {
                AlarmTriggerEventArgs args = new AlarmTriggerEventArgs();
                args.AlarmTurnedOff = false;

                //code to play your alarm sound goes here

                AlarmTriggerEvent(this, args);
                
            }
        }

        public void CancelAlarm(IAlarmClock iclock)
        {
            //make sure it's been cancelled
            if (!this.IsAlarmEnabled)
                this.AlarmTriggerEvent -= new AlarmTriggerEvenHandler(iclock.AlarmTurnedOff);

            //code to stop playing the alarm sound
        }

        public void AttachSetEvent(IAlarmClock iclock)
        {
            this.AlarmSetEvent += new AlarmSetEventHandler(iclock.AlarmClockSet);
        }

        public void AttachTriggerEvent(IAlarmClock iclock)
        {
            this.AlarmTriggerEvent += new AlarmTriggerEvenHandler(iclock.TriggerAlarm);
        }
    }
}


Now that we have the layout completed let's look at a quick implementation. We will need a timer class to monitor the time once the user sets the alarm. Since the actual timer control isnt available in a console application (which we are using for this example) we'll have to use the System.Threading.Timer class. First we need to create a callback method which matches the callback delegate (this will be used in the constructor of our timer control). In here we will set the value of a global DateTime variables being used to determine whether we trigger the alarm

private static void CheckTime(Object state)
{
    nowValue = DateTime.Now;
}

Then in main we ask the user for an alarm value, we then tick each second looking for the proper value and once we reach it we trigger the alarm. Once the alarm is triggered we give the user an option to turn the alarm off then act accordingly

private static DateTime nowValue;

static void Main(string[] args)
{
    Console.WriteLine("Please provide a time for your alarm to go off");
    DateTime setValue;

    if (!DateTime.TryParse(Console.ReadLine(), out setValue))
    {
        Console.WriteLine("Invalid entry");
    }
    else
    {
        //create a new stock isntance
        IAlarmClock c = new AlarmClock(setValue, true, false);

        //provide our stock market instance know the stock
        AlarmClockService service = new AlarmClockService((AlarmClock)c);

        //attach events to the stock market, so it can notify the investor
        //this uses the Observe pattern with delegates & events
        service.AttachSetEvent(c);
        service.AttachTriggerEvent(c);

        //start the stock market
        service.SetAlarm();

        TimerCallback call = new TimerCallback(CheckTime);

        //create a timer that ticks every second
        Timer timer = new Timer(call, null, 0, 1000);

        for (; ; )
        {
            if (nowValue == service.triggerValue)
            {
                service.TriggerAlarm();
                break;
            }
        }

        Console.WriteLine("Press C to cancel alarm");
        if (Console.ReadLine().ToLower() == "c")
        {
            service.IsAlarmEnabled = false;
            service.CancelAlarm(c);
        }
    }
           

    Console.ReadKey();
}

So that's how event driven programming works. I know this is a very simple example but I was trying to introduce you to the concept of event driven programming, and I know we could have made this more robust, such as snooze and such, but as stated this is just an example on how event driven programming works.

I also want to admit that this implementation probably isn't the most efficient way to do it, and maybe in the future I'll have an addition to this article with a more improved, robust and efficient example on an alarm clock application with event driven programming. Thanks for reading :)
  • 1


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