Monday, September 12, 2011

Monday 9.12.11

using System;
using System.Data;

namespace CreateAutoIncrementColumn
{
class Program
{
static void Main(string[] args)
{
//create a table and add two columns
DataTable dt = new DataTable();
DataColumn pkCol = dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Field1", typeof(string)).MaxLength = 50;


//make the Id column the primary key
dt.PrimaryKey = new DataColumn[] {dt.Columns["Id"]};

//make the primary key autoincrementing starting at 100
// and incrementing by 10 with each new record added
pkCol.AutoIncrement = true;
pkCol.AutoIncrementSeed = 100;
pkCol.AutoIncrementStep = 10;

//add five rows to the table
for (int i = 1; i <= 5; i++)
dt.Rows.Add(new object[] {null, "Value " + i});
//output the table rows to the console
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("Id = {0}\tField1 = {1}", row["Id"], row["Field1"]);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}


using System;
using System.Data;

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

//create the parent table and add to the DataSet
DataTable dt1 = new DataTable("Table-1");
dt1.Columns.Add("Id1", typeof(int));
dt1.Columns.Add("Field1", typeof(string)).MaxLength = 50;
ds.Tables.Add(dt1);

//create the child table and add to the DataSet
DataTable dt2 = new DataTable("Table-2");
dt2.Columns.Add("Id2", typeof(int));
dt2.Columns.Add("Id1", typeof(int));
dt2.Columns.Add("Field2", typeof(string)).MaxLength = 50;
ds.Tables.Add(dt2);

//create the foreign key constraint and add to the child table
ForeignKeyConstraint fk = new ForeignKeyConstraint("ForeignKey", dt1.Columns["Id1"], dt2.Columns["Id1"]);
dt2.Constraints.Add(fk);

try
{
AddParentRecord(dt1, 1, "Value 1.1");
AddParentRecord(dt1, 2, "Value 1.2");

AddChildRecord(dt2, 10, 1, "Value 2.10");
AddChildRecord(dt2, 11, 2, "Value 2.11");
AddChildRecord(dt2, 12, 3, "Value 2.12");

}
catch (Exception ex)
{
Console.WriteLine("Error: {0}\n", ex.Message);
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}

private static void AddParentRecord(DataTable dt, int id1, string field1)
{
Console.WriteLine("Adding parent record: {0}, {1}", id1, field1);
dt.Rows.Add(new object[] { id1, field1 });
Console.WriteLine("Done.\n");
}

private static void AddChildRecord(DataTable dt, int id2, int id1, string field2)
{
Console.WriteLine("Add child record: {0}, {1}, {2}", id2, id1, field2);
dt.Rows.Add(new object[] { id2, id1, field2 });
Console.WriteLine("Done.\n");
}
}
}



using System;
using System.Data;

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

//create the parent table and add to the DataSet
DataTable dt1 = new DataTable("Table-1");
dt1.Columns.Add("Id1", typeof(int));
dt1.Columns.Add("Id2", typeof(int));
dt1.Columns.Add("Field1", typeof(string)).MaxLength = 50;
ds.Tables.Add(dt1);

//creat eth child table and add to the dataset
DataTable dt2 = new DataTable("Table-2");
dt2.Columns.Add("Id3", typeof(int));
dt2.Columns.Add("Id1", typeof(int));
dt2.Columns.Add("Id2", typeof(int));
dt2.Columns.Add("Field2", typeof(string)).MaxLength = 50;
ds.Tables.Add(dt2);

//create the data relation and add to the DataSet
DataRelation dr = new DataRelation("DataRelation",
new DataColumn[] { dt1.Columns["Id1"], dt1.Columns["Id2"] },
new DataColumn[] { dt2.Columns["Id1"], dt2.Columns["Id2"] },
true);
ds.Relations.Add(dr);

try
{
AddParentRecord(dt1, 1, 10, "Value 1.1");
AddParentRecord(dt1, 2, 20, "Value 1.2");

AddChildRecord(dt2, 100, 1, 10, "Value 2.100");
AddChildRecord(dt2, 101, 2, 20, "Value 2.101");
AddChildRecord(dt2, 102, 3, 30, "Value 2.102");
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}\n", ex.Message);
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}

private static void AddParentRecord(DataTable dt, int id1, int id2, string field1)
{
Console.WriteLine("Adding parent record: {0}, {1}. {2}", id1, id2, field1);
dt.Rows.Add(new object[] { id1, id2, field1 });
Console.WriteLine("Done.\n");
}

public static void AddChildRecord(DataTable dt, int id3, int id1, int id2, string field2)
{
Console.WriteLine("Add child record: {0}, {1}, {2}, {3}", id3, id1, id2, field2);
dt.Rows.Add(new object[] { id3, id1, id2, field2 });
Console.WriteLine("Done.\n");
}
}
}


Public Class Form1

Private Function RateArray(ByVal elementCount As Integer) As Decimal()
Dim rates(elementCount - 1) As Decimal
For i As Integer = 0 To rates.Length - 1
rates(i) = (i + 1) / 100D
Next
Return rates 'returns array
End Function

Private Sub ConvertToCentimeters(ByRef measurements() As Double)
For i As Integer = 0 To measurements.Length - 1
measurements(i) *= 2.54
Next
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim rates() As Decimal = Me.RateArray(4)
txtDisplay.Multiline = True
txtDisplay.Height = 100

For Each r As String In rates
txtDisplay.Text &= r & vbCrLf
Next

Dim measurements() As Double = {1, 2, 3}
Me.ConvertToCentimeters(measurements)

End Sub
End Class


Dim numbers As New List(Of Integer)


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
numbers.Add(3)
numbers.Add(70)
Dim sum As Integer = 0
Dim number As Integer
For i As Integer = 0 To numbers.Count - 1
number = numbers(i) ' no cast is required
sum += number
Next
MsgBox(sum)
End Sub


Dim titles As New List(Of String)
Dim prices As New List(Of Decimal)
Dim lastNames As New List(Of String)(3)



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lastNames.Add("Boehm")
lastNames.Add("Prince")
lastNames.Add("Murach")
lastNames.Add("Taylor")
lastNames.Add("Vasquez")
lastNames.Add("Steelman")
lastNames.Add("Slivkoff")
For Each lname As String In lastNames
MsgBox(lname)
Next
End Sub


Imports System
Imports System.IO

Namespace Apress.VisualBasicRecipes.Chapter05
Public Class Recipe05_11
Public Shared Sub Main()
Dim args(1) As String
args(0) = "C:\inetpub\"
args(1) = "*.txt"

If args.Length = 2 Then
Dim dir As New DirectoryInfo(args(0))
Dim files As FileInfo() = dir.GetFiles(args(1))
'Display the name of all the files
For Each File As FileInfo In files
Console.Write("Name: " & File.Name + " ")
Console.WriteLine("Size: " & File.Length.ToString)
Next

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

Else
Console.WriteLine("USAGE: Recipe05-11 [directory]" & "[filterExpression]")
End If
End Sub
End Class
End Namespace


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

Namespace Apress.VisualBasicRecipes.Chapter05

Public Class Recipe05_12
Public Shared Sub Main()
Dim args(1) As String
args(0) = "C:\inetpub\test.txt"
args(1) = "C:\inetpub\Test2.txt"

If args.Length = 2 Then
Console.WriteLine("comparing {0} and {1}", args(0), args(1))
'creating the hashing object
Using hashAlg As HashAlgorithm = HashAlgorithm.Create
Using fsA As New FileStream(args(0), FileMode.Open), fsB As New FileStream(args(1), FileMode.Open)
'Calculate the has for the files
Dim hashBytesA As Byte() = hashAlg.ComputeHash(fsA)
Dim hashBytesB As Byte() = hashAlg.ComputeHash(fsB)

'compare the hashes
If BitConverter.ToString(hashBytesA) = BitConverter.ToString(hashBytesB) Then
Console.WriteLine("Files match.")
Else
Console.WriteLine("No match.")
End If
End Using

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

Friday, September 9, 2011

Friday 9.9.11

Private Sub VendorsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VendorsBindingNavigatorSaveItem.Click
Me.Validate()
Try
Me.VendorsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.PayablesDataSet)
Catch ex As DBConcurrencyException
MessageBox.Show("A concurrency error occurred. " & "The row was not updated.", "Concurrency Exception")
Me.VendorsTableAdapter.Fill(Me.PayablesDataSet.Vendors)
Catch ex As DataException
MessageBox.Show(ex.Message, ex.GetType.ToString)
VendorsBindingSource.CancelEdit()
Catch ex As SqlException
MessageBox.Show("SQL server error # " & ex.Number & ": " & ex.Message, ex.GetType.ToString)
End Try
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PayablesDataSet.Vendors' table. You can move, or remove it, as needed.
Try
Me.VendorsTableAdapter.Fill(Me.PayablesDataSet.Vendors)
Catch ex As SqlException
MessageBox.Show("Sql server error # " & ex.Number & ": " & ex.Message, ex.GetType.ToString)

End Try

End Sub

Thursday, September 8, 2011

9.8.11

Dim quote As String = "The important thnig is not to " & "stop questioning. --Albert Einstein"

'---left(quote, 3)
MsgBox(quote.Substring(0, 3))

'-----mid(quote,5,9)
MsgBox(quote.Substring(4, 9))

'-----right(quote, 8)
MsgBox(quote.Substring(quote.Length - 8))


Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim oldString As String = "The important thing is not to stop questioning. --Albert Einstein"
Dim newString As String = ""
Dim displayString As String = ""
Dim counter As Integer = 1


newString = oldString.ToUpper
addToString(newString, displayString, counter)

newString = UCase(oldString)

'to lower case
newString = oldString.ToLower()
addToString(newString, displayString, counter)
newString = LCase(oldString)

newString = StrConv(oldString, VbStrConv.ProperCase)

addToString(newString, displayString, counter)

newString = MixedCase(oldString)

addToString(newString, displayString, counter)

'---display results
MsgBox(displayString)

End Sub

Public Function MixedCase(ByVal origText As String) As String
'---convert a string to "proper" case
Dim counter As Integer
Dim textParts() As String = Split(origText, " ")

For counter = 0 To textParts.Length - 1
If (textParts(counter).Length > 0) Then
textParts(counter) = UCase(Microsoft.VisualBasic.Left(textParts(counter), 1)) & LCase(Mid(textParts(counter), 2))
End If
Next

Return Join(textParts, " ")
End Function

Private Sub addToString(ByVal addElem, ByRef addToElem, ByRef counter)
addToElem &= "[" & counter & "] " & addElem & vbCrLf & vbCrLf
counter = counter + 1
End Sub
End Class


#include
#define RATE1 0.12589
#define RATE2 0.17901
#define RATE3 0.20971
#define BREAK1 360.0
#define BREAK2 680.0
#define BASE1 (RATE1 * BREAK1)
#define BASE2 (BASE1 + (RATE2 * (BREAK2 - BREAK1)))

int main(void)
{
double kwh;
double bill;

printf("Please enter the kwh used.\n");
scanf("%lf", &kwh);
if (kwh <= BREAK1)
bill = RATE1 * kwh;
else if (kwh <= BREAK2)
bill = BASE1 + (RATE2 * (kwh - BREAK1));
else
bill = BASE2 + (RATE3 * (kwh - BREAK2));
printf("The charge for %.1f is $%1.2f.\n", kwh, bill);
return 0;

}


#include
#include

int main(void)
{
unsigned long num;
unsigned long div;
bool isPrime;

printf("Please enter an integer for analysis;");
printf("Enter q to quit.\n");
while (scanf("%lu", &num) == 1)
{
for (div = 2, isPrime = true; (div * div) <= num; div++)
{
if (num % div == 0)
{
if ((div * div) != num)
{
printf("%lu is divisible by %lu and %lu.\n", num, div, num / div);
} else {
printf("%lu is divisible by %lu.\n", num, div);
}

isPrime = false; //number is not prime
}
}
if (isPrime)
{
printf("%lu is prime.\n", num);
}
printf("Please enter another # for analysis;");
printf("Enter q to quit.\n");
}
printf("Bye.\n");

return 0;
}


#include
#include
#include
#define STOP '|'

int main(void)
{
char c; //read in character
char prev;//previous character read
long n_chars = 0L; //number of characters
int n_lines = 0; //number of lines
int n_words = 0; //number of words
int p_lines = 0; //number of partial lines
bool inword = false; // true if c is in a word

printf("Enter text to be analyzed (|to terminate):\n");
prev = '\n'; //used to identify complete lines
while ((c = getchar()) != STOP)
{
n_chars++;
if (c == '\n')
{
n_lines++; //count lines
}
if (!isspace(c) && !inword)
{
inword = true;
n_words++;
}
if (isspace(c) && inword)
{
inword = false; //reached end of word
}
prev = c;
}

if (prev != '\n')
{
p_lines = 1;
}
//%ld used for long
printf("characters = %ld, words = %d, lines =%d,", n_chars, n_words, n_lines);
printf("partial lines = %d\n", p_lines);

return 0;

}


#include
#define COVERAGE 200
//because the program is using type int, the division is truncated. that is, 215/200 becomes 1
int main(void)
{
int sq_feet;
int cans;

printf("Enter number of square feet to be painted:\n");
while (scanf("%d", &sq_feet) == 1)
{
cans = sq_feet / COVERAGE;
cans += ((sq_feet % COVERAGE == 0)) ? 0 : 1;
printf("You need %d %s of paint.\n", cans, cans == 1 ? "can" : "cans");
printf("Enter next value (q to quit):\n");
}

return 0;
}

Wednesday, September 7, 2011

Wednesday 9.7.11

Imports System
Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Namespace Apress.VisualBasicRecipes.Chapter05
Public Class Recipe05_09
Public Shared Sub Main()

'create a sample log file
Using w As StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("C:\inetpub\SampleLog.txt", False, System.Text.Encoding.UTF8)
'write sample log records to the file the parser will skip blank lines. also the TextFieldParser can be configured to
'ignore lines that are comments.
w.WriteLine("# In this sample log file, coments start with a # character.")
w.WriteLine("# The parser, when configured correclty, will ignore these lines.")
w.WriteLine("")
w.WriteLine("{0}, INFO, ""{1} """, DateTime.Now, "Some informational text.")
w.WriteLine("{0}, WARN, ""{1} """, DateTime.Now, "Some warning message.")
w.WriteLine("{0}, ERR!, ""{1} """, DateTime.Now, "[ERROR] Some exception has occurred.")
w.WriteLine("{0}, INFO, ""{1} """, DateTime.Now, "More informational text.")
w.WriteLine("{0}, ERR!, ""{1} """, DateTime.Now, "[ERROR] Some exception has occurred.")
End Using

Console.WriteLine("Press enter to read and parse the information.")
Console.ReadLine()

'Open the file in and parse the data into a TextFieldParser object
Using logFile As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser("C:\inetpub\SampleLog.txt")

Console.WriteLine("Parsing the text file")
Console.WriteLine(Environment.NewLine)

'write header informaton to the console
Console.WriteLine("{0, -29} {1} {2}", "Date/Time in RFC1123", "Type", "Message")

'Configure the parser. For this recipe, make sure HasFieldsEncolsedInQuotes is True.
logFile.TextFieldType = FieldType.Delimited
logFile.CommentTokens = New String() {"#"}
logFile.Delimiters = New String() {","}
logFile.HasFieldsEnclosedInQuotes = True

Dim currentRecord As String()

'loop through the file until we reach the end.
Do While Not logFile.EndOfData
Try
'Parse all the fields into the currentRow
'array This method automatically moves
'the file pointer to the next row.
currentRecord = logFile.ReadFields

'write the parsed record to the console.
Console.WriteLine("{0:r} {1} {2}", DateTime.Parse(currentRecord(0)), currentRecord(1), currentRecord(2))
Catch ex As MalformedLineException
'The MalformedLineException is thrown by the
'TextFieldParser anytime a line cannot be parsed.
Console.WriteLine("An exception occurred attempting to parse this row: ", ex.Message)
End Try
Loop
End Using

Console.WriteLine(Environment.NewLine)
Console.ReadLine()
End Sub

End Class
End Namespace


Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class EventsDemo : Inherits System.Windows.Forms.Form
Private btn As Button

Public Sub New()
btn = New Button()
btn.Location = New Point(50, 50)
btn.Text = "Test"

Controls.Add(btn)
AddHandler btn.Click, AddressOf btn_Click

End Sub

Public Shared Sub Main()
Application.Run(New EventsDemo())
End Sub

Private Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("btn_Click method ", "Events Demonstration")
End Sub
End Class


Imports System.Threading

Module Module1
Class MyEventArgs
Inherits System.EventArgs

Public Message As String
Public Time As DateTime

Public Sub New(ByVal s As String, ByVal dt As DateTime)
MyBase.New()
Message = s
Time = dt
End Sub
End Class

Class MyMonitor
Public Event EventStart(ByVal e As Object, ByVal args As MyEventArgs)
Public Sub GenerateEvent()
Dim Args As New MyEventArgs("Hacker, Hacker", Now())
RaiseEvent EventStart(Me, Args)
End Sub
End Class

Dim WithEvents HackerAlarm As New MyMonitor()
Dim attackNum As Integer = 1

Sub Attack(ByVal o As Object, ByVal args As MyEventArgs) Handles HackerAlarm.EventStart
Console.WriteLine("Hack attack in progress")
Console.WriteLine(args.Message)
Console.WriteLine(args.Time)
Console.WriteLine("Attack number {0}", attackNum)
attackNum = attackNum + 1

End Sub

Sub Main()
Dim i As Integer

Do While i < 10
HackerAlarm.GenerateEvent()
i += 1
Thread.Sleep(1100)
Loop


End Sub

End Module


Imports System
Imports System.Net
Imports System.IO
Imports System.Environment

Module GetURL
Sub Main()
Dim sOutput As String
Dim sURL As String = "http://www.java2s.com"
Try
Dim objNewRequest As WebRequest = HttpWebRequest.Create(sURL)
Dim objResponse As WebResponse = objNewRequest.GetResponse
Dim objStream As New StreamReader(objResponse.GetResponseStream())
sOutput = objStream.ReadToEnd()

Catch eUFE As UriFormatException
sOutput = "Error in URL Format: [" & sURL & "]" & NewLine() & eUFE.Message
Catch ex As Exception
sOutput = ex.ToString
Finally
Console.Write(sOutput)
End Try
End Sub
End Module


Module Tester
Sub Main()
Dim i As Integer
Dim array As Integer() 'declare array variable
array = New Integer(9) {}

Console.WriteLine("Subscript " & vbTab & "Value")

For i = 0 To array.GetUpperBound(0)
Console.WriteLine(i & vbTab & vbTab & array(i))
Next

Console.WriteLine("The array contains " & array.Length & " elements.")
End Sub
End Module

Tuesday, September 6, 2011

Tuesday 9.2.11

Public Shared Sub Main()

Dim info As FileVersionInfo = FileVersionInfo.GetVersionInfo("C:\Program Files (x86)\FileZilla FTP Client\filezilla.exe")

'Display Version information
Console.WriteLine("Checking File: " & info.FileName)
Console.WriteLine("Product Name: " & info.ProductName)
Console.WriteLine("Product Versions: " & info.ProductVersion)
Console.WriteLine("Company Name: " & info.CompanyName)
Console.WriteLine("File Version: " & info.FileVersion)
Console.WriteLine("File Description: " & info.FileDescription)
Console.WriteLine("Original Filename: " & info.OriginalFilename)
Console.WriteLine("Legal Copyright: " & info.LegalCopyright)
Console.WriteLine("InternalName: " & info.InternalName)
Console.WriteLine("IsDebug: " & info.IsDebug)
Console.WriteLine("IsPatched: " & info.IsPatched)
Console.WriteLine("IsPreRelease: " & info.IsPreRelease)
Console.WriteLine("IsPrivateBuild: " & info.IsPrivateBuild)
Console.WriteLine("IsSpecialBuild: " & info.IsSpecialBuild)


End Sub


Private Sub Fill(ByVal dirNode As TreeNode)
Dim dir As New DirectoryInfo(dirNode.FullPath)

'an exception could be thrown n this code if you don't
' have sufficient security permissions for a file or directory
'you can catch and then ignore this exception
For Each dirItem As DirectoryInfo In dir.GetDirectories
'add a node for the directory
Dim newNode As New TreeNode(dirItem.Name)
dirNode.Nodes.Add(newNode)
newNode.Nodes.Add("*")
Next
End Sub

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

'set the first node
Dim rootNode As New TreeNode("C:\")
treeDirectory.Nodes.Add(rootNode)

'fill the first level and expand it
Fill(rootNode)
treeDirectory.Nodes(0).Expand()
End Sub

Private Sub treeDirectory_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles treeDirectory.BeforeExpand
'if a dummy node is found, remove it and read teh real directory list
If e.Node.Nodes(0).Text = "*" Then
e.Node.Nodes.Clear()
Fill(e.Node)
End If
End Sub


Public Class Recipe05_07
Public Shared Sub Main()

'create a new file
Using fs As New FileStream("C:\inetpub\test4.txt", FileMode.Create)
'create a writer and specifiy the encoding the
'defaut (utf-8) supports special unicode characters,
'but encodes all standard characters in the same way as ASCII encoding
Using w As New StreamWriter(fs, Encoding.UTF8)
'write a decimal, string, special Unicode character and char
w.WriteLine(CDec(124.23))
w.WriteLine("Test string")
w.WriteLine("!")
End Using
End Using

Console.WriteLine("Press enter to read the information.")
Console.ReadLine()

'Open the file in read-only mode
Using fs As New FileStream("C:\inetpub\test4.txt", FileMode.Open)
Using r As New StreamReader(fs, Encoding.UTF8)
'read the data and convert it to the appropriate data type
Console.WriteLine(Decimal.Parse(r.ReadLine))
Console.WriteLine(r.ReadLine)
Console.WriteLine(Char.Parse(r.ReadLine))

End Using
End Using

'wait to continue
Console.WriteLine(Environment.NewLine)


End Sub
End Class


#include
char line[100];
int total;
int item;
int minus_items;

int main()
{
total = 0;
minus_items = 0;

while(1){
printf("Enter # to add\n");
printf(" or 0 to stop:");

fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &item);

if(item == 0)
{
break;
}

if(item<0)
{
++minus_items;
continue;
//the continue statement is very similar to the break statement
//except that instead of terminating the loop, continue starts reexecuting the body of the loop
//from the beginning
}
total += item;
printf("Total: %d\n", total);
}

printf("Final total %d\n", total);
printf("with %d negative items omitted\n", minus_items);

return 0;
}

Monday, September 5, 2011

Monday 9.6.11

#include
char line[100]; //input link from console
int value; //a value to double

int main()
{
printf("Enter a value: ");

fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &value);

printf("Twice %d is %d\n", value, value*2);
return(0);
}


#include
char line[50];
int radius = 0;
float pi = 3.14;
float fourThree = 4 / 3;

float volume = 0;

//find out the volume of a sphere given the radius
int main()
{
printf("Enter the radius: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &radius);

// 4/3(pi)(r^3)
volume = radius*radius*radius*pi*fourThree;
printf("The volume is %f", volume);
return(0);
}


#include
int old_number;
int current_number;
int next_number;

int main()
{
//start things out
old_number = 1;
current_number = 1;

printf("1\n"); //print first number

while(current_number < 500)
{
printf("%d\n", current_number);
next_number = current_number + old_number;

old_number = current_number;
current_number = next_number;
}
return(0);

}


#include
char line[100];
int total;
int item;

int main()
{
total = 0;
while (1) {
printf("Enter # to add to \n");
printf(" or 0 to stop: ");

fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &item);

if (item == 0)
{
break;
}

total += item;
printf("Total: %d\n", total);
}
printf("Final total %d\n", total);
return (0);
}

Friday, September 2, 2011

Friday 9.2.11

Option Strict On
Imports System

Namespace JaggedArray
Public Class Tester
Public Sub Run()
Const rowsUB As Integer = 3
Const rowZero As Integer = 5
Const rowOne As Integer = 2
Const rowTwo As Integer = 3
Const rowThree As Integer = 5

Dim i As Integer
'declare the jagged array as 4 rows high
Dim jaggedArray(rowsUB)() As Integer
'declare the rows of various lengths
ReDim jaggedArray(0)(rowZero)
ReDim jaggedArray(1)(rowOne)
ReDim jaggedArray(2)(rowTwo)
ReDim jaggedArray(3)(rowThree)

'fill some (but not all) elements of the rows
jaggedArray(0)(3) = 15
jaggedArray(1)(1) = 12
jaggedArray(2)(1) = 9
jaggedArray(2)(2) = 99
jaggedArray(3)(0) = 10
jaggedArray(3)(1) = 11
jaggedArray(3)(2) = 12
jaggedArray(3)(3) = 13
jaggedArray(3)(4) = 14

For i = 0 To rowZero
Console.WriteLine("jaggedArray(0)({0}) = {1}", i, jaggedArray(0)(i))
Next

For i = 0 To rowOne
Console.WriteLine("jaggedArray(1)({0}) = {1}", i, jaggedArray(1)(i))
Next

For i = 0 To rowTwo
Console.WriteLine("jaggedArray(2)({0}) = {1}", i, jaggedArray(2)(i))
Next

For i = 0 To rowThree
Console.WriteLine("jaggedArray(3)({0}) = {1}", i, jaggedArray(3)(i))
Next
End Sub

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

End Class
End Namespace


Option Strict On
Imports System
Namespace ReverseAndSort
Class Tester

Public Shared Sub DisplayArray(ByVal theArray() As Object)

Dim obj As Object
For Each obj In theArray
Console.WriteLine("Value : {0}", obj)
Next obj

Console.WriteLine(ControlChars.Lf)

End Sub 'DisplayArray

Public Sub Run()
Dim myArray As [String]() = {"Who", "is", "John", "Galt"}

Console.WriteLine("Display myArray...")
DisplayArray(myArray)

Console.WriteLine("Reverse and display myArray...")
Array.Reverse(myArray)
DisplayArray(myArray)

Dim myOtherArray As [String]() = _
{"We", "Hold", "These", "Truths", "To", "Be", "Self", "Evident"}

Console.WriteLine("Display myOtherArray...")
DisplayArray(myOtherArray)
Console.WriteLine("Sort and display myOtherArray...")
Array.Sort(myOtherArray)
DisplayArray(myOtherArray)

End Sub 'run

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

End Class 'Tester
End Namespace 'Reverse and sort


Option Strict On
Imports System

Namespace Indexers
'a simplified ListBox control
Public Class ListBoxTest
Private strings(255) As String
Private ctr As Integer = 0
'initialize the list box with strings
'because you cannot nkow how many strings will be added
'you use the keyword ParamArray
Public Sub New(ByVal ParamArray initialStrings() As String)
Dim s As String
'copy the strings passed in to the constructor
For Each s In initialStrings
strings(ctr) = s
ctr += 1
Next
End Sub

'add a single string to the end of the list box
Public Sub Add(ByVal theString As String)
If ctr >= strings.Length Then
'handle bad index
Else
strings(ctr) = theString
ctr += 1
End If
End Sub


'allow array-like access
Default Public Property Item(ByVal index As Integer) As String
Get
If index < 0 Or index >= strings.Length Then
'handle bad index
Else
Return strings(index)
End If
End Get

Set(ByVal value As String)
If index >= ctr Then
'handle error
Else
strings(index) = value
End If
End Set
End Property

'publish how many strings you hold
Public Function Count() As Integer
Return ctr
End Function
End Class

Public Class Tester
Public Sub Run()
'create a new list box and initialize
Dim lbt As New ListBoxTest("Hello", "World")
Dim i As Integer

Console.WriteLine("After creation...")
For i = 0 To lbt.Count - 1
Console.WriteLine("lbt({0}): {1}", i, lbt(i))
Next

lbt.Add("who")
lbt.Add("is")
lbt.Add("john")
lbt.Add("galt")

Console.WriteLine("After adding strings")

For i = 0 To lbt.Count - 1
Console.WriteLine("lbt({0}): {1}", i, lbt(i))
Next

'test the access

Dim subst As String = "Universe"
lbt(1) = subst

'access all the strings
Console.WriteLine("After editing strings...")
For i = 0 To lbt.Count - 1
Console.WriteLine("lbt({0}): {1}", i, lbt(i))
Next
End Sub

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


using System;
using System.Data;

namespace CreateUniqueConstraint
{
class Program
{
static void Main(string[] args)
{
//create a table
DataTable dt = new DataTable("Table-1");
//add two columns
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Field1", typeof(string)).MaxLength = 50;
//create a unique constraint on Field1
UniqueConstraint uc1 = new UniqueConstraint("UniqueConstraint", dt.Columns["Field1"]);
//add the constraints to the table
dt.Constraints.Add(uc1);
//output the properties of the table constraint added
OutputConstraintProperties(dt);

//verify the unique constraint by adding rows
try
{
AddRow(dt, 1, "Value 1");
AddRow(dt, 2, "Value 2");
AddRow(dt, 3, "Value 2");
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}

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

private static void OutputConstraintProperties(DataTable dt)
{
Console.WriteLine("DataTable {0} => Constraint Properties: ", dt.TableName);
Console.WriteLine("\tName = ", dt.Constraints[0].ConstraintName);
Console.WriteLine("\tIsPrimaryKey = {0}", ((UniqueConstraint)dt.Constraints[0]).IsPrimaryKey);
Console.WriteLine("\tColumns: ");
foreach (DataColumn col in ((UniqueConstraint)dt.Constraints[0]).Columns)
{
Console.WriteLine("\t\t{0}", col.ColumnName);
}
}

private static void AddRow(DataTable dt, int id, string field1)
{
Console.WriteLine("\nAdding row: {0}, {1}", id, field1);
dt.Rows.Add(new object[] { id, field1 });
Console.WriteLine("Row added.");
}
}
}