Monday, August 22, 2011

Monday 8.22.11

//use the math.h header file, handy for floating-point tests
#include
#include
int main(void)
{
const double ANSWER = 3.14159;
double response;

printf("What is the value of pi?\n");
scanf("%lf", &response);
while (fabs(response - ANSWER) > 0.0001)
{
printf("Try again!\n");
scanf("%lf", &response);
}
printf("Close enough!\n");

return 0;
}


#include
int main(void)
{
long num;
long sum = 0L;
_Bool input_is_good;
printf("Please enter an integer to be summed ");
printf("(q to quit): ");
//the parentheses enclosing the == expression are not needed
//but make the code easier to read
input_is_good = (scanf("%ld", &num) == 1);
while(input_is_good)
{
sum = sum + num;
printf("Please enter next integer (q to quit): ");
input_is_good = (scanf("%ld", &num) == 1);
}
printf("Those integers sum to %ld.\n", sum);

return 0;
}


<#include
int main(void)
{
const int NUMBER = 22;
int count = 1;

while (count <= NUMBER)
{
printf("Be my Valentine!\n");
count++;
}
return 0;

}


#include
int main(void)
{
const int NUMBER = 22;
int count;

for (count = 1; count <= NUMBER; count++)
{
printf("Be my Valentine!\n");
}
return 0;
}


#include
int main(void)
{
const int FIRST_OZ = 37;
const int NEXT_OZ = 23;
int ounces, cost;

printf(" ounces cost\n");
for (ounces=1, cost=FIRST_OZ; ounces <= 16; ounces++, cost += NEXT_OZ)
{
printf("%5d $%4.2f\n", ounces, cost/100.0);
}

return 0;
}



#include
int main(void)
{
const int secret_code = 13;
int code_entered;

do
{
printf("To enter the triskaidekaphobia therapy club, \n");
printf("please enter the secret code number: ");
scanf("%d", &code_entered);
} while (code_entered != secret_code);
printf("Congratulations! You are cured!\n");

return 0;
}


#include
int main(void)
{
const int secret_code = 13;
int code_entered;

do
{
printf("To enter the triskaidekaphobia therapy club, \n");
printf("please enter the secret code number: ");
scanf("%d", &code_entered);
} while (code_entered != secret_code);
printf("Congratulations! You are cured!\n");

return 0;
}


#include
#define ROWS 6
#define CHARS 10
int main(void)
{
int row;
char ch;

for (row = 0; row < ROWS; row++)
{
for (ch = 'A'; ch < ('A' + CHARS); ch++)
{
printf("%c", ch);
}
printf("\n");
}
return 0;
}

here are some vb tutorials


Option Strict On

Public Module TimerFunction
Public Sub Main()
Dim starttime, endtime As Integer
starttime = Environment.TickCount
For ctr As Integer = 0 To 100000000

Next
endtime = Environment.TickCount
Console.WriteLine("Ellapsed time is {0} milliseconds", endtime - starttime)
End Sub
End Module


Module Module1

Dim WithEvents ValueInfo As New Value()

Class Value
Public Event ValueUp(ByVal amount As Double)
Public Event ValueDown(ByVal amount As Double)
Public Event Result(ByVal amount As Double, ByVal announceDate As DateTime)

Public Sub GenerateEvents()
RaiseEvent ValueUp(2)
RaiseEvent ValueDown(-5.5)
RaiseEvent Result(1.25, Now())
End Sub
End Class

Sub PriceGoingUp(ByVal Price As Double)
Console.WriteLine("Up: " & Price)
End Sub

Sub PriceGoingDown(ByVal Price As Double)
Console.WriteLine("Down: " & Price)
End Sub

Sub ResultAnnouncement(ByVal Amount As Double, ByVal AnnounceDate As DateTime)
Console.WriteLine("Result: " & Amount & " " & AnnounceDate)
End Sub


Sub Main()
AddHandler ValueInfo.ValueUp, AddressOf PriceGoingUp
AddHandler ValueInfo.ValueDown, AddressOf PriceGoingDown
AddHandler ValueInfo.Result, AddressOf ResultAnnouncement

ValueInfo.GenerateEvents()
End Sub

End Module


Module Module1

Dim WithEvents ColorInfo As New Color()

Class Color
Public Event ColorChange(ByVal color As String)
Public Event ToneChange(ByVal tone As String)

Public Sub GetColor()
Console.WriteLine("What color?")
Dim newColor = Console.ReadLine()
RaiseEvent ColorChange(newColor)
End Sub

Public Sub GetTone()
Console.WriteLine("What tone?")
Dim newTone = Console.ReadLine()
RaiseEvent ToneChange(newTone)
End Sub


End Class

Sub ColorChanging(ByVal color As String)
Console.WriteLine("Color is now: " & color)
End Sub

Sub ToneChanging(ByVal tone As String)
Console.WriteLine("Tone is now: " & tone)
End Sub

Sub Main()


AddHandler ColorInfo.ColorChange, AddressOf ColorChanging
AddHandler ColorInfo.ToneChange, AddressOf ToneChanging
ColorInfo.GetColor()
ColorInfo.GetTone()

End Sub

End Module


Module Module1
Class DailyJob
Public Event Coding(ByVal Item As String, ByVal StartTime As DateTime)
Public Event Testing(ByVal Item As String, ByVal StartTime As DateTime)
Public Event Meeting(ByVal Item As String, ByVal StartTime As DateTime)

Public Sub GenerateEvents()
RaiseEvent Coding("Coding", Now())
RaiseEvent Testing("Testing", Now().AddMinutes(5.0))
RaiseEvent Meeting("Meeting", Now().AddMinutes(10.0))
End Sub
End Class

Dim WithEvents ThisDailyJob As New DailyJob()

Sub DoJob(ByVal Item As String, ByVal StartTime As DateTime)
Console.WriteLine("Starting " & Item & "at : " & StartTime)
End Sub

Sub Main()
AddHandler ThisDailyJob.Coding, AddressOf DoJob
AddHandler ThisDailyJob.Testing, AddressOf DoJob
AddHandler ThisDailyJob.Meeting, AddressOf DoJob

ThisDailyJob.GenerateEvents()

End Sub

End Module


using System;
using System.Data;

namespace CreateDataColumnAddDataTable
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();

//Add the column to the Data Table to create
DataColumn col1 = dt.Columns.Add();
//configure the column -- integer with a default = 0 that
//does not allow nulls
col1.ColumnName = "Column-1";
col1.DataType = typeof(int);
col1.DefaultValue = 0;
col1.Unique = true;
col1.AllowDBNull = false;

//create and configure the column
DataColumn col2 = new DataColumn();
//configure the colum -- string with max length = 50
col2.ColumnName = "Column-2";
col2.DataType = typeof(string);
col2.MaxLength = 50;
//add the column to the DataTable
dt.Columns.Add(col2);

//add a column directly using an overload of the Add()
//method of the DataTable.Columns collection -- the column
//is a string with max length = 50
dt.Columns.Add("Column-3", typeof(string)).MaxLength = 50;

//add multiple existing columns to the DataTable
DataColumn col4 = new DataColumn("Column-4");
//...configure column 4
DataColumn col5 = new DataColumn("Column-5", typeof(int));
//add columns 4 and 5 to the DataTable
dt.Columns.AddRange(new DataColumn[] { col4, col5 });

//Output the columns in the dataTable to the console
Console.WriteLine("DataTable has {0} DataColumns named: ", dt.Columns.Count);
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine("\t{0}", col.ColumnName);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}


using System;
using System.Data;

namespace CreateDataTableAddDataSet
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();

//add a DataTable named Table-1 directly
DataTable dt1 = ds.Tables.Add("Table-1");
//configure the DataTable...add some columns etc.
DataColumn col1 = dt1.Columns.Add();
col1.ColumnName = "PrimaryKey";
col1.DataType = typeof(int);
col1.Unique = true;
col1.AutoIncrement = true;

//add a DataTable named Table-2 by creating the table
//and adding it to the DataSet

DataTable dt2 = new DataTable("Table-2");
//configure the DataTable, add some columns, etc.
DataColumn col2 = new DataColumn();
col2.ColumnName = "CompanyName";
ds.Tables.Add(dt2);
//add multiple DataTables to the DataSet
DataTable dt3 = new DataTable("Table-3");
DataTable dt4 = new DataTable("Table-4");
//configure the DataTable -- add some columns, etc.
ds.Tables.AddRange(new DataTable[] {dt3, dt4});

//output the tables in the DataSet to the console.
Console.WriteLine("DataSet has {0} DataTables named: ", ds.Tables.Count);
foreach (DataTable dt in ds.Tables)
Console.WriteLine("\t{0}", dt.TableName);

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

Friday, August 19, 2011

Friday 8.18.11

using System;
using System.Windows.Forms;

public class MainClass : System.Windows.Forms.Form
{
public MainClass()
{
Application.ApplicationExit += new EventHandler(Form_OnExit);
}
[STAThread]
static void Main()
{
Application.Run(new MainClass());
}

private void Form_OnExit(object sender, EventArgs evArgs)
{
Console.WriteLine("Exit");
}
}


using System;
using System.Threading;
using System.Windows.Forms;

public class BlockLeftMouseButtonMessageFilter : IMessageFilter
{
const int WM_LEFTBUTTONDOWN = 0x201;

public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LEFTBUTTONDOWN)
{
Exception LeftButtonDownException;

LeftButtonDownException = new Exception("The left mouse button was pressed.");
Application.OnThreadException(LeftButtonDownException);
return true;
}
return false;
}
}


public class ApplicationEventHandlerClass
{
public void OnThreadException(object sender, ThreadExceptionEventArgs e)
{
Exception LeftButtonDownException;
LeftButtonDownException = e.Exception;
Console.WriteLine(LeftButtonDownException.Message);
}
}

public class MainForm : Form
{
public static void Main()
{
ApplicationEventHandlerClass AppEvents = new ApplicationEventHandlerClass();
MainForm myForm = new MainForm();
BlockLeftMouseButtonMessageFilter MsgFilter = new BlockLeftMouseButtonMessageFilter();

Application.AddMessageFilter(MsgFilter);
Application.ThreadException += new ThreadExceptionEventHandler(AppEvents.OnThreadException);
Application.Run(myForm);
}


public MainForm()
{
Text = "Application Exception Test";
}
}




Module Module1

Sub Main()
Console.Title = "Custom Command Window"
Console.BackgroundColor = ConsoleColor.White
Console.ForegroundColor = ConsoleColor.DarkBlue
Console.WindowHeight = Console.LargestWindowHeight - 15
Console.WindowWidth = Console.LargestWindowWidth - 15

Console.Clear()
Console.ReadLine()

End Sub

End Module



Module Module1

Sub Main(ByVal cmdArgs() As String)
Dim strArg As String

If cmdArgs.Length > 0 Then
For Each strArg In cmdArgs
Select Case strArg.Substring(0, 3)
Case "/a1"
Console.WriteLine("Processsing arg1: Value is {0}.", strArg.Substring(3, strArg.Length - 3))
Case "/a2"
Console.WriteLine("Processing arg1: Value is {0}.", strArg.Substring(3, strArg.Length - 3))
End Select
Next
End If

End Sub

End Module


Namespace MyApp.Info


Public Class Utilities
'Run time application
Public Sub DisplayData()
Console.WriteLine(Environment.MachineName)
Console.WriteLine(Environment.SystemDirectory)
Console.WriteLine(Environment.GetLogicalDrives())
Console.WriteLine(Environment.Version.ToString())
End Sub
End Class

Module Main

Sub Main()
Dim objHW As New MyApp.Info.Utilities
objHW.DisplayData()
End Sub

End Module

End Namespace


Sub Main(ByVal cmdArgs() As String)
If Environment.GetCommandLineArgs.Length > 0 Then
For Each strArg As String In Environment.GetCommandLineArgs
'process the arguments here
Console.WriteLine(strArg)
Next strArg
End If
End Sub


Public Class Tester
Public Shared Sub Main()
Console.WriteLine("Enter the numerator")
Dim a As Integer = Console.ReadLine()
Console.WriteLine("Enter the denominator")
Dim b As Integer = Console.ReadLine()


Try
Dim numerator As Integer = Convert.ToInt32(a)
Dim denominator As Integer = Convert.ToInt32(b)

Dim result As Integer = numerator \ denominator

Catch formattingException As FormatException
Console.WriteLine("You must enter two integers")
Catch dividingException As DivideByZeroException
Console.WriteLine(dividingException.Message)


End Try
End Sub

End Class


Imports System
Imports System.IO
Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_03

'create a byte array from a decimal
Public Shared Function DecimalToByteArray(ByVal src As Decimal) As Byte()
'Create a MemoryStream as a buffer to hold the binary data.
Using Stream As New MemoryStream
'Create a BinaryWriter to write binary data to the stream
Using writer As New BinaryWriter(Stream)
'write the decimal to the BinaryWriter/MemoryStream
writer.Write(src)
'return the byte representation of the decimal
Return Stream.ToArray
End Using
End Using

End Function

'create a decimal from a byte array
Public Shared Function ByteArrayToDecimal(ByVal src As Byte()) As Decimal
'create a MemoryStream containing the byte array.
Using Stream As New MemoryStream(src)
'create a binaryReader to read the decimal from the stream.
Using reader As New BinaryReader(Stream)
'Read and return the decimal from the
'BinaryReader/MemoryStream
Return reader.ReadDecimal
End Using
End Using

End Function


Public Shared Sub Main()

Dim b As Byte() = Nothing

'Convert a boolean to a byte array and display
b = BitConverter.GetBytes(True)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a boolean and display
Console.WriteLine(BitConverter.ToBoolean(b, 0))

'convert and interger to a byte array and display
b = BitConverter.GetBytes(3678)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to integer and display
Console.WriteLine(BitConverter.ToInt32(b, 0))

'convert a decimal to a byte array and display
b = DecimalToByteArray(285998345545.563846696D)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a decimal and display
Console.WriteLine(ByteArrayToDecimal(b))

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

End Sub


End Class
End Namespace


Imports System
Imports System.Text.RegularExpressions

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_05

Public Shared Function ValidateInput(ByVal expression As String, ByVal input As String) As Boolean

'Create a new Regex based on the specified regular expression.
Dim r As New Regex(expression)

'Test if the specified input matches the regular expression
Return r.IsMatch(input)

End Function


Sub New(ByVal args As String())

'Test the input frm the command line. The first argument is the regular expression, and the second is the input
Console.WriteLine("Regular Expressions: {0}", args(0))
Console.WriteLine("Input: {0}", args(1))
Console.WriteLine("Valued = {0}", ValidateInput(args(0), args(1)))

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

End Sub

End Class

Public Class MainClass

''must be shared if you define it inside a class
Public Shared Sub Main()
Console.WriteLine("Enter regex here")
Dim a = Console.ReadLine()
Console.WriteLine("Enter test string here")
Dim b = Console.ReadLine()

Dim stringArray(1) As String
stringArray(0) = a
stringArray(1) = b

Dim ex As New Recipe02_05(stringArray)


End Sub

End Class

End Namespace


#include
int main(void)
{
long num;
long sum = 0l;
int status;

printf("Please enter an integer to be summed");
printf("(q to quit): ");
status = scanf("%ld", &num);
while (status == 1) //means 'is equal to'
{
sum = sum +num;
printf("please enter next integer (q to quit): ");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);

return 0;
}


#include
int main(void)
{
int n = 5;

while(n < 7)
{
printf("n = %d\n", n);
n++;
printf("Now n = %d\n", n);
}
printf("The loop has finished.\n");

return 0;
}


using System;
using System.Data;

namespace CreateDataTableAddDataSet
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();

//add a DataTable named Table-1 directly
DataTable dt1 = ds.Tables.Add("Table-1");
//configure the DataTable...add some columns etc.
DataColumn col1 = dt1.Columns.Add();
col1.ColumnName = "PrimaryKey";
col1.DataType = typeof(int);
col1.Unique = true;
col1.AutoIncrement = true;

//add a DataTable named Table-2 by creating the table
//and adding it to the DataSet

DataTable dt2 = new DataTable("Table-2");
//configure the DataTable, add some columns, etc.
DataColumn col2 = new DataColumn();
col2.ColumnName = "CompanyName";
ds.Tables.Add(dt2);
//add multiple DataTables to the DataSet
DataTable dt3 = new DataTable("Table-3");
DataTable dt4 = new DataTable("Table-4");
//configure the DataTable -- add some columns, etc.
ds.Tables.AddRange(new DataTable[] {dt3, dt4});

//output the tables in the DataSet to the console.
Console.WriteLine("DataSet has {0} DataTables named: ", ds.Tables.Count);
foreach (DataTable dt in ds.Tables)
Console.WriteLine("\t{0}", dt.TableName);

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

Thursday, August 18, 2011

Thursday 8.18.11


//modulus
#include
#define SEC_PER_MIN 60
int main(void)
{
int sec, min, left;

printf("Convert seconds to minutes and seconds!\n");
printf("Enter the number of seconds (<=0 to quit):\n");
scanf("%d", &sec);
while (sec>0)
{
min = sec / SEC_PER_MIN; //truncated number of minutes
left = sec % SEC_PER_MIN; //number of seconds left over
printf("%d seconds is %d minutes, %d seconds.\n", sec, min, left);
printf("Enter next value (<=0 to quit):\n");
scanf("%d", &sec);
}
printf("Done!\n");

return 0;
}





#include
int main(void)
{
int ultra = 0, super = 0;

while (super < 5)
{
super++;
++ultra;
printf("super = %d, ultra = %d \n", super, ultra);
}

return 0;
}





#include
int main(void)
{
int a = 1, b = 1;
int aplus, plusb;

aplus = a++;
plusb = ++b;
printf("a aplus b plusb \n");
printf("%1d %5d %5d %5d\n", a, aplus, b, plusb);

return 0;
}




#include
int main(void)
{
int count, sum; //declaration statement

count = 0; //assignment statement
sum = 0; //assignment statement
while (count++ < 20) //while statement (structured statement)
{
sum = sum + count;
printf("sum = %d\n", sum); //function statement
}
return 0

}




#include
int main(void)
{
char ch;
int i;
float f1;

f1 = i = ch = 'C';
printf("ch = %c, i = %d, f1 = %2.2f\n", ch, i, f1);
ch = ch + 1;
i = f1 + 2 * ch;
f1 = 2.0 * ch + i;
printf("ch = %c, i = %d, f1 = %2.2f\n", ch, i, f1);
ch = 5212205.17;
printf("Now ch = %c\n", ch);

return 0;
}




#include
void pound(int n);

int main(void)
{
int times = 5;
char ch = '!'; //ASCII code is 33
float f = 6.0;

pound(times); //int argument
pound(ch); //char automatically -> int
pound((int) f); //cast forces f -> int

return 0;
}

void pound(int n)
{
while (n-- > 0)
{
printf("#");
}
printf("\n");
}




#include
const int S_PER_M = 60;
const int S_PER_H = 3600;
const double M_PER_K = 0.62137;

int main(void)
{
double distk, distm; //distance run in km and in miles
double rate; //average speed in mph
int min, sec; // minutes and seconds of running time
int time; //running time in seconds only
double mtime; //time in seconds for one mile
int mmin, msec; //minutes and seconds for one mile

printf("This program converts your time for a metric race\n");
printf("to a time for running a mile and to your average\n");
printf("speed in miles per hour.\n");
printf("Please enter, in kilometeres, the distance run.\n");
scanf("%lf", &distk); //%lf for type double
printf("Next, enter the time in minutes and seconds.\n");
printf("Begin by entering the minutes.\n");
scanf("%d", &min);
printf("Now enter the seconds.\n");
scanf("%d", &sec);
//converts time to pure seconds
time = S_PER_M * min + sec;
//convers kilometers to miles
distm = M_PER_K * distk;
//miles per sec x sec per hour = mph
rate = distm / time * S_PER_H;
// time/distance - time per mile
mtime = (double) time / distm;
//using the cast operator
mmin = (int) mtime / S_PER_M; //find whole minutes
msec = (int) mtime % S_PER_M; //find remain seconds
printf("Your ran %1.2f km (%1.2f miles) in %d min, %d sec.\n", distk, distm, min, sec);
printf("That pace corresponds to running a mile in %d min, ", mmin);
printf("%d sec.\n Your average speed was %1.2f mph.\n", msec, rate);

return 0;
}




using System;
using System.Windows.Forms;

public class MainClass : System.Windows.Forms.Form
{
public MainClass()
{
Console.WriteLine("Company: " + Application.CompanyName);
Console.WriteLine("App Name: " + Application.ProductName);
Console.WriteLine("I live here: " + Application.StartupPath);
}
[STAThread]
static void Main()
{
Application.Run(new MainClass());
}
}




Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface 'IStorable

'here's the new interface
Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'Document implements both interfaces
Public Class Document
Implements ICompressible, IStorable

'hold teh data for IStorable's Status property
Private myStatus As Integer = 0

'the Document constructor
Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'new

Public Sub Compress() Implements ICompressible.Compress
Console.WriteLine("Implementing Compress")
End Sub

Public Sub Decompress() Implements ICompressible.Decompress
Console.WriteLine("Implementing Decompress")
End Sub

Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set
End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub
End Class

Class Tester
Public Sub Run()
Dim doc As New Document("Test Document")
doc.Status = -1
doc.Read()
doc.Compress()
Console.WriteLine("Document Status: {0}", doc.Status)
End Sub 'Run

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

End Namespace




Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface 'IStorable

'the compressible interface is now the base for ICompressible2
Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'extend ICompressible to log the bytes saved
Interface ICompressible2
Inherits ICompressible
Sub LogSavedBytes()
End Interface 'ICompressible2


'Document implements both interfaces
Public Class Document
Implements ICompressible2, IStorable

Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'New

Public Sub LogSavedBytes() Implements ICompressible2.LogSavedBytes
Console.WriteLine("Implementing LogSavedBytes")
End Sub


Public Sub Decompress() Implements ICompressible2.Decompress
Console.WriteLine("Implementing decompress for ICompresible")
End Sub

Public Sub Compress() Implements ICompressible2.Compress
Console.WriteLine("Implementing compress for ICompressible")
End Sub


Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set

End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub

Private myStatus As Integer = 0

End Class

Class Tester
Public Sub Run()
Dim doc As New Document("Test Document")
If TypeOf doc Is IStorable Then
Dim isDoc As IStorable = doc
isDoc.Read()
Else
Console.WriteLine("Could not cast to IStorable")
End If

If TypeOf doc Is ICompressible2 Then
Dim ilDoc As ICompressible2 = doc
Console.Write("Calling both ICOmpressible And ")
Console.WriteLine("ICompressible2 methods...")
ilDoc.Compress()
ilDoc.LogSavedBytes()
Else
Console.WriteLine("Could not cast to ICompressible2")
End If
End Sub

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

End Class
End Namespace




Imports System
Imports System.Text

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_01

Public Shared Function ReverseString(ByVal str As String) As String

'Make sure we have a reversible string.
If str Is Nothing Or str.Length <= 1 Then
Return str
End If

'create a stringBuilder object with the required capacity.
Dim revStr As StringBuilder = New StringBuilder(str.Length)

'Convert the string to a character array so we can easily loop through it
Dim chars As Char() = str.ToCharArray()

'Loop backward through the soruce string one character ata time
'and append each characer to the StringBuilder
For count As Integer = chars.Length - 1 To 0 Step -1
revStr.Append(chars(count))
Next

Return revStr.ToString()

End Function

Public Shared Sub Main()
Console.WriteLine(ReverseString("Madam Im Adam"))

Console.WriteLine(ReverseString("The quick brown fox jumped over the lazy dog."))

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


End Class

End Namespace




Imports System
Imports System.IO
Imports System.Text.Encoding

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_02

Public Shared Sub Main()

'Create a file to hold the output.
Using output As New StreamWriter("C:\inetpub\output.txt")
'Create and Write a string containing the symbol for pi.
Dim srcString As String = String.Format("Area = {0}r^2", ChrW(&H3A0))
output.WriteLine("Source Text: " & srcString)

'write the UTF-15 encoded bytes of the source string.
Dim utf16String As Byte() = Unicode.GetBytes(srcString)
output.WriteLine("UTF-16 Bytes: {0}", BitConverter.ToString(utf16String))

'Convert the UTF-15 encoded source string to UTF-8 and ASCII
Dim utf8String As Byte() = UTF8.GetBytes(srcString)
Dim asciiString As Byte() = ASCII.GetBytes(srcString)

'write teh UTF-8 and ASCII encoded byte arrays.
output.WriteLine("UTF-8 Bytes: {0}", BitConverter.ToString(utf8String))
output.WriteLine("ASCII Bytes: {0}", BitConverter.ToString(asciiString))

'Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded string
'and write to the output file
output.WriteLine("UTF-8 Text: {0}", UTF8.GetString(utf8String))
output.WriteLine("ASCII Text: {0}", ASCII.GetString(asciiString))

End Using

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

End Sub
End Class
End Namespace





Imports System
Imports System.IO

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_03
Public Shared Function DecimalToByteArray(ByVal src As Decimal) As Byte()
'Create a MemoryStream as a buffer to holdthe binary data.
Using Stream As New MemoryStream
'Create a BinaryWriter to write binary data to the stream
Using writer As New BinaryWriter(Stream)
'write the decimal to the BinaryWriter/MemoryStream.
writer.Write(src)

'return the byte representation of the decimal.
Return Stream.ToArray
End Using
End Using

End Function

'create a decimal from a byte array.
Public Shared Function ByteArrayToDecimal(ByVal src As Byte()) As Decimal
'create a MemoryStream containing the byte array.
Using Stream As New MemoryStream(src)
'create a binaryReader to read the decimal from teh stream.
Using reader As New BinaryReader(Stream)
'read and return the decimal from teh BinaryReader/MemoryStream.
Return reader.ReadDecimal
End Using
End Using
End Function

Public Shared Sub Main()

Dim b As Byte() = Nothing

' Convert a boolean to a byte array and display.
b = BitConverter.GetBytes(True)
Console.WriteLine(BitConverter.ToString(b))

' Convert a byte array to a boolean and display
Console.WriteLine(BitConverter.ToBoolean(b, 0))

'convert an interger to a byte array and display
b = BitConverter.GetBytes(3678)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to integer and display
Console.WriteLine(BitConverter.ToInt32(b, 0))

'convert a decimal to a byte array and display
b = DecimalToByteArray(28599834554.563846696D)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a decimal and display
Console.WriteLine(ByteArrayToDecimal(b))

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

End Sub

End Class

End Namespace




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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//remove a substring from a string
string name = "Doe, John";
Console.WriteLine(name);
name = name.Remove(3, 1);
Console.WriteLine(name);

string name2 = "Johnson, Don";
Console.WriteLine(name2);
name2 = name2.Remove(7, 5);
Console.WriteLine(name2);

//if performance is critical, and particularly if the string removal operation occurs in a loop
//so that the operation is performed multiple times, you can instead use the Remove method of the
//stringbuilder object

StringBuilder str = new StringBuilder("1234abc5678", 12);
str.Remove(4, 3);
Console.WriteLine(str);

//to replace a delimiting character within a string, use the following code

string commaDelimitedString = "100,200,300,400,500";
Console.WriteLine(commaDelimitedString);
commaDelimitedString = commaDelimitedString.Replace(',', ':');
Console.WriteLine(commaDelimitedString);
commaDelimitedString = commaDelimitedString.Replace(':', '-');
Console.WriteLine(commaDelimitedString);

string theName = "Mary";
string theObject = "car";
string ID = "This is the property of .";
ID = ID.Replace("", theObject);
ID = ID.Replace("", theName);
Console.WriteLine(ID);


}
}
}

Wednesday, August 17, 2011

Wednesday 8.17.11

using System;
using System.IO;

public class MainClass
{
public static void Main()
{
FileInfo MyFile = new FileInfo(@"C:\inetpub\Test2.txt");
MyFile.Create();
}
}




using System;
using System.IO;

public class MainClass
{
public static int Main(string[] args)
{
FileInfo f = new FileInfo(@"C:\inetpub\test3.txt");
FileStream fs = f.Create();

Console.WriteLine("Creation: {0}", f.CreationTime);
Console.WriteLine("Full name: {0}", f.FullName);
Console.WriteLine("Full atts: {0}", f.Attributes.ToString());

fs.Close();
f.Delete();

return 0;
}
}


using System;
using System.IO;

public class MainClass
{
static void Main(string[] args)
{
FileInfo MyFile = new FileInfo(@"C:\inetpub\Testing3.txt");

MyFile.Delete();
}
}



using System;
using System.IO;

class MainClass
{

static void createFile()
{
FileInfo MyFile = new FileInfo(@"C:\inetpub\inputFile.txt");
MyFile.Create();
}

public static void Main(string[] args)
{

int i;
FileStream fin;
FileStream fout;



try
{
fin = new FileStream(@"C:\inetpub\inputFile.txt", FileMode.Open);
}
catch (FileNotFoundException exc)
{
Console.WriteLine(exc.Message + "\nInput File Not Found");
Console.WriteLine("Creating file now.");
createFile();
return;
}

try
{
fout = new FileStream(@"C:\inetpub\outputFile.txt", FileMode.Create);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + "\nError Opening Output File");
return;
}

try
{

do
{
i = fin.ReadByte();
if (i != -1)
{
fout.WriteByte((byte)i);
}
} while (i != -1);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + " File Error");
}

fin.Close();
fout.Close();
}
}



using System;
using System.IO;

class MainClass
{
public static void Main()
{
string[] aFiles = Directory.GetFiles(@"C:\inetpub\");

foreach (string s in aFiles)
{
Console.WriteLine(s);
}
}
}

OK, back to C. Classes start next week!


#include
int main(void)
{
int bph2o = 212;
int rv;

rv = printf("%d F is water's boiling point.\n", bph2o);
printf("The printf() function printed %d characters.\n", rv);
return 0;
}




#include
int main(void)
{
printf("Here's one way to print a ");
printf("long string.\n");
printf("Here's another way to print a \ long string.\n");
printf("Here's the newest way to print a "
"long string.\n");
return 0;
}




#include
int main(void)
{
unsigned width, precision;
int number = 256;
double weight = 242.5;

printf("What field width?\n");
scanf("%d", &width);
printf("The number is : %d:\n", width, number);
printf("Now enter a width and a precision:\n");
scanf("%d %d", &width, &precision);
printf("Width = %*.*f\n", width, precision, weight);
printf("Done!\n");

return 0;
}




#include
#define ADJUST 7.64
#define SCALE 0.325
int main(void)
{
double shoe, foot;

printf("Shoe size (men's) foot length\n");
shoe = 3.0;
while (shoe < 18.5)
{
foot = SCALE*shoe + ADJUST;
printf("%10.1f %15.2f inches\n", shoe, foot);
shoe = shoe + 1.0;
} //end while
printf("If the shoe fits, wear it.\n");

return 0;
}




#include
int main(void)
{
int num = 1;
while (num < 21)
{
printf("%4d %6d\n", num, num * num);
num = num + 1;
}
}




#include
#define SQUARES 64
#define CROP 1E15
int main(void)
{
double current, total;
int count = 1;

printf("square grains total ");
printf("fraction of \n");
printf(" added grains ");
printf("US total\n");
total = current = 1.0; //start with one grain
printf("%4d %13.2e %12.2e %12.2e\n", count, current, total, total/CROP);
while (count < SQUARES)
{
count = count + 1;
current = 2.0 * current;
total = total + current;
printf("%4d %13.2e %12.2e %12.2e\n", count, current, total, total/CROP);
}
printf("That's all.\n");

return 0;
}




#include
int main(void)
{
printf("integer division: 5/4 is %d \n", 5/4);
printf("integer division: 6/3 is %d \n", 6/3);
printf("integer division: 7/4 is %d \n", 7/4);
printf("floating division: 7./4. is %1.2f \n", 7./4.);
printf("mixed division: 7./4 is %1.2f \n", 7./4);

return 0;
}




#include
int main(void)
{
int n = 0;
size_t intsize;
intsize = sizeof (int);
printf("n = %d, n has %zd bytes; all ints have %zd bytes.\n", n, sizeof n, intsize);

return 0;
}




#include
#define SEC_PER_MIN 60
int main(void)
{
int sec, min, left;

printf("Convert seconds to minutes and seconds!\n");
printf("Enter the number of seconds (<=0 to quit:\n);
scanf("%d", &sec);
while (sec > 0)
{
min = sec / SEC_PER_MIN;
left = sec % SEC_PER_MIN;
printf("%d seconds is %d minutes, %d seconds.\n", sec, min, left);
printf("Enter next value (<=0 to quit:\n");
scanf("%d", &sec);
}
printf("Done!\n");
return 0;
}




#include
#define MAX 100
int main(void)
{
int count = MAX +1;
while(--count > 0) {
printf("%d bottles of beer on the wall, "
"%d bottles of beer!\n", count, count);
printf("Take one down and pass it around, \n");
printf("%d bottles of beer~\n\n", count - 1);
}

return 0;
}

Tuesday, August 16, 2011

Tuesday 8.16.11


using System;
using System.Data;
using System.Data.SqlClient;

namespace SetConnectionPoolingOptions
{
class Program
{

static void connection_StateChange(object sender, StateChangeEventArgs e)
{
Console.WriteLine("\tConnection.StateChange event occurred.");
Console.WriteLine("\tOriginalState = {0}", e.OriginalState.ToString());
Console.WriteLine("\tCurrentState = {0}", e.CurrentState.ToString());
}

static void Main(string[] args)
{
string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;";

SqlConnection connection = new SqlConnection();

//set up the event handler to detect connection state change
connection.StateChange += new StateChangeEventHandler(connection_StateChange);

//set the connection string with pooling options
connection.ConnectionString = sqlConnectString + "Connection Timeout=15;Connection Lifetime=0;" +
"Min Pool Size=0;Max Pool Size=100;Pooling=true;";

//output the connection string and open/close the connection
Console.WriteLine("Connection string = {0}", connection.ConnectionString);
Console.WriteLine("-> Open connection.");
Console.OpenStandardError();
Console.WriteLine("-> Close connection.");
connection.Close();

//Set the connection string with new pooling options
connection.ConnectionString = sqlConnectString + "Connection Timeout=30;Connection Lifetime=0;" + "Min Pool Size=0;Max Pool Size=200;Pooling=true;";

//output the connection string and open/close the conncetion
Console.WriteLine("\nConnection string = {0}", connection.ConnectionString);
Console.WriteLine("-> Open connection.");
connection.Open();
Console.WriteLine("-> Close connection.");
connection.Close();

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace DisplayConnectionPropertyDialog
{
public partial class Form1 : Form
{
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();

public Form1()
{
InitializeComponent();
propertyGrid1.SelectedObject = scsb;
}



private void Form1_Load(object sender, EventArgs e)
{

}

private void onPropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
connectString.Text = scsb.ConnectionString;
}

}
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace ConsoleApplication1
{
class Program
{
//makes the program thread safe for COM
//in a multi-threaded program several threads execute simultaneously
//in a shared address space
[STAThread]
static void Main(string[] args)
{
OpenFileDialog dlgOpen = new OpenFileDialog();

if (dlgOpen.ShowDialog() == DialogResult.OK)
{
string s = dlgOpen.FileName;
Console.WriteLine("Filename " + s);
Console.WriteLine("Created at " + File.GetCreationTime(s));
Console.WriteLine("Accessed at " + File.GetLastAccessTime(s));
}
}
}
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;


namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
OpenFileDialog dlgOpen = new OpenFileDialog();
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
FileInfo fi = new FileInfo(dlgOpen.FileName);
Console.WriteLine("Filename " + fi.FullName);
Console.WriteLine("Created at " + fi.CreationTime);
Console.WriteLine("Accessed at " + fi.LastAccessTime);
}
}
}
}




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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter(@"C:\inetpub\myfile.txt");
for (int i = 0; i < 5; i++)
{
writer.Write(i.ToString());
}
writer.Flush();
writer.Close();
foreach(string line in File.ReadAllLines(@"C:\inetpub\myfile.txt"))
{
Console.WriteLine(line);
}
}
}
}





using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

class MainClass
{
static void Main(string[] args)
{
string[] lines = new string[10];
for (int i = 0; i < 10; i++)
{
lines[i] = string.Format("This is line number {0}", i);
}

File.WriteAllLines(@"C:\inetpub\test.txt", lines);

foreach(string line in File.ReadAllLines(@"C:\inetpub\test.txt"))
{
Console.WriteLine(line);
}
}
}




#include
int main(void)
{
int age;
float assets;
char pet[30];

printf("Enter your age, assets, and favorite pet.\n");
scanf("%d %f", &age, &assets);
scanf("%s", pet);
printf("%d $%.2f %s\n", age, assets, pet);
return 0;
}

Monday, August 15, 2011

Monday 8.15.11


//uses the C preprocessor to define the symbolic constant DENSITY to represent the value 62.4
#include
#include
#define DENSITY 62.4
int main()
{
float weight, volume;
int size, letters;
char name[40]; //name is an array of 40 characters

printf("Hi! What's your first name?\n");
scanf("%s", name);
printf("%s, what's your weight in pounds?\n", name);
scanf("%f", &weight);
size = sizeof name;
letters = strlen(name);
volume = weight / DENSITY;
printf("Well, %s, your volume is %2.2f Cubic feet.\n", name, volume);
printf("Also, your first name has %d letters, \n", letters);
printf("and we have %d bytes to store it in.\n", size);
return 0;
}




#include
#include
#define PRAISE "What a super marvelous name!"
int main(void)
{
char name[40];

printf("What's your name?\n");
scanf("%s", name);
printf("Hello, %s. %s\n", name, PRAISE);
printf("Your name of %d letters occupies %d memory cells.\n", strlen(name), sizeof name);
printf("The phrase of praise has %d letters ", strlen(PRAISE));
printf("and occupies %d memory cells.\n", sizeof PRAISE);

return 0;
}




#include
#define PI 3.14159
int main(void)
{
float area, circum, radius;

printf("What is the radius of your pizza?\n");
scanf("%f", &radius);
area = PI * radius * radius;
circum = 2.0 * PI * radius;
printf("Your basic pizza parameters are as follows:\n");
printf("circumference = %1.2f, area = %1.2f\n", circum, area);
return 0;
}




#include
#include
#include
int main(void)
{
printf("Some number limits for this system:\n");
printf("Biggest int: %d\n", INT_MAX);
printf("Smallest long long: %lld\n", LLONG_MIN);
printf("One byte = %d bits on this system.\n", CHAR_BIT);
printf("Largest double: %e\n", DBL_MAX);
printf("Smallest normal float: %e\n", FLT_MIN);
printf("Float precision = %d digits\n", FLT_DIG);
printf("float epsilon = %e\n", FLT_EPSILON);

return 0;
}




//conversion specifiers
#include
#define PI 3.141593
int main(void)
{
int number = 5;
float espresso = 13.5;
int cost = 31000;

printf("The %d CEOs drank %f cups of espresso.\n", number, espresso);
printf("The value of pi is %f.\n", PI);
printf("Farewell! Thou are too dear for my possessing, \n");
printf("%c%d\n", '$', 2*cost);

return 0;
}




#include
#define PAGES 90
int main(void)
{
printf("*%d*\n", PAGES);
printf("*%2d*\n", PAGES);
printf("*%10d*\n", PAGES);
printf("*%-10d*\n", PAGES);

return 0;
}




#include
#define BLURB "Authentic Imitation!"
int main(void)
{
printf("/%2s/\n", BLURB);
printf("/%24s/\n", BLURB);
printf("/%24.5s/\n", BLURB);
printf("/%-24.5s/\n", BLURB);

return 0;
}





#include
#define PAGES 336
#define WORD 65618
int main(void)
{
short num = PAGES;
short mnum = -PAGES;

printf("num as short and unsigned short: %hd %hu\n", num, num);
printf("-num as short and unsigned short: %hd %hu\n", mnum, mnum);
printf("num as int and char: %d %c\n", num, num);
printf("WORDS as int, short, and char: %d %hd %c\n", WORD, WORD, WORD);

return 0;
}




#include
int main(void)
{
float n1 = 3.0;
double n2 = 3.0;
long n3 = 2000000000;
long n4 = 1234567890;

printf("%.1e %.1e %.1e %.1e\n", n1, n2, n3, n4);
printf("%1d %1d\n", n3, n4);
printf("%1d %1d %1d %1d\n", n1, n2, n3, n4);

return 0;
}
//using an %e specifier does not convert an integer to a floating-point number





using System;
using System.Data.SqlClient;

namespace ChangeConnectionDatabase
{
class Program
{
static void Main(string[] args)
{
string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;";

using (SqlConnection connection = new SqlConnection(sqlConnectString))
{
Console.WriteLine("ConnectionString = {0}\n", connection.ConnectionString);
//Open the connection
connection.Open();
Console.WriteLine("=> Connection opened.\n");

Console.WriteLine("Connection.State = {0}", connection.State);
Console.WriteLine("Database = {0}\n", connection.Database);

//change the databse
connection.ChangeDatabase("Northwind");
Console.WriteLine("Database changed to Northwind.\n");

Console.WriteLine("Connection.State = {0}", connection.State);
Console.WriteLine("Database = {0}\n", connection.Database);

//close the connection
connection.Close();
Console.WriteLine("=>Connection closed.\n");
Console.WriteLine("Connection.State = {0}", connection.State);
Console.WriteLine("Database = {0}", connection.Database);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

Sunday, August 14, 2011

Sunday 8.14.11


<?php
$textblock = 'see spot run, run spot run. See spot roll, roll spot roll!';
echo wordwrap($textblock, 20, "
");
?>




<?php
//define a maximum length for the data field.
define("MAXLENGTH", 10);
if(strlen('Hello World!') > MAXLENGTH){
echo "the field you have entered can be only " . MAXLENGTH . " characters in length.";
} else
{
echo "length is correct";
//insert the field into the database
}
?>




<?php
$stringone = 'something';
$stringtwo = 'something';
if($stringone == $stringtwo){
echo "These two strings are the same!";
}
?>





<?php
if(strncmp("something", "some", 4) == 0){
echo "A correct match!";
}

if(strncasecmp("SOMEthing", "some", 4) == 0){
echo "A correct match!";
}
?>