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);

Simple c# StringBuilder example

A simple example of using the StringBuilder to concat strings.

StringBuilder mySB = new StringBuilder();
mySB.Append("line 1");
mySB.Append("line 2");
mySB.Append("line 3");
Console.WriteLine(mySB.ToString());

String formating within C#

Below is an example of using string formating to print a time

int h = 12;
int m = 13;
int s = 14;
string myString = string.Format("{0}:{1}:{2}", h, m, s);
Console.WriteLine(myString);

To format a number to two decimal places, you could use the string format.

double s = 14.123;
string myString = string.Format("{0:0.00}", s);
Console.WriteLine(myString);

Reading a file with C#

Reading a text file line by line in C#. Dont forget to include using System.IO;

StreamReader myReader = new StreamReader(@"c:\test.txt");
string line = "";
while (line != null)
{
   line = myReader.ReadLine();
   Console.WriteLine(line);
}

You can read all the text within a file using the ReadAllText function.

string filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\test.txt";
string content = File.ReadAllText(filename);
MessageBox.Show(content);

Explicit Conversion of a string to Integer using c#

Explicit Conversion of a string to Integer, sometimes known as cast.

string myString = "7";
int myInt = int.Parse(myString);
Console.WriteLine(myInt);

The above code will fail if the string can not be converted to a integer. For example if myString=”Seven”, the code would fail. To avoid this problem use TryParse.

string myString = "Seven";
int myInt = 0;
if (int.TryParse(myString, out myInt) == true)
{
   Console.WriteLine("String converted");
}
else
{
   Console.WriteLine("String NOT converted");
}
Console.WriteLine(myInt);

Generate safe filenames using Python

This function removes illegal  characters to create file names that are safe to use on most operating systems.

import string

## Make a file name that only contains safe charaters
# @param inputFilename A filename containing illegal characters
# @return A filename containing only safe characters
def makeSafeFilename(inputFilename):   
  try:
     safechars = string.letters + string.digits + " -_."
    return filter(lambda c: c in safechars, inputFilename)
   except:
     return ""  
  pass

print makeSafeFilename("test1******.txt")  # test1.txt

print makeSafeFilename("test2:\.txt") # test2.txt

print makeSafeFilename("test39328764876!%^&*().txt") # test39328764876.txt

Detecting the Dominant points on an image using OpenCV

To detect the dominant points within an image first we must find the edges. In this example the edges are found using cvFindContours. The resulting contours are then processed to find the dominant points along the contour. This is done using the cvFindDominantPoints function, this function implements the IPAN99 algorithm to find the points. A small circle is then drawn at each dominant point.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include "cvaux.h"

int _tmain(int argc, _TCHAR* argv[])
{
	// open and display input image  
    IplImage* input = cvLoadImage("test.jpg", CV_LOAD_IMAGE_GRAYSCALE);  
    cvNamedWindow("Input", CV_WINDOW_AUTOSIZE);  
    cvShowImage("Input", input); 

	// create gray scale image for edge detection
	IplImage* edge = cvCreateImage(cvGetSize(input), 8,1);

	// create output image
	IplImage* output = cvCreateImage(cvGetSize(input), 8,1);

	// threshold the input image
	cvThreshold(input, edge, 230,255, CV_THRESH_BINARY);
	cvNamedWindow("Threshold", CV_WINDOW_AUTOSIZE);
	cvShowImage("Threshold", edge);

	// generate the contours
	CvMemStorage* storage = cvCreateMemStorage();
	CvSeq* contours = NULL;
	int Nc = cvFindContours(edge, storage, &contours, sizeof(CvContour), CV_RETR_LIST);

	// diplay the contours
	printf("Total contours found = %d\n", Nc);
	cvDrawContours(output, contours, cvScalarAll(255),cvScalarAll(255),10); 

	// generate the dominant points
	CvMemStorage* dominantstorage = cvCreateMemStorage();
	CvSeq* dominant = cvFindDominantPoints(contours, dominantstorage, CV_DOMINANT_IPAN,5,15,5,170);

	printf("dominant total=%d\n", dominant->total);

	// display the dominant points
	int i, idx;
    CvPoint p;
	for ( i = 0; i < dominant->total; i++)
    {
        idx = *(int *) cvGetSeqElem(dominant, i);
        p = *(CvPoint *) cvGetSeqElem(contours, idx);
        cvDrawCircle( output, p , 1, CV_RGB(255,0,0) );
        printf("%d %d %d\n", idx, p.x, p.y);
    }
	
	// show output
	cvNamedWindow("Output", CV_WINDOW_AUTOSIZE);
	cvShowImage("Output", output);

	// wait for user
	cvWaitKey(0); 

	// garbage collection	
	cvReleaseImage(&input);
	cvDestroyWindow("Input");
	cvReleaseImage(&edge);
	cvDestroyWindow("Threshold");
	cvReleaseImage(&output);
	cvDestroyWindow("Output");
	return 0;
}

Input Image

threshold

After threshold

Output

Image Contour detection and display using OpenCV

In this example we threshold the image based on the position of the track bar. Then find contours on the image an display the contours as white lines.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

// global variables
IplImage* input = NULL;
IplImage* gray = NULL;
int threshold = 100;
CvMemStorage* storage = NULL;

/** trackbar event
 * @param trackbar position
 */
void on_trackbar(int)
{
	
	if (storage == NULL)
	{
		// create storage
		gray = cvCreateImage(cvGetSize(input), 8,1);
		storage = cvCreateMemStorage(0);
	}
	else
	{
		// clear storage
		cvClearMemStorage(storage);
	}

	// convert to gray scale and then threshold
	cvCvtColor(input, gray, CV_BGR2GRAY);
	cvThreshold(gray,gray,threshold,255,CV_THRESH_BINARY);

	// find the edges
	CvSeq* edges = 0;
	cvFindContours(gray, storage, &edges);
	cvZero(gray);
	if (edges)
	{
		// display the edges as whiet lines
		cvDrawContours(gray, edges, cvScalarAll(255),cvScalarAll(255),100);
	}
	cvShowImage("Input", gray);
}

/** main function
 * @param argc arguments
 * @param argv argument values
 * @return exit code
 */
int _tmain(int argc, _TCHAR* argv[])
{
	// open and display input image  
    input = cvLoadImage("test.jpg");  
    cvNamedWindow("Input", CV_WINDOW_AUTOSIZE);  
    cvShowImage("Input", input); 

	// create trackbar callback
	cvCreateTrackbar("Threshold", "Input", &threshold, 255, on_trackbar);
	on_trackbar(0);

	// wait for user
	cvWaitKey(0);

	// garbage collection	
	cvReleaseImage(&input);
	cvDestroyWindow("Input");
	return 0;
}

The input image

Threshold value 100

Threshold value 150

Threshold value 200