Archive for August 2013

Split a name into First name and Last name using PHP

/** split a name into the first name and last name
 * @param input The name eg 'John Doe'
 * @return Array containing firstname and lastname eg array('firstname'=>'John', 'lastname'=>'Doe');
 */
function splitname($input)
{
   $output = array("firstname"=>"", "lastname"=>"");
   $space = strpos($input, " ");
   if ($space !== false)
   {
      $output['firstname'] = substr($input, 0, $space);
      $output['lastname'] = substr($input, $space, strlen($input));     
   }
   else
   {
      $output['lastname'] = $input;
   } 
   return $output;
}

Convert a url data in to Name Value Pairs array PHP

Convert a url data in to Name Value Pairs array.

/** Convert a url data in to Name Value Pairs array
 * @param url The url and the data string
 * @return array of named value pairs
 */
function urlToNvp($url)
{
   $output = array();
   
   $questionmark = strpos($url, '?');
   if ($questionmark !== false)
   {
      $url = substr($url, $questionmark+1, strlen($url));
   }   
   
   foreach(explode('&', $url) as $data)
   {
      $value = explode('=', $data);
      $output[$value[0]] = $value[1];
   }
      
   return $output;
}

Here are three examples of using this function

print_r(urlToNvp("www.example.co.uk?p1=one&p2=two"));
print_r(urlToNvp("p1=one&p2=two"));
print_r(urlToNvp("www.example.co.uk?p1=one"));

The result

Array ( [p1] => one [p2] => two )
Array ( [p1] => one [p2] => two )
Array ( [p1] => one )

Using OpenCV inside a C# WPF application

In this example I will create a C++ dll that with contain the OpenCV image processing code. I then will create a C# WPF application, within this application i will then include the dll and using the image processing function.

  1. Install OpenCV http://docs.opencv.org/doc/tutorials/introduction/windows_install/windows_install.html#windows-installation
  2. Create a C++ Win32 console Application, in this example it will be called ImageProcessingAgain
  3. Click Next. Select Application type dll. Then click finish.
  4. Click Property Manager, right click on debug, then select ‘Add Existing Property Sheet’. If you dont have a property sheet follow the following tutorial for creating The Local Method http://docs.opencv.org/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.html
  5. Add the following code to the cpp

    // ImageProcessAgain.cpp : Defines the exported functions for the DLL application.
    //
    
    #include "stdafx.h"
    
    #include "opencv\cv.h"
    #include "opencv\highgui.h"
    
    extern "C"
    {   
    	__declspec(dllexport) int exampleImageProcessing(LPCWSTR);
    }
    
    extern int __cdecl exampleImageProcessing(LPCWSTR filename)
    {
    	IplImage* img = cvLoadImage((char*)filename);
    	return img->width;
    }
    
  6. build the dll project
  7. Create a C# WPF project called UsingOpencvAgain
  8. copy the dll and then include the dll within the C# project
  9. Select the dll in the solution explorer, set the ‘copy to output directory’ property to ‘copy if newer’
  10. Create two textboxes and a button
  11. Add the following C# code to the application

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Runtime.InteropServices;
    
    namespace UsingOpencvAgain
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            [DllImport("ImageProcessAgain.dll", CallingConvention = CallingConvention.Cdecl)]
            public static extern int exampleImageProcessing(string filename);
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                textBox2.Text = exampleImageProcessing(textBox1.Text).ToString();
            }
        }
    }
    
    

Simple Write File using C#

A very simple method for writing to a file, not forget to include using System.IO;.

string filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\test.txt";
string content = "This is the new file content";
File.WriteAllText(filename, content);

Data Validation and Exceptions in C#

The setName funcion demostrates simple data validation on the argument value.

void setName(string value)
{
    // validate empty
    if (string.IsNullOrWhiteSpace(value))
    {
        throw new ArgumentNullException("Please enter a value");
    }

    // validate length
    if (value.Length > 10)
    {
        throw new ArgumentException("The value is too long");
    }

    // value is valid
    MessageBox.Show("The value is valid");
}

When calling the setName function it is important that we implement code to catch any exceptions

try
{
    setName(textBox1.Text);
}
catch (Exception ex)
{
    MessageBox.Show("Error " + ex.Message);
}

C# type checking with the is statement

A var type can be checked using the ‘is’ statement

var a = 1.0;

if (a is int)
{
    MessageBox.Show("int");
}
else
{
    MessageBox.Show("is NOT int");
}

C# class properties

The code below shows the short hand and long hand syntax for defining class properties.

public class Example
{
  // class property short hand
  public string Firstname {get; set;}


  // class property long hand
  private string _Lastname;
  public string Lastame
  {
     get {return _Lastname}
     set {_Lastname = value}
  }
}

Simple C# LINQ example

The LINQ example below creates a generic collection of the class Car. Then using a LINQ statement the collection is filtered to find cars that are newer than 2009.

List myCars = new List() {
    new Car() { Make="BMW", Model="550i", Year=2009 },
    new Car() { Make="Toyota", Model="4Runner", Year=2010 },
    new Car() { Make="BMW", Model="745li", Year=2008 },
    new Car() { Make="Ford", Model="Escape", Year=2008 },
    new Car() { Make="BMW", Model="550i", Year=2010 }
};


var newCars = from c in myCars
                where c.Year > 2009
                select new { c.Model, c.Make, c.Year };

foreach (var car in newCars)
{
    Console.WriteLine("{0} {1} - {2}", car.Make, car.Model, car.Year);
}

class Car
{
   public string Make { get; set; }
   public string Model { get; set; }
   public int Year { get; set; }
}

Enumerations with tryParse in C#

Here is an example of using enum with a tryParse. The program asks the user to enter a new state. The tryParse then attempts to convert the input into a enum.

// define current state
MyState currentState = MyState.off;
            
// get value from user
Console.WriteLine("Please enter the new state");
string input = Console.ReadLine();

if (Enum.TryParse(input, out currentState) == false)
{
    Console.WriteLine("Unable to compute input");
}
Console.WriteLine("Current state " + currentState);

Console.WriteLine("=== Finished ===");
Console.ReadLine();
}

enum MyState
{
on,
off,
idle
}

Adding days to a DateTime in C#

Add seven days to the current time.

DateTime start = DateTime.Now;
Console.WriteLine("Start date = " + start.ToString("dd/MM/yyyy hh:mm:ss"));
DateTime end = start.AddDays(7);
Console.WriteLine("End date = " + end.ToString("dd/MM/yyyy hh:mm:ss"));

Other methods for defining a DateTime object

DateTime start = DateTime.Parse("23/01/1984 01:02:03");
DateTime start = new DateTime(1984, 01, 23, 01, 02, 03);