Tuesday, December 27, 2011

12/27/11

Namespace StringManipulation
Class Tester

Public Sub Run()
Dim s1 As String = "abcd"
Dim s2 As String = "ABCD"

'concatentation method
Dim s3 As String = String.Concat(s1, s2)
Console.WriteLine("s3 concatenated from s1 and s2: {0}", s3)

'use the overloaded operator
Dim s4 As String = s1 & s2
Console.WriteLine("s4 concatenated from s1 & s2: {0}", s4)

End Sub 'run

Public Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub 'main

End Class
End Namespace


Public Sub RunCopy()
Dim s1 As String = "scdb"
Dim s2 As String = "CATNIP"

'the string copy method
Dim s5 As String = String.Copy(s2)
Console.WriteLine("s5 copied from s2: {0}", s5)

'use the overloaded operator
Dim s6 As String = s5
Console.WriteLine("s6 = s5: {0}", s6)

End Sub 'Run

Public Sub RunEquality()
Dim s1 As String = "qwerty"
Dim s2 As String = "QWERTY"

'the string copy method
Dim s5 As String = String.Copy(s2)
Console.WriteLine("s5 copied from s2: {0}", s5)

'copy with the overloaded operator
Dim s6 As String = s5
Console.WriteLine("s6 = s5: {0}", s6)

'member method
Console.WriteLine("Does s6.Equals(s5)?: {0}", s6.Equals(s5))

'shared method
Console.WriteLine("Does Equals(s6, s5)?: {0}", String.Equals(s6, s5))
End Sub 'Rnu Equality

Public Shared Sub Main()
Dim t As New Tester()
t.RunCopy()
Console.WriteLine()
t.RunEquality()

End Sub


Class Tester

Public Sub Run()
Dim s1 As String = "abcd"
Dim s2 As String = "ABCD"
Dim s3 As String = "Liberty Associates, Inc. provides "
s3 = s3 & "custom .NET development"

'the string copy method
Dim s5 As String = String.Copy(s2)

Console.WriteLine("s5 copied from s2: {0}", s5)

'the length
Console.WriteLine("String s3 is {0} characters long. ", s5.Length)

Console.WriteLine()
Console.WriteLine("s3: {0}", s3)

'test whether a String ends with a set of characters
Console.WriteLine("s3: ends with Training?: {0}", s3.EndsWith("training"))
Console.WriteLine("Ends with Development?: {0}", s3.EndsWith("development"))

Console.WriteLine()
'return the index fo teh string
Console.WriteLine("The first occurrrence of provides ")
Console.WriteLine("in s3 is {0}", s3.IndexOf("provides"))

'hold the location of provides as an integer
Dim location As Integer = s3.IndexOf("provides")
'insert the word usually before "provides"
Dim s10 As String = s3.Insert(location, "usually ")

Console.WriteLine("s10: {0}", s10)

'you can combine the two as follows:
Dim s11 As String = s3.Insert(s3.IndexOf("provides"), "usually ")
Console.WriteLine("s11: {0} ", s11)

Console.WriteLine()
'use the mid function to replace within the string
Mid(s11, s11.IndexOf("usually") + 1, 9) = "always!"
Console.WriteLine("s11 now: {0}", s11)
End Sub 'run

Public Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub 'Main

End Class


namespace practiceTuesday
{
class Program
{
static void Main(string[] args)
{
Person al = new Person("Al", 29);
al.Print();
}
}

class Person
{
//fields areadonly members that define the data the enclosing type consists of
private string _name;
private int _age;

public Person(string name, int age)
{
_name = name;
_age = age;
}

public void Print()
{
Console.WriteLine(_name + " is " + _age + " years young");
}
}
}


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

namespace ClassSample
{
class Program
{
static void Main(string[] args)
{
Vertex3d vd = new Vertex3d();
Vertex3d vd2 = new Vertex3d(4.5, 5.5, 8.0);
vd.Print();
vd2.Print();
}
}

public class Vertex3d
{
public const string Name = "Vertex";
private readonly int ver;

private double _x;
private double _y;
private double _z;

public void Print()
{
Console.WriteLine("{0} - {1} - {2}", _x, _y, _z);
}
//properties
public double X
{
get { return _x; }
set { _x = value; }
}

public double Y
{
get { return _y; }
set { _y = value; }
}

public double Z
{
get { return _z; }
set { _z = value; }
}

//method
public void SetToOrigin()
{
X = Y = Z = 0.0;
}

public static Vertex3d Add(Vertex3d a, Vertex3d b)
{
Vertex3d result = new Vertex3d();
result.X = a.X + b.X;
result.Y = a.Y + b.Y;
result.Z = a.Z + b.Z;
return result;
}

public Vertex3d()
{
_x = _y = _z = 0.0;


}

public Vertex3d(double x, double y, double z)
{
this._x = x;
this._y = y;
this._z = z;
}
}
}

Monday, December 26, 2011

Monday 12.26.11

Option Strict On
Imports System
Namespace QueueDemo
Class Tester
Public Sub Run()
Dim intQueue As New Queue()
'populate the array
Dim i As Integer
For i = 0 To 4
intQueue.Enqueue((i * 5))
Next i

'display the queue
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)

'remove an element from the queue
Console.WriteLine("(Dequeue) {0}", intQueue.Dequeue())

'display the Queue
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)

'remove another element from the queue
Console.WriteLine("(Dequeue) {0}", intQueue.Dequeue())

'display the queue
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)

'view the first element in the Queue but do not remove
Console.WriteLine("(Peek) {0}", intQueue.Peek())

'Display the queue
Console.WriteLine("intQueue values:")
DisplayValues(intQueue)
End Sub 'run

Public Shared Sub DisplayValues(ByVal myCollection As IEnumerable)
Dim myEnumerator As IEnumerator = myCollection.GetEnumerator()
While myEnumerator.MoveNext()
Console.WriteLine("{0} ", myEnumerator.Current)
End While
Console.WriteLine()
End Sub 'DisplayValues

Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub 'Main
End Class 'Tester
End Namespace 'QueueDemo


Option Strict On
Imports System
Namespace StackDemo
Class Tester
Public Sub Run()
Dim intStack As New Stack()

'populate the stack
Dim i As Integer
For i = 0 To 7
intStack.Push((i * 5))
Next i

'display the stack
Console.WriteLine("intStack values:")
DisplayValues(intStack)
'remove an element from the stack
Console.WriteLine("(Pop){0}", intStack.Pop())

'display the stack
Console.WriteLine("intStack values:")
DisplayValues(intStack)

'remove another element from the stack
Console.WriteLine("(Pop) {0}", intStack.Pop())

'display the Stack
Console.WriteLine("intStack values: ")
DisplayValues(intStack)

'view the first element in the stack
'but do not remove
Console.WriteLine("(Peek) {0}", intStack.Peek())

'display the stack
Console.WriteLine("intStack values:")
DisplayValues(intStack)
End Sub 'Run

Public Shared Sub DisplayValues(ByVal myCollection As IEnumerable)
Dim o As Object
For Each o In myCollection
Console.WriteLine(o)
Next o
End Sub

Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub 'Main
End Class ' Tester
End Namespace 'Stack demo


Namespace StackDemo
Class Tester

Public Sub Run()
Dim intStack As New Stack()

'populate the array
Dim i As Integer
For i = 1 To 4
intStack.Push((i * 5))
Next

'display the stack
Console.WriteLine("intStack values:")
DisplayValues(intStack)

Const arraySize As Integer = 10
Dim testArray(arraySize) As Integer

'populate the array
For i = 1 To arraySize - 1
testArray(i) = i * 100
Next i
Console.WriteLine("Contents of the test array")
DisplayValues(testArray)

'copy the intstack into the new array, start offset 3
intStack.CopyTo(testArray, 3)
Console.WriteLine("TestArray after copy:")
DisplayValues(testArray)

'copy the entire source stack to a new standard arry
Dim myArray As Object() = intStack.ToArray()

'display the values of the new standard array
Console.WriteLine("The new array:")
DisplayValues(myArray)
End Sub 'Run

Public Shared Sub DisplayValues(ByVal myCollection As IEnumerable)
Dim o As Object
For Each o In myCollection
Console.WriteLine(o)
Next
End Sub 'display values

Shared Sub Main()
Dim t As New Tester()
t.Run()
End Sub
End Class
End Namespace

Thursday, December 22, 2011

Thursday 12.22.11

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim PrintDoc As New Printing.PrintDocument
AddHandler PrintDoc.PrintPage, AddressOf Me.PrintText
PrintDoc.Print()

Catch ex As Exception
MessageBox.Show("Sorry - there is a problem printing", ex.ToString())
End Try
End Sub

'sub for printing text
Private Sub PrintText(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
'user drawstring to create text in a Graphics object
ev.Graphics.DrawString(TextBox1.Text, New Font("Arial", 11, FontStyle.Regular), Brushes.Black, 120, 120)
'specify that this is the last page to print
ev.HasMorePages = False
End Sub
End Class


mports System.IO
Imports System.Drawing.Printing

Public Class Form1

Private PrintPageSettings As New PageSettings
Private StringToPrint As String
Private PrintFont As New Font("Arial", 10)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click
Dim FilePath As String
'display Open dialog box and select text file
OpenFileDialog1.Filter = "Text files (*.txt) | *.txt"
OpenFileDialog1.ShowDialog()
'if cancel button not selected, load FilePath variable
If OpenFileDialog1.FileName <> "" Then
FilePath = OpenFileDialog1.FileName
Try
'read text file and laod into RichTextBox1
Dim myFileStream As New FileStream(FilePath, FileMode.Open)
RichTextBox1.LoadFile(myFileStream, RichTextBoxStreamType.PlainText)
myFileStream.Close()
'initialize string to print
StringToPrint = RichTextBox1.Text
'enable print button
btnPrint.Enabled = True
btnSetup.Enabled = True
btnPreview.Enabled = True
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
End Sub

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
Try
'specify the current page settings
PrintDocument1.DefaultPageSettings = PrintPageSettings
'specify document for print dialog box and show
StringToPrint = RichTextBox1.Text
PrintDialog1.Document = PrintDocument1
Dim result As DialogResult = PrintDialog1.ShowDialog()
'if click OK, print docuemnt to printer
If result = DialogResult.OK Then
PrintDocument1.Print()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim numChars As Integer
Dim numLines As Integer
Dim stringForPage As String
Dim strFormat As New StringFormat
'based on page setup, define drawable rectangle on page
Dim rectDraw As New RectangleF( _
e.MarginBounds.Left, e.MarginBounds.Top, _
e.MarginBounds.Width, e.MarginBounds.Height)
'define area to determine how much text can fit on a page
'make height one line shorter to ensure text doesn't clip
Dim sizeMeasure As New SizeF(e.MarginBounds.Width, _
e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics))

'when drawing long strings, break between words
strFormat.Trimming = StringTrimming.Word
'computer how many chars and lines can fit based on sizeMeasure
e.Graphics.MeasureString(StringToPrint, PrintFont, sizeMeasure, strFormat, numChars, numLines)
'compute string that will fit on a page
stringForPage = StringToPrint.Substring(0, numChars)
'print string on curent page
e.Graphics.DrawString(stringForPage, PrintFont, Brushes.Black, rectDraw, strFormat)
'if there is more text, indicate there are more pages
If numChars < StringToPrint.Length Then
'subtract text from string that has been printed
StringToPrint = StringToPrint.Substring(numChars)
e.HasMorePages = True
Else
e.HasMorePages = False
'all text has been printed, so restore string
StringToPrint = RichTextBox1.Text

End If
End Sub

Private Sub btnSetup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetup.Click
Try
'load page settings and display page setup dialog box
PageSetupDialog1.PageSettings = PrintPageSettings
PageSetupDialog1.ShowDialog()
Catch ex As Exception
'display error message
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click
Try
'specify current page settings
PrintDocument1.DefaultPageSettings = PrintPageSettings
'Specify document for print preview dialog box an dshow
StringToPrint = RichTextBox1.Text
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
Catch ex As Exception
'display error message
MessageBox.Show(ex.Message)
End Try
End Sub
End Class


Imports System.Reflection
Imports System
Imports System.Threading

Module Module1

Sub main()
'get and display the friendly name fo the default app domain
Dim callingDomainName As String = Thread.GetDomain().FriendlyName
Console.WriteLine(callingDomainName)

'get and display the full name of the EXE assembly
Dim exeAssembly As String = [Assembly].GetEntryAssembly().FullName
Console.WriteLine(exeAssembly)

'construct and initialize settings for a second appDomain
Dim ads As New AppDomainSetup()
ads.ApplicationBase = System.Environment.CurrentDirectory
ads.DisallowBindingRedirects = False
ads.DisallowCodeDownload = True
ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
' ads.ConfigurationFile = appDomain.CurrentDomain.SetupInformation.ConfigurationFile
Dim ad2 As AppDomain = AppDomain.CreateDomain("AD #2", Nothing, ads)
createNewDomain()
End Sub



Public Sub createNewDomain()
Console.WriteLine("Creating new AppDomain")
Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain")

Console.WriteLine("Host Domain: " + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine("Child Domain: " + domain.FriendlyName)

End Sub
End Module


Imports System.Threading

'our custom delegate
Public Delegate Function BinaryOp(ByVal x As Integer, ByVal y As Integer) As Integer


Module Module1

Sub Main()
Console.WriteLine("***** Synch Delegate Review *****")
Console.WriteLine()

'print out the ID of the executing thread
Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId)

'invoke Add() in a synchronous manner
Dim b As BinaryOp = AddressOf Add
Dim answer As Integer = b(10, 10)

'these lines will not execute until the Add() method has completed
Console.WriteLine("Doing more work in Main()!")
Console.WriteLine("10 + 10 is {0}.", answer)
Console.ReadLine()
End Sub


Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
'print out the ID of the executing thread
Console.WriteLine("Add() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId)
'pause to simualte a lengthy operation
Thread.Sleep(5000)
Return x + y
End Function

End Module

Wednesday, December 21, 2011

Wednesday 12.21.11

Sub Main()
'create sample data. for simplicity, the data consists of an array
'of anonymous types that contain three properties
'name (a Sting), CallSign (a string) and age (an integer)

Dim galactica() = { _
New With {.Name = "William Adama", _
.CallSign = "Husker", _
.Age = 65}, _
New With {.Name = "Saul Tigh", _
.CallSign = Nothing, _
.Age = 83}, _
New With {.Name = "Lee Adama", _
.CallSign = "Apollo", _
.Age = 30}, _
New With {.Name = "Kara Thrace", _
.CallSign = "Starbuck", _
.Age = 28}, _
New With {.Name = "Gaius Baltar", _
.CallSign = Nothing, _
.Age = 42}}

'variables used to store results of Any and All methods
Dim anyResult As Boolean
Dim allResult As Boolean

'display the contents of the galactica array
Console.WriteLine("Galactica Crew:")
For Each crewMember In galactica
Console.WriteLine(" {0}", crewMember.Name)
Next

Console.WriteLine(Environment.NewLine)

'determine if the galactica array has any data
anyResult = galactica.Any

'display the results of the previous test
Console.WriteLine("Does the array contain any data: ")
If anyResult Then
Console.Write("Yes")
Else
Console.Write("No")
End If
Console.WriteLine(Environment.NewLine)

'determine if any members have nothign set for the CallSign property, using any method
anyResult = galactica.Any(Function(crewMember) crewMember.callsign Is Nothing)

'display the results of the previous test
Console.WriteLine("Do any crew members NOT have a callsign: ")
If anyResult Then
Console.Write("Yes")
Else
Console.Write("No")
End If
Console.WriteLine(Environment.NewLine)

'determine if all members of the array have an Age property
'greater than 40, using the All method

allResult = galactica.All(Function(crewMember) crewMember.Age > 40)

'display the results of the previous test
Console.WriteLine("Are all of the crew members over 40:")
If allResult Then
Console.Write("Yes")
Else
Console.Write("No")
End If
Console.WriteLine(Environment.NewLine)
'display the contents of the galactica array in reverse
Console.WriteLine("Galactica Crew (Reverse Order):")
For Each crewMember In galactica.Reverse
Console.WriteLine(" {0}", crewMember.Name)
Next

Console.ReadLine()
End Sub


#include
int main()
{
using namespace std;
int chest = 42;
int waist = 0x42;
int inseam = 042;

cout << "Monsieur custs a striking figure!\n";
cout << "Chest = " << chest << "\n";
cout << "Waist = " << waist << "\n";
cout << "Inseam = " << inseam << "\n";
return 0;
}


#include <iostream>
int main()
{
using namespace std;
int chest = 42;
int waist = 42;
int inseam = 42;

cout << "Monsieur cuts a striking figure!" << endl;
cout << " chest = " << chest << "(decimal)" << endl;
cout << hex; //manipulator for changing number base
cout << "waist = " << waist << " (hexidecimal)" << endl;
cout << oct;
cout << "inseam = " << inseam << " (octal) " << endl;

return 0;
}


#include <iostream>
int main()
{
using namespace std;
char ch; //declare a char variable

cout << "Enter a character: " << endl;
cin >> ch;
cout << "Holla!";
cout << "Thank you for the " << ch << " character." << endl;

return 0;
}


Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'the AddressOf operator implicitly creates an object known as a delgate that forwards calls to the appropriate event handler when
'an event occurs
Try
AddHandler PrintDocument1.PrintPage, AddressOf Me.PrintGraphic
PrintDocument1.Print() 'print graphic
Catch ex As Exception
MessageBox.Show("Sorry, there is a problem printing", ex.ToString())
End Try
End Sub


'sub for printing graphic
Private Sub PrintGraphic(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
'create teh graphic using DrawImage
ev.Graphics.DrawImage(Image.FromFile(TextBox1.Text), ev.Graphics.VisibleClipBounds)
'specify that this is the last page to print
ev.HasMorePages = False
End Sub

Tuesday, December 20, 2011

Tuesday 12.20.11

class Program
{
static void Main()
{
int employeeID = 303;
object boxedID = employeeID;

employeeID = 404;
int unboxedID = (int)boxedID;

System.Console.WriteLine(employeeID.ToString());
System.Console.WriteLine(unboxedID.ToString());
}
}


class Program
{
static void Main()
{
String derivedObj = "Dummy";
Object baseObj1 = new Object();
Object baseObj2 = derivedObj;

Console.WriteLine("baseObj2 {0} String", baseObj2 is String ? "is" : "isnot");
Console.WriteLine("baseObj1 {0} String", baseObj1 is String ? "is" : "isnot");
Console.WriteLine("derivedObj {0} Object", derivedObj is Object ? "is" : "isnot");

int j = 123;
object boxed = j;
object obj = new Object();

Console.WriteLine("boxed {0} int", boxed is int ? "is" : "isnot");
Console.WriteLine("obj {0} int", obj is int ? "is" : "isnot");
Console.WriteLine("boxed {0} System.ValueType", boxed is ValueType ? "is" : "isnot");
}
}
}


static void Main()
{
DerivedType derivedObj = new DerivedType();
BaseType baseObj1 = new BaseType();
BaseType baseObj2 = derivedObj;

DerivedType derivedObj2 = baseObj2 as DerivedType;
if (derivedObj2 != null)
{
Console.WriteLine("Conversion Succeeded");
} else
{
Console.WriteLine("Conversion Failed");
}

//fails
derivedObj2 = baseObj1 as DerivedType;
if (derivedObj2 != null)
{
Console.WriteLine("Conversion Succeeded");
}
else
{
Console.WriteLine("Conversion Failed");
}

BaseType baseObj3 = derivedObj as BaseType;
if (baseObj3 != null)
{
Console.WriteLine("Conversion Succeeded");
}
else
{
Console.WriteLine("Conversion Failed");
}
}



class Program
{
static void Main()
{
Collection<int> numbers = new Collection();
numbers.Add(42);
numbers.Add(409);

Collection<string> strings = new Collection();
strings.Add("Joe");
strings.Add("Bob");

Collection<Collection> colNumbers = new Collection<Collection>();
colNumbers.Add(numbers);
IList<int> theNumbers = numbers;
foreach (int i in theNumbers)
{
Console.WriteLine(i);
}
}
}


public class A
{
public A()
{
this.y = 456;
SetField(ref this.y);

}

private void SetField(ref int val)
{
val = 888;
}

public readonly int x = 123;
public readonly int y;
public const int z = 555;

}
class Program
{
static void Main()
{
A obj = new A();
System.Console.WriteLine("x = {0}, y = {1}, z = {2}", obj.x, obj.y, A.z);
}
}


namespace IComparer
{
public class Employee : IComparable
{
private int empID;
private int yearsOfSvc = 1;

public Employee(int empID)
{
this.empID = empID;
}

public Employee(int empID, int yearsOfSvc)
{
this.empID = empID;
this.yearsOfSvc = yearsOfSvc;
}

public override string ToString()
{
return "ID: " + empID.ToString() + ". Years of Svc: " + yearsOfSvc.ToString();
}

public bool Equals(Employee other)
{
if (this.empID == other.empID)
{
return true;
}
else
{
return false;
}
}

//static method to get a comparer object
public static EmployeeComparer GetComparer()
{
return new Employee.EmployeeComparer();
}

//comparer delegates back to Employee
//Employee uses the integer's default
//compareto method

public int CompareTo(Employee rhs)
{
return this.empID.CompareTo(rhs.empID);
}

//special implementation to be called by custom comparer
public int CompareTo(Employee rhs, Employee.EmployeeComparer.ComparisonType which)
{
switch (which)
{
case Employee.EmployeeComparer.ComparisonType.EmpID:
return this.empID.CompareTo(rhs.empID);
case Employee.EmployeeComparer.ComparisonType.Yrs:
return this.yearsOfSvc.CompareTo(rhs.yearsOfSvc);
}
return 0;
}

//nested class which implements IComparer
public class EmployeeComparer : IComparer
{
//enumeration of comparison types
public enum ComparisonType
{
EmpID,
Yrs
};
public bool Equals(Employee lhs, Employee rhs)
{
return this.Compare(lhs, rhs) == 0;
}

public int GetHashCode(Employee e)
{
return e.GetHashCode();
}

//tell the employee objects to compare themselves
public int Compare(Employee lhs, Employee rhs)
{
return lhs.CompareTo(rhs, WhichComparison);
}
public Employee.EmployeeComparer.ComparisonType
WhichComparison { get; set; }
}

class Program
{
static void Main()
{
List empArray = new List();
//generate random numbers for both the integers and the employee IDs
Random r = new Random();

//populate the array
for (int i = 0; i < 5; i++)
{
//add a random employee id
empArray.Add(new Employee(r.Next(10) + 100, r.Next(20)));
}

//diplsay all the contents of the emploee array
for (int i = 0; i < empArray.Count; i++)
{
Console.Write("\n{0} ", empArray[i].ToString());
}
Console.WriteLine("\n");

//sort and display the employee array
Employee.EmployeeComparer c = Employee.GetComparer();
c.WhichComparison = Employee.EmployeeComparer.ComparisonType.EmpID;
empArray.Sort(c);

//display all the contents of the Employee array
for (int i = 0; i < empArray.Count; i++)
{
Console.Write("\n{0}", empArray[i].ToString());
}
Console.WriteLine("\n");

c.WhichComparison = Employee.EmployeeComparer.ComparisonType.Yrs;
empArray.Sort(c);

for (int i = 0; i < empArray.Count; i++)
{
Console.WriteLine("\n{0} ", empArray[i].ToString());
}
Console.WriteLine("\n");
}
}
}
}


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

namespace Queue
{
class Program
{
static void Main()
{
Queue intQueue = new Queue();

//populate the array
for (int i = 0; i < 5; i++)
{
intQueue.Enqueue(i * 5);
}

//display the Queue
Console.Write("intQueue values:\t");
PrintValues(intQueue);


//remove an element from the queue
Console.WriteLine("\n(Dequeue)\t{0}", intQueue.Dequeue());

//display the queue
Console.WriteLine("intQueue values:\t");
PrintValues(intQueue);

//remove another element from the queue
Console.WriteLine("\n(Dequeue)\t{0}", intQueue.Dequeue());

//display the queue
Console.WriteLine("intQueue values:\t");
PrintValues(intQueue);

//view the first element in the Queue but do not remove
Console.WriteLine("\n(Peek) \t{0}", intQueue.Peek());

//display the queue
Console.WriteLine("intQueue values:\t");
PrintValues(intQueue);
}

public static void PrintValues(IEnumerable myCollection)
{
IEnumerator myEnumerator = myCollection.GetEnumerator();
while (myEnumerator.MoveNext())
Console.WriteLine("{0} ", myEnumerator.Current);
Console.WriteLine();
}
}
}


namespace Stack
{
class Program
{
static void Main()
{
Stack intStack = new Stack();

//populate the array
for (int i = 0; i < 8; i++)
{
intStack.Push(i * 5);
}

//display the stack
Console.Write("intStack values:\t");
PrintValues(intStack);

//remove an element from the stack
Console.WriteLine("\n(Pop)\t{0}", intStack.Pop());

//display the stack
Console.Write("intStack values:\t");
PrintValues(intStack);

//Remove another element from the stack
Console.WriteLine("\n(Pop)\t{0}", intStack.Pop());

//display the stack
Console.Write("intStack values:\t");
PrintValues(intStack);

//view the first element in the stack
//but do not remove
Console.WriteLine("\n(Peek) \t{0}", intStack.Peek());

//display the stack
Console.Write("intStack values:\t");
PrintValues(intStack);

//declare an array object which will hold 12 integers
int[] targetArray = new int[12];

for (int i = 0; i < targetArray.Length; i++)
{
targetArray[i] = i * 100 + 100;
}

//display the values of the target array instance
Console.WriteLine("\nTarget Array: ");
PrintValues(targetArray);

//copy the entire source Stack to the
//target array instance, starting at index 6
intStack.CopyTo(targetArray, 6);

//display the values fo the target Array instance
Console.WriteLine("\nTarget array after copy: ");
PrintValues(targetArray);
}

public static void PrintValues(IEnumerable myCollection)
{
IEnumerator enumerator = myCollection.GetEnumerator();
while (enumerator.MoveNext())
Console.Write("{0} ", enumerator.Current);
Console.WriteLine();
}
}
}


Module Program


Sub Main()
'create a TimeSpan representing 2.5 days
Dim timespan1 As New TimeSpan(2, 12, 0, 0)

'create a Timespan representing 4.5 days
Dim timespan2 As New TimeSpan(4, 12, 0, 0)

'create a timepsan representing 1 week
Dim oneweek As TimeSpan = timespan1 + timespan2

'create a datetime with the current date and time
Dim now As DateTime = DateTime.Now

'create a DateTime representing one week ago
Dim past As DateTime = now - oneweek

'create a DateTime reprsenting 1 week in the future
Dim future As DateTime = now + oneweek

'create a datetime representing the next day using the addDays method
Dim tomorrow As DateTime = now.AddDays(1)

'display the DateTime instances
Console.WriteLine("Now : {0}", now)
Console.WriteLine("Past : {0}", past)
Console.WriteLine("Future : {0}", future)
Console.WriteLine("Tomorrow : {0}", tomorrow)
Console.WriteLine(Environment.NewLine)

'create various DateTimeOffset objects using the same
'methods demonstrated above using the dateTime structure
Dim nowOffset As DateTimeOffset = DateTimeOffset.Now
Dim pastOffset As DateTimeOffset = nowOffset - oneweek
Dim futureOffset As DateTimeOffset = nowOffset + oneweek
Dim tomorrowOffset As DateTimeOffset = nowOffset.AddDays(1)

'change the offset used by nowOffset to -8 (which is pacific standard time)
Dim nowPST As DateTimeOffset = nowOffset.ToOffset(New TimeSpan(-8, 0, 0))

'display the DateTimeOffset instances
Console.WriteLine("Now (with offset) : {0}", nowOffset)
Console.WriteLine("Past (with offset) : {0}", pastOffset)
Console.WriteLine("Future (with offset) : {0}", futureOffset)
Console.WriteLine("Tomorrow (with offset) : {0}", tomorrowOffset)
Console.WriteLine(Environment.NewLine)
Console.WriteLine("now (with offset of -8) : {0}", nowPST)

'wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter")
Console.ReadLine()



End Sub

End Module


Module Program


Sub Main()
'create a TimeZoneInfo object for the local time zone
Dim localTimeZone As TimeZoneInfo = TimeZoneInfo.Local
'create a TimeZoneInfo object for Coordinated Universal Time (UTC)
Dim utcTimeZone As TimeZoneInfo = TimeZoneInfo.Utc

'create a timezoneinfo object for Pacific Standard Time (PST)
Dim pstTimeZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")

'create a DateTimeOffset that represents the current time
Dim currentTime As DateTimeOffset = DateTimeOffset.Now

'display the lcoal time and the local time zone
If localTimeZone.IsDaylightSavingTime(currentTime) Then
Console.WriteLine("Current time in the local time zone ({0}):", localTimeZone.DaylightName)
Else
Console.WriteLine("Current time in the local time zone ({0}):", localTimeZone.StandardName)
End If
Console.WriteLine("{0}", currentTime.ToString())
Console.WriteLine(Environment.NewLine)

'display the results of converting the current local time to coordinated universal time (UTC)
If utcTimeZone.IsDaylightSavingTime(currentTime) Then
Console.WriteLine("Current time in {0}:", utcTimeZone.DaylightName)
Else
Console.WriteLine("Current time in {0}:", utcTimeZone.StandardName)
End If
Console.WriteLine(" {0}", TimeZoneInfo.ConvertTime(currentTime, utcTimeZone))
Console.WriteLine(Environment.NewLine)

'create a DateTimeoffset object that represents the current local time converted
'to the PST time zone
Dim pstDTO As DateTimeOffset = TimeZoneInfo.ConvertTime(currentTime, pstTimeZone)

'display the results of the conversion
If pstTimeZone.IsDaylightSavingTime(currentTime) Then
Console.WriteLine("Current time in {0}:", pstTimeZone.DaylightName)
Else
Console.WriteLine("Current time in {0}:", pstTimeZone.StandardName)
End If
Console.WriteLine(" {0}", pstDTO.ToString())

'display the previous results converted to Coordinated Universal Time (UTC)
Console.WriteLine(" {0} (Converted to UTC)", TimeZoneInfo.ConvertTimeToUtc(pstDTO.DateTime, pstTimeZone))
Console.WriteLine(Environment.NewLine)

'create a DateTimeOffset that represent the current local time
'converted to Mountain Standard Time using the ConvertTimeBySystemTimeoneId method
'this conversion works but it is best to creat an actual TimeZoneInfo object so you have access
'to determine if it is daylight saving time or not
Dim mstDTO As DateTimeOffset = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, "Mountain Standard Time")

'display the results of the conversion
Console.WriteLine("Current time in Mountain Standard Time:")
Console.WriteLine(" {0}", mstDTO.ToString())
Console.WriteLine(Environment.NewLine)

'wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter")
Console.ReadLine()
End Sub

End Module


Sub Main()
'create a new array and populate it
Dim array1 As Integer() = {4, 2, 9, 3}

'sort the array
Array.Sort(array1)

'display the contents of the sorted array
For Each i As Integer In array1
Console.WriteLine(i.ToString)
Next

'create a new ArrayList and populate it
Dim list1 As New ArrayList(4)
list1.Add("Amy")
list1.Add("Alaina")
list1.Add("Aidan")
list1.Add("Anna")

'sort the array list
list1.Sort()

'display the contents of the sorted array list
For Each s As String In list1
Console.WriteLine(s)
Next

'wait to continue
Console.ReadLine()

End Sub

Monday, December 19, 2011

Monday 12/19/11

#include
#include //must include !

int main()
{
using namespace std;
string myName = "Alfred Jensen";
string myStreet = "5127 S. 95th E. Ave";
string myCityStreet = "Tulsa, OK";

cout << myName << endl;
cout << myStreet << endl;
cout << myCityStreet << endl;


return 0;
}


#include
#include

int main()
{
using namespace std;
cout << "Please enter the distance in furlongs" << endl;
int furlong = 0;
cin >> furlong;
int yard = furlong * 220;
cout << endl << "That is " << yard << " yards long";

}


#include
#include

int twoTimes()
{
using namespace std;
string s = "Three blind mice";
cout << s << endl;
cout << s << endl;

return 0;
}

int twice()
{
using namespace std;
string s = "See how they run";
cout << s << endl;
cout << s << endl;

return 0;
}

int main()
{
twoTimes();
twice();

}


#include
#include

int main()
{
using namespace std;
cout << "Please enter the temp. in Celsius" << endl;
double celsius = 0.0;
cin >> celsius;
double fahrenheit = celsius * 1.8 + 32.0;
cout << "That is " << fahrenheit << " in Fahrenheit degrees";
}


#include
#include

int calculateAU(double);

int main(){
double lightYears = 0.0;

using namespace std;
cout << "Enter the distance in light years: " << endl;
cin >> lightYears;
calculateAU(lightYears);
}

int calculateAU(double lightYears)
{
double au = lightYears * 265608;
std::cout << "That is " << au << " in astronomical units." << std::endl;
return 0;
}


#include
#include

int main()
{
using namespace std;
int n_int = INT_MAX;
short n_short = SHRT_MAX;
long n_long = LONG_MAX;

//sizeof operator yileds size of type or of variables
cout << "int is " << sizeof(int) << " bytes." << endl;
cout << "short is " << sizeof n_short << " bytes." << endl;
cout << "long is " << sizeof n_long << " bytes." << endl;

cout << "Maximum Values: " << endl;
cout << " Int: " << n_int << endl;
cout << " Short: " << n_short << endl;
cout << " Long: " << n_long << endl << endl;

cout << "Minimum int value=" << INT_MIN << endl;
cout << "Bits per byte=" << CHAR_BIT << endl;

return 0;
}


#include
#define ZERO 0
#include
int main()
{
using namespace std;
short sam = SHRT_MAX;
unsigned short sue = sam;

cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl;
cout << "Add $1 to each account." << endl << "Now.";
sam = sam + 1;
sue = sue + 1;
cout << "Same has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited.\nPoor Sam!" << endl;
sam = ZERO;
sue = ZERO;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl;
cout << "Take $1 from each account." << endl << "Now";
sam = sam - 1;
sue = sue - 1;
cout << "Sam has " << sam << "dollars and Sue has " << sue;
cout << " dollars deposited. " << endl << "Lucky Sue!" << endl;

return 0;
}

Friday, December 16, 2011

Friday 12/16/11

#include
#include

int main()
{
using namespace std;

double area;
cout << "Enter the floor area, in square feet, of your house.";
cout << endl;
cin >> area;
double side;
side = sqrt(area);

cout << "That's the equivalent of a square " << side;
cout << " feet to the side. " << endl;
cout << "How Fascinating!" << endl;
return 0;

}


#include
void simon(int); //function prototype simon()

int main()
{
using namespace std;
simon(3);
cout << " Pick an integer: ";
int count;
cin >> count;
simon(count); //call it again
cout << "Done!" << endl;
return 0;
}

void simon(int n)
{
using namespace std;
cout << "Simon says touch your toes " << n << " times " << endl;
//void functions don't need return statements
}


#include
int stonetolb(int);
int main()
{
using namespace std;
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << " stone = ";
cout << pounds << " pounds. " << endl;
return 0;
}

int stonetolb(int sts)
{
return 14*sts;
}

Thursday, December 15, 2011

Thursday 12.15.11

#include
int main()
{
using namespace std;
cout << "Come up and see me some time.";
cout << endl;
cout << "You won't regret it!" << endl;
return 0;
}


///carrots.cpp food processing program
//use and display a program

#include

int main()
{
using namespace std;

int carrots; //declare an integer variable
carrots = 25;
cout << "I have ";
cout << carrots;
cout << " carrots. ";
cout << endl;
carrots = carrots - 1;
cout << "crunch, crunch, crunch now I have " << carrots << " carrots " << endl;
return 0;
}

Wednesday, December 14, 2011

Wednesday 12.14.11

Imports System
Imports System.Security.Cryptography

Module Module1

Sub Main()
Apress.VisualBasicRecipes.Chapter12.Recipe12_12.Main()
End Sub

End Module

Namespace Apress.VisualBasicRecipes.Chapter12
Public Class Recipe12_12
Public Shared Sub Main()
'create a byte array to hold the random data
Dim number As Byte() = New Byte(32) {}
'instantiate the default random number generator
Dim rng As RandomNumberGenerator = RandomNumberGenerator.Create

'generate 32 bytes of random data
rng.GetBytes(number)

'display the random number
Console.WriteLine(BitConverter.ToString(number))

'wait to continue
Console.WriteLine(Environment.NewLine)
Console.WriteLine("Main method complete. Press Enter.")
Console.ReadLine()
End Sub
End Class
End Namespace


Imports System
Imports System.Text

Imports System.Security.Cryptography

Module Module1

Sub Main()
Dim args As String() = {"SHA384CryptoServiceProvider", "nasal7Spray"}
Recipe12_13.Main(args)

End Sub

End Module

Public Class Recipe12_13

Public Shared Sub Main(ByVal args As String())
'create a hashalgorithm of the type specified by the first command-line argument
Dim hashAlg As HashAlgorithm = Nothing

'some of the lcasses cannot be instantiated using the factory method so they must be directly created
Select Case args(0).ToUpper()
Case "SHA1MANAGED"
hashAlg = New SHA1Managed
Case "SHA256CRYPTOSERVICEPROVIDER"
hashAlg = New SHA256CryptoServiceProvider
Case "SHA384CRYPTOSERVICEPROVIDER"
hashAlg = New SHA384CryptoServiceProvider
Case "SHA512CRYPTOSERVICEPROVIDER"
hashAlg = New SHA512CryptoServiceProvider
Case Else
hashAlg = HashAlgorithm.Create(args(0))
End Select

Using hashAlg
'convert the password string, provided as the second command-line arguemnt
'to an array of bytes
Dim pwordData As Byte() = Encoding.Default.GetBytes(args(1)) 'imports system.text
'generate the has code of the password
Console.WriteLine("Generate the hash code of the password")
Dim hash As Byte() = hashAlg.ComputeHash(pwordData)

'display the hash code of the password to the console
Console.WriteLine(BitConverter.ToString(hash))

'wait to continue
Console.WriteLine(Environment.NewLine)
Console.WriteLine("Main method complete. Press Enter.")
Console.ReadLine()
End Using
End Sub
End Class


Imports System
Imports System.IO
Imports System.Security.Cryptography

Module Module1

Sub Main()
Dim args As String() = {"SHA1Managed", "C:/new/VBDotNet.txt"}
Recipe12_14.Main(args)

End Sub

End Module

Public Class Recipe12_14

Public Shared Sub Main(ByVal args As String())
'create a hash algorith of the tpye specified by the first command-line argument
Dim hashAlg As HashAlgorithm = Nothing
'the sha1 managed algorithm cannot be implemented using the
'factory approach it must be instantiated directly
If args(0).CompareTo("SHA1Managed") = 0 Then
hashAlg = New SHA1Managed
Else
hashAlg = HashAlgorithm.Create(args(0))
End If

'open a FileStream to teh file specified by the second command-line argument
Using fileArg As New FileStream(args(1), FileMode.Open, FileAccess.Read)
'generate the hash code of the password
Dim hash As Byte() = hashAlg.ComputeHash(fileArg)
'display the hash code fo the password to the console
Console.WriteLine(BitConverter.ToString(hash))
'wait to continue
Console.ReadLine()
End Using
End Sub
End Class


Imports System
Imports System.IO
Imports System.Security.Cryptography

Module Module1

Sub Main()
Dim args As String() = {"SHA1Managed", "C:/new/VBDotNet.txt"}
Recipe12_14.Main(args)

End Sub

End Module

Public Class Recipe12_14

Public Shared Sub Main(ByVal args As String())
'create a hash algorith of the tpye specified by the first command-line argument
Dim hashAlg As HashAlgorithm = Nothing
'the sha1 managed algorithm cannot be implemented using the
'factory approach it must be instantiated directly
If args(0).CompareTo("SHA1Managed") = 0 Then
hashAlg = New SHA1Managed
Else
hashAlg = HashAlgorithm.Create(args(0))
End If

readHash(args(1), hashAlg)

Dim myFileStream As System.IO.FileStream

Try
myFileStream = New System.IO.FileStream(args(1), FileMode.Append, FileAccess.Write, FileShare.None)
Try
Dim myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine("Hello World!")
'flush before we close
myWriter.Flush()
myWriter.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Catch ex As Exception
MsgBox(ex.ToString())
Finally
myFileStream.Close()
End Try

readHash(args(1), hashAlg)
End Sub

Public Shared Sub readHash(ByVal fileName, ByVal hashAlg)
'open a FileStream to teh file specified by the second command-line argument
Using fileArg As New FileStream(fileName, FileMode.Open, FileAccess.Read)
'generate the hash code of the password
Dim hash As Byte() = hashAlg.ComputeHash(fileArg)
'display the hash code fo the password to the console
Console.WriteLine(BitConverter.ToString(hash))
'wait to continue
Console.WriteLine()
Console.ReadLine()
End Using
End Sub
End Class



namespace practice
{
class Program
{
static void Main(string[] args)
{
EntryPoint ep = new EntryPoint();
ep.Run();
Console.ReadLine();
}
}

public struct Coordinate //this is a value type
{
public int x;
public int y;
}

public class EntryPoint //this is a reference type
{
public static void AttemptToModifyCoord(Coordinate coord)
{
coord.x = 1;
coord.y = 1;
}

public static void ModifyCoord(ref Coordinate coord)
{
coord.x = 10;
coord.y = 10;
}

public void Run()
{
Coordinate location;
location.x = 50;
location.y = 50;

AttemptToModifyCoord(location);
System.Console.WriteLine("({0}, {1} )", location.x, location.y);

ModifyCoord(ref location);
System.Console.WriteLine("({0}, {1} )", location.x, location.y);
}
}
}


class Program
{
[Flags]
public enum AccessFlags
{
NoAccess = 0x0,
ReadAccess = 0x1,
WriteAccess = 0x2,
ExecuteAccess = 0x4
}

static void Main(string[] args)
{
AccessFlags access = AccessFlags.ReadAccess | AccessFlags.WriteAccess;
System.Console.WriteLine("Access is {0}", access);
}
}


static void Main(string[] args)
{
var myList = new List();

myList.Add(1);
myList.Add(2);
myList.Add(3);

foreach (var i in myList)
{
Console.WriteLine(i);
}
}


Imports System
Imports System.Reflection
Imports System.Security.Policy


Module ADSetupInformation

Sub Main()
'create the application domain setup information
Dim domainInfo As New AppDomainSetup()
domainInfo.ApplicationBase = System.Environment.CurrentDirectory
'create evidence for a new AppDomain
Dim adevidence As Evidence = AppDomain.CurrentDomain.Evidence

'create the new application domain using setup information
Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain", adevidence, domainInfo)

'write out the domain information
Console.WriteLine("Host Domain: " + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine("New child domain: " + domain.FriendlyName)
Console.WriteLine()
Console.WriteLine("Application base is: " + domain.SetupInformation.ApplicationBase)

AppDomain.Unload(domain)
Console.ReadLine()
End Sub

End Module

Tuesday, December 13, 2011

Tuesday 12.13.11

Public Interface IAppFunctionality
Sub DoIt()
End Interface

_
Public NotInheritable Class CompanyInfoAttribute
Inherits System.Attribute

Private companyName As String
Private companyUrl As String

Public Sub New()
End Sub
Public Property Name() As String
Get
Return companyName
End Get
Set(ByVal value As String)
companyName = value
End Set
End Property

Public Property Url() As String
Get
Return companyUrl
End Get
Set(ByVal value As String)
companyUrl = value
End Set
End Property

End Class

Imports System.Windows.Forms
Imports CommonSnappableTypes


Module Module1

Sub Main()
Dim s As New VbNetSpanInModule()
s.DoIt()
End Sub

End Module

_
Public Class VbNetSpanInModule
Implements IAppFunctionality

Public Sub New()

End Sub

Public Sub DoIt() Implements CommonSnappableTypes.IAppFunctionality.DoIt
MessageBox.Show("You have just used the VB 2008 snap in!")
End Sub
End Class




Imports System.Reflection
Imports CommonSnappableTypes

Public Class Form1

Private Sub SnapInModuleToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SnapInModuleToolStripMenuItem.Click
'allow user to select an assemnly to load
Dim dlg As New OpenFileDialog()

If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
If dlg.FileName.Contains("CommonSnappableTypes") Then
MessageBox.Show("CommonSnappableTypes has no snap-ins!")
ElseIf LoadExternalModule(dlg.FileName) = False Then
MessageBox.Show("nothing implements IAppFunctionality!")
End If
End If
End Sub

Private Function LoadExternalModule(ByVal path As String) As Boolean
Dim foundSnapin As Boolean = False
Dim itfAppFx As IAppFunctionality
Dim theSnapInAsm As Assembly = Nothing

'try to dynamically load the selected assembly
Try
theSnapInAsm = Assembly.LoadFrom(path)
Catch ex As Exception
MessageBox.Show(ex.Message)
Return foundSnapin
End Try

'get all IAppFunctionality compatible classes in assembly using a LINQ query and implicity typed data
Dim classTypes = From t In theSnapInAsm.GetTypes() Where t.IsClass And (t.GetInterface("IAppFunctionality") IsNot Nothing) Select t

For Each c As Object In classTypes
foundSnapin = True
'use late binding to create the type
Dim o As Object = theSnapInAsm.CreateInstance(c.FullName)

'call DoIt() off the interface
itfAppFx = CType(o, IAppFunctionality)
itfAppFx.DoIt()
lstLoadedSnapIns.items.add(c.FullName)

Next
Return foundSnapin


End Function


Module Module1

Sub Main()
ListAllRunningProcesses()
Console.ReadLine()

Dim theProc As Process
Try
theProc = Process.GetProcessById(987)
'manipulate the process handle...
Catch ex As Exception
Console.WriteLine("-> Sorry...bad PID!")
End Try
Console.ReadLine()
'Prompt user for a PID and print out the set of active threads
Console.WriteLine("***** Enter PID of process to investigate *****")
Console.Write("PID: ")
Dim pID As String = Console.ReadLine()
Try
Dim theProcID As Integer = Integer.Parse(pID)
EnumThreadsForPid(theProcID)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
Dim proc As Process() = Process.GetProcessesByName("ListAllProcesses")
For Each p In proc
Console.WriteLine("Proc name is {0}", p.ProcessName)
Console.WriteLine("Proc id is {0}", p.Id)
EnumModsForPid(p.Id)
Next
StartAndKillProcess()

End Sub


Public Sub ListAllRunningProcesses()
'get all the processes on the local machine
Dim runningProcs As Process() = Process.GetProcesses(".")

'print out each PID and name of each process
For Each p As Process In runningProcs
Dim info As String = String.Format("-> PID: {0}" & Chr(9) & "Name: {1}", p.Id, p.ProcessName)
Console.WriteLine(info)
Next
Console.WriteLine("*****************************")
Console.WriteLine()
End Sub

Public Sub EnumThreadsForPid(ByVal pID As Integer)
Dim theProc As Process
Try
theProc = Process.GetProcessById(pID)
Catch ex As Exception
Console.WriteLine("-> Sorry...bad PID!")
Console.WriteLine("***********************")
Console.WriteLine()
Return
End Try
Console.WriteLine("Here are the threads used by: {0}", theProc.ProcessName)

'list out stats for each thread in the specified process
Dim theThreads As ProcessThreadCollection = theProc.Threads
For Each pt As ProcessThread In theThreads
Dim info As String = String.Format("-> Thread ID: {0}" & Chr(9) & "Start Time {1}" & _
Chr(9) & "Priority {2}", _
pt.Id, pt.StartTime.ToShortTimeString(), pt.PriorityLevel)
Console.WriteLine(info)
Next
Console.WriteLine("*************************")
Console.WriteLine()
End Sub

Public Sub EnumModsForPid(ByVal pID As Integer)
Dim theProc As Process
Try
theProc = Process.GetProcessById(pID)

Catch ex As Exception
Console.WriteLine("->Sorry...bad PID!")
Console.WriteLine("********************")
Console.WriteLine()
Return
End Try
Console.WriteLine("Here are the loaded modules for: {0}", theProc.ProcessName)
Try
Dim theMods As ProcessModuleCollection = theProc.Modules
For Each pm As ProcessModule In theMods
Dim info As String = String.Format("-> Mod Name: {0}", pm.ModuleName)
Console.WriteLine(info)
Next
Console.WriteLine("******************")
Console.WriteLine()
Catch ex As Exception
Console.WriteLine("No mods!")
End Try
End Sub

Public Sub StartAndKillProcess()
'launch internet explorer
Console.WriteLine("--> Hit a key to launch IE")
Console.ReadLine()
Dim ieProc As Process = Process.Start("IExplorer.exe", "www.intertech.com")
Console.WriteLine("--> Hit a key to kill {0}...", ieProc.ProcessName)
Console.ReadLine()
'kill the iexplorer.exe process
Try
ieProc.Kill()
Catch 'in case the user already killed it...
End Try
End Sub
End Module

Monday, December 12, 2011

Monday 12/12/11

Imports System.Reflection

Module Module1

Sub Main()
Console.WriteLine("***** Welcome to MyTypeViewer *****")
Dim typeName As String = String.Empty

Do
Console.WriteLine()
Console.WriteLine("Enter a type name to evaluate")
Console.Write("or enter Q to quit: ")

'get name of type
typeName = Console.ReadLine()
'does user want to quit?
If typeName.ToUpper() = "Q" Then
Exit Do
End If

'try to display type
Try
Dim t As Type = Type.GetType(typeName)
Console.WriteLine()
ListVariousStats(t)
ListFields(t)
ListProps(t)
ListMethods(t)
ListInterfaces(t)
Catch ex As Exception
Console.WriteLine("Sorry, cant' find {0}.", typeName)
End Try
Loop
End Sub


Public Sub ListMethods(ByVal t As Type)
Console.WriteLine("***** Methods *****")
Dim mi As MethodInfo() = t.GetMethods()
For Each m As MethodInfo In mi
Dim retVal As String = m.ReturnType.FullName()
Dim paramInfo As String = "( "
For Each pu As ParameterInfo In m.GetParameters()
paramInfo &= String.Format("{0} {1} ", pu.ParameterType, pu.Name)
Next
paramInfo &= " )"
Console.WriteLine("->{0} {1} {2}", retVal, m.Name, paramInfo)
Next
Console.WriteLine()

End Sub
'display field names of type
Public Sub ListFields(ByVal t As Type)
Console.WriteLine("***** Field *****")
Dim fi As FieldInfo() = t.GetFields()
For Each field As FieldInfo In fi
Console.WriteLine("->{0}", field.Name)
Next
Console.WriteLine()
End Sub

'display property names of type
Public Sub ListProps(ByVal t As Type)
Console.WriteLine("***** Properties *****")
Dim pi As PropertyInfo() = t.GetProperties()
For Each prop As PropertyInfo In pi
Console.WriteLine("->{0}", prop.Name)
Next
Console.WriteLine()
End Sub

'print out th enames of any interfaces
'supported on the incoming type
Public Sub ListInterfaces(ByVal t As Type)
Console.WriteLine("***** Interfaces *****")
Dim ifaces As Type() = t.GetInterfaces()
For Each i As Type In ifaces
Console.WriteLine("->{0}", i.Name)
Next
Console.WriteLine()
End Sub

Public Sub ListVariousStats(ByVal t As Type)
Console.WriteLine("***** Various Statistics *****")
Console.WriteLine("Base class is: {0}", t.BaseType)
Console.WriteLine("Is type abstract? {0}", t.IsAbstract)
Console.WriteLine("Is type sealed? {0}", t.IsSealed)
Console.WriteLine("Is type generic? {0}", t.IsGenericTypeDefinition)
Console.WriteLine("Is type a class type? {0}", t.IsClass)
Console.WriteLine()
End Sub
End Module


'demonstrates dynamic laoding
Imports System.Reflection

Module Module1

Sub Main()
Console.WriteLine("***** External Assemly Viewer *****")
Dim asmName As String = String.Empty
Dim asm As Assembly = Nothing
Do
Console.WriteLine()
Console.WriteLine("Enter an assembly to evaluate")
Console.Write("or enter Q to quit: ")

'get name of assembly
asmName = Console.ReadLine()

'does user want to quit?
If asmName.ToUpper = "Q" Then
Exit Do
End If

Try 'try to load assembly
asm = Assembly.Load(asmName)
DisplayTypesInAsm(asm)
Catch ex As Exception
Console.WriteLine("Sorry, can't find assembly named {0}.", asmName)
End Try
Loop

End Sub

Sub DisplayTypesInAsm(ByVal asm As Assembly)
Console.WriteLine()
Console.WriteLine("***** Types in Assembly *****")
Console.WriteLine("->{0}", asm.FullName)
Dim types As Type() = asm.GetTypes()
For Each t As Type In types
Console.WriteLine("Type: {0}", t)
Next
Console.WriteLine()
End Sub

End Module

Saturday, December 10, 2011

Saturday 12/10/2011

'this type is in the root namespace,
' which is (by default) the same name
'as the initial project

Public Class SomeClass
End Class

'this naemspace is nested within the root. therefore the fully
'qualified name of this class is MyCodeLibrary.MyTypes.SomeClass
Namespace MyTypes
Public Class SomeClass
End Class

'it is possible to nest namespaces within other namespaces to gain a greater level of structure
'thus the fully qualified name of this enum is
'MyCodeLibary.MyTypes.MyEnums.TestEnum
Namespace MyEnums
Public Enum TestEnum
TestValue
End Enum
End Namespace
End Namespace

Imports System.Windows.Forms

Public Class SportsCar
Inherits Car

Public Sub New()
End Sub

Public Sub New(ByVal carName As String, ByVal max As Short, ByVal curr As Short)
MyBase.New(carName, max, curr)
End Sub


Public Overrides Sub TurboBoost()
MessageBox.show("Ramming speed!", "Faster is better...")
End Sub
End Class

Public Class MiniVan
Inherits Car

Public Sub New()

End Sub

Public Sub New(ByVal carName As String, ByVal max As Short, ByVal curr As Short)
MyBase.New(carName, max, curr)
End Sub

Public Overrides Sub TurboBoost()
'minivans have poor turbo capabilities!
egnState = EngineState.engineDead
MessageBox.Show("Time to call AAA", "Your car is dead")
End Sub
End Class

Friday, December 9, 2011

Friday 12/9/11

Namespace IntroToLINQ

Public Class Cars
Public PetName As String = String.Empty
Public Color As String = String.Empty
Public Speed As Integer
Public Make As String = String.Empty

Public Overrides Function ToString() As String
Return String.Format("Make={0}, Color={1}, Speed={2}, PetName={3}", Make, Color, Speed, PetName)
End Function
End Class

Public Class MainProgram

Public Shared Sub Main()
Console.WriteLine("***** Fun with Query Expressions *****")
'this array will be th basis of our testing
Dim myCars As Cars() = { _
New Cars With {.PetName = "Henry", .Color = "Silver", .Speed = 100, .Make = "BMW"}, _
New Cars With {.PetName = "Daisy", .Color = "Black", .Speed = 55, .Make = "VW"}, _
New Cars With {.PetName = "Mary", .Color = "Tan", .Speed = 90, .Make = "BMW"}, _
New Cars With {.PetName = "Clunker", .Color = "Rust", .Speed = 15, .Make = "Yugo"}, _
New Cars With {.PetName = "Hank", .Color = "Red", .Speed = 65, .Make = "Ford"}, _
New Cars With {.PetName = "Sven", .Color = "White", .Speed = 55, .Make = "VW"}, _
New Cars With {.PetName = "Mary", .Color = "Yellow", .Speed = 80, .Make = "VW"}, _
New Cars With {.PetName = "Zippy", .Color = "Green", .Speed = 75, .Make = "Ford"}, _
New Cars With {.PetName = "Melvin", .Color = "White", .Speed = 55, .Make = "Ford"}, _
New Cars With {.PetName = "Calvin", .Color = "Tan", .Speed = 65, .Make = "VW"} _
}

BasicSelections(myCars)
GetSubsets(myCars)
GetProjection(myCars)
ReversedSelection(myCars)
OrderedResults(myCars)
GetDiff()
Console.ReadLine()


End Sub

Shared Sub BasicSelections(ByVal myCars As Cars())
'get all cars. Similar to Select * in SQL
Console.WriteLine(vbLf & "All Cars: ")
Dim allCars = From c In myCars Select c

For Each c In allCars
Console.WriteLine("Car: {0}", c)
Next

'get only th pet names
Console.WriteLine(vbLf & "All PetNames:")
Dim allNames = From c In myCars Select c.PetName

For Each n In allNames
Console.WriteLine("Pet Name: {0}", n)
Next
'allNames is really a variable that implements IEnumerable(Of String) given that we are selecting only
'the values of the PetName property for each
'car object

Dim makes = From c In myCars Select c.Make Distinct
For Each m In makes
Console.WriteLine("Make: {0}", m)
Next
End Sub

Shared Sub GetSubsets(ByVal myCars As Cars())
'now get only the BMWs
Console.WriteLine("Only BMWs:")
Dim onlyBMWs = From c In myCars Where c.Make = "BMW" Select c
For Each n In onlyBMWs
Console.WriteLine("Name: {0}", n)
Next
End Sub

'project new forms of data from an existing data source
Shared Sub GetProjection(ByVal myCars As Cars())
'now get structured data that only accounts for the
'make and color of each item
Console.WriteLine(vbLf & "Makes and Color:")
Dim makesColors = From c In myCars Select New With {c.Make, c.Color}

For Each n In makesColors
Console.WriteLine("Name: {0}", n)
Next
End Sub

Shared Sub ReversedSelection(ByVal myCars As Cars())
'get everything in reverse
Console.WriteLine("All cars in reverse:")
Dim subset = (From c In myCars Select c).Reverse()
For Each c As Cars In subset
Console.WriteLine("{0} is going {1} MPH", c.PetName, c.Speed)
Next
End Sub

Shared Sub OrderedResults(ByVal myCars As Cars())
' order all the cars by PetName
Dim subset = From c In myCars Order By c.PetName Select c

Console.WriteLine("Ordered by PetName:")
For Each c As Cars In subset
Console.WriteLine("Car {0}", c)
Next

'now find the cars that are going faster than 55 mph, and order by descending PetName
subset = From c In myCars Where c.Speed > 55 Order By c.PetName Descending Select c

Console.WriteLine(vbLf & "Cars going faster than 55, ordered by descending PetName:")
For Each c As Cars In subset
Console.WriteLine("Car {0}", c)
Next
End Sub

'the last LINQ query we will examine involves obtaining a resutl set the determines the differences
'between two iEnumberable(of T) compatible containers

Shared Sub GetDiff()
'two lists of strings
Dim myCars As String() = {"Yugo", "Aztec", "BMW"}
Dim yourCars As String() = {"BMW", "Saab", "Aztec"}

'find the differences
Dim carDiff = (From c In myCars Select c).Except(From c2 In yourCars Select c2)

Console.WriteLine(vbLf & "here is what you don't have, but I do:")
For Each s As String In carDiff
'prints yugo
Console.WriteLine(s)
Next
End Sub

End Class

End Namespace


Module Module1

Sub Main()
Console.WriteLine("***** LINQ Transformations *****" & vbLf)
Dim subset As IEnumerable(Of String) = GetStringSubset()
For Each item As String In subset
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub

Function GetStringSubset() As IEnumerable(Of String)
Dim currentVideoGames() As String = {"Morrowind", "BioShock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}
'note subset is an IEnumerable(OF String) compatible object
Dim subset As IEnumerable(Of String) = From g In currentVideoGames Where g.Length > 6 Order By g Select g

Return subset

End Function
End Module

Thursday, December 8, 2011

Thursday 12.8.11

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DataRelations : System.Web.UI.Page
{
private readonly string connectionString = @"Data Source=Alfred-PC\SQLExpress;" + "Initial Catalog=AdventureWorksLT2008R2; Integrated Security=SSPI";

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateOrderDataSet();
OrderGridView.DataSource = ds.Tables["Orders"];
OrderGridView.DataBind();

UpdateDetailsGrid();
}
}

protected void OrderGridView_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateDetailsGrid();
}

private DataSet CreateOrderDataSet()
{
//create a database connection
SqlConnection connection = new SqlConnection(connectionString);

//create a DataAdapter for the SalesORderHeader GridView
SqlDataAdapter OrdersAdapter = CreateAdapterForOrders(connection);

//create the dataset and use the data adapter to fill it
DataSet dataSet = new DataSet();

try
{
connection.Open();
OrdersAdapter.Fill(dataSet);
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
return dataSet;
}

private void UpdateDetailsGrid()
{
int index = OrderGridView.SelectedIndex;
if (index != -1)
{
//get the order id from the data grid
DataKey key = OrderGridView.DataKeys[index];
int orderID = (int)key.Value;

//DataSet ds = CreateOrderDetailsDataSet(orderID);

OrderDetailsGridView.DataSource = ds;
OrderDetailsGridView.DataBind();
OrderDetailsPanel.Visible = true;
}
else
{
OrderDetailsPanel.Visible = false;
}
}
//the SqlCommand's CommandText property is set to the name fo the stored procedure

private SqlDataAdapter CreateAdapterForOrders(SqlConnection connection)
{
//set the command to use the spOrders sproc
SqlCommand cmd = new SqlCommand("spOrders", connection);
cmd.CommandType = CommandType.StoredProcedure;

//set the adapter to use sproc as command
SqlDataAdapter OrdersAdapter = new SqlDataAdapter(cmd);
OrdersAdapter.TableMappings.Add("Table", "Orders");
return OrdersAdapter;
}

private SqlDataAdapter CreateAdapterForOrderDetails(SqlConnection connection, int orderId)
{
//set the command to use the spOrderDetails sproc and parameter
SqlCommand cmd = new SqlCommand("spOrderDetails", connection);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter orderIdParameter = cmd.Parameters.AddWithValue("@OrderId", orderId);
orderIdParameter.Direction = ParameterDirection.Input;
orderIdParameter.DbType = DbType.Int32;

//set adapter to use sproc as command
SqlDataAdapter OrderDetailsAdapter = new SqlDataAdapter(cmd);
OrderDetailsAdapter.TableMappings.Add("Table", "OrderDetails");
return OrderDetailsAdapter;

}
}




using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UpdatingDBDirectly : System.Web.UI.Page
{

private readonly string connectionString = @"Data Source=Alfred-PC\SQLExpress;" + "Initial Catalog=AdventureWorksLT2008R2; Integrated Security=True;";

protected void Page_Load(object sender, EventArgs e)
{
PopulateCategoryList();
PopulateGrid();
}

private void PopulateCategoryList()
{
//create connection to AdventureWOrksLT
SqlConnection connection = new SqlConnection(connectionString);

//create SqlCommand
StringBuilder cmdString = new StringBuilder();
cmdString.Append("SELECT DISTINCT ProductCategoryID, Name ");
cmdString.Append("FROM SalesLT.ProductCategory ");
cmdString.Append("WHERE (ParentProductCategoryID IS NULL) ");
cmdString.Append("ORDER BY ProductCategoryID");
SqlCommand cmd = new SqlCommand(cmdString.ToString(), connection);

try
{
connection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

while (dr.Read())
{
ddlParentCategory.Items.Add(new ListItem(dr["Name"].ToString(), dr["ProductCategoryID"].ToString()));
}

dr.Close();
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}

private void PopulateGrid()
{
//create connection to Advneture works LT
SqlConnection connection = new SqlConnection(connectionString);

//create SqlCommand string
StringBuilder cmdString = new StringBuilder();
cmdString.Append("SELECT child.ProductCategoryId, ");
cmdString.Append("Child.Name AS 'Category', ");
cmdString.Append("child.ParentProductCategoryID, ");
cmdString.Append("parent.Name As 'ParentCategory' ");
cmdString.Append("FROM SalesLT.ProductCategory AS child ");
cmdString.Append("INNER JOIN SalesLT.ProductCategory AS parent ON ");
cmdString.Append("child.ParentProductCategoryID = parent.ProductCategoryID");

SqlCommand cmd = new SqlCommand(cmdString.ToString(), connection);

try
{
connection.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
CategoryGridView.DataSource = dr;
CategoryGridView.DataBind();

dr.Close();
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}

//gridviews selectedindexchanged event handlr
//uses gridviews cells collection for the selected row to discover teh values to use.
protected void CategoryGridView_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = CategoryGridView.SelectedIndex;

if (selectedIndex != -1)
{
TableCellCollection selectedValues = CategoryGridView.Rows[selectedIndex].Cells;

//have to know the order of these cells in the grid
hdnCategoryID.Value = selectedValues[1].Text;
txtName.Text = selectedValues[2].Text;
ddlParentCategory.SelectedValue = selectedValues[3].Text;
}
}

protected void btnAdd_Click(object sender, EventArgs e)
{
StringBuilder insertCommand = new StringBuilder();
insertCommand.Append("insert int SalesLT.ProductCategory ");
insertCommand.Append("([ParentProductCategoryID], [Name]) ");
insertCommand.AppendFormat("values ('{0}', '{1}')", ddlParentCategory.SelectedValue, txtName.Text);
UpdateDB(insertCommand.ToString());
PopulateGrid();
}

protected void btnEdit_Click(object sender, EventArgs e)
{
StringBuilder updateCommand = new StringBuilder("Update SalesLT.ProductCategory SET ");
updateCommand.AppendFormat("Name='{0}', ", txtName.Text);
updateCommand.AppendFormat("ParentProductCategoryID='{1}' ", ddlParentCategory.SelectedValue);
updateCommand.AppendFormat("where ProductCategoryID='{2}'", hdnCategoryID.Value);
UpdateDB(updateCommand.ToString());
PopulateGrid();
}

protected void btnDelete_Click(object sender, EventArgs e)
{
string deleteCommand = string.Format("delete from SalesLT.ProductCategory where ProductCategoryID = '{0}'", hdnCategoryID.Value);
UpdateDB(deleteCommand);
PopulateGrid();
}

private void UpdateDB(string cmdString)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(cmdString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}

Wednesday, December 7, 2011

Wednesday 12.07.11

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//call the method that creates the tables and the relations
DataSet ds = CreateDataSet();


//set the data source for the grid to the first table
BugsGridView.DataSource = ds.Tables["Bugs"];
BugsGridView.DataBind();

BugConstraintsGridView.DataSource = ds.Tables["Bugs"].Constraints;
BugConstraintsGridView.DataBind();
}
}

private DataSet CreateDataSet()
{
//create a new dataset object for tables and relations
DataSet dataSet = new DataSet();

//create the Bugs table and add it to the DataSet
DataTable tblBugs = CreateBugsTable();
dataSet.Tables.Add(tblBugs);


//create the Product Table and add it to the dataset
DataTable tblProduct = CreateProductTable();
dataSet.Tables.Add(tblProduct);

//create the people table and add it to the Dataset
DataTable tblPeople = CreatePeopleTable();
dataSet.Tables.Add(tblPeople);

//create the foreign key constraint
//Peopple.PersonID = Bugs.ReportID
CreateForeignKeyAndDataRelation(dataSet, "BugToPerson", tblPeople, "PersonID", tblBugs, "ReporterID");

//create the Foreign Key Constrain
//Product.ProductID = Bugs.ProductID
CreateForeignKeyAndDataRelation(dataSet, "BugToProduct", tblProduct, "ProductID", tblBugs, "ProductID");

return dataSet;
}

private DataTable CreateBugsTable()
{
DataTable tblBugs = new DataTable("Bugs");

//add columns
AddNewPrimaryKeyColumn(tblBugs, "BugID");
AddNewColumn(tblBugs, "System.Int32", "ProductID", false, 1);
AddNewColumn(tblBugs, "System.String", "Version", false, "0.1", 50);
AddNewColumn(tblBugs, "System.String", "Description", false, "", 8000);
AddNewColumn(tblBugs, "System.Int32", "ReporterID", false);

//add some rows to the table
AddNewBug(tblBugs, 1, "0.1", "Crashes on load", 5);
AddNewBug(tblBugs, 1, "0.1", "Does not report correct owner of bug", 5);
AddNewBug(tblBugs, 1, "0.1", "Does not show history of previous action", 6);
AddNewBug(tblBugs, 1, "0.1", "Fails to reload properly", 5);
AddNewBug(tblBugs, 2, "0.1", "Loses data overnight", 5);
AddNewBug(tblBugs, 2, "0.1", "HTML is not shown properly", 6);
return tblBugs;
}

private DataTable CreateProductTable()
{
DataTable tblProduct = new DataTable("lkProduct");

//add columns
AddNewPrimaryKeyColumn(tblProduct, "ProductID");
AddNewColumn(tblProduct, "System.String", "ProductDescription", false, "", 8000);

//add rows to the Product table
AddNewProduct(tblProduct, "BugX Bug Tracking");
AddNewProduct(tblProduct, "PIM - My Personal Information Manager");
return tblProduct;
}

private void AddNewProduct(DataTable productTable, string description)
{
DataRow newRow = productTable.NewRow();
newRow["ProductDescription"] = description;
productTable.Rows.Add(newRow);
}

private DataTable CreatePeopleTable()
{
DataTable tblPeople = new DataTable("People");

//add column
AddNewPrimaryKeyColumn(tblPeople, "PersonID");
AddNewColumn(tblPeople, "System.String", "FullName", false, "", 8000);
AddNewColumn(tblPeople, "System.String", "Email", false, "", 100);
AddNewColumn(tblPeople, "System.String", "Phone", false, "", 20);
AddNewColumn(tblPeople, "System.Int32", "Role", false, 0);

//add new people
AddNewPerson(tblPeople, "Dan Maharry", "danm@hmobius.com", "212-255-0285", 1);
AddNewPerson(tblPeople, "Jesse Liberty", "jliberty@libertyassociates.com", "617-555-7301", 1);
AddNewPerson(tblPeople, "Dan Hurwitz", "dhurwitz@stersol.com", "781-555-3375", 1);
AddNewPerson(tblPeople, "John Galt", "jGalt@franconia.com", "617-444-8732", 1);
AddNewPerson(tblPeople, "John Osborn", "jOsborn@oreilly.com", "617-554-3212", 3);
AddNewPerson(tblPeople, "Ron Petrusha", "ron@oreilly.com", "707-555-0515", 2);
AddNewPerson(tblPeople, "Tatiana Apandi", "tatiana@oreilly.com", "617-555-1234", 2);

return tblPeople;
}

private void AddNewPerson(DataTable table, string name, string email, string phone, int role)
{
DataRow newRow = table.NewRow();
newRow["FullName"] = name;
newRow["Email"] = email;
newRow["Phone"] = phone;
newRow["Role"] = role;
table.Rows.Add(newRow);
}


//AllowDBNull sets whether a value in that column can ever be null or not
//DefaultValue sets the default value for that column
//MaxLength sets the maximum length fo that column if it is of type string

private void AddNewColumn(DataTable table, string ColumnType, string ColumnName, bool AllowNulls, object DefaultValue, int MaxLength)
{
DataColumn newColumn = table.Columns.Add(ColumnName, Type.GetType(ColumnType));
newColumn.AllowDBNull = AllowNulls;
newColumn.MaxLength = MaxLength;
newColumn.DefaultValue = DefaultValue;
}

private void AddNewColumn(DataTable table, string ColumnType, string ColumnName, bool AllowNulls, object DefaultValue)
{
AddNewColumn(table, ColumnType, ColumnName, AllowNulls, DefaultValue, -1);
}

private void AddNewColumn(DataTable table, string ColumnType, string ColumnName, bool AllowNulls)
{
AddNewColumn(table, ColumnType, ColumnName, AllowNulls, null, -1);
}

//further properties must be set to identify a column as a primary key for the DataTable
//creates a reference to the new column and calls it PkColumn
private void AddNewPrimaryKeyColumn(DataTable table, string ColumnName)
{
AddNewColumn(table, "System.Int32", ColumnName, false);
DataColumn PkColumn = table.Columns[ColumnName];
//because thsi is to be an identity column, you'll want to set its AutoIncrement property to true and its AutoIncrementSeed and AutoIncrementStep proeprties to set
//the seed and step values to 1

//set column as auto-increment field
PkColumn.AutoIncrement = true;
PkColumn.AutoIncrementSeed = 1;
PkColumn.AutoIncrementStep = 1;

//make sure all values are unique
string constraintName = String.Format("Unique_{0}", ColumnName);
UniqueConstraint constraint = new UniqueConstraint(constraintName, PkColumn);
table.Constraints.Add(constraint);

//finally the DataColumn must be added to the DataTable's PrimaryKey property

//set column as priamry key for table
DataColumn[] columnArray = new DataColumn[] { PkColumn };
table.PrimaryKey = columnArray;
}

//add rows by calling the DataTable objects NewRow() method, which returns an empty DataRow object
//with the right structure for the DataTable to which it belongs

private void AddNewBug(DataTable bugTable, int product, string version, string description, int reporter)
{
DataRow newRow = bugTable.NewRow();
newRow["ProductID"] = product;
newRow["Version"] = version;
newRow["Description"] = description;
newRow["ReporterID"] = reporter;
bugTable.Rows.Add(newRow);
}

//you can encapsulate the relationship between tables in a DataRelation object
//the DeleteRule property of a ForeignKeyConstraint object determines the action that will occur
//when a row is deleted from the parent table.
private void CreateForeignKeyAndDataRelation(DataSet dataSet, string relationName, DataTable parentTable, string primaryKeyColumnName, DataTable childTable, string foreignKeyColumnName)
{
DataColumn primaryKeyColumn = parentTable.Columns[primaryKeyColumnName];
DataColumn foreignKeyColumn = childTable.Columns[foreignKeyColumnName];
string foreignKeyConstraintName = String.Format("FL_{0}", relationName);

//create the foreign key constraint
ForeignKeyConstraint fk = new ForeignKeyConstraint(foreignKeyConstraintName, primaryKeyColumn, foreignKeyColumn);
fk.DeleteRule = Rule.Cascade;
fk.UpdateRule = Rule.Cascade;
childTable.Constraints.Add(fk);

//add a datarelation representing the FKConstraint to the DataSet
DataRelation relation = new DataRelation(relationName, primaryKeyColumn, foreignKeyColumn);
dataSet.Relations.Add(relation);
}
}