Thursday, July 22, 2010

Generating Random Numbers - C#

Random numbers can be used in many ways. They can determine random events in game, pick a winner out of a list of contestants, or used to simulate a coin flip. Using random numbers is very simple in C#.

First you must declare an instance of the Random class.
Random ran = new Random();

The Random class has the following methods:

Next() - Returns a nonnegative random integer.
Next(int) - Returns a nonnegative random number below the value of int.
Next(int1, int2) - Returns a nonnegative random number that is at least int1, but less than int2
NextBytes() - Fills an array of bytes with random, nonnegative integers.
NextDouble() - Returns a random number between 0.0 and 1.0

Here is an example using random numbers. The following program generates a random number between 0-10 and prints results.
Random ran = new Random();

int result = ran.Next(0, 10); //number is at least 0, but less than 10

if(result >=5)
   Console.WriteLine("You Generated a BIG Number!");
else
   Console.WriteLine("You Generated a small Number :(");

Detecting Encoding of a File - C#

The following method reads the byte-order mark of a file and returns a string representing the encoding type.

Special Thanks to Heath Stewart - Your tutorial helped me understand Encoding better and allowed me to write this method. Check out his tutorial here.

//@Return: Returns the name of the encoding of the file at filePath
        public static string GetFileEncoding(string filePath)
        {
            FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            string encoding = null;

            try
            {
                
                if (file.CanSeek) //if file is readable
                {
                    byte[] bom = new byte[4]; //getting Byte-order mark

                    file.Read(bom, 0, 4);

                    if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)                     //utf-8
                        encoding = "UTF-8";
                    else if (bom[0] == 0xff && bom[1] == 0xfe)                                  // ucs-2le, ucs-4le, and ucs-16le
                        encoding = "UCS-21e, UCS-41e, and UCS-161e";
                    else if (bom[0] == 0xfe && bom[1] == 0xff)                                  // utf-16 and ucs-2
                        encoding = "UTF-16 and UCS-2";
                    else if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)    //ucs-4
                        encoding = "UCS-4";
                    else                                                                        //DEFAULT: ASCII
                        encoding = "ASCII";
                }

            }
            catch (Exception e)
            { Console.Error.WriteLine("ERROR: " + e.Message); }
            finally
            {
                if (file != null)
                    file.Close();
            }

            return encoding;
        }

Monday, July 19, 2010

Deleting a Directory and All Its Contents - C#

Quick code I wrote the delete all directories named, trg, within the source directory, src.
public void DeleteDirectory(DirectoryInfo dir, string trg)
        {
            foreach (DirectoryInfo sub in dir.GetDirectories())
            {
                if (sub.Name.Equals(trg))
                {
                    foreach (FileInfo file in sub.GetFiles())
                        file.Delete();

                    sub.Delete();
                }
                else
                    DeleteDirectory(sub, trg);
            }
        }

Friday, July 16, 2010

Loading a 2 Column Text File into Lists - C#

I came across a text file that is split into two columns, with each column split up by spaces or tabs. This method loads the text file into two different lists of strings.

Note: In this case, the columns are split up by at least 2 spaces.
Note2: The method is part of a bigger class that has the following variables:
List src = new List();
List trg = new List();
//loads a text file dictionary where both segments are on the same line and are seperated by multiple spaces
        //ex. "a specified period of time         eine genau bestimmte Frist"
        public void loadDictionary(FileInfo file)
        {
            fileName = file.Name.Substring(0, file.Name.Length - 4) + "_" + timeHolder + ".tmx"; //taking off extension

            Console.WriteLine("Loading language segments from dictionary {0}.", file.Name);
            StreamReader sr = new StreamReader(file.FullName);

            string line;

            while ((line = sr.ReadLine()) != null)
            {
                char[] chars = line.ToCharArray();
                int spaces = 0;
                int index = 0;

                foreach (char c in chars)
                {
                    if (c.Equals(' '))
                        spaces++;
                    else //not out of word
                        spaces = 0;


                    if (spaces >= 2) //if its a break between words
                    {
                        src.Add(lineIteg(line.Substring(0, index).Trim()));
                        trg.Add(lineIteg(line.Substring(index, line.Length - index).Trim()));
                        break;
                    }
                    index++;
                }
            }
            sr.Close();
        }

Thursday, July 15, 2010

Properties (Get/Set Alternate) - C#

If any of you have experience with Get/Set methods for variables, you know how tedious it can be to create multiple simple method for each variable, especially in a class where with many variables.

Starting with C# 3.0, there is an easier way to access and modify class variables, called properties.

Let's say you create a class called student, which has two variables, ID and Name.
public class Student
{
   public int ID{get; set;}
   public string Name {get; set;}
}
Instead of having to write a method like getID and setID, the variables can now be accessed by simply doing ClassName.ID.

Example:
Student calvin = new Student();

calvin.ID = 44;
calvin.Name = "Calvin";
Console.WriteLine("Student {0} has an ID # {1}", calvin.Name, calvin.ID);
Output = "Student Calvin has an ID # 44"

Split Text File by Line Size - C#

Just a quick program I wrote that separates a textfile into 2 different files: the first containing all lines that have < 5,000k characters, and the second containing all lines that have 5,000k or over characters. Each of these new files goes into a created directory named "5KSplit".

Note: The first line of the file is ignored because the format I was working with in this case contains a header line.

Note 2: StreamWriter is writing in UTF-8 Encoding because the format of file I was working with is best interpreted in UTF-8 as opposed to ASCII.

I apologize for the lack of format in the following code. For some reason when I copied it over it lost all formatting.
/*
* Creator: Calvin Hawkes 7-15-10
*/



public void FiveKCharSplit(FileInfo file)
{

StreamReader sr = new StreamReader(file.FullName);
DirectoryInfo trgDir = new DirectoryInfo(file.Directory.FullName + "\\5KSplit\\");

if (!trgDir.Exists)
  trgDir.Create();

StreamWriter sw = new StreamWriter(trgDir.FullName + file.Name, true, Encoding.UTF8); //File                 with <5k char lines

string header = sr.ReadLine(); //header
sw.WriteLine(header);
string line = null;
List over5k = new List(); //lines over5k



while ((line = sr.ReadLine()) != null)
{
  if (line.Length >= 5000) //change 5000 to character number you wish to split by
  {
  over5k.Add(line);
  }
  else //if good line
  {
  sw.WriteLine(line);
  }
}

sr.Close();
sw.Flush();

//Writing lines over 5k into different file
if (over5k.Count > 0)
{
  Console.WriteLine("{0} Contains Line(s) over 5,000 Char.\n Splitting now...", file.Name);
  sw = new StreamWriter(trgDir.FullName + file.Name.Substring(0, file.Name.Length - 4) +       
  "_Over5K.txt", true, Encoding.UTF8);
  sw.WriteLine(header);

  foreach (string s in over5k)
  {
    sw.WriteLine(s);
  }
  sw.Flush();
}
sw.Close(); 
  
}

Wednesday, July 14, 2010

Switch-Case Statements - C#

A Switch-Case statement is essentially the same thing as an If-Else If-Else statement. In other languages it is called a Select-Case statement. What it does is pick a variable, then check the value of the variable against different cases. If a case matches the value of the variable, the program executes the code within that case statement. There is also the option to add a 'default' case, which is the same thing as the last 'else' in a series of If statements.

Note: Every case statement must end with a 'break;', signifying the end of that case's code.

Here is a simple example using a Switch-Case statement.

With ints:
int test = 3;

switch(test)
{
   case 1:
      Console.WriteLine("1");
      break;
   case 2:
      Console.WriteLine("2");
      break;
   case 3:
      Console.WriteLine("3");
      break;
   default:
      Console.WriteLine("Int is not 1-3");
      break;
}
Output: 2

With Strings:
string test = "Weeee!";

switch(test)
{
   case "Wee.":
      Console.WriteLine("Meh.");
      break;
   case "Weee.":
      Console.WriteLine("Eh.");
      break;
   case "Weeee!":
      Console.WriteLine("Now You're Excited!");
      break;
   default:
      Console.WriteLine("Do Something");
      break;
}
Output: Now You're Excited!