Back to main page.

SnippetName/explanation:


I
mage


Code

read this the wrong waywrite that in the box-> derdnuheno + eno

 

 

ImageUpload:
jump to:1Limit keybord keys to only numbers and backspace
jump to:2 DoWhileLoops
jump to:3ENUM
jump to:4Break, Continue, goTo, Return
jump to:5Diffrence in public, private, protected and protected internal
jump to:6REF
jump to:7OUT
jump to:8Classmember Properties
jump to:9Access Modifiers for properties
jump to:10List
jump to:11Random spawning boxes
jump to:12Connect to MySql DB
jump to:13Boxes with life
jump to:14Key Press detection
jump to:15healt and color detection 100% white 75%green and so on
jump to:16Health numbers instead of X
jump to:17knwlege_rew 1
jump to:18Simple input/output test for C#
jump to:19ENUM test
jump to:20Overload Constructor test
jump to:21Private Constructor test
jump to:22Static Constructor
jump to:23Inheritance :base test
jump to:24ageFearTest
jump to:25Input test
jump to:26ThisKeyWord Test
jump to:27Text to Num edit
jump to:28Draw Text from File
jump to:29Simple command system
jump to:30Random Placement
jump to:31Recreating the tree command
jump to:32Testing Sprite Blending
jump to:332d Gravity
jump to:34Auto Aiming
jump to:35Collision test
jump to:36Get the MD5 value of a string
jump to:37Matrix
jump to:38Array Test
jump to:39Arrays test 2
jump to:40Arrays test 3
jump to:41Background worker test
jump to:42Get vaules from textboxes and put in to array
jump to:43Loop trough textboxes and null all.
jump to:44DB connection test
jump to:45add number to back of string variable
jump to:46input console
jump to:47get directoryname.
jump to:48Read from text file
jump to:49write to a text file
jump to:50Associative Array
jump to:51List files C#
jump to:52Logmein . com auto login C# code
jump to:53Move Mouse C# Macro and Inputblocker from keyboard and mouse while moving
jump to:54String to Int Parse c#
jump to:55c# CPU RAM monitor
jump to:56string to int og int to string.
jump to:57Foreach loop based on textbox names
jump to:58Calculate method from declaration /
jump to:59Calculate method from declaration of other class
jump to:60Multi Treading c# test
jump to:61Find the RGB value based on Mouse location C#
jump to:62String to array with Backgroundworker test
jump to:63Function to get random number
jump to:64Pass int by value and by reference.
jump to:65Get Set test C#
jump to:66Get Set test2 c#
jump to:67Replace text in string
jump to:68Enum test C# dont use magic numbers out them in a enum or make a constant
jump to:69String manipulation Stringbuilder in C# appending a variable
jump to:70get the second highest number inn a array C#
jump to:71DayOfWeek to number loop test
jump to:72Force update on the UI tread
jump to:73how to dynamic use textbox names in loop
jump to:74List create C#
jump to:75Write to file
jump to:76Testing Stack and heap memory refrence
jump to:77Testing Stack and heap memory refrence
jump to:78Stopwatch
jump to:79Using System.Diagnostic
jump to:80get set test
jump to:81PERL regex test
jump to:82PERL regex test 2 put domiant test to varialbe
jump to:83advanced Struct test
jump to:84Bouncing balls code.
jump to:85Sequence tester game
jump to:86sound class for above game
jump to:87Keys Loop test tool
jump to:88Color Check Tool
jump to:89kill process c#
jump to:90matrix code
jump to:91read and write to file
jump to:92grid spawn
jump to:93squareBox Corner Array
jump to:94Covert String to Byte[] array test
jump to:95Timer / stopwatch hos to time a function
jump to:96Delegate pointer test
jump to:97Delegate Using an Anonymous Method
jump to:98Delegate with a lambda expression
jump to:99Delegate that returns Void
jump to:100Delegate that returns Void using no arguments
jump to:101Delegate with a lambda expression geting int from key press from user.
jump to:102Generating 100 random numbers and finding the avarage
jump to:103List string var
jump to:104List with objects
jump to:105Console Calculator c#
jump to:106logmein v2
jump to:107web page, wait for full load
jump to:108get text from web page
jump to:109Background Worker III
jump to:110console meny test
jump to:111Progressbar simple
jump to:112opne wiki snippet
jump to:113Speed test
jump to:114Get input from Console in to Win Form
jump to:115Tread and delegate spawn/ multi treading
jump to:116LINQ test get max
jump to:117delegate Func test, func returns value
jump to:118Func test two param
jump to:119Func teste 1 param
jump to:120func test 2 param
jump to:121func teste 3 param
jump to:122Action test 2 param
jump to:123async delegate test
jump to:124Extract from embeded resource
jump to:125delegate test
jump to:126200mb byte array
jump to:127Get RealTimeFeedBack form second tread, Bacground worker CMD
jump to:128Encrypt decrypt methods
jump to:129Two Threads 1 Background worker updating GUI
jump to:130Design Flow Single Responsibility Prinsiple
jump to:131Modulus test, every 100th number
jump to:132event test
jump to:133RavenDB demo test writing to db
jump to:134Singelton desig pattern
jump to:135Generics simple test
jump to:136Exstension method test, adding finctionalty to class with extension method
jump to:137delegate
jump to:138MVC pattern
jump to:139Interface test
jump to:140Interface test 2
jump to:141Interface test 3
jump to:142move files
jump to:143Thread Updates to Gui Thread
jump to:144check screen code.
jump to:145queue test
jump to:146Delegate test



Name:
Limit keybord keys to only numbers and backspace
14:37:53 19/07/2009 CODE:
//begrens key press til tall og back key//
private void Form2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (((e.KeyChar < '0') || (e.KeyChar > '9')) && (e.KeyChar != (char)Keys.Back))
    //if ((e.KeyChar < "0" || e.KeyChar > "9") && e.KeyChar != ControlChars.Back && e.KeyChar != ".")
    {
        e.Handled = true;
    }
}
//END begrenss key press til tall og back key//


Name:
DoWhileLoops
14:38:23 19/07/2009 CODE:
static void Main(string[] args)
{
    sbyte i = 1;
 
    do
    {
        Console.WriteLine("int i = " + i);
        i++;
    } while (i < 5);
 
    Console.WriteLine("Finish");
    Console.ReadLine();
}




Name:
ENUM
14:53:39 19/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace enum
{
    enum Browser
    { 
        IE = 5,
        FireFox,
        Opera
    }

    enum IRCode
    { 
        Play = 53,
        Stop = 16,
        Rewind = 12,
        FastFoward = 13

    }

    enum GameState
    { 
        TitleScreen,
        Playing,
        LevelChange,
        Died,
        GameOver
    }

    class Program
    {
        static void Main(string[] args)
        {
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>//
            Browser myBrowser;
            myBrowser = Browser.FireFox;

            int i = (int) myBrowser;

            Console.WriteLine(myBrowser);
            Console.WriteLine(i);

            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>//
            IRCode transmitCode;
            //Loop start
            // --- get button press raw data
            transmitCode = IRCode.Play; //(IRCode)53; <-- kan og bruke
                transmit(transmitCode);
            // /Loop

            

            //3>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            GameState gameState;
            gameState = GameState.Died;

            switch (gameState)
            { 
                case GameState.TitleScreen:
                    Console.WriteLine("At the titlescreen");
                    break;
                case GameState.Died:
                    Console.WriteLine("you are dead");
                    break;
            }
            Console.ReadLine();
        }

        static void transmit(IRCode code)
        {
            Console.WriteLine("Transmission Acction: " + code);
            Console.WriteLine("transmitting IR code: " + (int)code);
        }

    }
}




Name:
Break, Continue, goTo, Return
14:55:12 19/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace manipulere_loops
{
    class Program
    {
        static void Main(string[] args)
        {
            //breakX();
            //continueX();
            //goToX();
            //----------
            returnX();
            Console.WriteLine("Finished");
            Console.ReadLine();
            //----------
        }

        static void breakX()
        {
            int i = 1;

            while (i < 5)
            {
                if (i == 3)
                {
                    break;
                }

                Console.WriteLine("i = " + i++);
            }
            Console.WriteLine("Finish");
            Console.ReadLine();
        }

        static void continueX()
        {
            int i = 0;

            while (i < 5)
            {
                i++;
                if (i == 3)
                {
                    continue;
                }
                Console.WriteLine("i = " + i);
            }
            Console.WriteLine("Finished");
            Console.ReadLine();
        }

        static void goToX()
        {
            int i = 1;

            while (i < 5)
            {
                if (i == 3)
                {
                    goto jumpOut;
                }
                Console.WriteLine("i = " + i++);
            }
            Console.WriteLine("Finished");
            jumpOut:
                Console.WriteLine("Jumped here");
            Console.ReadLine();
        }

        static void returnX()
        {
            int i = 1;
            while (i < 5)
            {
                if (i == 3)
                {
                    return;
                }
                Console.WriteLine("i = " + i++);

            }
           
        }

 
    }
}




Name:
Diffrence in public, private, protected and protected internal
19:12:25 19/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassMembers_fields
{
    class Program
    {
        static void Main(string[] args)
        {
            GameItem player = new GameItem();
            player.name = "Bob2";
            player.health = 100000;
            player.DisplayHealth();
            Console.WriteLine(player.gender);
            Console.ReadKey();
        }
    }
    //diffrence in public, private, protected and protected internal//
    class GameItem
    {
        public string name;
        //protected internal int health = 50;
        //protected int health = 50;
        public int health = 50;
        //private int health = 50;
        public readonly char gender = 'F';

        void ResetHealth()
        {
            health = 100;
        }

        public void DisplayHealth()
        {
            //ResetHealth();
            Console.WriteLine(health);    
        }
    }

    class Enemy : GameItem
    {
        //hide the gameitem health//
        new private float health;

        void Regenerate()
        {
            health++;
        }
    }
}




Name:
REF
01:54:06 20/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int A = 5;
            Console.WriteLine("Before call_ A= " + A);
            DoubleMe(ref A);
            Console.WriteLine("After call_ A= " + A);

            Console.ReadLine();
        }

        static void DoubleMe(ref int num)
        {
            num *= 2;
        }
    }
}




Name:
OUT
13:20:05 20/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace OUT_test
{
    class Program
    {
        static void Main(string[] args)
        {
            Vector2 vector = new Vector2(15.5f, 12.2f);
            float x;
            float y;

            getFloats(vector, out x, out y);
            Console.WriteLine("x = " + x);
            Console.WriteLine("y = " + y);
            Console.ReadLine();
        }
        //out is used when the method inititates teh variable
        //if you dont use out in this scenario you wold get a comnpiler error 
        //Use of unassigned local variable 'x'	

        static void getFloats(Vector2 vector,out float x, out float y)
        {
            x = vector.X;
            y = vector.Y;
        }
    }
}




Name:
Classmember Properties
17:04:22 20/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace classmembers_Properties
{
    class Program
    {
        static void Main(string[] args)
        {
            GameItem player = new GameItem();
            Console.WriteLine("Player's health is: " + player.Health);
            Console.WriteLine("Damage Taken: " + player.DamageTaken +"\n");
            
            player.Health -= 10;
            Console.WriteLine("Player's health is: " + player.Health);
            Console.WriteLine("Damage Taken: " + player.DamageTaken + "\n");
            //hit player with 200 but the set propertie will not let healt go negative
            player.Health -= 200;
            Console.WriteLine("Player's health is: " + player.Health);
            Console.WriteLine("Damage Taken: " + player.DamageTaken + "\n");
            Console.ReadLine();
        }
    }

    class GameItem
    {
        const int DEFAULT_HELATH = 100;
        private int health = DEFAULT_HELATH;

        public int Health
        {
            get { return health; }
            set 
            { 
                health = value;
                if (health < 0)
                    health = 0;
            }
        }

        public int DamageTaken
        {
            get { return DEFAULT_HELATH - health; }
        }
    }
}




Name:
Access Modifiers for properties
17:23:47 20/07/2009 CODE:
Access Modifiers

public             
//accessible to all methods in any assemblies

private            
//accessible only in the defining type

protected         
//Only accessible in the defining type or the derived type

internal          
//accessible to all methods int teh defining assembly 
//its like public but only for the defineing assembly

protected internal 
//accessible to all methods int teh defining assembly 
//OR accesible to dirived types in exsternal assemblyes

OTHER modifiers

static
//the propertie will belong to the class

new
//hide an inhereted propertie

virtual
//means that the implimentation of the propertie can be changed by in a //dirived class

abstract
//must be defined in a abstract class

override
//new overide proberties



           




Name:
List
11:40:03 21/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace List_Generic_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            List enemies = new List();

            // count
            Console.WriteLine("Total number of enemies: " + enemies.Count);
            Console.WriteLine();

            // add
            enemies.Add(new Enemy("Spider"));
            enemies.Add(new Enemy("AxeMan"));
            enemies.Add(new Enemy("Dog"));

            Console.WriteLine("Total number of enemies: " + enemies.Count);
            Console.WriteLine();

            // retrieving an item by index
            Enemy tempEnemy = enemies[2];
            tempEnemy.Update();
            Console.WriteLine();

            // for loop
            for (int i = 0; i < enemies.Count; i++)
            {
                tempEnemy = enemies[i];
                Console.WriteLine("The selected enemy is: " + tempEnemy.Name);
            }
            Console.WriteLine();

            // foreach
            foreach (Enemy enemy in enemies)
            {
                enemy.Update();
            }
            Console.WriteLine();

            // remove
            tempEnemy = enemies[1];
            enemies.Remove(tempEnemy);

            Console.WriteLine();
            Console.WriteLine("Enemies after removal: ");
            // foreach
            foreach (Enemy enemy in enemies)
            {
                Console.WriteLine(enemy.Name);
            }
            Console.WriteLine();
            enemies.RemoveAt(0);

            Console.WriteLine("Enemies after removal: ");
            foreach (Enemy enemy in enemies)
            {
                Console.WriteLine(enemy.Name);
            }
            Console.WriteLine();
            
            // clear list
            enemies.Clear();

            // count
            Console.WriteLine("Total number of enemies: " + enemies.Count);
            Console.ReadLine();
        }
    }
    class Enemy
    {
        public string Name;

        public Enemy(string name)
        {
            Name = name;
        }

        public void Update()
        {
            Console.WriteLine("Updating enemy: " + Name);
        }
    }  
}




Name:
Random spawning boxes
13:49:45 21/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;


namespace Box_X
{
    class Program
    {


        static List boxes;
        static Random random;
        static public bool boxA = false;
        static public bool boxB = false;
        static public bool boxC = false;
       
        static void Main(string[] args)
        {
            boxes = new List();
            random = new Random();
          


            Box newBox;
            newBox = new Box();
            newBox.Velocity = new Point(1, 1);
            newBox.Color = ConsoleColor.Green;
            newBox.Charter = 'X';
            boxes.Add(newBox);



            for (int i = 0; i < 2; i++)
            {
                AddRandomBox(ConsoleColor.Red);
                AddRandomBox(ConsoleColor.Yellow);
                AddRandomBox(ConsoleColor.Blue);
            }



            while (true)
            {
                Console.Clear();

                foreach (Box box in boxes)
                {
                    box.Update();
                    box.Draw();
               
                }
                if (boxA == true)
                {
                    Box newBox2;
                    newBox2 = new Box();
                    newBox2.Velocity = new Point(1, 1);
                    newBox2.Color = ConsoleColor.Cyan;
                    newBox2.Charter = '°';
                    boxes.Add(newBox2);
                }
                if (boxB == true)
                {

                    Box newBox2;
                    newBox2 = new Box();
                    newBox2.Velocity = new Point(random.Next(1, 4), random.Next(1, 4));
                    newBox2.Color = ConsoleColor.Cyan;
                    newBox2.Charter = '±';
                    boxes.Add(newBox2);
                }
                if (boxes.Count >= 100)
                {
                    boxes.Clear();
                }
                
                System.Threading.Thread.Sleep(100);
            }

     

        }

        static public void AddRandomBox(ConsoleColor color)
        {
            Box box;
            box = new Box();
            box.Color = color;
            box.Velocity = new Point(random.Next(1, 4), random.Next(1, 4));
            box.Position = new Point(random.Next(Console.WindowWidth), random.Next(Console.WindowHeight));
            box.Charter = '█';
            boxes.Add(box);
        }

    }

}


using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;


namespace Box_X
{
    class Box
    {
        private Point position;
        private Point velocity;
        private ConsoleColor color;

        private char charter;  

        #region properties

        public Point Position
        {
            get { return position; }
            set { position = value; }
        }
        public Point Velocity
        {
            get { return velocity; }
            set { velocity = value; }
        }
        public ConsoleColor Color
        {
            get { return color; }
            set { color = value; }
        }
        public char Charter
        {
            get { return charter; }
            set { charter = value; }
        }

        #endregion

        #region metods

        public void Update()
        {
            position.X += velocity.X;
            position.Y += velocity.Y;

            CheckWallCollision();
        }

        public void Draw()
        {
            Console.ForegroundColor = color;
            Console.SetCursorPosition(position.X, position.Y);
            Console.Write(Charter);
        }

        private void CheckWallCollision()
        {
            if (position.X < 0)
            {
                position.X = 0;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Yellow;
                Program.boxA = true;
            }
            else if (position.X > Console.WindowWidth - 2)
            {
                position.X = Console.WindowWidth - 2;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Green;
                Program.boxB = true;
            }

            if (position.Y < 0)
            {
                position.Y = 0;
                velocity.Y *= -1;
                Console.ForegroundColor = ConsoleColor.Red;
                Program.boxA = false;
            }
            else if (position.Y > Console.WindowHeight - 2)
            {
                position.Y = Console.WindowHeight - 2;
                velocity.Y *= -1;
                Console.ForegroundColor = ConsoleColor.Blue;
                Program.boxB = false;
            }
        }

        #endregion

    }
}




Name:
Connect to MySql DB
14:00:02 21/07/2009 CODE:
try
{ 
     //connect til DB//
     MySqlConnection mysqlCon = new MySqlConnection("server=#; Database = #; user id=#; password=#;");

     //1 spørring//
     MySqlCommand cmd1 = new MySqlCommand("SELECT brukernavn From bruker where ID = '" + br1id.Text +"';", mysqlCon);
     mysqlCon.Open();
              
     br1txt3.Text = cmd1.ExecuteScalar().ToString();
     catch (Exception ex)
     {
                 MessageBox.Show(ex.Message, "Error in Processing SQL", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
}    




Name:
Boxes with life
16:50:44 21/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;


namespace Box_X
{
    class Program
    {


        static List boxes;
        static Random random;


        static public bool boxA = false;
        static public bool boxB = false;
        static public bool boxC = false;
       
        static void Main(string[] args)
        {
            boxes = new List();
            random = new Random();



            Box newBox;
            newBox = new Box();
            newBox.Velocity = new Point(1, 1);
            newBox.Color = ConsoleColor.Green;
            newBox.Charter = 'X';
            boxes.Add(newBox);

            //Console.WriteLine("Box health is: " + newBox.Health);


            for (int i = 0; i < 2; i++)
            {
                AddRandomBox(ConsoleColor.Red);
                AddRandomBox(ConsoleColor.Yellow);
                AddRandomBox(ConsoleColor.Blue);
            }



            while (true)
            {
                Console.Clear();


              

                //edited the foreach to a for loop for the LIFE handeling.
                //foreach (Box box in boxes)
                for (int i = boxes.Count - 1; i >= 0; i--)
                {
                   
                    boxes[i].Update();
                    if (boxes[i].Health == 0)
                    {
                        boxes.RemoveAt(i);
                        continue;
                    }
                    boxes[i].Draw();
               
                }
                


                System.Threading.Thread.Sleep(10);
            }

     

        }

        static public void AddRandomBox(ConsoleColor color)
        {
            Box box;
            box = new Box();
            box.Color = color;
            box.Velocity = new Point(random.Next(1, 4), random.Next(1, 4));
            box.Position = new Point(random.Next(Console.WindowWidth), random.Next(Console.WindowHeight));
            box.Charter = '█';

            boxes.Add(box);
        }

      }
    }


using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;


namespace Box_X
{
    class Box
    {
        private Point position;
        private Point velocity;
        private ConsoleColor color;
        //new variables for LIFE handeling
        const int WALL_DAMAGE = 10;
        const int DEFAULT_HEALTH = 100;
        public int health = DEFAULT_HEALTH;
        //----//

        private char charter;  

        #region properties
        // new Propertie for LIFE handeling
        public int Health
        {
            get { return health; }
        }
        //----//

        public Point Position
        {
            get { return position; }
            set { position = value; }
        }
        public Point Velocity
        {
            get { return velocity; }
            set { velocity = value; }
        }
        public ConsoleColor Color
        {
            get { return color; }
            set { color = value; }
        }
        public char Charter
        {
            get { return charter; }
            set { charter = value; }
        }

        #endregion

        #region metods

        public void Update()
        {
            position.X += velocity.X;
            position.Y += velocity.Y;

            CheckWallCollision();
        }

        public void Draw()
        {
            Console.ForegroundColor = color;
            Console.SetCursorPosition(position.X, position.Y);
            Console.Write(Charter);
        }
        //new method in LIFE handeling
        public void TakeDamage(int damage)
        {
            health -= damage;
            if (health < 0)
                health = 0;
        }
        //----//
        private void CheckWallCollision()
        {
            if (position.X < 0)
            {
                position.X = 0;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Yellow;
                Program.boxA = true;
                //calling wall hit in LIFE handleing
                ProcessWallHit();
               
            }
            else if (position.X > Console.WindowWidth - 2)
            {
                position.X = Console.WindowWidth - 2;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Green;
                Program.boxB = true;
                //calling wall hit in LIFE handleing
                ProcessWallHit();
            }

            if (position.Y < 0)
            {
                position.Y = 0;
                velocity.Y *= -1;
                Console.ForegroundColor = ConsoleColor.Red;
                Program.boxA = false;
                //calling wall hit in LIFE handleing
                ProcessWallHit();
                
            }
            else if (position.Y > Console.WindowHeight - 1)
            {
                position.Y = Console.WindowHeight - 2;
                velocity.Y *= -1;
                Console.ForegroundColor = ConsoleColor.Blue;
                Program.boxB = false;
                //calling wall hit in LIFE handleing
                ProcessWallHit();
            }
        }
        //new method in LIFE handeling
        private void ProcessWallHit()
        {
            TakeDamage(WALL_DAMAGE);
        }
        //----//



        #endregion

    }
}




Name:
Key Press detection
17:57:20 21/07/2009 CODE:
                // added this to Boxes to spawn 1 box each 
                //time SPACE was pressed
                if (Console.KeyAvailable)
                {
                ConsoleKeyInfo keyinfo = Console.ReadKey();
                
                    if (keyinfo.Key == ConsoleKey.Spacebar)
                    {
                        AddRandomBox(ConsoleColor.Red);
                    }
                }




Name:
healt and color detection 100% white 75%green and so on
15:55:59 22/07/2009 CODE:
namespace Box_X
{
    class Program
    {
        static List boxes;
        static Random random;


        static public bool boxA = false;
        static public bool boxB = false;
        static public bool boxC = false;
       
        static void Main(string[] args)
        {
            boxes = new List();
            random = new Random();
            //oldState = Keyboard.GetState();

            while (true)
            {
                Console.Clear();
                
                for (int i = boxes.Count - 1; i >= 0; i--)
                {
                   
                    boxes[i].Update();
                    if (boxes[i].Health == 0)
                    {
                        boxes.RemoveAt(i);
                        continue;
                    }
                    boxes[i].Draw();

                    
                }
                
                if (Console.KeyAvailable)
                {
                ConsoleKeyInfo keyinfo = Console.ReadKey();
                
                    if (keyinfo.Key == ConsoleKey.Spacebar)
                    {
                        AddRandomBox();
                    }
                }

                //UpdateInput();
                System.Threading.Thread.Sleep(100);
            }
        }
        
       



        static public void AddRandomBox()
        {
            Box box;
            box = new Box();
            // Runs new method
            box.Initalize();
           
            box.Velocity = new Point(random.Next(1, 4), random.Next(1, 4));
            box.Position = new Point(random.Next(Console.WindowWidth), random.Next(Console.WindowHeight));
            box.Charter = '█';
            boxes.Add(box);
        }
      }
    }

namespace Box_X
{
    class Box
    {
        private Point position;
        private Point velocity;

        // Changed the Color Field to a list
        // OLD ->private ConsoleColor color;
        private List colors;

        const int WALL_DAMAGE = 10;
        const int DEFAULT_HEALTH = 100;
        public int health = DEFAULT_HEALTH;
      

        private char charter;  

        #region properties
       
        public int Health
        {
            get { return health; }
        }
       

        public Point Position
        {
            get { return position; }
            set { position = value; }
        }
        public Point Velocity
        {
            get { return velocity; }
            set { velocity = value; }
        }
        //removed the Color properties
        //public ConsoleColor Color
        //{
        //    get { return color; }
        //    set { color = value; }
        //}
        public char Charter
        {
            get { return charter; }
            set { charter = value; }
        }

        #endregion

        #region metods
        // created a nye method for color list init
        public void Initalize()
        {
            colors = new List();
            colors.Add(ConsoleColor.Red);
            colors.Add(ConsoleColor.Yellow);
            colors.Add(ConsoleColor.Green);
            colors.Add(ConsoleColor.White);
            colors.Add(ConsoleColor.Blue);

        }



        public void Update()
        {
            position.X += velocity.X;
            position.Y += velocity.Y;

            CheckWallCollision();
        }

        public void Draw()
        {
            //here i run the color check
            float percent =(float)health / DEFAULT_HEALTH;
            int colorIndex = (int)(percent * colors.Count);
            colorIndex = Math.Min(colorIndex, colors.Count - 1);

            Console.ForegroundColor = colors[colorIndex];
            Console.SetCursorPosition(position.X, position.Y);
            Console.Write(Charter);
        }
     
        public void TakeDamage(int damage)
        {
            health -= damage;
            if (health < 0)
                health = 0;
        }
  
        private void CheckWallCollision()
        {
            if (position.X < 0)
            {
                position.X = 0;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Yellow;
                Program.boxA = true;
                
                ProcessWallHit();
               
            }
            else if (position.X > Console.WindowWidth - 2)
            {
                position.X = Console.WindowWidth - 2;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Green;
                Program.boxB = true;
               
                ProcessWallHit();
            }

            if (position.Y < 0)
            {
                position.Y = 0;
                velocity.Y *= -1;
                Console.ForegroundColor = ConsoleColor.Red;
                Program.boxA = false;
               
                ProcessWallHit();
                
            }
            else if (position.Y > Console.WindowHeight - 1)
            {
                position.Y = Console.WindowHeight - 2;
                velocity.Y *= -1;
                Console.ForegroundColor = ConsoleColor.Blue;
                Program.boxB = false;
                
                ProcessWallHit();
            }
        }
        
        private void ProcessWallHit()
        {
            TakeDamage(WALL_DAMAGE);
        }
        //----//



        #endregion

    }
}





Name:
Health numbers instead of X
16:10:13 22/07/2009 CODE:
//Changed this
Console.Write(health);
//and this to get healt nubers isntead off X
else if (position.X > Console.WindowWidth - health.ToString().Length)
            {
                position.X = Console.WindowWidth - health.ToString().Length;
                velocity.X *= -1;
                Console.ForegroundColor = ConsoleColor.Green;
                Program.boxB = true;
               
                ProcessWallHit();
            }




Name:
knwlege_rew 1
16:14:21 22/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace knwlege_rew
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";

            while (input.ToLower() != "exit")
            {
                Console.WriteLine("Enter a number:");
                input = Console.ReadLine();

                int value;
                if (int.TryParse(input, out value))
                {

                    for (int i = value - 1; i > -value; i--)
                    {
                        Console.Write(value - Math.Abs(i) + " ");
                    }

                    //nr1
                    //for (int i = 1; i <= value; i++)
                    //{
                    //    Console.Write(i + " ");
                    //}

                    //for (int i = value - 1; i > 0; i--)
                    //{
                    //    Console.Write(i + " ");
                    //}
                    //nr1 slutt


                }
                else
                {
                    Console.WriteLine("Invalid number");
                }
                Console.WriteLine("\n\n");
            }
        }
        
        //static string numA;
        //static int numX;
        //static int num1 = 1;
        
        //static void numerX()
        //{
        //    Console.WriteLine("Enter a number: ");
        //    Console.WriteLine("");
        //    numA = Console.ReadLine();
        //    numX = System.Convert.ToInt32(numA);
        //    Console.WriteLine("");
        //}
        //static void loopX()
        //{
        //    for (; num1 <= numX; num1++)
        //    {
        //        Console.WriteLine(num1);
                
        //    } 

            
        //    for (num1 = num1 -2; num1 >= 1; --num1)
        //    {
        //        Console.WriteLine(num1);
        //    }

        //        Console.ReadLine();
           
        //}
    }
}




Name:
Simple input/output test for C#
16:16:13 22/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace knwl_75_1
{
    class Program
    {
        static void Main(string[] args)
        {
            string A;
            string B;
            int X;
            int Z;
            

            int sum;

            try
            {
                Console.WriteLine("how old are you? ");
                A = Console.ReadLine();
                X = System.Convert.ToInt32(A);

                
                Console.WriteLine("what age do you fear? ");
                B = Console.ReadLine();
                Z = System.Convert.ToInt32(B);


                if ((X > Z))
                {
                    sum = (X - Z);
                    Console.WriteLine("you have surevived " + sum + "years from your fear");
                }
                else if ((X < Z))
                {
                    sum = (Z - X);
                    Console.WriteLine("You have " + sum + "years to your fear year");
                }
            }
            
            catch
            {
                Console.WriteLine("du have no grasp on numerical values, terminating program");
            }
            Console.ReadLine();

        }
    }
}




Name:
ENUM test
16:17:30 22/07/2009 CODE:
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace knwl_75_2
{
    class Program
    {
       
        enum IRSignal
        {
            Play = 53,
            Stop = 16,
            Rewind = 12,
            FastFoward = 13
        }
        static void Main(string[] args)
        {
            transmit(53);
            Console.ReadLine();
        }

        static void transmit(int rawCode)
        {

            IRSignal code = (IRSignal)rawCode;

            if (isCodeValid(code))
            {
                Console.WriteLine("Transmission Acction: " + code);
                Console.WriteLine("transmitting IR code: " + (int)code);
            }
            else
            {
                Console.WriteLine("Transmision aborted " + code);
            }

        }

        static bool isCodeValid(IRSignal code)
        {
            switch (code)
            {
                case IRSignal.Play:
                case IRSignal.Stop:
                case IRSignal.Rewind:
                case IRSignal.FastFoward:
                    return true;
                default:
                    return false;
            }
        }
    }
}




Name:
Overload Constructor test
13:57:29 25/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace constructors
{
    class Program
    {
        static void Main(string[] args)
        {
            GameItem player = new GameItem(75, "BoB");
           
            player.ShowHealth();
            player.ShowName(); 
            
            GameItem enemy = new GameItem();
            enemy.ShowHealth();
            enemy.ShowName();
            Console.ReadLine();
        }
    }
    class GameItem
    {
        private int health;
        private string name;
        //overload constructor test.
                            //calls the overladed constructor to set default values.
        public GameItem() : this(100, "Not Set")
        {
            Console.WriteLine("Default constructor called");
        }
                            //hides the field health, so you must use "this" keyword
        public GameItem(int health, string name)
        {
            Console.WriteLine("GameItem object created!");
            //this.health refers to the field health
            this.health = health;
            this.name = name;
           
        }

        public void ShowHealth()
        {
            Console.WriteLine("health = " + this.health);
        }
        public void ShowName()
        {
            Console.WriteLine("Name = " + this.name + "\n");
        }
    }
}




Name:
Private Constructor test
16:01:04 27/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Constructor_private
{
    class Program
    {
        static void Main(string[] args)
        {
            GameItem player = GameItem.MakeGameItem();
            player.ShowText();

            Console.ReadLine();
        }
    }

    class GameItem
    {
        public static GameItem MakeGameItem()
        {
            return new GameItem();
        }

        private GameItem()
        { 
        
        }

        public void ShowText()
        {
            Console.WriteLine("Works!!");
        }
    }
}




Name:
Static Constructor
16:21:59 27/07/2009 CODE:
    class Program
    {
        static void Main(string[] args)
        {
            GameItem.ShowText();

            Console.ReadLine();
        }
    }

    class GameItem
    {
        public static int Count;

        //IMPORTANT  the static constructor allwayt fires first when somthing
        //is called in a class with a static constructor
        static GameItem()
        {
            Console.WriteLine("In static Constructor");
        }

        public static void ShowText()
        {
            Console.WriteLine("In Method");
        }
    }





Name:
Inheritance :base test
13:29:35 29/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace XNA_95_inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Enemy spider = new Enemy("x", 75, Vector2.Zero, 85, 15);
            spider.ShowInfo();
            Console.ReadLine();
        }
    }

    class GameItem
    {
        protected string name;
        protected Vector2 position;

        public GameItem(string name, Vector2 position)
        {
            this.name = name;
            this.position = position;
        }

    
    }

    class Pawn : GameItem
    {
        protected int health;
        
        public Pawn(string name, int health, Vector2 position) : base(name, position)
        {
            this.health = health;

        }

    }

    class Enemy : Pawn
    {
        private int iq;
        private int retreatHealth;

        public Enemy(string name, int health, Vector2 position, int iq, int retreatHealth)
            : base(name, health, position)
        {
            this.iq = iq;
            this.retreatHealth = retreatHealth;
        }

        public void ShowInfo()
        {
            Console.WriteLine("Name: " + name);
            Console.WriteLine("Health: " + health);
            Console.WriteLine("IQ: " + iq);
        }
    }

    class Player : Pawn
    {
        public Player(string name, int health, Vector2 position)
            : base(name, health, position)
        { 
        
        }
    }

    class Prop : GameItem
    { 
        public Prop(string name, Vector2 position) : base(name, position)
        {
        }
    }
}




Name:
ageFearTest
21:47:50 31/07/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ageFearTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string A;
            string B;
            int X;
            int Z;
            

            int sum;

            try
            {
                Console.WriteLine("how old are you? ");
                A = Console.ReadLine();
                X = System.Convert.ToInt32(A);

                
                Console.WriteLine("what age do you fear? ");
                B = Console.ReadLine();
                Z = System.Convert.ToInt32(B);


                if ((X > Z))
                {
                    sum = (X - Z);
                    Console.WriteLine("you have surevived " + sum + "years from your fear");
                }
                else if ((X < Z))
                {
                    sum = (Z - X);
                    Console.WriteLine("You have " + sum + "years to your fear year");
                }
            }
            
            catch
            {
                Console.WriteLine("du have no grasp on numerical values, terminating program");
            }
            Console.ReadLine();

        }
    }
}




Name:
Input test
00:36:09 01/08/2009 CODE:
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            helloTest.test();
            Console.ReadLine();
        }
    }

    class helloTest
    {
        public static string xA;

        public static void test()
        {
            Console.WriteLine("Hei ka e navnet ditt?");
            xA = Console.ReadLine();

            Console.WriteLine("Hei :) " + xA);
        }


    }
}




Name:
ThisKeyWord Test
12:15:14 01/08/2009 CODE:
namespace ThisKeyWord
{
    class Program
    {
        static void Main(string[] args)
        {
            List gameItems = new List();
            gameItems.Add(new GameItem("Enemy1"));
            gameItems.Add(new GameItem("Enemy2"));
            gameItems.Add(new GameItem("Player"));
            gameItems.Add(new GameItem("TREE"));

            foreach (GameItem item in gameItems)
                item.update();

            Console.ReadLine();
        }
    }

    class GameItem
    {
        public string name;

        public GameItem(string name)
        {
            this.name = name;
        }

        public void update()
        {
            RenderingEngine.Draw(this);
        }

        
    }

    static class RenderingEngine
    {
        public static void Draw(GameItem item)
        {
            Console.WriteLine("Draw the following item: " + item.name);
        }
    }
}




Name:
Text to Num edit
12:46:53 01/08/2009 CODE:
  private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox1.KeyPress += new KeyPressEventHandler(Form1_KeyPress);

        decimal sum = decimal.Parse(textBox1.Text) + decimal.Parse(textBox2.Text);
        label1.Text = sum.ToString();
    } 

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (((e.KeyChar < '0') || (e.KeyChar > '9')) && (e.KeyChar!=(char)Keys.Back))
        e.Handled = true;
    } 




Name:
Draw Text from File
12:48:27 01/08/2009 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test_drawing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //text variablelen
        public string teXt;

        public void Form1_Load(object sender, EventArgs e)
        {

        }
        //tegne ned texten
        public void Form1_Paint(object sender, PaintEventArgs e)
        {

        }
        //timed ticker updater
        private void timer1_Tick(object sender, EventArgs e)
        {
            string file_name = "c:\\temp\\test.txt";
            
            System.IO.StreamReader objReader;
            objReader = new System.IO.StreamReader(file_name);
            //textBox1.Text = objReader.ReadToEnd();
            teXt = objReader.ReadToEnd();
            objReader.Close();
           
            System.Drawing.Graphics graphicsObj;
            graphicsObj = this.CreateGraphics();
            graphicsObj.Clear(Color.Aqua);
            Font myFont = new System.Drawing.Font("Helvetica", 40, FontStyle.Italic);
            Brush myBrush = new SolidBrush(System.Drawing.Color.Red);
            graphicsObj.DrawString(teXt, myFont, myBrush, 30, 30);
        }
    }
} 




Name:
Simple command system
13:50:55 06/08/2009 CODE:
Class program
{
     while (true)
     {
          CommandManager.ProssesCommand(Console.ReadLine());
     }
}

static class CommandManager
{
        public static void ProssesCommand(string line)
        {
            string[] arguments = line.Split(' ');

            if (arguments.Length > 0)
            {
                switch (arguments[0])
                { 
                    case "clear":
                        Console.Clear();
                        break;
                }
            }
        }
}




Name:
Random Placement
12:40:31 08/08/2009 CODE:
//Random Placement


/*how to place a unit on the screen at a random location. 
In this sample this is how I am doing it. First thing I do is set up 
4 floats to hold the minimum and maximum screen positions that are possible.*/

        // Variables to hold the min and max positions that a "unit" can be placed in.
        float minX, minY, maxX, maxY;

//Then in the LoadContent method I set them.

        // Set the min max values
        minX = GraphicsDevice.Viewport.TitleSafeArea.Left + (obj.image.Width / 2);
        minY = GraphicsDevice.Viewport.TitleSafeArea.Top + (obj.image.Height / 2);

        maxX = GraphicsDevice.Viewport.TitleSafeArea.Right - (obj.image.Width / 2);
        maxY = GraphicsDevice.Viewport.TitleSafeArea.Bottom - (obj.image.Height / 2);

//I then randomly set the position of the unit.

        // Randomly place the object.
        obj.Position = GetRandomPosition();
        obj.spriteBatch = spriteBatch;

 

//GetRandomPosition() looks like this:

        // Method to generate a random position on the screen.
        private Vector2 GetRandomPosition()
        {
            return new Vector2((float)MathHelper.Lerp(minX, maxX, (float)rnd.NextDouble()),
                                (float)MathHelper.Lerp(minY, maxY, (float)rnd.NextDouble()));
        }

//Random Movement

/*The next thing in the post was random movement. 
As you might have read in the post, 
I don’t think that this is really what is wanted, 
but I have done it here any was as a matter of completeness.

In the Update method of the sample, 
depending on the movement type selected 
(Default is random movement) I move the unit. 
So when in random movement the position of the object is altered like this:*/

        case MovementTypes.TotalyRandom:
        // Randomly move the object..
        obj.Position.X += (float)MathHelper.Lerp(-obj.image.Width, obj.image.Width, (float)rnd.NextDouble());
        obj.Position.Y += (float)MathHelper.Lerp(-obj.image.Height, obj.image.Height, (float)rnd.NextDouble());
        break;

 

/*This is a pretty clumsy movement method and was done out of haste really. 
A much better way to move any game avatar is by using a velocity 
which I will cover in a later related post. 
In fact the BaseDrawable2DObject that is used in this sample is a 
foundation of this up coming post.*/

//Random Patrol Path


/*now I think a much better and maybe useful method is for the unit to follow a patrol path. 
This is just a number of points on the screen that the unit will move to in turn. 
Now if you have any sense you will tie this in with your A.I. 
and depending on the various states you can send the unit to specified points. 
This is out of the scope of this simple sample, 
but I am sure you will get what I mean.

Anyway onto the patrol path stuff. 
We first need a list of patrol points as well as some way of 
marking what point we want to head for..*/

        // Entities used to represent the patrol points.
        List patrolPoints = new List();
        // This is the next target destination in the patrol points.
        int pathTarget = 0;

/*We now have a list of patrol points and a marker to denote the 
point we want to be moving to. So our movement code now looks like this*/

        case MovementTypes.PatrolListPath:                    
        case MovementTypes.PatrolMap:
            // Move towards current patrol point..
            if (patrolPoints.Count > 0)
            {
                Vector2 dir = patrolPoints[pathTarget].Position - obj.Position;
                dir.Normalize();
                obj.Translate(dir * 4);
                if (obj.collisionRect.Intersects(patrolPoints[pathTarget].collisionRect))
                    pathTarget++;
                if (pathTarget >= patrolPoints.Count)
                    pathTarget = 0;
            }
            break;

/*I get the direction from the units position to the desired location, 
normalize it and then move in that direction 
(the * 4 is there to speed it up a bit). 
I then check if the unit has arrived at the required destination,
if it has I move the pathTarget on one. 
I then see if my pathTarget is still in the range of the list of patrol points 
and if it is beyond that I set it back to 0.

To set the patrol path up I use the following method:*/

    // Method to generate a random patrol path.
    private void GenerateRandomPatrolPath()
    {
        ClearPatrolPoints();

        for (int p = 0; p < rnd.Next(4, 8); p++)
        {
            BaseDrawable2DObject point = new BaseDrawable2DObject(this, "Textures/box");
            point.ForeColor = Color.Gold;
            point.Enabled = true;
            point.Scale = .5f;
            point.Position = GetRandomPosition();
            point.spriteBatch = spriteBatch;
            Components.Add(point);
            patrolPoints.Add(point);
        }
    }

/*What this does is clear out the old list, 
then populate the list with between 4 to 8 patrol points, 
each point being randomly placed on the screen.

Here is the ClearPatrolPoints() method so you wont 
think I am over loading the Components collection :)*/

    // Method to clear the patrol points out.
    private void ClearPatrolPoints()
    {
        // Remove any old points
        foreach (BaseDrawable2DObject o in patrolPoints)
            if (Components.Contains(o))
                Components.Remove(o);
        patrolPoints.Clear();
    }

/*That is pretty much it, do forgive the clumsy movement mechanism, 
this was written to show the random position generation 
and patrol paths. In the next related post 
I intend to cover simple physics and sprite animation, 
this may end up being spread over a number of posts.*/




Name:
Recreating the tree command
14:16:16 09/08/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace tree
{
    class Program
    {
        private const int TREE_DRAW_OFFSET = 4;
        private const char CHAR_HLINE = (char)0x2500;
        private const char CHAR_VLINE = (char)0x2502;
        private const char CHAR_TJOINT = (char)0x251C;
        private const char CHAR_ANGLE = (char)0x2514;


        static void Main(string[] args)
        {
            string path = @"D:\";
            string drive = path.Split('\\')[0];
            DirectoryInfo dir = new DirectoryInfo(path);
            Console.WriteLine(drive);
            ShowTree(dir.GetDirectories(), "");

            Console.ReadLine();
        }

        private static void ShowTree(DirectoryInfo[] directories, string padding)
        {
            for (int i = 0; i < directories.Length; i++)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(padding);

                StringBuilder padBuilder = new StringBuilder();
                padBuilder.Append(padding);

                if (i < directories.Length - 1)
                {
                    sb.Append(CHAR_TJOINT);
                    padBuilder.Append(CHAR_VLINE);
                    padBuilder.Append(' ', TREE_DRAW_OFFSET - 1);
                }
                else
                {
                    sb.Append(CHAR_ANGLE);

                    padBuilder.Append(' ', TREE_DRAW_OFFSET);
                }

                sb.Append(CHAR_HLINE, TREE_DRAW_OFFSET - 1);
                sb.Append(directories[i]);

                Console.WriteLine(sb.ToString());
                ShowTree(directories[i].GetDirectories(), padBuilder.ToString());
            }

        }

    }
}




Name:
Testing Sprite Blending
14:41:46 10/08/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace SpriteBlender
{
    /// 
    /// This is the main type for your game
    /// 
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D texture;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

       
        protected override void Initialize()
        {
            
            base.Initialize();
        }

      
        protected override void LoadContent()
        {
            
            spriteBatch = new SpriteBatch(GraphicsDevice);

            texture = Content.Load(@"Textures\target");
         
        }

     
        protected override void UnloadContent()
        {
         
        }
        protected override void Update(GameTime gameTime)
        {
         
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            Vector2 pos1 = CircleMove(gameTime, new Vector2(150, 150), 2f, 150f, 0f);
            Vector2 pos2 = CircleMove(gameTime, new Vector2(150, 150), 2f, 150f, 3.14f / 2);

            spriteBatch.Begin(SpriteBlendMode.Additive);
                              //number to be drawn
            DrawSeq(pos1, pos2, 60);
            spriteBatch.End();

            base.Draw(gameTime);
        }

        private Vector2 CircleMove(GameTime gameTime, Vector2 position, float frq, float amp, float offset)
        {
            double timeVal = (gameTime.TotalGameTime.TotalSeconds + offset) * frq;
            return new Vector2((float)Math.Sin(timeVal), (float)Math.Cos(timeVal)) * amp + position;
        }

        private void DrawSeq(Vector2 pos1, Vector2 pos2, int segm)
        {
            for (int i = 0; i < segm; i++)
            {
                Vector2 cupPos = Vector2.Lerp(pos1, pos2, (float)i / segm);
                                                                         //Edit denne for ocupaci 
                spriteBatch.Draw(texture, cupPos, new Color(255, 255, 255, 64));
            }
        }
    }
}




Name:
2d Gravity
10:30:48 14/08/2009 CODE:

player.position = new Vector2(200, 200);
player.velocity = new Vector2(0, 0);
player.jumpVelocity = new Vector2(0, -10);
gravity = new Vector2(0, 3);

/*Each frame, add the gravity vector to your player's velocity, then add the velocity to your player's position.*/

player.velocity += gravity;
player.position += player.velocity;

/*When your player lands on something (collision), set your player's velocity.Y back to 0.*/

if (player.position.Y > 500) 
    player.velocity.Y = 0;

/*Every frame that your player does not land on something, player.velocity.Y will continue to increase, simulating gravitational acceleration.*/

/*To make your player jump, just add player.jumpVelocity to player.velocity when the player hits the jump button (The jump Y value must be enough to overcome the force (Y value) of gravity).

Play with the Y values of player.jumpVelocity and gravity until you get something that works for your game.

You can change the X & Y values of gravity at any time during your game to simulate a gravity shift.

Consider adding a terminal velocity so you don't fall too fast.*/




Name:
Auto Aiming
10:52:26 14/08/2009 CODE:
/*A: your position
B: enemy's position
V: enemy's velocity
s: speed of your bullet
t: time variable

The trajectory of your enemy is given by p(t) = B + Vt.

At some time t, the distance between you and your enemy is ||p(t) - A|| = ||(B - A) + Vt||.

In t units of time, your bullet travels a distance of st.

So you want to solve the following for t:

||(B - A) + Vt|| = st

Let U = B - A for shorthand.  This simplifies as follows:

square both sides:   = (st)2
expand the inner product:   + 2t + t2 = s2t2

Let  a =  - s2,  b = 2,  c = . Then you simply have to solve this quadratic equation:

at2 + bt + c = 0

The possible solutions you could get are:

(A) two complex solutions.  This means you cannot hit the target (maybe because it's moving faster than the bullet).
(B) one real solution with multiplicity 2.  If t is this solution, the direction to fire the bullet is Normalize(B + Vt - A).
(C) two real solutions.  Only nonnegative solutions (ie t >=0) are valid.  Take the (lesser) nonnegative solution and solve for the direction to fire the bullet as in (B).*/

 




Name:
Collision test
12:00:57 14/08/2009 CODE:
        private Vector2 CheckExplosion()  
        {  
            foreach (Jeep aJeep in mJeeps)  
            {  
                foreach (Bomb aBomb in mBombs)  
                {  
                    //Test if abomb.X is within the range of aJeep's onscreen width  
                    if (aBomb.Position.X > aJeep.Position.X && aBomb.Position.X < aJeep.Position.X + aJeep.Width)  
                    {  
                        //Test if abomb.Y is within the range of aJeep's onscreen height  
                        if (aBomb.Position.Y > aJeep.Position.Y - aJeep.Height / 2 && aBomb.Position.Y < aJeep.Position.Y + aJeep.Height / 2)  
                        {  
                            //if both are true, we have a box-point collision  
                             aJeep.aCurrentJeepstate = Jeep.Jeepstate.destroyed;    
                             aBomb.aCurrentbombstate = Bomb.bombstate.jeephit;  
                        }  
                    }  
                }  
            }  
        } 




Name:
Get the MD5 value of a string
15:27:31 21/08/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // get teh MD5 string of a password
            string password = "test";

            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            password = s.ToString();
            Console.WriteLine(password);
            Console.ReadLine();
        }
    }
}




Name:
Matrix
11:35:25 22/08/2009 CODE:
using System;

namespace Matrix
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Matrix";
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WindowHeight = Console.BufferHeight = 32;
            Console.WindowWidth = Console.BufferWidth = 100;

            Console.CursorVisible = false;
            int width, height;
            int[] X;
            int[] O;
            Initialize(out width, out height, out X, out O);
            int ms;
            while (true)
            {
                DateTime t1 = DateTime.Now;
                MatrixStep(width, height, X, O);
                ms = 10 - (int)((TimeSpan)(DateTime.Now - t1)).Seconds;
            }
        }

        static bool thistime = false;

        private static void MatrixStep(int width, int height, int[] y, int[] l)
        {
            int x;
            thistime = !thistime;
            for (x = 0; x < width; ++x)
            {
                if (x % 11 == 5)
                {
                    if (!thistime)
                        continue;
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.SetCursorPosition(x, inBoxY(y[x] - 20 - (l[x] / 40 * 2), height));
                    Console.Write(R);
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Console.SetCursorPosition(x, y[x]);
                Console.Write(R);
                y[x] = inBoxY(y[x] + 1, height);
                Console.SetCursorPosition(x, inBoxY(y[x] - l[x], height));
                Console.Write(' ');
            }
        }

        private static void Initialize(out int width, out int height, out int[] y, out int[] l)
        {
            int h1;
            int h2 = (h1 = (height = Console.WindowHeight) /2) / 2;
            width = Console.WindowWidth - 1;
            y = new int[width];
            l = new int[width];
            int x;
            Console.Clear();
            for (x = 0; x < width; ++x)
            {
                y[x] = r.Next(height);
                l[x] = r.Next(h2 * ((x % 11 != 10) ? 2 : 1), h1 * ((x % 11 != 10) ? 2 : 1));
            }
        }

        static Random r = new Random();
        static char R
        {
            get
            {
                int t = r.Next(20);
                if (t <= 2)
                    return (char)('0' + r.Next(15));
                else if (t <= 4)
                    return (char)('a' + r.Next(15));
                else if (t <= 6)
                    return (char)('A' + r.Next(15));
                else
                    return (char)(r.Next(0, 9));
            }
        }

        public static int inBoxY(int n, int height)
        {
            n = n % height;
            if (n < 0)
                return n + height;
            else
                return n;
        }
    }
}




Name:
Array Test
12:39:51 12/09/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class WallSegment
    {
        public int Height;
    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] x;
            x = new int[4];

            x[2] = 15;

            Console.WriteLine(x[0]);
            Console.WriteLine(x[1]);
            Console.WriteLine(x[2]);
            Console.WriteLine(x[3]);

            WallSegment[] walls = new WallSegment[2] { new WallSegment(), new WallSegment() };
            

            Console.ReadLine();


        }
    }
}




Name:
Arrays test 2
13:10:39 12/09/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program
  {
        static void Main(string[] args)
        {
            string[] farge = new string[4] { "█████Blå█████", "█████Grøn█████", "█████Rød█████", "█████Gul█████" };

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey(true);
                                               
                int index = (int)key.KeyChar - 48; //hex value of 0 is 30. 30 hex to dec = 48
                if (index >= 0 && index <= 3)
                {
                    if (index == 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(farge[index]);
                    }
                    else if (index == 1)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine(farge[index]);
                    }
                    if (index == 2)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(farge[index]);
                    }
                    if (index == 3)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine(farge[index]);
                    }
                    Console.ResetColor();
                }
            }

            Console.ReadLine();
        }
    }
}




Name:
Arrays test 3
14:55:06 12/09/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace array_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] flavors = new string[] {"Lime", "Cherry", "Grape", "Cola", "Lemon"};

            //Console.WriteLine(flavors.Length);
            //**************************
            //for LOOP
            for (int i = 0; i < flavors.Length; i++)
            {
                Console.WriteLine(flavors[i]);
            }
            Console.WriteLine();

            //**************************
            //foreach LOOP
            foreach (string flavor in flavors)
            {
                Console.WriteLine(flavor);
            }
            Console.WriteLine();

            //**************************
            //string array
            string text = "Dont run if you cant hide";
            string[] words = text.Split(' ');

            for (int i = 0; i < words.Length; i++)
            {
                Console.WriteLine(words[i]);
            }
            Console.WriteLine();
            //**************************
            //string array
            DirectoryInfo directory = new DirectoryInfo(@"c:\temp");
            FileInfo[] files = directory.GetFiles();

            for (int i = 0; i < files.Length; i++)
            {
                Console.WriteLine(files[i]);
            }


            Console.ReadLine();
        }
    }
}




Name:
Background worker test
18:09:22 24/09/2009 CODE:
public partial class Form2 : Form
{
        static BackgroundWorker bw = new BackgroundWorker();
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            bw.DoWork += new DoWorkEventHandler(loopX);
            bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(textX);
            bw.RunWorkerAsync();
        }

        public void loopX(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 30; i++)
            {
                Thread.Sleep(100);
            }
            
        }
        public void textX(object sender, RunWorkerCompletedEventArgs e)
        { 
            label1.Text = "Done";
        }
}




Name:
Get vaules from textboxes and put in to array
13:50:28 29/09/2009 CODE:
            verdierX = (from Control control in Controls
                      where control.GetType() == typeof(TextBox) &&
                            control.Name.StartsWith("box")
                      select Convert.ToInt32(((TextBox)control).Text))
                                        .ToArray();   




Name:
Loop trough textboxes and null all.
13:51:24 29/09/2009 CODE:
        private void nullX()
        {
            foreach (Control c in this.Controls)
            {
                // null alle textboxer
                if (c is TextBox)
                {
                    TextBox txt = (TextBox)c;
                    txt.Text = "0";
                }

            }

        }




Name:
DB connection test
13:49:46 02/10/2009 CODE:
  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // utvikling - MySqlConnection mysqlCon = new MySqlConnection("server=#; Database = #; user id=#; password=#;");
            MySqlConnection mysqlCon = new MySqlConnection("server=#; Database = #; user id=#; password=#;");

            try
            {
                mysqlCon.Open();
                mysqlCon.Close();
                pictureBox1.BackColor = Color.Green;
                MessageBox.Show("Funker");
            }
            catch (System.Exception excep)
            {
                mysqlCon.Close();
                pictureBox1.BackColor = Color.Red;
                MessageBox.Show(excep.Message);
            }
        }
    }




Name:
add number to back of string variable
19:04:52 02/10/2009 CODE:
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int sum1 = 1;
        private void button1_Click(object sender, EventArgs e)
        {
            
            textBox1.Text = "test";

            var var1 = textBox1.Text + sum1;
            sum1++;

            textBox2.Text = var1;
        }
    }
}




Name:
input console
20:07:02 06/10/2009 CODE:
using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter your name: ");
            string input = Console.ReadLine();
            Console.WriteLine("Your input: {0}", input);

            Console.ReadLine();

        }
    }
}




Name:
get directoryname.
20:20:07 06/10/2009 CODE:
using System;
using System.Collections.Generic;
using System.Text;


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
            //Console.WriteLine(System.Windows.Forms.Application.StartupPath);
            
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
            
            Console.WriteLine(path);

            Console.ReadLine();

        }
    }
}




Name:
Read from text file
20:28:17 06/10/2009 CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(@"C:\test.txt");

            while(!reader.EndOfStream)
            {
                Console.WriteLine(reader.ReadLine());
            }
            reader.Dispose();

            Console.ReadLine();
        }
    }
}




Name:
write to a text file
20:32:26 06/10/2009 CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter writer = new StreamWriter(@"C:\test1234567.txt");

            writer.WriteLine("Line 1");

            writer.Dispose();
        }
    }
}




Name:
Associative Array
20:46:33 06/10/2009 CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary record = new Dictionary();
            record.Add("id", "1");
            record.Add("name", "glennwiz");
            record.Add("content", "videos");

            Console.WriteLine("Enter field: ");
            string field = Console.ReadLine();

            Console.WriteLine("Value: {0}", record[field]);
            Console.ReadLine();
        }
    }
}




Name:
List files C#
20:52:12 06/10/2009 CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            ListFiles(new DirectoryInfo(@"D:\Temp"));
            Console.ReadLine();
        }

        static void ListFiles(DirectoryInfo directory)
        {
            FileInfo[] files = directory.GetFiles();
            for (int i = 0; i < files.Length; i++)
            {
                Console.WriteLine((files[i]));
            }
        }
    }
}




Name:
Logmein . com auto login C# code
21:13:26 09/11/2009 CODE:
using System.Windows.Forms;
using System.Threading;


namespace Logmein_app
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                webBrowser1.Document.All.GetElementsByName("email")[0].SetAttribute("Value", "USERNAME");
                webBrowser1.Document.All.GetElementsByName("password")[0].SetAttribute("Value", "PASSWORD");
                webBrowser1.Document.GetElementById("loginbtn").InvokeMember("click");
            }
            Thread.Sleep(600);
                 webBrowser1.Url = new System.Uri("https://secure.logmein.com/mycomputers_connect.asp?hostid=IDNR&hostpath=/go=r", System.UriKind.Absolute);

        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (webBrowser1.Document != null)
            {
                webBrowser1.Document.All.GetElementsByName("password")[0].SetAttribute("Value", "PASSWORD");
                webBrowser1.Document.GetElementById("loginButton").InvokeMember("click");
            }
        }
    }
}




Name:
Move Mouse C# Macro and Inputblocker from keyboard and mouse while moving
12:48:17 12/11/2009 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;


namespace Move_mouse
{
    public partial class Form1 : Form
    {
        bool needUnblock = false;

        public Form1()
        {
            InitializeComponent();
        }

        public void inputBlocker()
        {
            if (needUnblock == false)
                BlockInput(true);
            if (needUnblock == true)
            {
                BlockInput(false);
                needUnblock = false;
            }
        }
        #region 
        [DllImport("user32.dll")]
        static extern bool BlockInput(bool fBlockIt);
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
           inputBlocker();
           Cursor.Position = new Point(Cursor.Position.X + 100, Cursor.Position.Y + 100);
           Thread.Sleep(600);
           Cursor.Position = new Point(Cursor.Position.X + 100, Cursor.Position.Y + 100);
           Thread.Sleep(600);
           Cursor.Position = new Point(Cursor.Position.X + 100, Cursor.Position.Y + 100);
           Thread.Sleep(600);
           Cursor.Position = new Point(Cursor.Position.X + 100, Cursor.Position.Y + 100);
           Thread.Sleep(600);
           Cursor.Position = new Point(Cursor.Position.X + 100, Cursor.Position.Y + 100);
           needUnblock = true;
           inputBlocker();

        }
    }
}




Name:
String to Int Parse c#
13:43:25 12/11/2009 CODE:
            int xX, yY;
            xX = int.Parse(this.Location.X.ToString());
            yY = int.Parse(this.Location.Y.ToString());




Name:
c# CPU RAM monitor
20:21:25 13/11/2009 CODE:
/*
First you have to create the 2 performance counters
using the System.Diagnostics.PerformanceCounter class.
*/

protected PerformanceCounter cpuCounter;
protected PerformanceCounter ramCounter;

cpuCounter = new PerformanceCounter();

cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";

ramCounter = new PerformanceCounter("Memory", "Available MBytes");

/*
Call this method every time you need to know
the current cpu usage.
*/

public string getCurrentCpuUsage(){
            cpuCounter.NextValue()+"%";
}

/*
Call this method every time you need to get
the amount of the available RAM in Mb
*/
public string getAvailableRAM(){
            ramCounter.NextValue()+"Mb";
} 




Name:
string to int og int to string.
19:53:31 15/11/2009 CODE:
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            sumX(System.Convert.ToInt16(textBox1.Text), System.Convert.ToInt16(textBox2.Text));
        }

        private void sumX(int a, int b)
        {
            int c = a + b;
            label1.Text = c.ToString();
            
        }
    }
}


namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            sumX(textBox1.Text, textBox2.Text);
        }

        private void sumX(string a, string b)
        {
            int c = int.Parse(a) + int.Parse(b);
            label1.Text = c.ToString();
            
        }
    }
}






Name:
Foreach loop based on textbox names
15:37:45 18/11/2009 CODE:
Size newSize = new Size(27, 20);
foreach (Control c in this.Controls)
{
   if (c is TextBox && c.Name.EndsWith("txt2"))
   {
      c.Size = newSize;
   }
}





Name:
Calculate method from declaration /
21:46:55 18/11/2009 CODE:
using System;
using System.Windows.Forms;

namespace class_test_input
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //asks for plussInt method to calculate 10, and put
            //result in to returnedIntX
            var returnedIntX = plussInt(10);
            label1.Text = returnedIntX.ToString();
        }
                             //puts 10 into plussMeg 
        private static int plussInt(int plussMeg)
        {
            //puts the result in to a variable to return
            var intX = plussMeg*2;
            //returns result to returnedIntX
            return intX;
        }
    }
}




Name:
Calculate method from declaration of other class
21:58:24 18/11/2009 CODE:
using System;
using System.Windows.Forms;

namespace class_test_input
{
    public partial class form1 : Form
    {
        public form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            var zc = new intZ();
            var returnedIntX = intZ.intY(10);
            label1.Text = returnedIntX.ToString();
        }
    }
    public class intZ
    {
        public static int intY(int incomingInt)
        {
            incomingInt = incomingInt*3;
            return incomingInt;
        }
    }




Name:
Multi Treading c# test
22:14:58 18/11/2009 CODE:
using System;
using System.Threading;

namespace Treading_test2
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadWork threadWork = new ThreadWork();
            Thread firstTread = new Thread(new ThreadStart(threadWork.firstCountMethod));
            Thread secondTread = new Thread(new ThreadStart(threadWork.secondCountMethod));
            firstTread.Start();
            secondTread.Start();
            Console.ReadKey();
        
        }
    }
    class ThreadWork
    {
        public void firstCountMethod()
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine("This is the first tread count, nr {0}", i);
                Thread.Sleep(100);
            }
        }
        public void secondCountMethod()
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine("This is the second tread count, nr {0}", i);
                Thread.Sleep(100);
            }
        }
    }
}




Name:
Find the RGB value based on Mouse location C#
15:09:36 20/11/2009 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;


namespace Color_tool
{
    public partial class Form1 : Form
    {
        Regex rgbInputR;
        Regex rgbInputG;
        Regex rgbInputB;

        Match R, G, B;
        int r;
        int g;
        int b;


        string colorX;

        [DllImport("gdi32")]
        private static extern int GetPixel(IntPtr hdc, int x, int y);
        [DllImport("User32")]
        private static extern IntPtr GetWindowDC(IntPtr hwnd);

        private static readonly IntPtr DesktopDC = GetWindowDC(IntPtr.Zero);

        public static System.Drawing.Color GetPixelAtCursor()
        {
            System.Drawing.Point p = Cursor.Position;
            return System.Drawing.Color.FromArgb(GetPixel(DesktopDC, p.X, p.Y));
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.BackColor = Color.Black;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            colorX = GetPixelAtCursor().ToString();
            Color backX = GetPixelAtCursor();
            this.BackColor = Color.FromArgb(r,g,b);
            label1.Text = colorX;
            RGB_value();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled == false)
                timer1.Enabled = true;
            else
                timer1.Enabled = false;
        }

        private void RGB_value()
        {
            rgbInputR = new Regex(@"(?<=R=)\d{0,3}");
            rgbInputG = new Regex(@"(?<=G=)\d{0,3}");
            rgbInputB = new Regex(@"(?<=B=)\d{0,3}");

            Match R, G, B;

            R = rgbInputR.Match(colorX);
            G = rgbInputG.Match(colorX);
            B = rgbInputB.Match(colorX);
            //had to flip the R and B ???
            b = int.Parse(R.Groups[0].Value);
            g = int.Parse(G.Groups[0].Value);
            r = int.Parse(B.Groups[0].Value);
        }
     }
}




Name:
String to array with Backgroundworker test
17:15:10 23/11/2009 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MouseKeyboardLibrary;
using System.Threading;


namespace test_Keys_loop
{
    public partial class Form1 : Form
    {        
        string text = null;
        int pross = 100;
        int value_bar;
        string inputString;
        char[] inputArrayX;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            inputString = label1.Text;
            inputArrayX = inputString.ToCharArray();
            backgroundWorker1.RunWorkerAsync();
        }

        private void startThread()
        {
            startMacro(inputArrayX);
        }

        private void startMacro(char[] arrayX)
        {
            for (int i = 0; i < arrayX.Length; i++)
            {
                text = text + arrayX[i].ToString();
                Thread.Sleep(1000);
                pross = pross + value_bar;
                backgroundWorker1.ReportProgress(pross, "test");
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            value_bar = pross / inputArrayX.Length;
            pross = 0;
            startMacro(inputArrayX);    
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = pross;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
             textBox1.Text = text.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox2.Text = textBox2.Text + 1;
        }
    }
}




Name:
Function to get random number
00:03:48 27/11/2009 CODE:
//Function to get random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
    lock(syncLock) { // synchronize
        return random.Next(min, max);
    }
}




Name:
Pass int by value and by reference.
13:49:36 29/11/2009 CODE:
using System;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            int teller1 = 0;
            SeedCounter(teller1);
            //this will output 0 as the result because the value 
            //is not passed as ref
            //so a copy of teller1 is passed to the method and a new
            //stack location is created with the new value.
            Console.WriteLine(teller1);

            int teller2 = 0;
            SeedCounter(ref teller2);
            //this will output 1 because the value is passed
            //as ref so the method does the calc directly to
            //the stack int teller2 loaction
            Console.WriteLine(teller2);
        }
        private static void SeedCounter(int teller)
        {
            teller = 1;
        }
        private static void SeedCounter(ref int teller)
        {
            teller = 1;
        }
    }
}




Name:
Get Set test C#
14:41:50 29/11/2009 CODE:
using System;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            var person = new Person();
            person.Name = "glenn";  // the set accessor is invoked here                

            Console.Write(person.Name);  // the get accessor is invoked here
            Console.ReadKey();
        }
    }
    class Person
    {
        public string Name // the Name property
        { get; set; }
    }

}




Name:
Get Set test2 c#
18:02:24 29/11/2009 CODE:
using System;

namespace ConsoleApplication1
{
    class Program
    {
        public static int X = 30;
        public static void Main()
        {
            var cX = new testme();
            cX.intX = 12;
            Console.WriteLine(cX.intX);
            cX.intX = X;
            Console.WriteLine(cX.intX);
            Console.ReadKey();
        }
    }
    class testme
    {
        //to protect the val field you can use the get set properties
        private int val;
        public int intX
        {
            get { return val;}
            set { val = value; }
        }
    }
}




Name:
Replace text in string
19:14:24 30/11/2009 CODE:
using System;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string tempX = "test sting replace text";
            tempX = tempX.Replace("test", "done");

            Console.WriteLine(tempX);
            Console.ReadKey();

        }
    }
}




Name:
Enum test C# dont use magic numbers out them in a enum or make a constant
19:33:39 30/11/2009 CODE:
using System;


namespace ConsoleApplication2
{
    class Program
    {
        private enum enumtest
        {
            first = 100,
            second = 200
        }
        static void Main(string[] args)
        {
            const int val = (int)enumtest.first;
            Console.WriteLine(val);
            Console.WriteLine((int)enumtest.second);
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

using System;


namespace ConsoleApplication2
{
    class Program
    {
        private const int FIRST = 100;
        private const int SECOND = 200;
        static void Main(string[] args)
        {
            const int val = FIRST;
            Console.WriteLine(val);
            Console.WriteLine(SECOND);
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}




Name:
String manipulation Stringbuilder in C# appending a variable
19:39:21 30/11/2009 CODE:
using System;
using System.Text;


namespace ConsoleApplication2
{
    class Program
    {
        private static string tempX;
        private static string tempY = "test";
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("This ");
            sb.Append("is ");
            sb.Append("a ");
            sb.Append("string ");
            sb.Append("builder ");
            sb.Append(tempY);
            tempX = sb.ToString();
            Console.WriteLine(tempX);
            Console.ReadKey();
        }
    }
}




Name:
get the second highest number inn a array C#
16:19:38 06/12/2009 CODE:
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
    if (i > largest)
    {
        second = largest;
        largest = i;
    }
    else if (i > second)
        second = i;
}

System.Console.WriteLine(second);




Name:
DayOfWeek to number loop test
12:24:45 14/12/2009 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            insertX();
            Console.WriteLine("Dags Verdi er " + antallDager);
            Console.WriteLine(DAY);
            Console.ReadLine();
        }

        static int antallDager = 0;
        static string DAY = null;
        static private void getDagVerdinummer(DayOfWeek dayX)
        {
            string dagString = dayX.ToString();
            DAY = dayX.ToString();
            if (dagString == "Monday")
                antallDager = 5;
            else if (dagString == "Tuesday")
                antallDager = 4;
            else if (dagString == "Wednesday")
                antallDager = 3;
            else if (dagString == "Thursday")
                antallDager = 2;
            else if (dagString == "Friday")
                antallDager = 1;
        }
        static private void insertX()
        {

            DayOfWeek dayX = DateTime.Now.DayOfWeek;
            getDagVerdinummer(dayX);

        }

    }
}




Name:
Force update on the UI tread
14:46:44 14/12/2009 CODE:
Application.DoEvents();




Name:
how to dynamic use textbox names in loop
15:48:24 14/12/2009 CODE:
 string string1, string2, string3;

            for (int i = 1; i < 31; i++)
            {
                string1 = "br" + i + "txt" + '1';
                string2 = "br" + i + "txt" + '2';
                string3 = "br" + i + "id";
                
                TextBox txtBCont1 = (TextBox)this.Controls[string1];
                TextBox txtBCont2 = (TextBox)this.Controls[string2];
                Label lblCont1 = (Label)this.Controls[string3];
                
                cmd.Connection = conn;
                cmd.CommandText = "UPDATE saker set NyeSaker = NyeSaker + '" + txtBCont2.Text + "', GamleSaker  = GamleSaker  + '" + txtBCont1.Text + "' where bruker_ID = '" + lblCont1.Text + "' AND Dato = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "'";
                cmd.ExecuteNonQuery();
            }




Name:
List create C#
21:25:53 18/12/2009 CODE:
creating a num int list from 1 to 10
// you can do this.
List numList = new List();
for (int i = 1; i <= 10; i++)
{
 numList.Add(i);
}

//or you can do this
List numList = Enumerable.Range(1, 10).ToList();

//for a list with numbers 10 to 20 you wold do this.
List numList = Enumerable.Range(10, 10).ToList();








Name:
Write to file
17:38:06 22/12/2009 CODE:
using(var writer = new System.IO.StreamWriter("Minfil.txt"))
{
  writer.WriteLine("Hello World!");
}



using(var writer = new System.IO.BinaryWriter("Minfil.dat"))
{
  writer.Write("Hello World!");
}


using(var fs = new System.IO.FileStream("Minfil.dat"))
{
  var writer = new System.IO.StreamWriter(fs);
  writer.WriteLine("Hello World!");
}




Name:
Testing Stack and heap memory refrence
13:17:44 03/01/2010 CODE:
using System;
 

namespace ConsoleApplication1
{
    class Program
    {
        //mem stack and heap location test.
        static void Main(string[] args)
        {
            //instance 1 of test
            test vartest = new test();
            int c = vartest.a;
            vartest.a = c + 100;
            c = vartest.a;
            Console.WriteLine(c.ToString());
            Console.ReadKey();
            
            //instance 2 of test
            test vartest2 = new test();
            int d = vartest2.a;
            Console.WriteLine(d.ToString());
            Console.ReadKey();

            //here i change the refrence from instance 2
            //over to instance 1
            vartest2 = vartest;
            Console.WriteLine(vartest.a.ToString());
            Console.WriteLine(vartest2.a.ToString());
            
            Console.ReadKey();
            
            
            testStruct str = new testStruct(300, 300);
            Console.WriteLine(testStruct.a.ToString());
            testStruct.a = 10001;
            Console.WriteLine(testStruct.a.ToString());
            Console.WriteLine(testStruct.b.ToString());
            Console.ReadKey();
        }
    }

    public class test
    {
        public int a = 1;
        public int b = 2;
    }
    // testing struct
    public struct testStruct
    {
        static public int a = 1;
        static public int b = 2;

        internal testStruct(int x, int y)
        {
            a = x;
            b = y;
        }
    }
}




Name:
Testing Stack and heap memory refrence
13:18:02 03/01/2010 CODE:
using System;
 

namespace ConsoleApplication1
{
    class Program
    {
        //mem stack and heap location test.
        static void Main(string[] args)
        {
            //instance 1 of test
            test vartest = new test();
            int c = vartest.a;
            vartest.a = c + 100;
            c = vartest.a;
            Console.WriteLine(c.ToString());
            Console.ReadKey();
            
            //instance 2 of test
            test vartest2 = new test();
            int d = vartest2.a;
            Console.WriteLine(d.ToString());
            Console.ReadKey();

            //here i change the refrence from instance 2
            //over to instance 1
            vartest2 = vartest;
            Console.WriteLine(vartest.a.ToString());
            Console.WriteLine(vartest2.a.ToString());
            
            Console.ReadKey();
            
            
            testStruct str = new testStruct(300, 300);
            Console.WriteLine(testStruct.a.ToString());
            testStruct.a = 10001;
            Console.WriteLine(testStruct.a.ToString());
            Console.WriteLine(testStruct.b.ToString());
            Console.ReadKey();
        }
    }

    public class test
    {
        public int a = 1;
        public int b = 2;
    }
    // testing struct
    public struct testStruct
    {
        static public int a = 1;
        static public int b = 2;

        internal testStruct(int x, int y)
        {
            a = x;
            b = y;
        }
    }
}




Name:
Stopwatch
16:14:13 03/01/2010 CODE:
 var s = new Stopwatch();
                    double average = 0.0;
                    s.Start();
                    for (int x = 0; x < 99; x++)
                    {
                        for (int i = 0; i < numbers; i++)
                        {
                            average += arr[i];
                        }

                        average = average / numbers;
                    }
                    s.Stop();
                    Console.WriteLine("{0} ms spent...", s.ElapsedMilliseconds);




Name:
Using System.Diagnostic
16:15:00 03/01/2010 CODE:
 var s = new Stopwatch();
                    double average = 0.0;
                    s.Start();
                    for (int x = 0; x < 99; x++)
                    {
                        for (int i = 0; i < numbers; i++)
                        {
                            average += arr[i];
                        }

                        average = average / numbers;
                    }
                    s.Stop();
                    Console.WriteLine("{0} ms spent...", s.ElapsedMilliseconds);




Name:
get set test
12:37:39 08/01/2010 CODE:
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            GetSetClass.IntX = 100;
            for (int i = 0; i < 90; i++)
            {
                Console.WriteLine(GetSetClass.IntX.ToString());
                GetSetClass.IntX--;
            }
            Console.ReadKey();
        }
    }

    static class GetSetClass
    {
        static private int intX = 0;

        static public int IntX
        {
            get { return intX; }
            set { intX = value; }
        }
    }
}




Name:
PERL regex test
11:35:01 12/01/2010 CODE:
#!/usr/bin/perl -w

$testX = "Gyldig";
$testY = "Ikke Gyldig";

while ($testX)
{
    print "Skriv in en mail adresse: ";
    $mailADR = ;
    chomp($mailADR);
    
    if ($mailADR =~ /^(\w+\.?\w+\@\w+\.\w{2,}.*)$/)
    {
        print $testX;
        print "\n";
    }
    else
    {
        print $testY;
        print "\n";
    }

}







Name:
PERL regex test 2 put domiant test to varialbe
13:35:00 12/01/2010 CODE:
#!/usr/bin/perl -w

$testX = "Gyldig";
$testY = "Ikke Gyldig";

while ($testX)
{
    print "Skriv in en mail adresse: ";
    $mailADR = ;
    chomp($mailADR);
    
    if ($mailADR =~ /^\w+\.?\w+\@(\w+\.\w{2,}.*)$/)
    {
        print $1;
        print "\n";
        
        $testO = $1;
        
        if (system("host -t MX $testO"))
        { 
        #print $testO;
        print "\n";
        }
    }
    else
    {
        print $testY;
        print "\n";
    }

}




Name:
advanced Struct test
22:22:28 04/02/2010 CODE:
using System;

namespace struct_test
{
    struct Point
    {
        private int x;
        private int y;

        #region properties
        
        public int X
        {
            get { return this.x; }
            set { this.x = value; }
        }
        public int Y
        {
            get{ return this.y;}
            set{ this.y = value;}
        }

        #endregion

        public static double Distance(Point pointA, Point pointB)
        {
            int a = pointA.x - pointB.x;
            int b = pointA.y - pointB.y;

            double c = Math.Sqrt((a*a + b*b));
            return c;
        }

        public double Distance(Point p)
        {
            return Distance(this, p);
        }

        public override string ToString()
        {
            return x + "," + y;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Point p1 = new Point(); // call consturctor with = new Point(); used for initinals fields
            Point p2 = new Point();

            p1.X = 2;
            p1.Y = 4;

            p2.X = 1;
            p2.Y = 1;


            Console.WriteLine(p1.X + "," + p1.Y);
            Console.WriteLine(p2.X + "," + p2.Y);
            Console.WriteLine();
            Console.WriteLine(Point.Distance(p1,p2));
            Console.WriteLine(p1.Distance(p2));
            
            //using override ToString
            Console.WriteLine(p1);
            Console.WriteLine(p2);

            Console.ReadLine();
        }
    }
}



/*output for this is.
2,4
1,1

3,16227766016838
3,16227766016838
2,4
1,1*/







Name:
Bouncing balls code.
00:13:59 05/02/2010 CODE:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace BouncY
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        public const int SCREEN_WIDTH = 640;
        public const int SCREEN_HEIGHT = 480;

        const int BUTTON_NUM = 8;
        public const int BUTTON_RADIUS = 16;
        const float BUTTON_SPEED_MIN = 1f;
        const float BUTTON_SPEED_MAX = 4f;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Texture2D buttonTexture;
        public static Random random;

        private static float Range(float min, float max)
        {
            return (float) random.NextDouble()*(max - min) + min;
        }

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
            graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
            Content.RootDirectory = "Content";
        }

        protected override void LoadContent()
        {

            spriteBatch = new SpriteBatch(GraphicsDevice);
            random = new Random();
            buttonTexture = Content.Load(@"Textures\button");

            for (int i = 0; i < 8; i++)
            {
                Button button = new Button();
                button.SetRandomPosition();

                float speed = Range(BUTTON_SPEED_MIN, BUTTON_SPEED_MAX);
                button.SetRandomDirection(speed);
            }
        }
        
        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            for (int i = Actor.Actors.Count - 1; i >= 0; i--)
            {
                Actor actor = Actor.Actors[i];
                actor.Move(actor.Velocity);
                actor.Update(gameTime);
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin();

            foreach (Actor actor in Actor.Actors)
            {
                spriteBatch.Draw(buttonTexture, actor.Position,null,actor.Color,0f, new Vector2(BUTTON_RADIUS,BUTTON_RADIUS),1f,SpriteEffects.None, 0f );
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}


using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BouncY
{
    class Actor
    {
        protected Vector2 position;
        protected Vector2 velocity;
        private Color color;

        public static List Actors;


        #region properties

        public Vector2 Position
        {
            get { return position; }
            set { position = value; }
        }

        public Vector2 Velocity
        {
            get { return velocity; }
            set { velocity = value; }
        }
        public Color Color
        {
            get { return color; }
            set { color = value; }
        }
        #endregion

        static Actor()
        {
            Actors = new List();
        }

        public Actor()
        {
            Actors.Add(this);
            color = Color.White;
        }

        public void Move(Vector2 ammount)
        {
            position += ammount;
        }

        public void SetRandomPosition()
        {
            position = new Vector2(Game1.random.Next(Game1.BUTTON_RADIUS, Game1.SCREEN_WIDTH - Game1.BUTTON_RADIUS), 
                                   Game1.random.Next(Game1.BUTTON_RADIUS, Game1.SCREEN_HEIGHT - Game1.BUTTON_RADIUS));
        }

        public void SetRandomDirection(float speed)
        {
            float rotation = (float) (Game1.random.NextDouble()*Math.PI*2);
            velocity = new Vector2((float) Math.Sin(rotation),
                                   (float) Math.Cos(rotation))*speed;
        }

        public virtual void Update(GameTime gameTime){}

    }
}


using System;
using Microsoft.Xna.Framework;

namespace BouncY
{
    class Button : Actor
    {
        public override void Update(GameTime gameTime)
        {
            CheckWallCollision();
            CheckActorCollision();
        }

        private void CheckWallCollision()
        {
            if(position.X < Game1.BUTTON_RADIUS)
            {
                position.X = Game1.BUTTON_RADIUS;
                velocity.X *= -1;
            }
            if (position.X > Game1.SCREEN_WIDTH - Game1.BUTTON_RADIUS)
            {
                position.X = Game1.SCREEN_WIDTH - Game1.BUTTON_RADIUS;
                velocity.X *= -1;
            }
            if (position.Y < Game1.BUTTON_RADIUS)
            {
                position.Y = Game1.BUTTON_RADIUS;
                velocity.Y *= -1;
            }
            if (position.Y > Game1.SCREEN_HEIGHT - Game1.BUTTON_RADIUS)
            {
                position.Y = Game1.SCREEN_HEIGHT - Game1.BUTTON_RADIUS;
                velocity.Y *= -1;
            }
        }

        private void CheckActorCollision()
        {
            foreach (Actor actor in Actors)
            {
                if(actor == this)
                    continue;
                
                Button buttonA = this as Button;
                Button buttonB = actor as Button;

                if (buttonA ==  null || buttonB == null)
                    continue;

                float overlap = Game1.BUTTON_RADIUS * 2 - Vector2.Distance(buttonA.Position, buttonB.Position);
                
                if (overlap > 0f)
                {
                    Vector2 velocityA = buttonA.Velocity;
                    buttonA.Velocity = buttonB.Velocity  ;
                    buttonB.Velocity = velocityA ;

                    Vector2 direction = Vector2.Normalize(buttonA.Position - buttonB.Position);
                    buttonA.Move(direction * overlap /2);
                    buttonB.Move( -direction * overlap /2);
                }

            }
        }

    }
}





Name:
Sequence tester game
13:49:50 07/02/2010 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Sequence
{
    enum GameState
    { 
        Input,
        Output,
        Succeed,
        Fail

    }

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private SpriteFont spriteFont;
        private Random random;

        GameState gameState;
        Button[] buttons;
        List sequence;
        List playerSequence;

        int sequenceIndex;

        double pulseDuration = 0.2d;
        double timeInterval = 0.5d;
        double timeRemaining;

        private void AppendSequence(int count)
        {
            for (int i = 0; i < count; i++)
            {
                sequence.Add((byte)random.Next(buttons.Length));

            }
        }

        private void Pulse(byte buttonIndex)
        {
            buttons[buttonIndex].Pulse(pulseDuration);
        }

        private void PressButton(byte buttonIndex)
        {
            if (playerSequence.Count < sequence.Count)
            {
                playerSequence.Add(buttonIndex);
                Pulse(buttonIndex);
                CheckSequence();
            }
        }

        private void CheckSequence()
        {
            for (int i = 0; i < playerSequence.Count; i++)
            {
                if (playerSequence[i] != sequence[i])
                {
                    gameState = GameState.Fail;
                    return;
                }
            }
            if (playerSequence.Count == sequence.Count && gameState != GameState.Fail)
            {
                gameState = GameState.Succeed;
            }

        }


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            random = new Random();
            spriteBatch = new SpriteBatch(GraphicsDevice);

            buttons = new Button[] { new Button(),
                                     new Button(),
                                     new Button(),
                                     new Button()
                                   };

            sequence = new List();
            playerSequence = new List();
            AppendSequence(3);

            timeRemaining = timeInterval;

            gameState = GameState.Output;

            base.Initialize();
        }

        protected override void LoadContent()
        {
            buttons[0].Texture = Content.Load(@"TEXTURES\left_arrow");
            buttons[1].Texture = Content.Load(@"TEXTURES\up_arrow");
            buttons[2].Texture = Content.Load(@"TEXTURES\down_arrow");
            buttons[3].Texture = Content.Load(@"TEXTURES\rigth_arrow");

            spriteFont = Content.Load(@"TEXTURES\SpriteFont1");
        }


        protected override void UnloadContent()
        {
           
        }

        protected override void Update(GameTime gameTime)
        {
           
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            for (int i = 0; i < buttons.Length; i++)
            {
                buttons[i].Update(gameTime);
            }

            InputHelper.Update();

            switch (gameState)
            { 
                case GameState.Input:

                    for (int i = 0; i < buttons.Length; i++)
                    {
                            if (InputHelper.gameKeys[i].Pressed)
                                PressButton((byte)i);
                           
                    }
                  
                    break;
                case GameState.Output:
                    timeRemaining -= gameTime.ElapsedGameTime.TotalSeconds;
                    if (timeRemaining <= 0d)
                    {
                        Pulse(sequence[sequenceIndex]);
                        sequenceIndex++;
                        if (sequenceIndex >= sequence.Count)
                        {
                            playerSequence.Clear();
                            gameState = GameState.Input;
                        }
                        timeRemaining = timeInterval;
                    }
                    break;
                case GameState.Succeed:
                case GameState.Fail:
                    if (InputHelper.gameKeys[4].Pressed)
                    {
                        if (gameState == GameState.Succeed)
                            AppendSequence(1);
                        
                        sequenceIndex = 0;
                        gameState = GameState.Output;
                    }
                    break;

            }

            base.Update(gameTime);
        }


        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin();

            for (int i = 0; i < buttons.Length; i++)
            {
                Vector2 position = new Vector2(i * 64, 0f);
                spriteBatch.Draw(buttons[i].Texture, position, buttons[i].color);
            }

            
            Color textColor = Color.Black;
            string text = "";
            if (gameState == GameState.Fail)
            {
                text = "FAIL";
                textColor = Color.Red;
            }
            else if (gameState == GameState.Succeed)
            {
                text = "SUCCESS";
                textColor = Color.Blue;
            }
            Vector2 textposition = spriteFont.MeasureString(text);
            textposition.X = 400 - textposition.X / 2;
            textposition.Y = 300 - textposition.Y / 2;
            spriteBatch.DrawString(spriteFont, text, textposition, textColor);

            base.Draw(gameTime);
            
            spriteBatch.End();
        }
    }
}


using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Sequence
{
    class Button
    {
        public Texture2D Texture;
        public Color color;

        private double timeRemaining;

        public Button()
        {
            this.color = Color.Gray;
        }

        public void Pulse(double duration)
        {
            this.timeRemaining = duration;
            this.color = Color.White;
        }

        public void Update(GameTime gameTime)
        {
            if (this.timeRemaining > 0d)
            {
                this.timeRemaining -= gameTime.ElapsedGameTime.TotalSeconds;
                if (this.timeRemaining <= 0d)
                {
                    this.color = Color.Gray;
                }
            }
        }

    }
}



using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Sequence
{
    struct GameKey
    {
        public Keys Key;
        public bool Down;
        public bool Pressed;
        public bool Released;

        public GameKey(Keys key)
        {
            this.Key = key;
            this.Down = false;
            this.Pressed = false;
            this.Released = false;
        }
    }

    static class InputHelper
    {
        public static GameKey[] gameKeys;
        private static KeyboardState keyboardState;
        private static KeyboardState lastKeyboardState;

        static InputHelper()
        {
            gameKeys = new GameKey[] {new GameKey(Keys.Left), 
                                      new GameKey(Keys.Up),
                                      new GameKey(Keys.Down),
                                      new GameKey(Keys.Right),
                                      new GameKey(Keys.Enter)};
        }

        public static void Update()
        {
            keyboardState = Keyboard.GetState();

            for (int i = 0; i < gameKeys.Length; i++)
            {
                if (keyboardState.IsKeyDown(gameKeys[i].Key))
                {
                    gameKeys[i].Down = true;
                    if (lastKeyboardState.IsKeyUp(gameKeys[i].Key))
                        gameKeys[i].Pressed = true;
                    else
                        gameKeys[i].Pressed = false;
                }
                else 
                {
                    gameKeys[i].Down = false;
                    if (lastKeyboardState.IsKeyDown(gameKeys[i].Key))
                        gameKeys[i].Released = true;
                    else
                        gameKeys[i].Released = false;
                }
            }

            lastKeyboardState = keyboardState;
        }


    }
}






Name:
sound class for above game
15:34:41 07/02/2010 CODE:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

namespace Sequence
{
    static class SoundHelper
    {
        static AudioEngine audioEngine;
        static WaveBank waveBank;
        static SoundBank soundBank;

        static string[] sounds;

        public static void Initialize()
        {
            audioEngine = new AudioEngine(@"Content\Sounds\Audio.xgs");

            waveBank = new WaveBank(audioEngine, @"Content\Sounds\Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, @"Content\Sounds\sound Bank.xsb");

            sounds = new string[]{"sound_1", "sound_2", "sound_3", "sound_4"};
        }

        public static void Update()
        {
            audioEngine.Update();
        }

        public static void PlaySound(int pitchIndex)
        {
            soundBank.PlayCue(sounds[pitchIndex]);
        }
    }
}

and to teh game1 class add
private void Pulse(byte buttonIndex)
        {
 SoundHelper.PlaySound(buttonIndex);

protected override void Initialize()
        {
            SoundHelper.Initialize();


and under update
SoundHelper.Update();




Name:
Keys Loop test tool
15:25:49 09/02/2010 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MouseKeyboardLibrary;
using System.Threading;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;


namespace test_Keys_loop
{
    public partial class Form1 : Form
    {
        bool blueX = false;
        bool redX = false;
        string colorX;
        int r;
        int g;
        int b;
        bool needUnblock = false;
        int xX, yY;
        int x, y;
        int pross = 100;
        int value_bar;
        string inputString;
        char[] inputArrayX;

        public Form1()
        {
            InitializeComponent();
            inputString = label1.Text;
            inputArrayX = inputString.ToCharArray();
        }     
        #region user32 imports
        [DllImport("user32.dll")]
        static extern bool BlockInput(bool fBlockIt);
        [DllImport("gdi32")]
        private static extern int GetPixel(IntPtr hdc, int x, int y);
        [DllImport("User32")]
        private static extern IntPtr GetWindowDC(IntPtr hwnd);



        #endregion

        #region Pixel color test

        private static readonly IntPtr DesktopDC = GetWindowDC(IntPtr.Zero);

        public static System.Drawing.Color GetPixelAtCursor()
        {
            System.Drawing.Point p = Cursor.Position;
            int color = GetPixel(DesktopDC, p.X, p.Y);
            return System.Drawing.Color.FromArgb(color & 0xFF, color >> 8 & 0xFF, color >> 16);
        }


        public void getColor()
        {
            this.Location = new Point(0, 0);
            userMousePos();
            checkColorBlue();
            checkColorRed();
            Cursor.Position = new Point(x, y);
        }
        
        private void getPixel()
        {
            Color backX = GetPixelAtCursor();

            r = backX.R;
            g = backX.G;
            b = backX.B;
        }
        
        public void checkColorBlue()
        {
            Cursor.Position = new Point(741, 143);
            getPixel();
            if (r == 0 && g == 84 && b == 227)
                blueX = true;
        }

        public void checkColorRed()
        {

            Cursor.Position = new Point(661, 142);
            getPixel();
            if (r == 255 && g == 0 && b == 0)
                redX = true;
        }

        #endregion


        private void userMousePos()
        {
            x = MousePosition.X;
            y = MousePosition.Y;
        }

        private void defaultMousePos()
        {
            Cursor.Position = new Point(xX, yY);
        }

        public void inputBlocker()
        {
            if (needUnblock == false)
                BlockInput(true);
            if (needUnblock == true)
            {
                BlockInput(false);
                needUnblock = false;
            }
        }

        private void MouseMacroChangeUser()
        {

            //move form to 0,0
            this.Location = new Point(0, 0);
            //set xy to mouse current pos
            userMousePos();
            //inputBlocker();
            xX = int.Parse(this.Location.X.ToString());
            yY = int.Parse(this.Location.Y.ToString());
            defaultMousePos();
            //Thread.Sleep(600);

            Cursor.Position = new Point(Cursor.Position.X + 739, Cursor.Position.Y + 162);
            //Thread.Sleep(100);
            MouseSimulator.DoubleClick(MouseButton.Left);
            //Cursor.Position = new Point(this.Location.X + 1219, this.Location.Y + 363);
            //Thread.Sleep(100);
            MouseSimulator.DoubleClick(MouseButton.Left);
            for (int i = 0; i < inputArrayX.Length; i++)
            {
                string tempX = inputArrayX[i].ToString();
                Keys keys = mapToKeyboardMacro(tempX);
                KeyboardSimulator.KeyPress(keys);
            }
            KeyboardSimulator.KeyPress(Keys.Enter);
            //Thread.Sleep(500);
            //Cursor.Position = new Point(this.Location.X + 1228, this.Location.Y + 278);
            MouseSimulator.Click(MouseButton.Left);


            //reset mouse to user pos.
            Cursor.Position = new Point(x, y);

            needUnblock = true;

            //inputBlocker();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            inputString = label1.Text;
            inputArrayX = inputString.ToCharArray();
            backgroundWorker1.RunWorkerAsync();
        }

        private void startThread()
        {
            startMacro(inputArrayX);
        }

        private void startMacro(char[] arrayX)
        {
            for (int i = 0; i < arrayX.Length; i++)
            {
                text = text + arrayX[i].ToString();
                Thread.Sleep(1000);
                pross = pross + value_bar;
                backgroundWorker1.ReportProgress(pross, "test");
            }
        }

        private void runKeyboardMacro(string key, string sta)
        {
            Keys keys = mapToKeyboardMacro(key);
            if (sta == "Down")
            {
                KeyboardSimulator.KeyDown(keys);
            }
            else if (sta == "Up")
            {
                KeyboardSimulator.KeyUp(keys);
            }
            else if (sta == "Press")
            {
                KeyboardSimulator.KeyPress(keys);
            }
            else
            {
                MessageBox.Show("Run KeyBoard Error.");
            }
        }

        private Keys mapToKeyboardMacro(string key)
        {
            if (key == "space")
            {
                return Keys.Space;
            }
            else if (key == "a")
            {
                return Keys.A;
            }
            else if (key == "b")
            {
                return Keys.B;
            }
            else if (key == "c")
            {
                return Keys.C;
            }
            else if (key == "d")
            {
                return Keys.D;
            }
            else if (key == "e")
            {
                return Keys.E;
            }
            else if (key == "f")
            {
                return Keys.F;
            }
            else if (key == "g")
            {
                return Keys.G;
            }
            else if (key == "h")
            {
                return Keys.H;
            }
            else if (key == "i")
            {
                return Keys.I;
            }
            else if (key == "j")
            {
                return Keys.J;
            }
            else if (key == "k")
            {
                return Keys.K;
            }
            else if (key == "l")
            {
                return Keys.L;
            }
            else if (key == "m")
            {
                return Keys.M;
            }
            else if (key == "n")
            {
                return Keys.N;
            }
            else if (key == "o")
            {
                return Keys.O;
            }
            else if (key == "p")
            {
                return Keys.P;
            }
            else if (key == "q")
            {
                return Keys.Q;
            }
            else if (key == "r")
            {
                return Keys.R;
            }
            else if (key == "s")
            {
                return Keys.S;
            }
            else if (key == "t")
            {
                return Keys.T;
            }
            else if (key == "u")
            {
                return Keys.U;
            }
            else if (key == "v")
            {
                return Keys.V;
            }
            else if (key == "w")
            {
                return Keys.W;
            }
            else if (key == "x")
            {
                return Keys.X;
            }
            else if (key == "y")
            {
                return Keys.Y;
            }
            else if (key == "z")
            {
                return Keys.Z;
            }
            else if (key == "F1")
            {
                return Keys.F1;
            }
            else if (key == "F2")
            {
                return Keys.F2;
            }
            else if (key == "F3")
            {
                return Keys.F3;
            }
            else if (key == "F4")
            {
                return Keys.F4;
            }
            else if (key == "F5")
            {
                return Keys.F5;
            }
            else if (key == "F6")
            {
                return Keys.F6;
            }
            else if (key == "F7")
            {
                return Keys.F7;
            }
            else if (key == "F8")
            {
                return Keys.F8;
            }
            else if (key == "F9")
            {
                return Keys.F9;
            }
            else if (key == "F10")
            {
                return Keys.F10;
            }
            else if (key == "F11")
            {
                return Keys.F11;
            }
            else if (key == "F12")
            {
                return Keys.F12;
            }
            else if (key == "Caps Lock")
            {
                return Keys.CapsLock;
            }
            else if (key == "Enter")
            {
                return Keys.Enter;
            }
            else if (key == "Shift")
            {
                return Keys.Shift;
            }
            else if (key == "Ctrl")
            {
                return Keys.Control;
            }
            //else if(key == "Window"){
            //    return Keys;
            //}
            else if (key == "Alt")
            {
                return Keys.Alt;
            }
            else if (key == "Apps")
            {
                return Keys.Apps;
            }
            else if (key == "Left")
            {
                return Keys.Left;
            }
            else if (key == "Right")
            {
                return Keys.Right;
            }
            else if (key == "Up")
            {
                return Keys.Up;
            }
            else if (key == "Down")
            {
                return Keys.Down;
            }
            else if (key == "Backspace")
            {
                return Keys.Back;
            }
            else if (key == "Home")
            {
                return Keys.Home;
            }
            else if (key == "PageUp")
            {
                return Keys.PageUp;
            }
            else if (key == "PageDown")
            {
                return Keys.PageDown;
            }
            else if (key == "Delete")
            {
                return Keys.Delete;
            }
            else if (key == "End")
            {
                return Keys.End;
            }
            else if (key == "NumLock")
            {
                return Keys.NumLock;
            }
            else if (key == "Tab")
            {
                return Keys.Tab;
            }
            else if (key == "Decimal")
            {
                return Keys.Decimal;
            }
            else if (key == ";")
            {
                return Keys.OemSemicolon;
            }
            else if (key == "")
            {
                MessageBox.Show("Command Error : Cant map Null Keyboard");
                return Keys.BrowserRefresh;
            }
            else
            {
                MessageBox.Show("Command Error : Cant map Keyboard");
                return Keys.BrowserRefresh;
            }
        }


        string text = null;
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            value_bar = pross / inputArrayX.Length;
            pross = 0;
            startMacro(inputArrayX);    
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = pross;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
             textBox1.Text = text.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox2.Text = textBox2.Text + 1;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Location = new Point(0, 0);
            xX = int.Parse(this.Location.X.ToString());
            yY = int.Parse(this.Location.Y.ToString());
            defaultMousePos();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            getColor();
            try
            {
                if (blueX == true && redX == true)
                {
                    MouseMacroChangeUser();
                }
                else
                {
                    MessageBox.Show("blue = " + blueX.ToString() + "  " +"redX = " + redX.ToString());
                }
            }
            catch(System.Exception excep)
            {
                    MessageBox.Show(excep.Message);
            }

            blueX = false;
            redX = false;
            
        }

        private void label4_MouseMove(object sender, MouseEventArgs e)
        {
            label4.Location = new Point(this.Location.X + Cursor.Position.X, this.Location.X + Cursor.Position.Y);

        }
    }
}




Name:
Color Check Tool
15:28:37 09/02/2010 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace Color_tool
{
    public partial class Form2 : Form
    {
        string colorX;
        int r;
        int g;
        int b;

        public Form2()
        {
            InitializeComponent();
        }

        [DllImport("gdi32")]
        private static extern int GetPixel(IntPtr hdc, int x, int y);
        [DllImport("User32")]
        private static extern IntPtr GetWindowDC(IntPtr hwnd);

        private static readonly IntPtr DesktopDC = GetWindowDC(IntPtr.Zero);

        public static System.Drawing.Color GetPixelAtCursor()
        {
            System.Drawing.Point p = Cursor.Position;
            int color = GetPixel(DesktopDC, p.X, p.Y);
            return System.Drawing.Color.FromArgb(color & 0xFF, color >> 8 & 0xFF, color >> 16);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            colorX = GetPixelAtCursor().ToString();
            Color backX = GetPixelAtCursor();

            r = backX.R;
            g = backX.G;
            b = backX.B;

            this.BackColor = Color.FromArgb(r, g, b);
            label1.Text = colorX;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled == false)
                timer1.Enabled = true;
            else
                timer1.Enabled = false;
        }
    }
}




Name:
kill process c#
14:54:50 10/02/2010 CODE:
Process[] processes = Process.GetProcessesByName("NOC_Ticker");

            foreach (Process p in processes)
            {
                //p.CloseMainWindow();
                p.Kill();;
            }
            System.Diagnostics.Process.Start(@"C:\noc_beta\Ticker\NOC_Ticker.appref-ms");




Name:
matrix code
12:14:06 11/02/2010 CODE:
Program.cs

using System;

namespace Matrix
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Matrix";
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WindowHeight = Console.BufferHeight = 32;
            Console.WindowWidth = Console.BufferWidth = 100;

            Console.CursorVisible = false;
            int width, height;
            int[] X;
            int[] O;
            Initialize(out width, out height, out X, out O);
            int ms;
            while (true)
            {
                DateTime t1 = DateTime.Now;
                MatrixStep(width, height, X, O);
                ms = 10 - (int)((TimeSpan)(DateTime.Now - t1)).Minutes ;
            }
        }

        static bool thistime = false;

        private static void MatrixStep(int width, int height, int[] y, int[] l)
        {
            int x;
            thistime = !thistime;
            for (x = 0; x < width; ++x)
            {
                if (x % 11 == 5)
                {
                    if (!thistime)
                        continue;
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.SetCursorPosition(x, inBoxY(y[x] - 20 - (l[x] / 40 * 2), height));
                    Console.Write(R);
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                Console.SetCursorPosition(x, y[x]);
                Console.Write(R);
                y[x] = inBoxY(y[x] + 1, height);
                Console.SetCursorPosition(x, inBoxY(y[x] - l[x], height));
                Console.Write(' ');
            }
        }

        private static void Initialize(out int width, out int height, out int[] y, out int[] l)
        {
            int h1;
            int h2 = (h1 = (height = Console.WindowHeight) / 2) / 2;
            width = Console.WindowWidth - 1;
            y = new int[width];
            l = new int[width];
            int x;
            Console.Clear();
            for (x = 0; x < width; ++x)
            {
                y[x] = r.Next(height);
                l[x] = r.Next(h2 * ((x % 11 != 10) ? 2 : 1), h1 * ((x % 11 != 10) ? 2 : 1));
            }
        }

        static Random r = new Random();
        static char R
        {
            get
            {
                int t = r.Next(20);
                if (t <= 2)
                    return (char)('0' + r.Next(15));
                else if (t <= 4)
                    return (char)('a' + r.Next(15));
                else if (t <= 6)
                    return (char)('A' + r.Next(15));
                else
                    return (char)(r.Next(0, 9));
            }
        }

        public static int inBoxY(int n, int height)
        {
            n = n % height;
            if (n < 0)
                return n + height;
            else
                return n;
        }
    }
}





Name:
read and write to file
16:20:37 22/02/2010 CODE:
// Write to text file
// The output will be in your Bin/Debug folder by default, this can be changed by adding your own path

                System.IO.StreamWriter StreamWriter1 =
                new System.IO.StreamWriter("myFile.txt");
                StreamWriter1.WriteLine(textBox1.Text);
                StreamWriter1.Close();


// Read the text file
            System.IO.StreamReader StreamReader1 =
            new System.IO.StreamReader("myFile.txt");
            textBox1.Text = StreamReader1.ReadToEnd();
            StreamReader1.Close();

// Write to specific lines in a text file
// Note that the first line is [0]
            StreamWriter writer = new StreamWriter("myFile.txt");
            writer.WriteLine("Line1");
            writer.WriteLine("Line2");
            writer.WriteLine("Line3");
            writer.WriteLine("Line4");
            writer.Close();

// Read from specific lines in a text file
// Note that the first line is [0]

StreamReader reader = new StreamReader("myFile.txt");
            string strAllFile = reader.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r", "\n");
            string[] arrLines = strAllFile.Split(new char[] { '\n' });
            textBox1.Text = arrLines[0];
            textBox2.Text = arrLines[1];
            reader.Close();

// The output of this will be textBox1 will say "Line1" and textBox2 will say "Line2"




Name:
grid spawn
14:49:50 13/03/2010 CODE:
 int numCols = 8;
            int numRows = 6;

            for (int i = 0; i < numCols; i++)
            {
                for (int j = 0; j < numRows; j++)
                {
                    Box box = new Box(32,32);
                    box.Position = new Vector2(i * 80 + 48, j * 80 + 48);

                }
            }




Name:
squareBox Corner Array
23:53:03 13/03/2010 CODE:
            this.CornerMarkers = new float[4];
            this.CornerMarkers[0] = MathHelper.Pi/4;
            
            for (int i = 1; i < CornerMarkers.Length; i++)
            {
                this.CornerMarkers[i] = this.CornerMarkers[i - 1] + MathHelper.Pi/2;
            }




Name:
Covert String to Byte[] array test
18:36:05 14/03/2010 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringToByteConvert
{
    class Program
    {
        static string printX;

        static Byte[] ByteArray;

        static void Main(string[] args)
        {
            ConvertMethod("Test to byte[]Array");

            //print out the bytes in the array
            for (int i = 0; i < ByteArray.Length; i++)
            {
                Console.WriteLine(ByteArray[i]);
            }
            
            ConvertMethod(ByteArray);

            Console.WriteLine(printX);
            Console.ReadKey();
        }
        //convert from string to ByteArray
        private static void ConvertMethod(string stringX)
        {
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            ByteArray = UTF8.GetBytes(stringX);
        }

        //Convert from ByteArray to string
        private static void ConvertMethod(Byte[] ByteArray)
        {
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            printX = UTF8.GetString(ByteArray);
        }
    }
}




Name:
Timer / stopwatch hos to time a function
21:12:51 14/03/2010 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TimeFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            // Start the stopwatch
            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < 100; i++)
                Console.WriteLine("Hello World!");

            // Stop the stopwatch
            sw.Stop();

            // Report the results
            Console.WriteLine("Time used (float): {0} ms", sw.Elapsed.TotalMilliseconds);
            Console.WriteLine("Time used (rounded): {0} ms", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }
}




Name:
Delegate pointer test
11:46:41 21/03/2010 CODE:
using System;

namespace Delegate_test
{
    class Program
    {
        // sets a delegate that returns and takes an int
        public delegate int IntX(int x);
        
        //created a method for the delgate to point at.
        static public int DoubleX(int x)
        {
            return x * 2;
        }

        static void Main()
        {
            IntX tempDelegate = new IntX(DoubleX);

            Console.WriteLine("{0}", tempDelegate(5));
            Console.ReadLine();
        }
    }
}




Name:
Delegate Using an Anonymous Method
11:53:30 21/03/2010 CODE:
using System;

namespace Delegate_test
{
    class Program
    {
        // sets a delegate that returns and takes an int
        public delegate int IntX(int x);
        
        static void Main()
        {
            //using an anonymous method you cold write it like this.
            IntX tempDelegate = new IntX(delegate(int x){return x * 2;});

            Console.WriteLine("{0}", tempDelegate(5));
            Console.ReadLine();
        }
    }
}




Name:
Delegate with a lambda expression
11:55:53 21/03/2010 CODE:
using System;

namespace Delegate_test
{
    class Program
    {
        // sets a delegate that returns and takes an int
        public delegate int IntX(int x);
        
        static void Main()
        {
            //using a lambda expression you cold type it like this.
            IntX tempDelegate = x => x * 2;

            Console.WriteLine("{0}", tempDelegate(5));
            Console.ReadLine();
        }
    }
}




Name:
Delegate that returns Void
12:13:42 21/03/2010 CODE:
using System;

namespace Delegate_test
{
    class Program
    {
        // sets a delegate that returns a void and takes an string
        public delegate void WriteToConsole(string arg);
        
        static void Main(string[] args)
        {

            WriteToConsole o = a =>
            {
                Console.WriteLine(a);
                Console.ReadLine();
                Console.WriteLine("Works realy well");
                Console.ReadLine();
                };

            o("Press Enter to move on.");

        }
    }
}




Name:
Delegate that returns Void using no arguments
12:17:35 21/03/2010 CODE:
using System;

namespace Delegate_test
{
    class Program
    {
        // sets a delegate that returns a void 
        public delegate void WriteToConsole();
        
        static void Main(string[] args)
        {

            WriteToConsole o = () =>
            {
                Console.WriteLine("test works press enter.");
                Console.ReadLine();
                Console.WriteLine("Works realy well");
                Console.ReadLine();
                };

            o();

        }
    }
}




Name:
Delegate with a lambda expression geting int from key press from user.
19:21:23 21/03/2010 CODE:
using System;

namespace Delegate_test
{
    class Program
    {
        public delegate int tempInt(int x);

        static void Main(string[] args)
        {
            while (true)
            {
                //The Lambda expression created
                tempInt tempx = x => (x + 2) * 4;

                Console.WriteLine();
                Console.WriteLine("Type a number:");
                
                //read nummer in to key
                var num = Console.ReadLine();
                
                //calling the delegate puts in the number from user
                int fe = tempx(int.Parse(num.ToString()));

                Console.WriteLine("What you typed is x");
                Console.WriteLine("Lambda expression is");
                Console.WriteLine("(x => (x + 2) * 4)");
                Console.WriteLine("result is: " + fe.ToString());
            } 
        }
    }
}




Name:
Generating 100 random numbers and finding the avarage
23:40:18 22/03/2010 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GetRandomInt
{
    class Program
    {
        private static Random randomint = new Random();
        private static List intS = new List();

        static void Main(string[] args)
        {
            GetRandomInt();
        }

        private static void GetRandomInt()
        { 
            int i = 0;
            
            while (i < 100)
            {
                int x = randomint.Next(1, 10);
                Console.WriteLine(x);
                intS.Add(x);
                i++;
            }
            
            int lenght = intS.Count;

            int tempX = 0;

            for (int j = 0; j < lenght; j++)
            {
                tempX = tempX + intS[j]; 
            }
            int tempY = tempX/lenght;
            Console.WriteLine("average is: " + tempY);
            Console.ReadKey();
        }
    }
}




Name:
List string var
13:47:58 26/03/2010 CODE:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List listX = new List();

            listX.Add("one");
            listX.Add("two");
            listX.Add("tree");
            listX.Add("four");
            listX.Add("five");

            for (int i = listX.Count - 1; i >= 0; i--)
            {
                //put the item inn to a var.
                string tempY = listX[i]; 
                //prosses th item in the list.
                Console.WriteLine(listX[i]);
                //use the var to remove the item just been prossesed
                listX.Remove(tempY);
            }

            Console.ReadLine();

            listX.Add("one");
            listX.Add("two");
            for (int i = listX.Count - 1; i >= 0; i--)
            {
                Console.WriteLine(listX[i]);
            }
        }
    }
}




Name:
List with objects
16:02:44 26/03/2010 CODE:
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    { 
        static List husList = new List();

        static void Main(string[] args)
        {
           

            addHouses();

            GetHouseInfo(husList);
        }

        private static void GetHouseInfo(List husList)
        {
            for (int i = 0; i < husList.Count; i++)
            {
                Console.ForegroundColor = husList[i].color;
                Console.WriteLine("\n████The house color is████");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("House m2 = " + husList[i].areal);
                Console.WriteLine("House height = " + husList[i].height);
            }
            Console.WriteLine("\n\nthere is this many houses in the list = " + husList.Count);
            Console.ReadKey();
            
        }
        

        private static void addHouses()
        {
            

            hus hs = new hus();
            hs.color = ConsoleColor.Blue;
            hs.areal = 42;
            hs.height = 100;
            husList.Add(hs);

            hus hs2 = new hus();
            hs2.color = ConsoleColor.Cyan;
            hs2.areal = 100;
            hs2.height = 32;
            husList.Add(hs2);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class hus
    {
        public ConsoleColor color = ConsoleColor.Black;
        public int areal = 0;
        public int height = 0;
    }
}




Name:
Console Calculator c#
17:32:55 28/03/2010 CODE:
using System;

namespace Calculator_test
{
    internal class Program
    {
        private static void Main()
        {
                StartCalc();
                return;
        }

        private static void StartCalc()
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("SimpleCalculator");
            GetCalc();
        }

        private static void GetCalc()
        {
            GetNumberOne();
        }

        private static void GetNumberOne()
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Enter first number then press enter:");

            string num1 = Console.ReadLine();
            double tempInt;

            bool isNum = double.TryParse(num1, out tempInt);

            if (isNum)
            {
                if (num1 != null) calc.Num1 = int.Parse(num1);
            }

            else
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("you have entered a error, enter only numbers ");
                Console.ForegroundColor = ConsoleColor.Cyan;

                GetNumberOne();
            }

            //get the operator
            GetOperatorsForCalc();
        }

        private static void GetNumberTwo()
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Enter second number then press enter:");

            string num2 = Console.ReadLine();
            double tempInt;

            bool isNum = double.TryParse(num2, out tempInt);

            if (isNum)
            {
                if (num2 != null) calc.Num2 = int.Parse(num2);
            }

            else
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("you have entered a error, enter only numbers ");
                Console.ForegroundColor = ConsoleColor.Cyan;

                GetNumberTwo();
            }
            DoCalculation();
        }

        private static void GetOperatorsForCalc()
        {
            Console.WriteLine("What do you want to do press +,-,* or / and press enter:");
            string x = Console.ReadLine();

            if (x == "+" || x == "-" || x == "*" || x == "/")
            {
                calc.OPr = x;
                GetNumberTwo();
            }
            else
            {
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("you have entered a error, use +,-,* or / ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                GetOperatorsForCalc();
            }
        }

        private static void DoCalculation()
        {
            Console.WriteLine("The expressions is: " + calc.Num1 + " " + calc.OPr + " " + calc.Num2);
            Console.WriteLine("And the awnser is:");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(calc.calcXYZ());
            Console.ReadKey();
            Console.Clear();
            Main();
        }
    }
}

namespace Calculator_test
{
    static class calc
    {
        private static int num1 = 0;
        private static int num2 = 0;
        static string oPr = "null";

        #region properties
        public static int Num1
        {
            get
            {
                return num1;
            }
            set
            {
                num1 = value;
            }
        }
        public static int Num2
        {
            get
            {
                return num2;
            }
            set
            {
                num2 = value;
            }
        }
        public static string OPr
        {
            get
            {
                return oPr;
            }
            set
            {
                oPr = value;
            }
        }
        #endregion

        public static int calcXYZ()
        {
            if(oPr == "+")
            {
                int x = num1 + num2;
                return x;
            }
            if(oPr == "-")
            {
                int x = num1 - num2;
                return x;
            }
            if (oPr == "/")
            {
                int x = num1 / num2;
                return x;
            }
            if (oPr == "*")
            {
                int x = num1 * num2;
                return x;
            }
            else
            {
                int x = 0;
                return x;
            }
        }
    }
}




Name:
logmein v2
17:10:12 30/09/2010 CODE:
using System;
using System.Threading;
using System.Windows.Forms;

namespace Logmein_app
{
    public partial class Form1 : Form
    {
        private char[] myChar;

        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser2.Document != null)
            {
                webBrowser2.Document.All.GetElementsByName("email")[0].SetAttribute("Value", "***");
                webBrowser2.Document.All.GetElementsByName("password")[0].SetAttribute("Value", "****");
                webBrowser2.Document.GetElementById("loginbtn").InvokeMember("click");
                webBrowser2.DocumentCompleted -= webBrowser2_DocumentCompleted;
                webBrowser2.DocumentCompleted += webBrowser2_LoginCompleted;
            }
            Thread.Sleep(600);
            webBrowser2.Url =
                new Uri("https://secure.logmein.com/mycomputers_connect.asp?hostid=48563898&hostpath=/go=r",
                        UriKind.Absolute);
        }

        private void webBrowser2_LoginCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser2.Document != null)
            {
                webBrowser2.Document.All.GetElementsByName("password")[0].SetAttribute("Value", "***");

                webBrowser2.Document.GetElementById("loginButton").InvokeMember("click");
                webBrowser2.DocumentCompleted -= webBrowser2_LoginCompleted;
                webBrowser2.DocumentCompleted += webBrowser2_LoginSiste;
            }
        }

        private void webBrowser2_LoginSiste(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser2.Document != null)
            {
                if (webBrowser2.Document != null)
                {
                    string URL = webBrowser2.Url.ToString();
                    myChar = new[] {'l', 'm', 't', 'h', '.', 'n', 'i', 'a', 'm'};
                    URL = URL.TrimEnd(myChar) + "remctrl.html";
                    webBrowser2.Url = new Uri(URL, UriKind.Absolute);
                    webBrowser2.DocumentCompleted -= webBrowser2_LoginSiste;
                    webBrowser2.DocumentCompleted += webBrowser2_DocumentCompleted;
                }
            }
        }
    }
}




Name:
web page, wait for full load
23:01:11 01/10/2010 CODE:
private const int sleepTimeMiliseconds = 5;

public void NavigateAndWaitForLoad(WebBrowser wb, string link, int waitTime)
{
    wb.Navigate(link);
    int count = 0;
    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
        Thread.Sleep(sleepTimeMiliseconds);
        Application.DoEvents();
        count++;
        if (count > waitTime / sleepTimeMiliseconds)
            break;
    }
}




Name:
get text from web page
23:45:48 01/10/2010 CODE:
System.Net.WebClient wc = new System.Net.WebClient();

  System.IO.StreamReader webReader = new System.IO.StreamReader(
         wc.OpenRead("http://your_website.com"));

  string webPageData = webReader.ReadToEnd();




Name:
Background Worker III
23:54:04 19/11/2010 CODE:
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace Background_worker_test
{
    public partial class Form1 : Form
    {
        private static int x;

        public Form1()
        {
            InitializeComponent();
        }

        private void StartButton(object sender, EventArgs e)
        {
            bw.RunWorkerAsync();
        }

        private void StopButton(object sender, EventArgs e)
        {
            if (bw.IsBusy)
            {
                bw.CancelAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = BackgroundProcessLogicMethod();
            if (bw.CancellationPending)
            {
                e.Cancel = true;
            }
        }

        private string BackgroundProcessLogicMethod()
        {
            const string result = "ferdig";
            for (int i = 0; i < 100; i++)
            {
                x = i;
                Thread.Sleep(100);
                bw.ReportProgress(x, "test");
            }
            return result;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) MessageBox.Show("Operation was canceled");
            else if (e.Error != null) MessageBox.Show(e.Error.Message);
            else getInfo.Text = e.Result.ToString();
        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            textBox1.Text = textBox1.Text + x.ToString();
        }
    }
}




Name:
console meny test
15:18:10 05/12/2010 CODE:
using System;
using System.Collections.Generic;
using System.Threading;

namespace console_meny_test
{
    internal static class Program
    {
        private static void Main()
        {
            var menu = new CMenu();
            menu.AddMenu(0); //create new menu with ID 0
            menu.AddSubMenu(0, new[] {"Goto Menu2", "Goto Menu2"});

            //Second menu
            menu.AddMenu(1); //create new menu with ID 1
            menu.AddSubMenu(1, new[] {"Goto Menu1", "[Back]"});

            while (true)
            {
                Thread.Sleep(50);
                menu.Refresh(); //lets refresh the menu...

                //put here ur own code to show stuff at the console...

                switch (menu.CurrentMenu)
                {
                    case 0:
                        Console.WriteLine("-- MENU 1 --");
                        switch (menu.SelectedIndex)
                        {
                            case 0:
                                if (menu.KeyPressed.Key == ConsoleKey.Enter)
                                {
                                    menu.CurrentMenu = 1;
                                    menu.KeyPressed = new ConsoleKeyInfo();
                                }
                                Console.WriteLine("1 temp");
                                break;
                            case 1:
                                if (menu.KeyPressed.Key == ConsoleKey.Enter)
                                {
                                    menu.CurrentMenu = 1;
                                    menu.KeyPressed = new ConsoleKeyInfo();
                                }
                                Console.WriteLine("test 2");
                                break;
                        }
                        break;
                    case 1:
                        Console.WriteLine("-- MENU 2 --");
                        switch (menu.SelectedIndex)
                        {
                            case 0:
                                if (menu.KeyPressed.Key == ConsoleKey.Enter)
                                {
                                    menu.CurrentMenu = 0;
                                    menu.KeyPressed = new ConsoleKeyInfo();
                                }
                                Console.WriteLine("push");
                                break;
                            case 1:
                                if (menu.KeyPressed.Key == ConsoleKey.Enter)
                                {
                                    menu.CurrentMenu--; //easy ha ?
                                    menu.KeyPressed = new ConsoleKeyInfo();
                                }
                                Console.WriteLine("pop");
                                break;
                        }
                        break;
                }
            }
        }

        #region Nested type: CMenu

        private class CMenu
        {
            private readonly Thread keyHandlerThread;
            private readonly SortedList menu;
            private readonly ConsoleColor nonSelectColor;
            private readonly ConsoleColor selectColor;
            public int CurrentMenu;
            public ConsoleKeyInfo KeyPressed;
            public int SelectedIndex;

            public CMenu()
            {
                menu = new SortedList();
                keyHandlerThread = new Thread(KeyPressHandler);
                keyHandlerThread.Start();
                selectColor = ConsoleColor.Green;
                nonSelectColor = ConsoleColor.Gray;
            }

            public void Refresh()
            {
                Console.Clear();
                Console.WriteLine("");
                for (int y = 0; y < menu[CurrentMenu].Length; y++)
                {
                    if (SelectedIndex == y)
                        Console.ForegroundColor = selectColor;
                    else
                        Console.ForegroundColor = nonSelectColor;

                    Console.Write(menu[CurrentMenu][y].PadLeft(12));
                    Console.ResetColor();
                }
                Console.WriteLine("");
                Console.WriteLine("");
            }

            private void KeyPressHandler()
            {
                while (true)
                {
                    KeyPressed = Console.ReadKey();
                    if (KeyPressed.Key == ConsoleKey.RightArrow)
                    {
                        if (SelectedIndex < menu[CurrentMenu].Length - 1)
                            SelectedIndex++;
                    }
                    else if (KeyPressed.Key == ConsoleKey.LeftArrow)
                    {
                        if (SelectedIndex > 0)
                            SelectedIndex--;
                    }
                }
            }

            public void AddMenu(int index)
            {
                menu.Add(index, new string[] {});
            }

            public void AddSubMenu(int index, string[] subMenu)
            {
                if (subMenu == null) throw new ArgumentNullException("subMenu");
                menu[index] = subMenu;
            }
        }

        #endregion
    }
}




Name:
Progressbar simple
00:50:03 12/12/2010 CODE:
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = (2 + 2).ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(50);
                backgroundWorker1.ReportProgress(i,null);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label2.Text = e.ProgressPercentage.ToString();
            progressBar1.Value = e.ProgressPercentage;
            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            label2.Text = "Finshed!!!";
        }
    }
}




Name:
opne wiki snippet
13:54:56 22/12/2010 CODE:
        private void startWikiButton_Click(object sender, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = "iexplore.exe";
            p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
            p.StartInfo.Arguments = "http://wiki.lyse.net/login.action?os_destination=%2Fhomepage.action";
            p.Start();

        }




Name:
Speed test
00:31:38 27/12/2010 CODE:
using System;
using System.Net;
using System.Windows.Forms;

namespace Altibox_Speed_Test
{
    public partial class Form1 : Form
    {
        //http://www.csharp-examples.net/download-files/
        	//Upload 1MB file to your webserver and put down our location!
        const string Url = @"http://81.166.80.108/speedtest/100mbtrue.txt";
        readonly WebClient wc = new WebClient();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            double starttime = Environment.TickCount;
            wc.DownloadFile(Url, Application.StartupPath + "/fart");

            double endtime = Environment.TickCount;
            double tid = Math.Floor(endtime - starttime) / 1000;
            double tid2 = Math.Round(tid, 0);

            System.IO.File.Delete(Application.StartupPath + "/fart");
            label1.Text = (tid + tid2).ToString();


        }
    }
}




Name:
Get input from Console in to Win Form
17:30:43 31/12/2010 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace ConsoleGetTestWinform
{
    public partial class Form1 : Form
    {
        private string _command = "tracert www.altibox.no";
        private string _application = "cmd";
        private string _exitCommand = "exit";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text += GetTrace();
        }

        private string GetTrace()
        {
            Process myprocess = new Process();
            System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
            StartInfo.FileName = _application;
            StartInfo.RedirectStandardInput = true;
            StartInfo.RedirectStandardOutput = true;
            StartInfo.UseShellExecute = false;
            StartInfo.CreateNoWindow = true;
            myprocess.StartInfo = StartInfo;
            myprocess.Start();
            System.IO.StreamReader SR = myprocess.StandardOutput;
            System.IO.StreamWriter SW = myprocess.StandardInput;
            SW.WriteLine(_command);
            SW.WriteLine(_exitCommand);
            string x = SR.ReadToEnd();
            SW.Close();
            SR.Close();
            return x;
        }
    }
}




Name:
Tread and delegate spawn/ multi treading
15:04:15 03/01/2011 CODE:
        private void button1_Click(object sender, EventArgs e)
        {
            //creating and starting new tread 
            Thread t = new Thread(() => testMethod(100));
            t.Start();
        }

        private void testMethod(int p)
        {
            //simultaing work done on new tread
            int sleepTime = p;
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(sleepTime);
            }
            //Cast the delegate into a method invoker
            Invoke((MethodInvoker)delegate
            {   //updating label on GUI tread
                label1.Text = "done!!";
            });

        }




Name:
LINQ test get max
15:57:17 11/01/2011 CODE:
namespace LINQ_TEST
{
    class Test 
    {
        public int x {get;set;}
        public int y {get;set;}
        public int z {get;set;}
    }
    class Program
    {
        static void Main(string[] args)
        {
            var TestArray = new[]
            {
                new Test { x = 10, y = 20, z = 30 },
                new Test { x = 11, y = 21, z = 31 },
                new Test {x = 1038, y = 423423, z = 53}
            };

            var getMaxFromZ = TestArray.Select(i => i.z).Max();

            Console.WriteLine(getMaxFromZ);
            Console.ReadKey();
        }
    }
}




Name:
delegate Func test, func returns value
13:22:26 13/01/2011 CODE:
namespace LambdaTest
{
    class Program
    {
        delegate int FuncTest(int x);

        static void Main(string[] args)
        {
            FuncTest f = x => x * 3;

            int i = f(5);

            Console.WriteLine(i);
            Console.ReadLine();
        }
    }
}




Name:
Func test two param
13:32:44 13/01/2011 CODE:
namespace LambdaTest
{
    class Program
    {
        delegate int FuncTest(int x, int y);

        static void Main(string[] args)
        {
            FuncTest f = (x, y) => x * y;

            int i = f(5,6 );

            Console.WriteLine(i);
            Console.ReadLine();
        }
    }
}




Name:
Func teste 1 param
13:37:33 13/01/2011 CODE:
namespace LambdaTest
{
    class Program
    {
        

        static void Main(string[] args)
        {
            Func f = x => x * 2;

            int i = f.Invoke(5);

            Console.WriteLine(i);
            Console.ReadLine();
        }
    }
}




Name:
func test 2 param
13:44:31 13/01/2011 CODE:
namespace LambdaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Func f = (x,y) => 5 * x * y;
            Console.WriteLine(f.Invoke(3, 3));
            Console.ReadLine();
        }
    }
}




Name:
func teste 3 param
13:45:53 13/01/2011 CODE:
namespace LambdaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Func f = (x, y, z ) => 5 * x * y / (z * 4);
            Console.WriteLine(f.Invoke(3, 3, 2));
            Console.ReadLine();
        }
    }
}




Name:
Action test 2 param
14:02:05 13/01/2011 CODE:
namespace LambdaTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Action f = (s, y) =>
                {
                    Console.WriteLine("Tester ut Lambdas");
                    Console.WriteLine(s * y);
                };
            f.Invoke(5, 6);
            Console.ReadLine();

        }
    }
}




Name:
async delegate test
14:30:08 13/01/2011 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace LambdaTest
{
    public delegate string SlowDelegateCaller(int sec, out int treadID);

    public class SlowWorkerClass
    {
        public string slowMethod(int sec, out int treadID)
        {
            Console.WriteLine("Slow Method executes on tread {0}", Thread.CurrentThread.ManagedThreadId);
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(sec / 5 * 1000);
                Console.WriteLine("The Async task is running on tread {0}", Thread.CurrentThread.ManagedThreadId);
            }
            treadID = Thread.CurrentThread.ManagedThreadId;
            return String.Format("I did {0} sec of work on tread {1}", sec.ToString(), Thread.CurrentThread.ManagedThreadId);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SlowWorkerClass SWC = new SlowWorkerClass();

            SlowDelegateCaller sdc = new SlowDelegateCaller(SWC.slowMethod);

            int treadID;
            Console.WriteLine("Before making the Async call... Thread ID = {0}", Thread.CurrentThread.ManagedThreadId);
            IAsyncResult result = sdc.BeginInvoke(30, out treadID, null, null);
            Console.WriteLine("after making the Async call Thread ID = {0}", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Working on main tread counter!!!");
            for (int i = 30; i > 1; i--)
            {
                Thread.Sleep(1000);
                Console.WriteLine("{0}...", i);

            }
            Console.WriteLine("Waiting for the async call to return now...");
            string returnValue = sdc.EndInvoke(out treadID, result);
            Console.WriteLine("The call got executed on thread {0}", treadID);
            Console.WriteLine("The value returned was - {0}", returnValue);

        }
    }
}




Name:
Extract from embeded resource
15:21:34 13/01/2011 CODE:
private void ExtractFromAssembly()
{
    string strPath = Application.LocalUserAppDataPath + "\\OutputFile.xlsx";
    if (File.Exists(strPath)) File.Delete(strPath);
    Assembly assembly = Assembly.GetExecutingAssembly();
    //In the next line you should provide NameSpace.FileName.Extension that you have embedded
    var input = assembly.GetManifestResourceStream("Sample.File.exe");
    var output = File.Open(strPath, FileMode.CreateNew);
    CopyStream(input, output);
    input.Dispose();
    output.Dispose();
    System.Diagnostics.Process.Start(strPath);
}

private void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[1024];
    while (true)
    {
        int read = input.Read(buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write(buffer, 0, read);
    }
}




Name:
delegate test
15:53:24 13/01/2011 CODE:
delegate void TestDelegate(string melding);

    class Program
    {
        static void Main(string[] args)
        {
            TestDelegate t = new TestDelegate(LogTest);

            t.Invoke("test");
        }

        static void LogTest(string x)
        {
            Console.WriteLine(x);
            Console.ReadLine();
        }
    }




Name:
200mb byte array
01:12:09 17/01/2011 CODE:
using System;

namespace ByteTest
{
    class Program
    {
        static Random r = new Random();

        static void Main(string[] args)
        {
            //Building an array of 200mb = 209715200bytes
            byte[] byteArray = new byte[209715200];
            r.NextBytes(byteArray);
            for (int i = 0; i < 209715200; i++)
            {  
                Console.WriteLine(byteArray[i].ToString());
            }
        }
    }
}




Name:
Get RealTimeFeedBack form second tread, Bacground worker CMD
12:18:59 17/01/2011 CODE:
using System;
using System.Windows.Forms;
using System.Diagnostics;


namespace GetTraceFormTest
{
    public partial class Form1 : Form
    {
        private const string Command = "tracert www.google.com";
        private const string Application = "cmd";
        private const string ExitCommand = "exit";
        readonly StringHolder sh = new StringHolder();


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();

        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Process myprocess = new Process();
            ProcessStartInfo StartInfo = new ProcessStartInfo();
            StartInfo.FileName = Application;
            StartInfo.RedirectStandardInput = true;
            StartInfo.RedirectStandardOutput = true;
            StartInfo.UseShellExecute = false;
            StartInfo.CreateNoWindow = true;
            myprocess.StartInfo = StartInfo;
            myprocess.Start();
            System.IO.StreamReader _streamreader = myprocess.StandardOutput;
            System.IO.StreamWriter _streamwriter = myprocess.StandardInput;
            _streamwriter.WriteLine(Command);
            _streamwriter.WriteLine(ExitCommand);
            while (_streamreader.EndOfStream == false)
            {
 
                sh.Buffer = _streamreader.ReadLine();
                backgroundWorker1.ReportProgress(1, sh.Buffer);
            }
            _streamwriter.Close();
            _streamreader.Close();

        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            richTextBox1.Text += "\n" + e.UserState;
        }
    }

    public class StringHolder
    {
        public string Buffer { get; set; }
    }

}




Name:
Encrypt decrypt methods
10:42:38 19/01/2011 CODE:
	private string Encrypt(string plainMessage, string password)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = new byte[8];
			PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[0]);
			des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
			MemoryStream ms = new MemoryStream(plainMessage.Length * 2);
			CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
			byte[] plainBytes = Encoding.UTF8.GetBytes(plainMessage);
			encStream.Write(plainBytes, 0, plainBytes.Length);
			encStream.FlushFinalBlock();
			byte[] encryptedBytes = new byte[ms.Length];
			ms.Position = 0;
			ms.Read(encryptedBytes, 0, (int)ms.Length);
			encStream.Close();
			ms.Close();
			return Convert.ToBase64String(encryptedBytes);
		}
		private string Decrypt(string encryptedBase64, string password)
		{
			TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
			des.IV = new byte[8];
			PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[0]);
			des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
			byte[] encryptedBytes = Convert.FromBase64String(encryptedBase64);
			MemoryStream ms = new MemoryStream(encryptedBase64.Length);
			CryptoStream decStream = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
			decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
			decStream.FlushFinalBlock();
			byte[] plainBytes = new byte[ms.Length];
			ms.Position = 0;
			ms.Read(plainBytes, 0, (int)ms.Length);
			decStream.Close();
			ms.Close();
			return Encoding.UTF8.GetString(plainBytes);
		}




Name:
Two Threads 1 Background worker updating GUI
23:37:02 20/01/2011 CODE:
using System;
using System.Threading;
using System.Windows.Forms;

namespace TreadTesting
{
    public partial class Form1 : Form
    {
        private Thread _thread1;
        private Thread _thread2;

        public static string Z = "null";

        private string[] _stringArray = new string[2];

        public Form1()
        {
            InitializeComponent();
            StringHolder.Y = 100;
        }

        private void StartThreads()
        {
            _thread1 = new Thread(BackgroundThread1)
                           {
                               IsBackground = true,
                               Priority = ThreadPriority.AboveNormal
                           };
            _thread1.Start();


            _thread2 = new Thread(BackgroundThread2)
                           {
                               IsBackground = true,
                               Priority = ThreadPriority.AboveNormal
                           };
            _thread2.Start();
        }

        private static void BackgroundThread1()
        {
            while (true)
            {
                StringHolder.X++;
                lock (Z)
                {
                    Z = StringHolder.X.ToString();
                }
                
                Thread.Sleep(1);
            }
        }
        private static void BackgroundThread2()
        {
            while (true)
            {
                StringHolder.Y++;
                StringHolder.Y = StringHolder.Y;
                StringHolder.X--;
                lock (Z)
                {
                    Z = StringHolder.X.ToString(); 
                }
                Thread.Sleep(3);
            }
        }

        private void Button1Click(object sender, EventArgs e)
        {
            StartThreads();
        }

        private void Button2Click(object sender, EventArgs e)
        {
                backgroundWorker1.RunWorkerAsync();
        }

        private void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (true)
            {
                _stringArray[0] = Z;
                _stringArray[1] = Z + 100000;
                backgroundWorker1.ReportProgress(1, _stringArray);
                Thread.Sleep(50);
            } 
        }

        private void BackgroundWorker1ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            var x = (string[])e.UserState;
            
            label2.Text = x[0];
            label1.Text = StringHolder.Y.ToString();
        }
    }

    public static class StringHolder
    {
        public static int X { get; set; }
        public static int Y { get; set; }
    } 
}




Name:
Design Flow Single Responsibility Prinsiple
11:15:39 21/01/2011 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignFlowSingleResponsibilityPrinsiple
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class PersonCreator
    {
        public Person CreatePerson()
        {
            Func prompt = p =>
            {
                Console.Write(string.Format("{0}\n", p));
                return Console.ReadLine();
            };

            return new Person
            {
                FirstName = prompt("First Name"),
                LastName = prompt("Last Name")
            };
        }
    }

    class PersonPrinter
    {
        public void PrintPerson(Person person)
        {
            Console.WriteLine(string.Format("{0} {1}", person.FirstName, person.LastName));
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            var personCreator = new PersonCreator();
            var person1 = personCreator.CreatePerson();

            var personPrinter = new PersonPrinter();
            personPrinter.PrintPerson(person1);

            Console.ReadLine();

        }
    }
}




Name:
Modulus test, every 100th number
23:56:49 25/01/2011 CODE:
namespace ModulusTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            for (int i = 0; i < 36896; i++)
            {
                if (i % (36896 / 40) == 0)
                {
                    Console.WriteLine(x.ToString());
                    Console.WriteLine(i.ToString());
                    x++;
                }
            }
            Console.ReadLine();
        }
    }
}




Name:
event test
17:27:18 14/02/2011 CODE:
using System;

namespace EventTest
{
    //time get/set
    public class TimerTick : EventArgs
    {
        public DateTime Time { get; set; }
    }

    internal class Adder
    {
        #region Delegates
        /*callng just the tick event
        public delegate void EventFire(Adder m, EventArgs e);*/

        /*sending datetime with event handel*/
        public delegate void EventFire(Adder m, TimerTick t);

        #endregion 

        //public EventArgs e;

        public event EventFire Tick;

        public int Addnumbers(int x, int y)
        {
           /* if (Tick != null)
            {
                Tick(this, e);
            }*/
            System.Threading.Thread.Sleep(1000);
            if (Tick != null)
            {
                TimerTick tot = new TimerTick();
                tot.Time = DateTime.Now;

                Tick(this, tot);
            }
            return (x + y);
        }
    }

    internal class Eventer
    {
        public void Subscribe(Adder m)
        {
            m.Tick += FireMe;
        }

        private static void FireMe(Adder m, TimerTick e)
        {
            Console.WriteLine(string.Format("{0} {1}","Event Fired!!",  e.Time));
        }
    }

    internal class Program
    {
        private static void Main()
        {
            var a = new Adder();
            var e = new Eventer();

            e.Subscribe(a);
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(a.Addnumbers(i, i));  
            }
            Console.ReadLine();
        }
    }
}




Name:
RavenDB demo test writing to db
22:57:31 20/02/2011 CODE:
using System;
using System.Windows.Forms;
using Raven.Client;
using Raven.Client.Document;

namespace RavenDbDemo
{
    static class Program
    {
        private static DocumentStore _documentStore;

        public static void InSession(Action action)
        {
            using (var session = _documentStore.OpenSession())
            {
                action(session);
                session.SaveChanges();
            }
        }

        [STAThread]
        static void Main()
        {
            _documentStore = new DocumentStore { Url = "http://3p2ghz-station:8080" };

            using (var store = _documentStore)
            {
                store.Initialize();

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
            }

            _documentStore.Dispose();
        }
    }
}



using System;
using System.Windows.Forms;
using RavenDbDemo.Model;

namespace RavenDbDemo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainFormLoad(object sender, EventArgs e)
        {
            Program.InSession(session =>
                                  {
                                      foreach (Account account in session.Query())
                                      {
                                          AddAccountToAccountList(account);
                                      }
                                  });
        }

        private void AddAccountToAccountList(Account account)
        {
            AccountList.Items.Add(new ListViewItem(new[]
                                                       {
                                                           account.Name.FirstName,
                                                           account.Name.LastName
                                                       })
                                      {
                                          Tag = account
                                      });
        }

        private void AddFirstNameTxbKeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                AddButtonClick(AddButton, new EventArgs());
            }
        }

        private void AddButtonClick(object sender, EventArgs e)
        {
            Program.InSession(session =>
                                  {
                                      var account = new Account
                                                        {
                                                            Id = string.Format("accounts/{0}", Guid.NewGuid()),
                                                            Name = new Name
                                                                       {
                                                                           FirstName = AddFirstNameTxb.Text,
                                                                           LastName = AddLastNameTxb.Text
                                                                       }
                                                        };
                                      AddAccountToAccountList(account);
                                      session.Store(account);
                                  });

            AddFirstNameTxb.Text = "";
            AddLastNameTxb.Text = "";
            AddFirstNameTxb.Focus();
        }
    }
}

namespace RavenDbDemo.Model
{
    internal class Name
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

namespace RavenDbDemo.Model
{
    class Account
    {
        public string Id { get; set; }
        public Name Name { get; set; }
    }
}







Name:
Singelton desig pattern
16:43:15 22/02/2011 CODE:
using System;

namespace ConsoleApplication4
{
    class SingeltonTestClass
    {
        //create a private static field to hold the instance
        private static SingeltonTestClass singelton;

        //create a private constructor to contain the class to be instansiated.
        private SingeltonTestClass()
        {}

        //create a public method that instansiates the instance, or returns it if already there
        public static SingeltonTestClass GetInstance()
        {
            if (singelton != null)
            {
                return singelton;
            }
            var x = new SingeltonTestClass();
            return x;
        }

        public int addnum(int x,int y)
        {
            return x + y;
        }
    }

    class Program
    {
        static void Main()
        {
            var x = SingeltonTestClass.GetInstance();
            x.addnum(5, 6);
            Console.ReadLine();
        }

    }
}




Name:
Generics simple test
17:07:17 22/02/2011 CODE:
using System;

namespace ConsoleApplication5
{
    class Program
    {
        static void Print(TType itemToPrint)
        {
            Console.WriteLine(itemToPrint);
            Console.Beep();
        }

        static void Main(string[] args)
        {
            Print("test ok");
            Print(10);
            Print(3.545363);
            Print(100*100*2/5);

            Console.ReadKey();
        }
    }
}




Name:
Exstension method test, adding finctionalty to class with extension method
17:28:27 22/02/2011 CODE:
using System;

namespace ConsoleApplication5
{
    class player
    {
        public void walk()
        {
        }
    }
    
    //must be static
    static class ExtensionMethodTest
    {
        //must be static with (this player that)syntax
        public static void run(this player that, int arg1)
        {
            //adding funcsionalty to the player class with this static class
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var p = new player();
            p.run(10);

            Console.ReadKey();
        }
    }
}




Name:
delegate
14:34:14 16/03/2011 CODE:
namespace ConsoleApplication1
{
    internal delegate void Test();
    
    class Program
    {
        static void Main(string[] args)
        {
            Test t = Write;
            DoSomthing(t);
        }

        static void DoSomthing(Test test) 
        {
            test.Invoke();
        }

        static void Write()
        {
            Console.Write("Tester");
            Console.ReadLine();
        }
    }
}




Name:
MVC pattern
13:31:48 31/03/2011 CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVC_DesignPattern
{
    #region FramWork

    interface IView
    {
        void Render();
    }

    #endregion

    #region Model

    class PersonDTO
    {
        
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    class PersonEntity
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    class PeopleStore 
    {
        private readonly LinkedList people;

        public PeopleStore()
        {
            people = new LinkedList();
        }

        public PersonEntity GetPersonById(int id)
        {
            return people.SingleOrDefault(p => p.Id == id);
        }

        public void StorPerson(PersonDTO personDTO) 
        {
            people.AddLast(new PersonEntity 
            { 
                Id = people.Count,
                FirstName = personDTO.FirstName,
                LastName = personDTO.LastName
            });
        }

        public IEnumerable GetAllPeople()
        {
            return people.ToArray();
        }
    }

    #endregion

    #region View
    class DisplayPersonView : IView
    {
        private readonly PersonEntity person;

        public DisplayPersonView(PersonEntity person)
        {
            this.person = person;
        }

        public void Render()
        {
            Console.WriteLine(string.Format("{0} - {1} - {2}", person.Id, person.FirstName, person.LastName));
        }
    }

    class ConfirmPersonView : IView
    {
        private readonly PersonDTO dto;

        public ConfirmPersonView(PersonDTO dto) 
        {
            this.dto = dto; 
        }

        public void Render() 
        {
            Console.WriteLine(string.Format("{0} - {1}", dto.FirstName, dto.LastName));
        }
    }

    class DisplayPeopleView : IView 
    {
        private readonly IEnumerable people;

        public DisplayPeopleView(IEnumerable people)
        {
            this.people = people;
        }

        public void Render() 
        {
            people.Select(p => new DisplayPersonView(p)).ToList().ForEach(p => p.Render());
        }
    }
    #endregion

    #region Controller
    class PeopleController 
    {
        private readonly PeopleStore store;

        public PeopleController(PeopleStore store)
        {
            this.store = store;
        }

        public IView ListPeople()
        {
            return new DisplayPeopleView(store.GetAllPeople());
        }

        public IView AddPerson(string firstName, string lastName)
        {
            var person = new PersonDTO { FirstName = firstName, LastName = lastName };
            store.StorPerson(person);

            return new ConfirmPersonView(person);
        }

        public IView DisplayPeople(int id) 
        {
            var person = store.GetPersonById(id);
            return new DisplayPersonView(person);
        }
    }
    #endregion

    class Program
    {
        static void Main(string[] args)
        {
            var personModel = new PeopleStore();
            var personController = new PeopleController(personModel);

            while (true)
            {
                var input = Console.ReadLine();
                if (input == "list")
                    personController.ListPeople().Render();
                else if (input == "add-person")
                {
                    var firstname = Console.ReadLine();
                    var lastname = Console.ReadLine();
                    personController.AddPerson(firstname, lastname);
                }
                else if (input == "show-person")
                {
                    var id = Convert.ToInt32(Console.ReadLine());
                    personController.DisplayPeople(id).Render();
                }
                    
            }
        }
    }
}




Name:
Interface test
14:07:34 02/04/2011 CODE:
using System;
using System.Collections.Generic;
using System.Text;

namespace Interfacetest
{
    class Program
    {
        static void Main(string[] args)
        {

            DoSomething();
            Console.ReadLine();
        }           
        public static void GreetEveryone(IHelloWorld hw)
        {
                hw.SayHello();
        }

        public static void DoSomething()
        {
            // here i change out the implimentation but keeping the functinalety witht he interface
            // HelloWorld helloWorld = new HelloWorld();
            changeme helloWorld = new changeme();
            GreetEveryone(helloWorld);
        }
    }

    interface IHelloWorld
    {
        void SayHello();
        void SayGodby();
    }

    public  class HelloWorld : IHelloWorld
    {
        public void SayHello()
        {
            Console.WriteLine("HelloWorld!!!");
        }

        public void SayGodby()
        {
            Console.WriteLine("Good Bye World!!!");
        }
    }

    public class changeme : IHelloWorld
    {
        public void SayHello()
        {
            Console.WriteLine("This is the new implimentation");
        }

        public void SayGodby()
        {
            throw new NotImplementedException();
        }
    }
}




Name:
Interface test 2
13:52:25 21/04/2011 CODE:
class Program
    {
        static void Main(string[] args)
        {
            Character bob = new Character();
            Character Lisa = new Character();
            Gun gun = new Gun();
            Bow bow = new Bow();

            bob.GiveWeapon(gun);
            Lisa.GiveWeapon(bow);

            bob.UseWeapon();
            Lisa.UseWeapon();

            Console.ReadLine();
        }
    }


public class Character
    {
        IWeapon wp;

        public void GiveWeapon(IWeapon wp)
        {
            this.wp = wp;
        }

        public void UseWeapon()
        {
            wp.Use();
        }
    }


public interface IWeapon
    {
        void Use();
    }

public class Gun : IWeapon
    {
        public void Use()
        {
            Console.WriteLine("Gun Fired!!");
        }
    }

 public class Bow : IWeapon
    {
        public void Use()
        {
            Console.WriteLine("Bow Fired!!");
        }
    }




Name:
Interface test 3
13:56:45 23/04/2011 CODE:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            var player1 = new Charter(100) {Name = "Glenn", Role = "DPS", Wp = new Gun(10)}; 

            var player2  = new Charter(100) {Name = "Enemy", Wp = new Gun(10)};

            UseGun(player1, player2);
        }

        private static void UseGun(Charter player, Charter enemy)
        {
            player.Wp.Use(player, enemy);
            Console.ReadLine();
            UseGun(player, enemy);
        }
    }
}

using System;
using ConsoleApplication9.Intrefaces;

namespace ConsoleApplication9
{
    public class Charter : IPlayer
    {
        public Charter(int health)
        {
            Health = health;
        }

        public string Name { get; set; }

        public string Role { get; set; }

        public int Health { get; set; }

        public IWeapon Wp { get; set; }

        public void Run()
        {
            Console.WriteLine("Player is running!");
        }

        public void Walk()
        {
            Console.WriteLine("Player is Walking!!");
        }

        public void Jump()
        {
            Console.WriteLine("Player is Jumping!");
        }
    }
}

using System;

namespace ConsoleApplication9
{
    public class Gun : Intrefaces.IWeapon
    {
        public Gun(int ammo)
        {
            this.Ammo = ammo;
        }

        public int Ammo { get; set; }

        public void Use(Charter player, Charter enemy)
        {
            if (Ammo <= 0)
                Reload(player.Name);

            Console.WriteLine("{0} {1} class is using gun! - 1 bullet Bullets left = {2}", player.Name,player.Role, Ammo);

            if (enemy.Health > 0)
            {
                enemy.Health -= 8;
                if (enemy.Health < 0)
                {
                    Console.WriteLine("enemy hit and is dead!");
                    return;
                }
                Console.WriteLine("Enemy hit has healt left {0}", enemy.Health);
            }
            else
            {
                Console.WriteLine("enemy hit and is dead!");
            }
            
            Ammo--;
        }

        public void Reload(string name)
        {
            Console.WriteLine(name + " is reloading gun! + 10 bullets");
            Ammo = 10;
        }
    }
}

namespace ConsoleApplication9.Intrefaces
{
    public interface IPlayer
    {
        string Name { get; set; }
        string Role { get; set; }
        int Health { get; set; }
        IWeapon Wp { get; set; }

        void Run();
        void Walk();
        void Jump();
    }
}


namespace ConsoleApplication9.Intrefaces
{
    public interface IWeapon
    {
        int Ammo{get;set;}

        void Use(Charter name, Charter enemy);

        void Reload(string name);
    }
}





Name:
move files
21:58:41 01/05/2011 CODE:
static void Main(string[] args)
    {
        String mask = "*.txt";
        String source = @"c:\source\";
        String destination = @"c:\destination\";

        String[] files = Directory.GetFiles(source, mask, SearchOption.AllDirectories);
        foreach (String file in files)
        {
            File.Move(file, destination + new FileInfo(file).Name);
        }
    }




Name:
Thread Updates to Gui Thread
13:28:40 23/05/2011 CODE:
        private void button1_Click(object sender, EventArgs e)
        {
            Thread worker = new Thread(startCalc);
            worker.Name = "Worker";
            worker.Start(1000000000);
        }

        private void startCalc(object x)//must use object and cast to int in call.
        {
            Invoke(new Action(res => richTextBox1.Text = res),  Calc(x).ToString());

        }

        private int Calc(object x)
        {
            for (int i = 0; i < (int)x; i++)
            {
                y++;
            }
            return y;
        }




Name:
check screen code.
00:53:35 22/06/2011 CODE:
namespace ScreenShot_BoundsTest
{
    
    public partial class Form1 : Form
    {
        Bitmap _memoryImage1;
        Bitmap _memoryImage2;

        Color[,] _first;
        Color[,] _second;

        private string _valueX;

        public Form1()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void GetImage()
        {
            _memoryImage2 = _memoryImage1;
            CaptureScreen();
            pictureBox2.Image = pictureBox1.Image;
            if (_memoryImage1 != null) _first = Bitmap2Imagearray(_memoryImage1);


            pictureBox1.Image = _memoryImage1;
            if (_memoryImage2 != null) _second = Bitmap2Imagearray(_memoryImage2);

            var x = CompareArrays();

            _valueX = x != true ? "false" : "true";
        }

        private bool CompareArrays()
        {
            for (var i = 0; i < _memoryImage1.Width; i++)
            {
                for (var j = 0; j < _memoryImage1.Height; j++)
                {
                    if (_first == null) continue;
                    if (_second != null)
                        if (_first[i,j] != _second[i,j])
                        {
                            return false;
                        }
                }
            }
            return _first != null && _second != null;
        }

        private void CaptureScreen()
        {
            Size s;
            using (var myGraphics = CreateGraphics())
            {
                s = new Size(100, 50);
                _memoryImage1 = new Bitmap(s.Width, s.Height, myGraphics);
            }

            var memoryGraphics = Graphics.FromImage(_memoryImage1);
            memoryGraphics.CopyFromScreen(100, 100, 10, 10, s);
            
            
        }

        private static Color[,] Bitmap2Imagearray(Bitmap b)
        {
            var imgArray = new Color[b.Width, b.Height];
            for (var y = 0; y < b.Height; y++)
            {
                for (var x = 0; x < b.Width; x++)
                {
                    imgArray[x, y] = b.GetPixel(x, y);
                }
            }
            return imgArray;
        }

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            GetImage();
            Thread.Sleep(100);
        }

        private void BackgroundWorker1RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            label1.Text = _valueX;
            backgroundWorker1.RunWorkerAsync();
        }

    }
}




Name:
queue test
16:27:14 26/06/2011 CODE:
static void Main(string[] args)
        {
            var queue = new Queue();

            queue.Enqueue("Hello");
            queue.Enqueue("how");
            queue.Enqueue("are");
            queue.Enqueue("you");


            while (queue.Count > 0)
            {
                Console.WriteLine(queue.Peek());
                Console.WriteLine("Elements in que left = " + queue.Count);
                Console.WriteLine(queue.Dequeue());
                Console.WriteLine("Elements in que left = " + queue.Count);
            }
            

            Console.ReadLine();
        }




Name:
Delegate test
12:48:04 17/07/2011 CODE:
using System;

namespace delegateTese
{
    class Program
    {
        public delegate void ToInts(int x, int y);

        static void Main()
        {
            var ex = new ExampleClass();

            ToInts pointer = null;

            //adding more than one function called multicast delegate.
            pointer += ex.Add;
            pointer += ex.Multiply;

            pointer(2, 5);

            Console.ReadLine();
        }
    }

    public class ExampleClass
    {
        public void Add(int x, int y)
        {
            Console.WriteLine("The sum is: " + (x + y));
        }

        public void Multiply(int x, int y)
        {
            Console.WriteLine("The product is: " + (x * y));
        }
    }
}