Thursday, January 5, 2012

Thursday 1/5/12

@autoreleasepool {
int a = 25, b = 5, c = 10, d = 7;

NSLog(@"a %% b = %i", a % b);
NSLog(@"a %% c = %i", a % c);
NSLog(@"a %% d = %i", a % d);
NSLog(@"a / d * d + a %% d = %i", a / d * d + a % d);
}


@autoreleasepool {
float f1 = 123.125, f2;
int i1, i2 = -150;

i1 = f1;

NSLog(@"%f assigned to an int produces %i", f1, i1);
f1 = i2; //integer to floating conversion
NSLog(@"%i assigned to a float produces %f", i2, f1);
f1 = i2 / 100; //integer divided by integer
NSLog(@"%i divided by 100 produces %f", i2, f1);

f2 = i2 / 100.0; //integer divided by a float
NSLog(@"%i divided by 100.0 produces %f", i2, f2);

f2 = (float) i2 / 100; //type cast operator
NSLog (@"(float) %i divided by 100 produces %f", i2, f2);

}

#include

void congratulateStudent(char *student, char *course, int numDays)
{
printf("%s has done as much %s programming as I could fit into %d days.\n", student, course, numDays);
}

int main (int argc, const char * argv[])
{
congratulateStudent("Mark", "Cocoa", 5);
congratulateStudent("Bo", "Objective-C", 2);
congratulateStudent("Mike", "Python", 5);
congratulateStudent("Ted", "iOS", 5);
}

#include

void singTheSong(int numberOfBottles)
{
if (numberOfBottles == 0) {
printf("There are simply no more bottles of beer on the wall.\n");
} else {
printf("%d bottles of beer on the wall. %d bottles of beer.\n", numberOfBottles, numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass it around, %d bottles of beer on the wall.\n", oneFewer);
singTheSong(oneFewer); //this function class itself
}
}


int main (int argc, const char * argv[])
{
singTheSong(99);



#include

float fahrenheitFromCelsius(float cel)
{
float fahr = cel * 1.8 + 32.0;
printf("%f Celsius is %f Fahrenheit\n", cel, fahr);
return fahr;

}


int main (int argc, const char * argv[])
{
float freezeInC = 0;
float freezeInF = fahrenheitFromCelsius(-freezeInC);
printf("Water freezes at %f degrees Fahrenheit\n", freezeInF);
return 0;
}



#include

float remainingAngle(float angleA, float angleB)
{
return 180 - (angleA + angleB);
}

int main (int argc, const char * argv[])
{

float angleA = 30.0;
float angleB = 60.0;
float angleC = remainingAngle(angleA, angleB);
printf("The third angle is %.2f\n", angleC);
return 0;
}




#include

int main (int argc, const char * argv[])
{
int x = 255;
printf("x is %d.\n", x);
printf("In octal, x is %o.\n", x);
printf("In hexadecimal, x is %x.\n", x);

long y = 2873;
printf("y is %ld.\n", y);
printf("In octal, y is %lo.\n", y);
printf("In hexadecimal, y is %lx.\n", y);

printf("3 * 3 + 5 * 2 = %d\n", 3 * 3 + 5 * 2);
printf("11 / 3 = %d remainder of %d \n", 11 / 3, 11 % 3);

//use the cast operator
printf("11 / 3.0 = %f\n", 11 / (float)3);


printf("The absolute value of -5 is %d\n", abs(-5));
return 0;

}



#include

int main (int argc, const char * argv[])
{
int i = 0;
while (i < 12) {
printf("%d. Aaron is Cool.\n", i);
i++;
}

for (i = 9; i < 12; i++){
printf("Checking i = %d\n", i);
if (i + 90 == i * i){
break;
}
}
printf("The answer is %d.\n", i);

i = 99;
while (i >= 0){
printf("%d\n", i);
if(i % 5 == 0){
printf("Found one!\n");
}
i -= 3;

}
return 0;
}




int main (int argc, const char * argv[])
{
int i = 17;
float *ptr;
int *addressOfI = &i;
printf("i stores its value at %p\n", addressOfI);

printf("i stores its value at %p\n", &i);
printf("the int stored at addressOfI is %d\n", *addressOfI);
*addressOfI = 87;
printf("Now i is %d\n", i);
printf("this function starts at %p\n", main);

int j = 23;
int *addressOfj = &j;
printf("j stores its value at %p\n", addressOfj);
*addressOfj = 100;
printf("Now j is %d\n", j);
printf("An int is %zu bytes\n", sizeof(int));
printf("A pointer is %zu bytes\n", sizeof(int *));

printf("A float is %zu bytes.\n", sizeof(float));
return 0;
}



#include
#include

typedef struct {
float heightInMeters;
int weightInKilos;
} Person;



int main (int argc, const char * argv[])
{
Person person;
person.weightInKilos = 96;
person.heightInMeters = 1.8;
printf("person weighs %i kilograms\n", person.weightInKilos);
printf("person is %.2f meters tall\n", person.heightInMeters);

long secondsSince1970 = time(NULL);
printf("it has been %ld seconds since 1970\n", secondsSince1970);

struct tm now;
printf("The time is %d:%d:%d\n", now.tm_hour, now.tm_min, now.tm_sec);

return 0;
}

Wednesday, January 4, 2012

Wednesday 1.4.12

Option Strict On
Imports System
Namespace StringSearch
Class Tester
Public Sub Run()
'create some strings to work with
Dim s1 As String = "One Two Three Four"
Dim index As Integer
'get the index of the last space
index = s1.LastIndexOf(" ")
'get the last word
Dim s2 As String = s1.Substring((index + 1))
'set s1 to the substring starting at 0
'and ending at index (the start of the last word)
'thus s1 has One Two Three
s1 = s1.Substring(0, index)

'find the last space in s1 (after "two")
index = s1.LastIndexOf(" ")

'set s3 to the substring starting at index
'the space after "two" plus one more
'thus s3 = "three"
Dim s3 As String = s1.Substring((index + 1))

'reset s1 to the substring starting at 0
'and ending at index, thus the string "one Two"
s1 = s1.Substring(0, index)

'reset index to the space betwee "One" and "Two"
index = s1.LastIndexOf(" ")

'set s4 to the substring starting one space after index, thus the substring "two"
Dim s4 As String = s1.Substring((index + 1))

'reset s1 to teh substring starting at 0
' and ending at index, thus "one"
s1 = s1.Substring(0, index)

'set index to the last space, but there is none so index now = -1
index = s1.LastIndexOf(" ")

'set s4 to the substring at one past the last space, there was no last space
'so this sets s5 to the substring starting at zero
Dim s5 As String = s1.Substring((index + 1))

Console.WriteLine("s1: {0}", s1)
Console.WriteLine("s2: {0}", s2)
Console.WriteLine("s3: {0}", s3)
Console.WriteLine("s4: {0}", s4)
Console.WriteLine("s5: {0}", s5)

End Sub 'run

Public Shared Sub main()
Dim t As New Tester()
t.Run()
End Sub 'main
End Class 'tester
End Namespace 'StringSearch


Public Sub Run()
'create some strings to work with
Dim s1 As String = "One, Two, Three Liberty Associates, Inc."

'constants for the space and comma characters
Const Space As Char = " "c
Const Comma As Char = ","c

'array of delimiters to split the sentence with
Dim delimiters() As Char = {Space, Comma}
Dim output As String = ""
Dim ctr As Integer = 0

'split the string and then iterate over the
'resulting array of string
Dim resultArray As String() = s1.Split(delimiters)

Dim substring As String
For Each substring In resultArray
ctr = ctr + 1
output &= ctr.ToString()
output &= ": "
output &= substring
output &= Environment.NewLine
Next
Console.WriteLine(output)
End Sub 'run


namespace SimpleProject2
{
class Program
{
static int Main(string[] args)
{
ShowEnvironmentDetails();
Console.ReadLine();

return -1;
}

static void ShowEnvironmentDetails()
{
//print out drives no this machine, and other interesting details
foreach (string drive in Environment.GetLogicalDrives())
Console.WriteLine("Drive: {0}", drive);
Console.WriteLine("OS: {0}", Environment.OSVersion);
Console.WriteLine("Number of processors: {0}", Environment.ProcessorCount);
Console.WriteLine(".NET Version: {0}", Environment.Version);
}
}
}


static int Main(string[] args)
{
Console.WriteLine("***** Basic Console I/O *****");
GetUserData();
Console.ReadLine();

return -1;
}

static void GetUserData()
{
//get name and age
Console.Write("Please enter your name: ");
string userName = Console.ReadLine();
Console.Write("Please enter your age: ");
string userAge = Console.ReadLine();

//change echo color, just for fun
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;

//echo the console
Console.WriteLine("Hello {0}! You are {1} years old.", userName, userAge);

//restore previous color;
Console.ForegroundColor = prevColor;
}


static int Main(string[] args)
{
Console.WriteLine("***** Format Numerical Data *****");
FormatNumericalData();
Console.ReadLine();

return -1;
}

static void FormatNumericalData()
{
Console.WriteLine("The value 99999 in various formats:");
Console.WriteLine("c format: {0:c}", 99999);
Console.WriteLine("d9 format: {0:d9}", 99999);
Console.WriteLine("f3 format: {0:f3}", 99999);
Console.WriteLine("n format: {0:n}", 99999);

//notice that upper or lowercasing for hex
//determines if letters are upper or lowercase
Console.WriteLine("E format: {0:E}", 99999);
Console.WriteLine("e format: {0:e}", 99999);
Console.WriteLine("X format: {0:X}", 99999);
}


#import

int main (int argc, const char * argv[])
{

@autoreleasepool {

// insert code here...
NSLog(@"Programming is fun!");
NSLog(@"Programming in Objective-C is even more fun!");
NSLog(@"Testing...\n...1\n...2\n...3");
int sum;
sum = 50 + 25;
NSLog(@"The sum of 50 and 25 is %i", sum);
int value1, value2;
value1 = 50;
value2 = 25;
sum = value1 + value2;
NSLog(@"\nThe sum of %i and %i is %i", value1, value2, sum);
}
return 0;
}


int main (int argc, const char * argv[])
{

@autoreleasepool {
NSLog(@"In Objective-C, lowercase letters are significant");
NSLog(@"\n main is where program execution begins.");
NSLog(@"\nOpen and closed braces enclose program statements in a routine.");

int difference;
difference = 87 - 15;
NSLog(@"\n The difference of 87 and 15 is %i", difference);

int answer, result;
answer = 100;
result = answer - 10;
NSLog(@"The result is %i\n", result + 5);
}
return 0;
}



#import

@interface Fraction: NSObject

-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;

@end

@implementation Fraction
{
int numerator;
int denominator;
}
-(void) print
{
NSLog (@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
numerator = n;
}

-(void) setDenominator: (int) d
{
denominator = d;
}

@end

// ----- program section -------

int main (int argc, const char * argv[])
{

@autoreleasepool {
Fraction *myFraction;

//create an instance of a fraction
myFraction = [Fraction alloc];
myFraction = [myFraction init];

//set fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];

//display the fraction using the print method
NSLog(@"The value of myFraction is:");
[myFraction print];
}
return 0;
}

//----- interface section -----
@interface Fraction: NSObject

-(void) print;
- (void) setNumerator: (int) n;
- (void) setDenominator: (int) d;

@end

//---implementation section -----

@implementation Fraction
{
int numerator;
int denominator;
}

-(void) print
{
NSLog(@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
numerator = n;
}

-(void) setDenominator: (int) d
{
denominator = d;
}

@end
// ----- program section -------

int main (int argc, const char * argv[])
{


@autoreleasepool {
Fraction *frac1 = [[Fraction alloc] init];
Fraction *frac2 = [[Fraction alloc] init];

//set first fraction to 2/3
[frac1 setNumerator: 2];
[frac1 setDenominator: 3];

//set second fraction to 3/7
[frac2 setNumerator: 3];
[frac2 setDenominator: 7];

//display the fractions
NSLog(@"First fraction is:");
[frac1 print];
NSLog(@"Second fraction is:");
[frac2 print];

}
return 0;
}





@interface Fraction: NSObject

- (void) print;
- (void) setNumerator: (int) n;
- (void) setDenominator: (int) d;
- (int) numerator;
- (int) denominator;

@end

//--- @implementation section ----

@implementation Fraction
{
int numerator;
int denominator;
}

-(void) print
{
NSLog(@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
numerator = n;
}

- (void) setDenominator: (int) d
{
denominator = d;
}

- (int) numerator
{
return numerator;
}

- (int) denominator
{
return denominator;
}
@end



// ----- program section -------

int main (int argc, const char * argv[])
{


@autoreleasepool {
Fraction *myFraction = [[Fraction alloc] init];

//set fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];

//display the fraction using our two new methods
NSLog(@"The value of myFraction is: %i/%i", [myFraction numerator], [myFraction denominator]);


}
return 0;
}



int main (int argc, const char * argv[])
{
{
@autoreleasepool {
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 8.44e+11;
char charVar = 'W';

NSLog(@"integerVar = %i", integerVar);
NSLog(@"floatingVar = %f", floatingVar);
NSLog(@"doubleVar = %g", doubleVar);
NSLog(@"charVar = %c", charVar);
}
}


return 0;
}


int main (int argc, const char * argv[])
{
{
@autoreleasepool {
int a = 100;
int b = 2;
int c = 25;
int d = 4;
int result;

result = a - b;
NSLog(@"a - b = %i", result);

result = b * c;
NSLog(@"b * c = %i", result);

result = a / c;
NSLog(@"a / c = %i", result);

result = a + b * c;
NSLog(@"a + b * c = %i", result);

NSLog(@"a * b + c * d = %i", a * b + c * d);
}
}


return 0;
}



@autoreleasepool {
int a = 25;
int b = 2;
float c = 25.0;
float d = 2.0;

NSLog(@"6 + a / 5 * b = %i", 6 + a / 5 * b);
NSLog(@"a / b * b = %i", a / b * b);
NSLog(@"c / d * d = %f", c / d * d);
NSLog(@"-a = %i", -a);
}

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