Friday, July 30, 2010

Retrieving a File or Directory from a Path that is Too Long to Read - C#

Microsoft has a limitation of 260 characters for a path or file name. Usually Windows is smart enough and wont allow you to create a file or folder if the path will be too long, but sometimes, some way or another, files/folders get trapped and you can't access them because the name is too long. This can be a huge inconvenience and can cause your program to crash.

The following method overwrites the Windows API and allows you to move a folder or directory if its path is over 260 characters:
Note: Replace "H:\Calvin\kernel32.dll" with the path to kernel32.dll (can be found in your system32 folder)
Note2: You can call Move on a directory or file
[DllImport(@"H:\Calvin\kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool MoveFile(string lpExistingFileName, string lpNewFileName);

public static void Move(string fileName, string toPath) 
{
    string formattedName = @"\\?\" + fileName;
    MoveFile(formattedName, toPath);
            
}

If you have the problem where you don't the exact path you want to retrieve because you can't access it in the first place, ABTO created a nice little DLL that helps you with paths that are too long. The trial version has enough functionality to work. Download it HERE.

If you want to do other functions besides move a file, check out the File Management Functions documentation and alter the above code.

References:
Kim Hamilton

Thursday, July 22, 2010

EncodingTool Class: Detects, Checks for Consistency, and Converts Encoding - C#

Download the class here.
The following class can identify encoding in a file, check a file for consistent encoding, and convert encoding in a file.
class EncodingTool
    {
        //@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;
        }

        //@Return: Returns true if encoding is consistant throughout the file, else print all encodings
        public static bool ConsistantEncoding(string filePath)
        {
            FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            string encoding = null;
            bool consistant = true;

            try
            {

                if (file.CanSeek) //if file is readable
                {

                    byte[] bom = new byte[4]; //getting Byte-order mark

                    while (file.Read(bom, 0, 4) != 0)
                    {
                        if (encoding == null)
                        {
                            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";
                        }
                        else
                        {
                            if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)                     //utf-8
                            {
                                if (encoding != "UTF-8")
                                    consistant = false;
                            }
                            else if (bom[0] == 0xff && bom[1] == 0xfe)                                  // ucs-2le, ucs-4le, and ucs-16le
                                if (encoding != "UCS-21e, UCS-41e, and UCS-161e")
                                    consistant = false;
                                else if (bom[0] == 0xfe && bom[1] == 0xff)                                  // utf-16 and ucs-2
                                    if (encoding != "UTF-16 and UCS-2")
                                        consistant = false;
                                    else if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)    //ucs-4
                                        if (encoding != "UCS-4")
                                            consistant = false;
                                        else                                                                        //DEFAULT: ASCII
                                            if (encoding != "ASCII")
                                                consistant = false;
                        }
                    }
                }

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

            return consistant;

        }

        //@Done: Converts a file to specified unicode and names it: Name_Encoding_.txt
        public static void ConvertEncoding(string filePath, Encoding enc)
        {
            StreamReader sr = new StreamReader(filePath);
            StreamWriter sw = new StreamWriter(filePath.Substring(0, filePath.Length - 4) + "_" + enc.EncodingName + ".txt", true, enc);

            string line;
            using (sw)
            {
                while ((line = sr.ReadLine()) != null)
                {
                    sw.WriteLine(line);
                }
            }
        }
    }

Download the class here.

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!

War (Card Game) - Java

This is just a java version of the card game War, created for a class project 4 years ago. Forgive my amateur errors.

To see the rules of the card game, click here.

Card Class
//Jordan Kestler & Calvin Hawkes
//Nov 8
//has all of the values for the card class

public class Card 
{    
    private String suit;
    private int value;

    public Card(int initValue)
    {
        value = findCard(initValue);
        suit = findSuit(initValue);
    }
    
    public Card(String initSuit, int initValue)
    {
        suit = initSuit;
        value = initValue;
    }
        
    //pre: takes a number from the array
    //post: returns what suit it is
    public String getSuit()
    {
        return suit;
    }
    
    //pre: takes number from array
    //post: returns a numerical value for it
    public int getValue()
    {
        return this.value;
    }
    
    //pre: enter an integer
    //post: finds the number of the card    
    public int findCard(int cardNum)
    {
        int card = (cardNum % 13);
        
        return card;
    }
    
    //pre: enter an integer
    //post: finds the suit of the card
    public String findSuit(int cardNum)
    {
        String suit = "";

        if ((cardNum / 13) == 0) //If the card is a Diamond
            suit = "DIAMOND";
        else if((cardNum / 13) == 1) //If card is a Heart
            suit = "HEART";
        else if((cardNum / 13) == 2) //If card is a Spade
            suit = "SPADE";
        else if((cardNum / 13) == 3) //If card is a Club
            suit = "CLUB";
        else
            System.out.println("INVALID CARD: " + cardNum);
            
        return suit;
    }

    
    //pre: takes two cards
    //post: returns which 1 if THIS card is bigger. -1 if second is bigger. 0 if equal
    public int compare(Card a)
    {
        int compared;
        
        
        if (this.value != 0 && a.value != 0) //if neither cards are aces
        {
            if (this.value > a.value)
                compared =  1;
            else if (this.value < a.value)
                compared = -1;
            else
                compared =  0;
        }
        else if(this.value == 0 && a.value != 0) //if the first card is an ace
            compared = 1;
        else if(this.value != 0 && a.value == 0) //if the second card is an ace
            compared = -1;
        else //if both cards are aces
            compared = 0;
            
        return compared;
    }
    
    //pre: takes its value 
    //post: converts it to a name. ie jack, king, queen, ace
    public String toString()
    {
        String name = "";
        if (value >= 10 || value == 0)
        {
            if (value == 12)
                name = "king";
            else if (value == 11)
                name = "queen";
            else if (value == 10)
                name = "jack";
            else if (value == 0)
                name = "ace";
    
            return name + suit;
        }
        else
            return "" + (value + 1) + suit;    

    }
    
    
}

Hand Class
//Jordan Kestler & Calvin Hawkes
//Nov 8
//makes two decks for each player

import java.util.*;

public class Hand 
{
    ArrayList  cardList = new ArrayList  (53);
    
    //pre: takes top card off deck
    //Post: returns top card
    public Card playCard()
    {
        return cardList.remove(0);
    }
    
    //pre: takes cards that are won
    //Post: puts cards won on bottom
    public void addCard(Card a)
    {
        cardList.add(a);    
    }
    
    //pre: takes the array of the hand
    //post: returns how many cards are in it and checks if its empty
    public int numCards()
    {
        int numCards = cardList.size();
        return numCards;
    }
    
    //pre: none
    //post: prints out hand
    public void printHand()
    {
        for(int i=0; i < cardList.size(); i++)
            System.out.println(i + ". " + cardList.get(i));
    }
    
    
    
}
Deck Class
/*Calvin Hawkes & Jordon Kestler
 *Nov. 8 2007
 *Deck Class That should work with any card game
 */
 
 import java.util.*;


public class Deck 
{
    private final int CARDS = 52; //amount of cards in a deck
    private Card [] deck; //creating an array of cards
    private int top = 0; //the top of the deck
    
    public Deck()
    {
        deck = new Card[CARDS];
        //Creates all 52 cards
        
        for(int i=0; i < CARDS; i++)
            deck[i] = new Card(i);
    }
    
    //pre: must be passed a deck of cards
    //post: returns the deck with cards in random order
    public void shuffle()
    {
        Random rand = new Random();
            
        for (int i=0; i < CARDS; i++)
        {
            int ranCard = rand.nextInt(52); //random number 0-51
            
            Card temp;
            temp = deck[i];
            
            deck[i] = deck[ranCard];
            deck[ranCard] = temp;
        }
    }
    
    //pre: must be passed a deck of cards
    //post: returns true if the deck is empty else false
    public boolean isEmpty()
    {
        boolean empty = false;
        
        if (top == 52)
            empty = true;
            
        return empty;    
    }
    
    //pre: must be passed a deck of cards
    //post: returns the top card on the deck and removes it from the deck
    public Card deal()
    {
        int temp = top;
        top ++;
        
        return deck[temp];
    }
    
    //pre: must be passed a deck of cards
    //post: prints out every card in the deck in order. Used for testing
    public void printDeck()
    {
        for(int i=0; i < CARDS; i++)
            System.out.println(i + ". " + deck[i]);
    }
    
    
    
    
}
Game Class
/*Calvin Hawkes & Jordon Kestler
 *Nov. 9 2007
 *The Game Class for a Card Game Called War
 */


public class Game 
{

    public static void main(String[] args) 
    {
        
        Deck warDeck = new Deck(); //Creating the Deck of Cards
        
        Hand player1 = new Hand(); //Creating player 1's hand
        Hand player2 = new Hand(); //Creating player 2's hand
        
        warDeck.shuffle(); //Shuffling the Deck
        
        boolean done = false;
        
        while(!done) //Dealing the Cards
        {
            if(!(warDeck.isEmpty()))
                player1.addCard(warDeck.deal());
            else
                done = true;
            
            
            if(!(warDeck.isEmpty()))
                player2.addCard(warDeck.deal());
            else
                done = true;
        }
        
       
        while(player1.numCards() != 0 && player2.numCards() != 0)
        {
        
            //Playing the Game
            Card p1Card = player1.playCard();
            Card p2Card = player2.playCard();
        
            if (p1Card.compare(p2Card) == 1) //if player1 wins
            {
                System.out.println("Player 1 Wins!");
                player1.addCard(p1Card);
                player1.addCard(p2Card);
            }
                
            else if (p1Card.compare(p2Card) == -1) //if player2 wins
            {
                System.out.println("Player 2 Wins!");
                player2.addCard(p1Card);
                player2.addCard(p2Card);
            }
            else //if a war is declared
            {
                if (player1.numCards() >= 4 && player2.numCards() >= 4)
                    war(player1 , player2);
                else if (player1.numCards() == 3 || player2.numCards() == 3)
                    war2(player1 , player2);
                else if (player1.numCards() == 2 || player2.numCards() == 2)
                    war3(player1 , player2);
                else
                    war4(player1 , player2);
            }
                
        }
        
        //Declaring the Winner
        if(player2.numCards() == 0)
            System.out.println("PLAYER 1 WINS THE GAME!!!");
        else
            System.out.println("PLAYER 2 WINS THE GAME!!!");
        
        
        
    }
    
    //pre: if two hands are created and both users have 4 or more cards
    //post: plays war when two cards are equal
    public static void war(Hand player1, Hand player2)
    {
        System.out.println("WAR!!!");
        
        //Playing 3 Cards Facedown
        Card p1Card1 = player1.playCard();
        Card p1Card2 = player1.playCard();
        Card p1Card3 = player1.playCard();
        Card p1Card4 = player1.playCard();
        
        Card p2Card1 = player2.playCard();
        Card p2Card2 = player2.playCard();
        Card p2Card3 = player2.playCard();
        Card p2Card4 = player2.playCard();
        
        if (p1Card4.compare(p2Card4) == 1) //if player1 wins
        {
            System.out.println("Player 1 Wins!");
            player1.addCard(p1Card1);
            player1.addCard(p1Card2);
            player1.addCard(p1Card3);
            player1.addCard(p1Card4);
            player1.addCard(p2Card1);
            player1.addCard(p2Card2);
            player1.addCard(p2Card3);
            player1.addCard(p2Card4);
        }
                
        else if (p1Card4.compare(p2Card4) == -1) //if player2 wins
        {
            System.out.println("Player 2 Wins!");
            player2.addCard(p1Card1);
            player2.addCard(p1Card2);
            player2.addCard(p1Card3);
            player2.addCard(p1Card4);
            player2.addCard(p2Card1);
            player2.addCard(p2Card2);
            player2.addCard(p2Card3);
            player2.addCard(p2Card4);
        }
        else //if a war is declared
        {
                if (player1.numCards() >= 4 && player2.numCards() >= 4)
                    war(player1 , player2);
                else if (player1.numCards() == 3 || player2.numCards() == 3)
                    war2(player1 , player2);
                else if (player1.numCards() == 2 || player2.numCards() == 2)
                    war3(player1 , player2);
                else
                    war4(player1 , player2);    
        }
        
    }
    
    //pre: if two hands are one user has 3 cards
    //post: plays war when two cards are equal
    public static void war2(Hand player1, Hand player2)
    {
        System.out.println("WAR!!!");
        
        //Playing 2 Cards Facedown
        Card p1Card1 = player1.playCard();
        Card p1Card2 = player1.playCard();
        Card p1Card4 = player1.playCard();
        
        Card p2Card1 = player2.playCard();
        Card p2Card2 = player2.playCard();
        Card p2Card4 = player2.playCard();
        
        if (p1Card4.compare(p2Card4) == 1) //if player1 wins
        {
            System.out.println("Player 1 Wins!");
            player1.addCard(p1Card1);
            player1.addCard(p1Card2);
            player1.addCard(p1Card4);
            player1.addCard(p2Card1);
            player1.addCard(p2Card2);
            player1.addCard(p2Card4);
        }
                
        else if (p1Card4.compare(p2Card4) == -1) //if player2 wins
        {
            System.out.println("Player 2 Wins!");
            player2.addCard(p1Card1);
            player2.addCard(p1Card2);
            player2.addCard(p1Card4);
            player2.addCard(p2Card1);
            player2.addCard(p2Card2);
            player2.addCard(p2Card4);
        }
        else //if a war is declared
        {
                if (player1.numCards() >= 4 && player2.numCards() >= 4)
                    war(player1 , player2);
                else if (player1.numCards() == 3 || player2.numCards() == 3)
                    war2(player1 , player2);
                else if (player1.numCards() == 2 || player2.numCards() == 2)
                    war3(player1 , player2);
                else
                    war4(player1 , player2);    
        }
        
    }
    
    //pre: if two hands are one user has 2 cards
    //post: plays war when two cards are equal
    public static void war3(Hand player1, Hand player2)
    {
        System.out.println("WAR!!!");
        
        //Playing 1 Cards Facedown
        Card p1Card1 = player1.playCard();
        Card p1Card4 = player1.playCard();
        
        Card p2Card1 = player2.playCard();
        Card p2Card4 = player2.playCard();
        
        if (p1Card4.compare(p2Card4) == 1) //if player1 wins
        {
            System.out.println("Player 1 Wins!");
            player1.addCard(p1Card1);
            player1.addCard(p1Card4);
            player1.addCard(p2Card1);
            player1.addCard(p2Card4);
        }
                
        else if (p1Card4.compare(p2Card4) == -1) //if player2 wins
        {
            System.out.println("Player 2 Wins!");
            player2.addCard(p1Card1);
            player2.addCard(p1Card4);
            player2.addCard(p2Card1);
            player2.addCard(p2Card4);
        }
        else //if a war is declared
        {
                if (player1.numCards() >= 4 && player2.numCards() >= 4)
                    war(player1 , player2);
                else if (player1.numCards() == 3 || player2.numCards() == 3)
                    war2(player1 , player2);
                else if (player1.numCards() == 2 || player2.numCards() == 2)
                    war3(player1 , player2);
                else
                    war4(player1 , player2);    
        }
        
    }
    
    //pre: if two hands are one user has 1 card
    //post: plays war when two cards are equal
    public static void war4(Hand player1, Hand player2)
    {
        System.out.println("WAR!!!");
        
        //Playing 1 Card Faceup
        Card p1Card4 = player1.playCard();
        Card p2Card4 = player2.playCard();
        
        if (p1Card4.compare(p2Card4) == 1) //if player1 wins
        {
            System.out.println("Player 1 Wins!");
            player1.addCard(p1Card4);
            player1.addCard(p2Card4);
        }
                
        else if (p1Card4.compare(p2Card4) == -1) //if player2 wins
        {
            System.out.println("Player 2 Wins!");
            player2.addCard(p1Card4);
            player2.addCard(p2Card4);
        }
        else //if a war is declared
        {
            System.out.println("Game is tied. We all win!");        
        }
        
    }
}
/* OUTPUT

--------------------Configuration: War - JDK version 1.6.0_02  - --------------------
Player 1 Wins!
Player 1 Wins!
Player 2 Wins!
WAR!!!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 2 Wins!
Player 1 Wins!
Player 1 Wins!
Player 1 Wins!
Player 1 Wins!
Player 1 Wins!
Player 2 Wins!
Player 2 Wins!
Player 1 Wins!
Player 1 Wins!
Player 1 Wins!
Player 1 Wins!
Player 1 Wins!
Player 2 Wins!
Player 2 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 2 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
WAR!!!
Player 1 Wins!
Player 1 Wins!
Player 2 Wins!
Player 2 Wins!
Player 2 Wins!
Player 1 Wins!
Player 2 Wins!
Player 1 Wins!
...EDITED FOR SIZE...
PLAYER 2 WINS THE GAME!!!

Process completed. */

Introduction to Java Part 3: Classes, Objects, and Methods - Java

Just some notes from a Computer Science class on Java
Account checking = new Account();
Account = class
Checking = object
Class:
-Blueprint for an object…definition for the object.
-Can be many objects for one class once blueprint is made
-Nouns and verbs
-Public classes can be called in other classes, Private classes cannot.
class Window
Nouns (Variables):
-Location
-Size
-Contents
-Color
Verbs (Methods):
-Close
-Change Size
-Move

Object:
-Made from the blueprint (class)

Methods:
-Verbs of a class
-Setters
public void deposit(int amount) //method
{
   balance += amount //variable
}
void = not returning anything. Not giving anything back.
-'void' is the return type. It means nothing is returned by this method. Alternately, it could say 'int' or 'string' or any type of variable.

savings.balance();
-Calls the method balance from the object savings

Private Variables/Attributes:
-Nouns of a class
Ex.
class Account
Nouns:
-balance
-interestRate
Verbs:
-deposit
-withdraw
-postInterest
-getBalance

Constructor:
Ex. Of constructors
public Account() //Default Values
{
   balance = 0;
   interest = 0;
}

public Account(int bal, int rate) //Paremeters: bal, rate
{
  balance = bal;
  interest =rate;
}

Parameters/Arguments:
Account savings = new Account(200,2);
200 & 2 = Parameters
-Set properties of a class

Accessor:
Checking.getBalance();
-Returns a value, doesn’t set anything
-Getters

Introduction to Java Part 2 - Java

Output:
System.out.println (“text”);         //WORKS
System.out.println (“I want to print //WONT WORK
a really long message”); 
-The 2nd line won’t work, it will give an error, if your output goes to more than one line, change the code to the following:
System.out.println (“I want to print”) +
(“a really long message”);

Scanner Class:
-Makes input easy
-Imports special statements that are required for scanner class.
import java.util.*;
//or
import java.util.Scanner;
public class Hello
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in); //‘in’ can be changed, that is the name of the new Scanner.
int num;
double num2;
System.out.println (“Enter an integer”);
num = in.nextInt();
}
}
-This code takes the next integer typed into the keyboard and assigned it to the variable ‘num’
Escape Sequence:
-If I wanted to put a character like ‘ or “ the computer wont let me. What you have to do is put a \ then the character. \
char key = ‘\”’;
-The Variable ‘char’ would equal “
\n = New Line
\t = Tab


Debugging:
-Compile Errors (Gives error when compiling)
-Runtime Errors (Compiles fine but when you run it crashes)
-Logic Errors (Error in coding but computer doesn’t give an error)

Introduction to Java Part 1 - Java

Note: These are notes from 4 years ago when I took Computer Science AB in school.

Identifiers:
-Start with a letter.
-Then letters, numbers or ‘_’
-No spaces
-No Reserved Words
-Case sensitive

Naming Conventions:
-Use names not letters (i.e. instead of ‘g’ we use ‘grade’)
-Variable start lowercase
--If more than one word, first word is not capitalized every word after that is (ex. studentGrade, studentInClass)
-Class start uppercase
-All capitals only used for constants (ex. PI)

Data Types:
int (integer)
-May not hold decimals. If an integer is assigned to ‘3.14’ the value will be displayed as ‘3’.
double (floating-point number)
-Larger in memory than an integer. May hold decimals or integers. If double is assigned to ‘3’ the value will be displayed as ‘3.0’.
char (character)
-Must be defined with quotes ‘’ around the value. (ex. ‘value’). Can hold any character on the keyboard.
boolean (true or false)
-Can only hold the value ‘true’ or ‘false’

Variables:
How to Declare and Assign Variables:
int grade; //declaration
grade = 11; //assignment
//or
int grade = 11; //combining declaration and assignment
//or
int a,b; //creates a integer ‘a’ and and integer ‘b’

int = variable type
grade = variable
value of grade = 11

Math Operators:
Computer knows order of operations.
double y = 7.0;
double answer;
answer = 3.0 + 5.0;
answer = y – 2.5;
answer = y * 3.2;
answer = y / 2.0;
/*‘answer’ would only equal the value of 3.5 The computer goes down the list and ignores previous assignments.*/ 
double a ,b = 5.0; //creates a blank double, ‘a’ and creates a double with the value of 5.0, ‘b’
int x = 2;
a = b / x;
a = 2.5
a = (int) b / x;
a = 2.0. 
/*This is because b is converted into an integer for this equation. 5/2, an integer/integer, will result in an integer answer. The real answer is 2.5 but it discards the decimal making it 2. a is a double however, so the value of a is 2.0*/

Modulus Operator = %
-Only works with integers
int a = 7;
int b = 2;
int c;
c = a % b;
c = 7 % 2
c = 1
Printing:
System.out.println ( “bla” ); //prints out “bla”
System.out.println ( c ); //prints out the value of the variable c
System.out.println ( “c = “ + c); //prints out “c = “ and the value of c

Assignment Operators:
int a = 7;
a = a + 5 //adds 5 to the value of a
a = 12

Monday, July 12, 2010

Retrieving Sheet Names in Excel - C#

The following code returns an array of string; each element in the array is the name of a sheet in the excelFile.

The one parameter is a string to the path of the excel file.
public String[] GetExcelSheetNames(string excelFile)
{
     OleDbConnection objConn = null;
     System.Data.DataTable dt = null;

     try
     {
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                            "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        
        // Open connection with the database.
        objConn.Open();

        // Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if (dt == null)
        {
           return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        // Add the sheet name to the string array.
        foreach (DataRow row in dt.Rows)
        {
           excelSheets[i] = cleanSheetName(row["TABLE_NAME"].ToString());
           i++;
        }

        return excelSheets;
    }
    catch (Exception ex){return null;}

    finally
    {
      // Clean up.
      if (objConn != null)
      {
         objConn.Close();
         objConn.Dispose();
      }
      if (dt != null)
      {
         dt.Dispose();
      }
   }
}

Note: Credits cannot go to me for this one. I found most of this code on Google and only edited it slightly.

Reading Excel Column into a List - C#

Note: I'm sure there is a way to retrieve the column and sheet name from an Excel sheet...I just don't know how so for this program they must be specified as a parameter. The method to retrieve the name of an excel sheet can be seen here.

//Given a column name in an Excel sheet, it returns each cell of the column in an List of strings
//xlsDir = Directory of the excel sheet
//col = name of the column in sheet
//sheetName = the name of the excel sheet
//@return: Each element of the List is a cell in the column
public List excelColtoArr(string xlsDir, string col, string sheetName)
{
            
    string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; data source=" + xlsDir + "; Extended Properties='Excel 8.0;HDR=YES;'";
    OleDbConnection con = new OleDbConnection(connectionString);
    // Select using a Worksheet name
    string selectString = "SELECT * FROM [" + sheetName + "$]";

            
    OleDbCommand cmd = new OleDbCommand(selectString, con);

     List arr = new List();
     try
     {
         con.Open();
         OleDbDataReader theData = cmd.ExecuteReader();
         while (theData.Read())
         {
            arr.Add(replaceIllegalChars(theData[col].ToString().Trim()));
         }


     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     finally
     {
         con.Dispose();
     }

     return arr;
}

Replace Illegal XML Characters - C#

The following method replaces characters illegal in XML with their appropriate substitutes.

        /// 
        /// Removes illegal characters in an XML file with appropriate replacements
        /// 
        /// xml line        /// line with replacements made
        public string replaceIllegalChars(string line)
        {
            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;

            byte[] utf8bytes = System.Text.Encoding.UTF8.GetBytes(line);

            line = System.Text.Encoding.UTF8.GetString(utf8bytes);

            line = line.Replace("&", "&");
            line = line.Replace("<", "<");
            line = line.Replace("\"", """);
            line = line.Replace("\'", "'");
            line = line.Replace(">", ">");


            return line;

        }

Retrieving Files by Type - C#

The following code searches a given directory and all subdirectories for files of a certain type and moves them to a specified directory.

static void RetriveFiles(DirectoryInfo srcDir, DirectoryInfo finalDir, string type)
        {
            FileInfo[] files = srcDir.GetFiles("*" + type);
            foreach (FileInfo file in files) 
            {
                file.MoveTo(finalDir.FullName);
            }
            DirectoryInfo[] directories = srcDir.GetDirectories();
            foreach (DirectoryInfo subdirectory in directories)
            {
                RetriveFiles(subdirectory, finalDir, type); 
            }
        }

Renaming All Files in a Directory - C#

The following method searches a given directory (dir), and all subdirectories for files. Each file is renamed with a time stamp and an additional tag specified by a user (userADD).


        public static void renameDir(DirectoryInfo dir, string userADD)
        {
            System.DateTime dt = System.DateTime.Now;
            string timeHolder = String.Format("{0:MMddyyyy}", dt);

            DirectoryInfo renamed = new DirectoryInfo(dir.FullName + "\\renamed\\");
            if (!renamed.Exists)
                renamed.Create();


            foreach (FileInfo file in dir.GetFiles())
            {
                string temp = (renamed.FullName + "\\" + file.Name.Substring(0, file.Name.Length - 4) +
                            "_" + userADD +
                            "_" + timeHolder +
                            file.Extension);

                //file.CopyTo(temp);
                File.Move(file.FullName, temp);
                
            }
            foreach (DirectoryInfo subDir in dir.GetDirectories())
            {
                if (!subDir.Name.Equals("renamed"))
                    renameDir(subDir , userADD);
            }
        }

Reading a Text File Using StreamReader - C#

Before using StreamReader, you will need to utilize System.IO.

Paste this code at the top of your program:
using System.IO;

There are many ways to read a text file, but by far the easiest is StreamReader. The StreamReader constructor takes one parameter, the Stream to read. The code is pretty self explanatory. It reads each line of the file and prints it out in Console. The function ReadLine(), not only returns the next line, but sets the programs pointer at the following one, so be careful.

StreamReader sr = new StreamReader(@"C:\test.txt")
string line = null;

while( (line = sr.ReadLine()) != null) //reading line by line to the end of the file
{
   Console.WriteLine(line);
}

Alternately, you could read an entire file into an array of strings, splitting it line by line, then iterate through the array later.

Note: This will crash on really big text files because they are too big to be stored in a string during ReadToEnd().
Note2: To use Regex, you will also need to add:
using System.Text.RegularExpressions;

The following code reads a text file to the end and prints out every line:
StreamReader sr = new StreamReader(@"K:\log.txt");
            
                string fullText = sr.ReadToEnd();
                string[] lines = Regex.Split(fullText, Environment.NewLine);

                foreach (string s in lines)
                    Console.WriteLine(s);

Adding Date & Time Stamp to Code Using DateTime - C#

It is often useful to add a date or time stamp to files you are processing, or log entries you are adding. To do this we use DateTime.

Here is some sample code using DateTime:
System.DateTime dt = System.DateTime.Now;
            string timeHolder = String.Format("{0:MMddYYYY}", dt);
            Console.WriteLine(timeHolder); //Output: 07122010

You can alter the format of the date and time using different forms of String.Format. Here are some examples:
String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

Accepting Command Line Arguments - C#

Often times it is useful or necessary to let the user input arguments in command prompt prior to the program being run. These arguments are called command line arguments.

In order to access these arguments, we must use the Main functions single parameter: args.

static void Main(string[] args)
{
}

The command line arguments are stored in the array args. The first one can be accessed at args[0], the second at args[1]...etc.

Note: Since args is simply an array of user inputs, it is good to check to make sure the user inputted correctly formed arguments.

Here is an example of a code that requires one argument. It checks if the user used command line arguments, and if not, prompts the user for input.

Code:
static void Main(string[] args)
        {
            string dir = null;

            if (args.Length == 1)
            {
                dir = args[0];
            }
            else
            {
                Console.WriteLine("Please Enter Path: ");
                dir = Console.ReadLine();
            }

            start(dir);
        }

String Manipulation: GetStringBetween & GetStringAfter - C#

Here are some methods to ease with string manipulation.


GetStringBetween - Given a source string, it reads between two separate strings.
Ex. If Source String = "The Cat Ran", GetStringBetween(Source, "The ", " Ran) would return "Cat"

GetStringAfter - Given a source string, returns everything after the first instance of a string
Ex. If Source String = "The Cat Ran", GetStringAfter(Source, "The ") would return "Cat Ran"


Code:
        private static string GetStringAfter(string src, string start)
        {
            int lnStart;
            string ret = "";
            if (src.Contains(start))
            {
                lnStart = src.IndexOf(start, 1) + start.Length;
                if(lnStart != -1)
                    ret = src.Substring(lnStart + 1, src.Length-lnStart-1);
            }

            return ret;
        }
        private static string GetStringBetween(string src, string start, string end)
        {
            int lnStart, lnEnd;
            string ret = "";
            if (src.Contains(start) && src.Contains(end))
            {
                lnStart = src.IndexOf(start, 1) + start.Length;
                lnEnd = src.IndexOf(end);
                if(lnStart != -1 && lnEnd != -1)
                    ret = src.Substring(lnStart + 1, lnEnd - lnStart - 1);
            }
  
                return ret;
        }

Iterate Through All Files and Folders in a Directory - C#

The following code iterates through a given directory, first processing all files in a directory, then searching each of its subdirectories. It uses a concept known as recursion, which is a self-calling method.

Code:
//Iterates through all directories and subdirectories, printing out each file name it encounters.
public static void printFileNames(DirectoryInfo dir)
{
   foreach(FileInfo file in dir.GetFiles())
   {
      Console.WriteLine(file.Name);
   }
   foreach(DirectoryInfo subDir in dir.GetDirectories())
   {
      printFileNames(subDir);
   }
}

Friday, July 9, 2010

1.2 Textboxes Command Buttons Labels and Listboxes - VB6

TextBoxes - These are possibly the most common objects you will use in VB. Basically, anytime the user needs to input data into the program, you will use a textbox. For example, if the user needs to type in a user name and password, he would type it in a textbox. To create a textbox, go to the left hand tool bar and click this icon.

Go to the form. Click and drag the textbox to as big as you want it to be. Once created, name the textbox with a name starting with "txt". You can also change what the actual text is by changing the text property.
If you wanted to later change the text inside a textbox, you would use the code
Code:
txtNAMEOFTEXTBOX.Text = "whatever you want"

Command Buttons - Command buttons are exactly what they sound like, buttons that do commands. Anytime you want an action preformed at the users request, use a command button. For example, if on the click of a button you want to erase the text in a form, or log in, you would use a command button. To make a command button, go to the left hand bar and click the command button icon.

Go to the form. Click and drag until the button is the size you want it to be. Make sure you name command buttons starting with "cmd". Another property you will often use is the 'Caption' property, which changes the text that is displayed on the button. To write the code that the button will do, double click the button on the form. A code window should pop up, and the cursor should be in the appropriate place.

Labels - Labels are...labels. They are used when you want to label anything such as a textbox, or a listbox. You can even use a label as a status bar. Like the other elements, click the label button on the left hand bar, and draw it onto the form.

Label's names should start with "lbl". To change what you want the label to say, use the caption property, or if you want to change the label's text while the program is running, use code like this
Code:
lblNAMEOFLABEL.Caption = "whatever you want"
Other label properties that can be changed are the background, text colors, font, and many more.

Listboxes - A listbox is almost exactly like a textbox, except that it cannot be directly edited, and that a listbox has an infinate amount of lines. Each line of the listbox is treated as its own textbox. Listboxes are very often used as a log for programs. To create a listbox, go to the left hand toolbar, select the listbox icon, and draw it on the form.

Name all listboxes starting with "lst".
Ex. lstNAMEHERE
Some handy code to know with a listbox is how to add an item to the list. To do this use this code:
Code:
lstNAME.AddItem "whatever"



Download .doc & .pdf versions here:
http://www35.zippyshare.com/v/95632623/file.html

1.1 Getting to Know VB6 - VB6

NOTE: PICTURES ARE AVALIABLE IN .pdf and .doc VERSIONS DOWNLOAD LINK BELOW.

This tutorial is to help you get oriented with vb6, for those that want to learn how to program.


1.Open Microsoft Visual Basic 6 (VB6)

2.A prompt asks you whether you want to open an existing project, or create a new one. Since you haven't made anything yet select 'Standard EXE' under the NEW tab.

3.A form appears on screen. This form is your workspace, this is what the user will see when he opens the program.

4.Notice on the top of the screen you have the Menu Bar. File..Edit..Tools...ect. Get to know this area as tyou will be useing it an awful lot. Some common things you will be doing in the Menu Bar are:

File> Make PROGRAMNAME.exe
File> Save Project
Project> Add Component

Also on the top bar there are some handy icons, such as the floppy disk (automatically saves the project), the folder icon (opens another project), or the blue play button (runs your project).

5.On the left hand side of the screen is the toolbar. Each icon represents a unique tool. Each tool had a different function. Some common tools you will be using are the command button tool, the textbox tool, and the label tool.

6.On the lower-right hand side of the screen is the properties window. The object that selected propertie's will show up in the property window. Every object will have a 'NAME' property. Unlike most other properties, this needs to be unique. No two objects may have the same name. Each object is given a default name (Text1, Label2) but these are often very hard to remeber. Programmers, being the crafty people they are, have thought of a way to make each object's purpose easier to identify in its name.
Format:
--First three letters represent type of object
---EX. Textbox = txt. Label = lbl. Option Bar = opt. Command Button = cmd.
--The next letter is a capital.
EX. A textbox that will have a username in it could be called txtUser. A command button that initiates a login could be called cmdLogin.
Other properties you will often use are:
Caption
Value
Text
Enabled

7. In the upper right hand corner of the screen is the project tree. It contains the current project, and all of its components and forms.


You should be pretty orientated with the layout of VB6 now. As a reminder, don't forget to name each object with a unique name, as you create them.

This tutorial was created by Calvin Hawkes



.PDF & .DOC Versions:
http://www35.zippyshare.com/v/30984235/file.htm