Friday, August 12, 2011

Friday 8/12/11

//print2.c-more printf() properties
#include
int main(void)
{
unsigned int un = 300000000;
short end = 200;
long big = 65537;
long long verybig = 12345679008643;

printf("un = %u and not %d\n", un, un);
printf("end = %hd and %d\n", end, end);
printf("big = %ld and not %hd\n", big, big);
printf("verybig = %lld and not %ld\n", verybig, verybig);

return 0;
}
//using wrong specification can produce unexpected results
//the unsigned value 3000000000 and the signed value -129496296 have exactly the same internal representation in memory on our system


//displays code number for a character
#include
int main(void)
{
char ch;
printf("Please enter a cahracter.\n");
int i = 0;
while(i<5)
{
//you need to put a space in front of %c in order to keep the computer from interpreting the carriage return as input
scanf(" %c", &ch); //user inputs character
printf("The code for %c is %d. \n", ch, ch);
i = i + 1;
}
return 0;
}



//altnames.c portable names for integer types
#include
#include //supports portable types

int main(void)
{
int16_t me16;

me16 = 4593;
printf("First, assume int16_t is short: ");
printf("me16 = %hd\n", me16);
printf("Next, let's not make any assumptions.\n");
printf("Instead, use a \"macro\" from inttypes.h: ");
printf("me16 = %" PRId16 "\n", me16);

return 0;
}


//displays float value in two ways

#include
int main(void)
{
float aboat = 32000.0;
double abet = 2.14e9;
long double dip = 5.32e-5;

printf("%f can be written %e\n", aboat, aboat);
printf("%f can be written %e\n", abet, abet);
printf("%f can be written %e\n", dip, dip);

return 0;
}



//uses escape characters
#include
int main(void)
{
float salary;
printf("\aEnter your desired monthly salary:");
// \b is the backspace character
printf(" $______\b\b\b\b\b\b");
scanf(" %f", &salary);
printf("\n\t$%.2f a month is $%.2f a year.", salary, salary * 12.0);
printf("\rGee!\n");
return 0;
}



#include
int count = 0;
void test1(void){
printf("\ntest1 count = %d ", ++count);
}

void test2(void){
static int count;
printf("\ntest2 count = %d ", ++count);
}

int main(void)
{
int count = 0;
for( ; count < 5; count++)
{
test1();
test2();
}
}


#include
int i = 0;
int main()
{
int i;
//void f1(void);
i = 0;
printf("value of i in main %d\n", i);
f1();
printf("value of i after call %d\n", i);
}

int f1(void)
{
int i = 0;
i = 50;
printf("value of i in call %d\n", i);
}



#include
int g = 10;

int main()
{
f1();
printf(" after first call \n");
f1();
printf(" after second call \n");
f1();
printf(" after third call \n");
}

int f1(void)
{
static int k = 0;
int j = 10;
printf("value of k %d j %d", k, j);
k = k + 10;

return 0;
}



using System;
using System.Collections;
using System.Collections.Generic;

namespace program
{
static class CharStrExtMethods
{
public static int[] FindAll(this string matchStr, string searchedStr, int startPos)
{
int foundPos = -1; // -1 represents not found.
int count = 0;
List foundItems = new List();
Console.WriteLine("The search for item length is " + matchStr.Length);
do
{
foundPos = searchedStr.IndexOf(matchStr, startPos, StringComparison.Ordinal);
if(foundPos > - 1)
{
startPos = foundPos + 1;
count++;
foundItems.Add(foundPos);
Console.WriteLine("Found item at position: " + foundPos.ToString());
}
} while (foundPos > -1 && startPos < searchedStr.Length);

return ((int[])foundItems.ToArray());
}
}

class MainClass
{
static void Main(string[] args)
{
string data = "Red";
int[] allOccurrences = data.FindAll("BlueTeaRedredGreenRedYellow", 0);
}

}
}

Monday, August 8, 2011

Monday 8.8.11

using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;

namespace ConnectSqlServer
{
class Program
{
static void Main(string[] args)
{
//connect using .net data provider for SQl Server and integrated security
string sqlConnectString1 = @"Data Source=Alfred-PC\SQLExpress;" +
"Integrated Security=SSPI;Initial Catalog=AdventureWorks;";

using (SqlConnection connection = new SqlConnection(sqlConnectString1))
{
connection.Open();
//return some information about the server
Console.WriteLine("---.NET data provider for SQL Server" + " with Windows Authentication mode---");
Console.WriteLine("ConnectionString = {0}\n", sqlConnectString1);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}

Console.WriteLine("--------------------------------------------------");

//connect using .NET data provider for SQL Server and SQL Server authentication
string sqlConnectString2 = @"Data Source=Alfred-PC\SQLExpress;" +
"User ID=sa;Password=china;Initial Catalog=AdventureWorks;";
using (SqlConnection connection = new SqlConnection(sqlConnectString2))
{
connection.Open();
//return some information about the server
Console.WriteLine("\n---.Net data provider for SQL Server " + "with SQL Server Authentication mode---");
Console.WriteLine("ConnectionString = {0}\n", sqlConnectString2);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}

Console.WriteLine("--------------------------------------------------");

//connect using .NET data provider for OLE DB.
string oledbConnectString = @"Provider=SQLOLEDB;Data Source=Alfred-PC\SQLExpress;" +
"Initial Catalog=AdventureWorks;User Id=sa; Password=china;";

using (OleDbConnection connection = new OleDbConnection(oledbConnectString))
{
connection.Open();
//return some information about the server.
Console.WriteLine("\n---.NET data provider for OLE DB---");
Console.WriteLine("ConnectionString = {0}\n", oledbConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}

Console.WriteLine("--------------------------------------------------");

//connect using .NET data provider for ODBC.
//(COULD NOT GET THIS ONE TO WORK)
string odbcConnectString = "Driver={SQL Native Client};" + @"Server=Alfred-PC\SQLexpress;Database=AdventureWorks;uid=sa;pwd=china;";

using (OdbcConnection connection = new OdbcConnection(odbcConnectString))
{
connection.Open();

//return some information about the server
Console.WriteLine("\n---.NET data provider for ODBC---");
Console.WriteLine("ConncetionString = {0}\n", odbcConnectString);
Console.WriteLine("State = {0}", connection.State);
Console.WriteLine("DataSource = {0}", connection.DataSource);
Console.WriteLine("ServerVersion = {0}", connection.ServerVersion);
}
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sqlText = "SELECT TOP 15 * FROM Person.Contact";
string connectString =
ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(sqlText, connectString);
da.Fill(dt);
foreach (DataRow row in dt.Rows)

Response.Write( "ID" + " " + row["ContactID"] + " - " + row["LastName"] + ", " + row["FirstName"] + "
");
string sqlText2 = "SELECT TOP 15 * FROM HumanResources.Employee";
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(sqlText2, connectString);
da2.Fill(dt2);
foreach (DataRow row in dt2.Rows)
Response.Write(row["employeeID"] + "\n" + row["title"] + "
");
}
}


#include
int main(void)
{
char firstName[12] = {"Alfred"};
char lastName[12] = {"Jensen"};

printf("%s, %s \n", firstName, lastName);
printf("%s \n", firstName);
printf("%s \n", lastName);
printf("%s, %s \n", firstName, lastName);
}


#include
void jolly(void);//c function prototyping

int main(void)
{
jolly();
jolly();
jolly();
printf("Which nobody can deny!\n");
}

void jolly(void)
{
printf("For he's a jolly good fellow!\n");
}



/*rhodium.c your weight in rhodium */
#include
int main(void)
{
float weight;
float value;
printf("Are you worth your weight in rhodium?\n");
printf("Let's check it out.\n");
printf("Please enter your weight in pounds:");

//get inpput from the user
scanf("%f", &weight);
//assume rhodium is $770 per ounce
value = 770.0 * weight * 14.5833;
printf("Your weight in rhodium is worth $%.2f.\n", value);
printf("You are easily worth that! If rhodium prices drops, \n");
printf("eat more to maintain your value.");
}

Friday, August 5, 2011

Friday August 5th


Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_LOad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'only executed if page is being loaded for the first time
If Not IsPostBack Then
Dim iIndex As Integer
For iIndex = 50 To 500 Step 50
ddlMonthlyInvestment.Items.Add(iIndex)
Next iIndex
End If
End Sub

Protected Sub btnCalculate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim iMonths As Integer
Dim dInterestRate, dMonthlyInvestment As Decimal
Dim dFutureValue As Decimal
If IsValid Then
iMonths = txtYears.Text * 12
dInterestRate = txtInterestRate.Text / 12 / 100
dMonthlyInvestment = ddlMonthlyInvestment.SelectedValue
dFutureValue = FutureValue(iMonths, dInterestRate, dMonthlyInvestment)
lblFutureValue.Text = FormatCurrency(dFutureValue)
End If
End Sub

Private Function FutureValue(ByVal Months As Integer, ByVal InterestRate As Decimal, ByVal MonthlyInvestment As Decimal) As Decimal
Dim iIndex As Integer
Dim dFutureValue As Decimal
For iIndex = 1 To Months
dFutureValue = (dFutureValue + MonthlyInvestment) * (1 + InterestRate)
Next iIndex
Return dFutureValue
End Function

Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtInterestRate.Text = ""
txtYears.Text = ""
lblFutureValue.Text = ""
End Sub
End Class


and this is some of the ASP code


<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtInterestRate" Display="Dynamic"
ErrorMessage="Interest rate is required"></asp:RequiredFieldValidator>

<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtInterestRate" Display="Dynamic"
ErrorMessage="Interest Rate must range from 1 to 20" MaximumValue="20" MinimumValue="1" Type="Double"></asp:RangeValidator>
<p>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtYears" Display="Dynamic"
ErrorMessage="Number of years is required"></asp:RequiredFieldValidator>

<asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="txtYears" Display="Dynamic"
ErrorMessage="Years must range from 1 to 45" MaximumValue="45" MinimumValue="1" Type="Integer"></asp:RangeValidator>




using System;
using System.Data;
using System.Data.SqlClient;
//It's not only necessary to use the namespace System.Configuration. You have also to add the reference to the assembly System.Configuration.dll ,
//by right-click-ing on the References tab, choose add reference and then find System.Configuration
using System.Configuration;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//enumerate connection string
Console.WriteLine("---Connection string enumeration---");
foreach (ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
Console.WriteLine(css.Name);
Console.WriteLine(css.ProviderName);
Console.WriteLine(css.ConnectionString);
}
//retrieve a connection string and open/close it
Console.WriteLine("\n---Using a connection string---");
Console.WriteLine("-> Retrieving connection string AdventureWorks");

//retrieve connection string and open/close it
string sqlConnectString = ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
SqlConnection connection = new SqlConnection(sqlConnectString);

Console.WriteLine("-> Opening Connection String");

connection.Open();
Console.WriteLine("Connection string state = {0}", connection.State);
connection.Close();
Console.WriteLine("-> Closing connection string.");
Console.WriteLine("Connection string state = {0}", connection.State);
Console.WriteLine("\nPres any key to continue.");
Console.ReadKey();
}
}
}




using System;
using System.Data.SqlClient;

namespace BuildConnectionString
{
class Program
{
static void Main(string[] args)
{
//create a connection string builder
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
//define connection string attributes using three techniques
//also prepend the string with the @ character
csb.DataSource = @"Alfred-PC\SQLExpress";
csb.Add("Initial Catalog", "AdventureWorks");
csb["Integrated Security"] = true;

//output the connection string from the connection string builder
Console.WriteLine("Connection string:\n{0}", csb.ConnectionString);
//create a connection string from the connection string builder
SqlConnection connection = new SqlConnection(csb.ConnectionString);
//open and close the connection
connection.Open();
Console.WriteLine("\nConnectionState={0}", connection.State);
connection.Close();
Console.WriteLine("ConnectionState={0}", connection.State);
Console.WriteLine("\nPress any key to continue");
Console.ReadKey();
}
}
}

Thursday, August 4, 2011

Thursday 8.4.11


Option Strict On
Imports System

Public Class Window
'constructor takes two integers to fix location on the console
Public Sub New(ByVal top As Integer, ByVal left As Integer)
Me.top = top
Me.left = left
End Sub 'new

'simulates drawing the window
Public Sub DrawWindow()
Console.WriteLine("Drawing window at {0}, {1}", top, Left)
End Sub 'drawWindow

'these members are private and thus invisible
'to derived class methods; we'll examine this later in the chapter
Private top As Integer
Private left As Integer

End Class 'Window

'ListBox derives from Window
Public Class ListBox
Inherits Window
Dim mListBoxContents As String
'constructor adds a parameter
Public Sub New(ByVal top As Integer, ByVal left As Integer, ByVal theContents As String)
MyBase.New(top, left) ' call base constructor
mListBoxContents = theContents
End Sub 'new

'a shadow version (note keyword) because in the derived method we chagne the behavior
Public Shadows Sub DrawWindow()
Console.WriteLine("Using myBase")
MyBase.DrawWindow() 'invoke the base method
Console.WriteLine("Writing string to the listbox: {0}", mListBoxContents)
End Sub 'drawWindow
End Class

Module Module1
Sub Main()
'create a base instance
Dim w As New Window(5, 10)
w.DrawWindow()

'create a derived instance
Dim lb As New ListBox(20, 30, "Hello world")
lb.DrawWindow()
End Sub
End Module




Option Strict On
Imports System
Public Class Window

'constructor takes two integers to fix location
'on the console
Public Sub New(ByVal top As Integer, ByVal left As Integer)
Me.top = top
Me.left = left
End Sub 'new

'simulates the drawing of the window
Public Overridable Sub DrawWindow()
Console.WriteLine("_____________________________________________")
Console.WriteLine("Window: drawing Window at {0}, {1}", top, left)
Console.WriteLine("_____________________________________________")
End Sub 'drawWindow

'these members are protected and thus visible
'to derived class methods
'we'll examine this later in the chapter

Protected top As Integer
Protected left As Integer

End Class 'window

'ListBox derives from Window
Public Class ListBox
Inherits Window
'constructor adds a parameter
Public Sub New(ByVal top As Integer, ByVal left As Integer, ByVal contents As String)
MyBase.New(top, left) 'call base constructor
listBoxContents = contents
End Sub ' new

'an overridden version(note keyword)
'because in the derived method we change the behavior
Public Overrides Sub DrawWindow()
MyBase.DrawWindow() 'invoke the base method
Console.WriteLine("Writing string to the listbox: {0}", listBoxContents)
End Sub 'DrawWindow

Private listBoxContents As String ' new member variable
End Class 'ListBox

Public Class Button
Inherits Window
Public Sub New(ByVal top As Integer, ByVal left As Integer)
MyBase.New(top, left)
End Sub 'new

'an overriden version (note keyword) because in the derived method
'we change the behavior
Public Overrides Sub DrawWindow()
Console.WriteLine("-------------------------------")
Console.WriteLine("Drawing a button at {0}, {1}" + ControlChars.Lf, top, left)
Console.WriteLine("-------------------------------")
End Sub 'DrawWindow
End Class 'Button

Module Module1
Sub Main()
Dim win As New Window(1, 2)
Dim lb As New ListBox(3, 4, "Stand alone list box")
Dim b As New Button(5, 6)
win.DrawWindow()
lb.DrawWindow()
b.DrawWindow()
Dim winArray(3) As Window
winArray(0) = New Window(1, 2)
winArray(1) = New ListBox(3, 4, "ListBox in array")
winArray(2) = New Button(5, 6)

Dim i As Integer
For i = 0 To 2
winArray(i).DrawWindow()
Next i
End Sub
End Module




Option Strict On
Imports System
Public Class Dog
Private weight As Integer
'constructor
Public Sub New(ByVal weight As Integer)
Me.weight = weight
End Sub 'new

'override Object.ToString
Public Overrides Function ToString() As String
Return weight.ToString()
End Function 'ToString
End Class 'Dog

Module Module1
Sub Main()
Dim i As Integer = 5
Console.WriteLine("The value of i is: {0}", i.ToString())

Dim milo As New Dog(52)
Console.WriteLine("My dog Milo weighs {0} pounds", milo.ToString())
End Sub 'main
End Module 'tester




Option Strict On
Imports System

Public Class UnboxingTest
Public Shared Sub Main()
Dim myIntegerVariable As Integer = 123
'boxing

Dim myObjectVariable As Object = myIntegerVariable
Console.WriteLine("MyObjectVariable: {0}", myObjectVariable.ToString())
'unboxing
Dim anotherIntegerVariable As Integer = DirectCast(myObjectVariable, Integer)
Console.WriteLine("anotherIntegerVariable: {0}", anotherIntegerVariable)
End Sub
End Class





using System;

namespace MainProgram
{

static class CharStrExtMethods
{
public static bool IsCharEqual(this char firstChar, char secondChar)
{
//calls the seocnd IsCharEqual method with two parameters
return (IsCharEqual(firstChar, secondChar, false));
}

public static bool IsCharEqual(this char firstChar, char secondChar, bool caseSensitiveCompare)
{
if (caseSensitiveCompare)
{
return (firstChar.Equals(secondChar));
}
else
{
return (char.ToUpperInvariant(firstChar).Equals(char.ToUpperInvariant(secondChar)));
}
}


}//end class CharStrExtMethods


class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("hello world");
char char1 = 'c';
char char2 = 'X';
char char3 = 'f';
char char4 = 'F';

Console.WriteLine(CharStrExtMethods.IsCharEqual(char1, char2));
Console.WriteLine(CharStrExtMethods.IsCharEqual(char3, char4));
Console.WriteLine(CharStrExtMethods.IsCharEqual(char3, char4, true));
}
}
}

Wednesday, August 3, 2011

Wednesday 8.3.11


Option Strict On
Imports System
Module Module1

Sub Main()
Dim x As Integer = 5
Dim y As Integer = 7

Dim andValue As Boolean
Dim orValue As Boolean
Dim xorValue As Boolean
Dim notValue As Boolean

andValue = x = 3 And y = 7
orValue = x = 3 Or y = 7
xorValue = x = 3 Xor y = 7
notValue = Not x = 3

Console.WriteLine("x = 3 and Y = 7. {0}", andValue)
Console.WriteLine("x = 3 or Y = 7. {0}", orValue)
Console.WriteLine("x = 3 Xor y = 7. {0}", xorValue)
Console.WriteLine("Not x = 3. {0}", notValue)

End Sub
End Module




Option Strict On
Imports System
Module Module1

Sub Main()
Dim minDrinkingCoffee As Integer = 5
Dim minReadingNewspaper As Integer = 10
Dim minArguing As Integer = 15
Dim minDawdling As Integer = 20

Dim numAdults As Integer = 2
Dim numChildren As Integer = 2

Dim wastedByEachAdult As Integer
Dim wastedByAllAdults As Integer
Dim wastedByEachKid As Integer
Dim wastedByAllKids As Integer
Dim wastedByFamily As Integer
Dim totalSeconds As Integer

wastedByEachAdult = minDrinkingCoffee + minReadingNewspaper
wastedByAllAdults = wastedByEachAdult * numAdults
wastedByEachKid = minDawdling + minArguing
wastedByAllKids = wastedByEachKid * numChildren
wastedByFamily = wastedByAllAdults + wastedByAllKids
totalSeconds = wastedByFamily * 60
Console.WriteLine("Each adult wastes {0} minutes", wastedByEachAdult)
Console.WriteLine("Each child wastes {0} minutes", wastedByEachKid)
Console.WriteLine("Total minutes wasted by entire family: {0}", wastedByFamily)
Console.WriteLine("Total wasted seconds: {0}", totalSeconds)


End Sub
End Module





Option Strict On
Imports System
Public Module Module1

Public Class Dog
Public weight As Integer
End Class



Public Class Tester

Public Sub Run()
'create an integer
Dim firstInt As Integer = 5
'create a second integer
Dim secondInt As Integer = firstInt
'display the two integers
Console.WriteLine("firstInt: {0} secondInt: {1}", firstInt, secondInt)

'modify the second integer
secondInt = 7
'display the two integers
Console.WriteLine("firstInt: {0} secondInt: {1}", firstInt, secondInt)

'create a dog
Dim milo As New Dog()
'assign a value to weight
milo.weight = 5
'create a second reference to teh dog
Dim Fido As Dog = milo
'dispaly their values
Console.WriteLine("Milo: {0}, fido: {1}, milo.weight, fido.weight")
'assign a new weight to the second reference
Fido.weight = 7
'display the two values
Console.WriteLine("Milo: {0}, fido: {1}", milo.weight, Fido.weight)

End Sub
End Class

Sub Main()
Dim testObject As New Tester()
testObject.Run()
End Sub

End Module




Option Strict On
Imports System
Public Class Time
'Private variables
Private Year As Integer
Private Month As Integer
Private tDate As Integer
Private Hour As Integer
Private Minute As Integer
Private Second As Integer
'Public methods
Public Sub DisplayCurrentTime()
Console.WriteLine("stub for DisplayCurrentTime")
End Sub 'Display Current Time
End Class 'Time

Module Module1
Sub Main()
Dim timeObject As New Time()
timeObject.DisplayCurrentTime()
End Sub
End Module




Option Strict On
Imports System
Public Class TestClass
Sub SomeMethod(ByVal firstParam As Integer, ByVal secondParam As Single)
Console.WriteLine("Here are the parameters received: {0}, {1}", firstParam, secondParam)
End Sub
End Class

Module Module1
Sub Main()
Dim howManyPeople As Integer = 5
Dim pi As Single = 3.14F

Dim tc As New TestClass()
tc.SomeMethod(howManyPeople, pi)
End Sub
End Module




Option Strict On
Imports System
Public Class Time
'Private variables
Private Year As Integer
Private Month As Integer
Private tDate As Integer
Private Hour As Integer
Private Minute As Integer
Private Second As Integer

'Public methods
Public Sub DisplayCurrentTime()
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, tDate, Year, Hour, Minute, Second)
End Sub

'Constructor
Public Sub New(ByVal theYear As Integer, ByVal theMonth As Integer, ByVal theDate As Integer, ByVal theHour As Integer, ByVal theMinute As Integer, ByVal theSecond As Integer)
Year = theYear
Month = theMonth
tDate = theDate
Hour = theHour
Minute = theMinute
Second = theSecond
End Sub
End Class 'Time

Module Module1
Sub Main()
Dim timeObject As New Time(2005, 3, 25, 8, 35, 20)
timeObject.DisplayCurrentTime()
End Sub
End Module




'copy constructor
Option Strict On
Imports System
Public Class Time
'Private Variables
Private Year As Integer
Private Month As Integer
Private tDate As Integer
Private Hour As Integer
Private Minute As Integer
Private Second As Integer = 30

'Public methods
Public Sub DisplayCurrentTime()
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, tDate, Year, Hour, Minute, Second)
End Sub


Public Sub New(ByVal theYear As Integer, ByVal theMonth As Integer, ByVal theDate As Integer, ByVal theHour As Integer, ByVal theMinute As Integer)
Year = theYear
Month = theMonth
tDate = theDate
Hour = theHour
Minute = theMinute
End Sub

Public Sub New(ByVal existingObject As Time)
Year = existingObject.Year
Month = existingObject.Month
tDate = existingObject.tDate
Hour = existingObject.Hour
Minute = existingObject.Minute
End Sub

End Class

Module Module1
Sub Main()
Dim timeObject As New Time(2006, 3, 24, 10, 36)
Dim t2 As New Time(timeObject)
timeObject.DisplayCurrentTime()
t2.DisplayCurrentTime()
End Sub
End Module




'a common use of shared member variables, or fields, is to keep track of the number of instances/objects that currently exist
'for your class

Option Strict On
Imports System
Class Cat
'the cat class begins by defining a shared member variable, instances, that is initialized to 0
Private Shared instances As Integer = 0
Private weight As Integer
Private name As String

Public Sub New(ByVal nane As String, ByVal weight As Integer)
instances += 1
Me.name = name
Me.weight = weight
End Sub

Public Shared Sub HowManyCats()
Console.WriteLine("{0} cats adopted", instances)
End Sub

Public Sub TellWeight()
Console.WriteLine("{0} is {1} pounds", name, weight)
End Sub

End Class 'cat


Module Module1
Sub Main()
Cat.HowManyCats()
Dim frisky As New Cat("Frisky", 5)
frisky.TellWeight()
Cat.HowManyCats()
Dim whiskers As New Cat("Whiskers", 7)
whiskers.TellWeight() 'instance method
whiskers.HowManyCats() 'shared method through instance
Cat.HowManyCats() 'shared method through clas name
End Sub


End Module





Option Strict On
Imports System
Public Class Time
'private member variables
Private mYear As Integer
Private mMonth As Integer
Private mDate As Integer
Private mHour As Integer
Private mMinute As Integer
Private mSecond As Integer

Property Hour() As Integer
Get
Return mHour
End Get
Set(ByVal value As Integer)
mHour = value
End Set
End Property

Property Minute() As Integer
Get
Return mMinute
End Get
Set(ByVal value As Integer)
mMinute = value
End Set
End Property



'public accessor methods
Public Sub DisplayCurrentTime()
Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", mMonth, mDate, mYear, mHour, mMinute, mSecond)
End Sub 'displayCurrentTime

'Constructors
Public Sub New(ByVal dt As System.DateTime)
mYear = dt.Year
mMonth = dt.Month
mDate = dt.Day
mHour = dt.Hour
mMinute = dt.Minute
mSecond = dt.Second
End Sub 'New

Public Sub New(ByVal mYear As Integer, ByVal mMonth As Integer, ByVal mDate As Integer, ByVal mHour As Integer, ByVal mMinute As Integer, ByVal mSecond As Integer)
Me.mYear = mYear
Me.mMonth = mMonth
Me.mDate = mDate
Me.mHour = mHour
Me.mMinute = mMinute
Me.mSecond = mSecond
End Sub 'new

End Class 'time

Module Module1
Sub Main()
Dim currentTime As System.DateTime = System.DateTime.Now
Dim time1 As New Time(currentTime)
time1.DisplayCurrentTime()

'extract the hour to a local variable
Dim theHour As Integer = time1.Hour
'display the local variable
Console.WriteLine("Retrieved the hour: {0}", theHour)

'add one to the local variable
theHour += 1
'write the time back to the object
time1.Hour = theHour
'display the result
Console.WriteLine("Updated the hour: {0}", time1.Hour)

Dim theMinute As Integer = time1.Minute
Console.WriteLine("Retrieved the minute: {0}", theMinute)
theMinute += 1
time1.Minute = theMinute
Console.WriteLine("Updated the minute: {0}", time1.Minute)
End Sub
End Module




#include
int main(void)
{
int dogs;

printf("How many dogs do you have?\n");
scanf("%d", &dogs);
printf("So you have %d dog(s)!\n", dogs);

return 0;
}




#include
int main(void)
{
int num;
num = 1;

printf("I am a simple "); /* use the printf() function */
printf("computer.\n");
printf("My favorite number is %d because it is first.\n", num);

return 0;
}




//converts two fathoms to feet
#include
int main(void)
{
int feet, fathoms;
fathoms = 2;
feet = 6 * fathoms;
printf("There are %d feet in %d fathoms!\n", feet, fathoms);
printf("Yes, I said %d feet!\n", 6 * fathoms);

return 0;
}




#include
void butler(void);
int main(void)
{
printf("I will summon the butler function.\n");
butler();
printf("Yes, bring me some tea and crumpets.\n");
return 0;
}

void butler(void)
{
printf("You rang, sir?\n");
}




Option Strict On
Imports System
Public Class Cat
Private mWeight As Integer

Public Sub New(ByVal weight As Integer)
mWeight = weight
End Sub

Public Property Weight() As Integer
Get
Return mWeight
End Get
Set(ByVal value As Integer)
mWeight = value
End Set
End Property

Public Overrides Function ToString() As String
Return mWeight.ToString()
End Function

End Class ' Cat

Public Class Tester
Public Sub Run()
'declare a Cat and intialize it to 5
Dim theVariable As New Cat(5)
'display its value
Console.WriteLine("in Run. theVariable: {0}", theVariable)
'call a method and pass in the variable
Doubler(theVariable)
'return and display the value again
Console.WriteLine("back in run. the variable {0}", theVariable)
End Sub

Public Sub Doubler(ByVal param As Cat)
'display the value that was passed in
Console.WriteLine("In Method1. Received param: {0}", param)
'double the value
param.Weight = param.Weight * 2

'display the doubled value before returning
Console.WriteLine("Updated param. Returning new value: {0}", param)
End Sub
End Class 'tester

Module Module1
Sub Main()
Dim t As New Tester()
t.Run()
End Sub
End Module




SELECT ProductName, UnitPrice, UnitsInStock FROM Products
WHERE (ProductName BETWEEN 'A' AND 'D')

Tuesday, August 2, 2011

Tuesday 8/2/11


Sub Main()
Dim MyInt As Integer = 7
Console.WriteLine("Initialized myInt: {0}", MyInt)
MyInt = 5
Console.WriteLine("After assignment myInt: {0}", MyInt)
End Sub




Module Module1
Sub Main()
Const FreezingPoint As Integer = 32 ' degrees Farenheit
Const BoilingPoint As Integer = 212

System.Console.WriteLine("Freezing point of water: {0}", FreezingPoint)
System.Console.WriteLine("Boiling point of water: {0}", BoilingPoint)
End Sub
End Module




Module Module1
Enum Temperatures
WickedCold = 0
FreezingPoint = 32
LightJacketWeather = 60
SwimmingWeather = 72
BoilingPoint = 212
End Enum 'Temperatures


Sub Main()
System.Console.WriteLine("Freezing point of water: {0}", Temperatures.FreezingPoint)
System.Console.WriteLine("Boiling point of water: {0}", Temperatures.BoilingPoint)
System.Console.WriteLine("Freezing point of water: {0}", CInt(Temperatures.FreezingPoint))
System.Console.WriteLine("Boiling point of water: {0}", CInt(Temperatures.BoilingPoint))
End Sub
End Module




Option Strict On
Imports System
Module Module1
Sub Main()
Console.WriteLine("In Main! Calling SomeMethod()...")
SomeMethod()
Console.WriteLine("Back in Main().")
End Sub 'Main

Sub SomeMethod()
Console.WriteLine("Greetings from SomeMethod!")
End Sub 'someMethod
End Module




Option Strict On
Imports System
Module Module1

Sub Main()
Dim valueOne As Integer = 10
Dim valueTwo As Integer = 20
Dim valueThree As Integer = 30

Console.WriteLine("Testing valueOne against valueTwo...")
If valueOne > valueTwo Then
Console.WriteLine("ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo)
End If

Console.WriteLine("Testing valueThree against valueTwo..")
If valueThree > valueTwo Then
Console.WriteLine("ValueThree: {0} larger than ValueTwo: {1}", valueThree, valueTwo)
End If

Console.WriteLine("Testing is valueTwo > 15 (one line)...")
If valueTwo > 15 Then
Console.WriteLine("Yes it is.")
End If
End Sub 'Main
End Module




Option Strict On
Imports System
Module Module1

Sub Main()
Dim valueOne As Integer = 10
Dim valueTwo As Integer = 20
Dim valueThree As Integer = 30

Console.WriteLine("Testing valueOne against valueTwo...")
If valueOne > valueTwo Then
Console.WriteLine("ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo)
Else
Console.WriteLine("Nope, ValueOne: {0} is NOT larger than valueTwo: {1}", valueOne, valueTwo)
End If
End Sub
End Module




Option Strict On
Imports System

Module Module1
Sub Main()
Dim temp As Integer = 32
If temp <= 32 Then
Console.WriteLine("Warning! Ice on road!")
If temp = 32 Then
Console.WriteLine("Temp exactly freezing, beware of water.")
Else
Console.WriteLine("Watch for black ice! Temp:{0}", temp)
End If 'temp = 32
End If 'temp <=32
End Sub 'Main
End Module





Option Strict On
Imports System
Module Module1

Sub Main()
Dim temp As Integer = -32
If temp > 32 Then
Console.WriteLine("Safe driving...")
ElseIf temp = 32 Then
Console.WriteLine("Warning, 32 degrees, watch for ice and water")
ElseIf temp > 0 Then
Console.WriteLine("Watch for ice...")
ElseIf temp = 0 Then
Console.WriteLine("Temperature = 0")
Else
Console.WriteLine("Tmeperatures below zero, Wicked Cold!")
End If
End Sub
End Module




Option Strict On
Imports System
Module Module1

Sub Main()
Dim targetInteger As Integer = 15
Select Case targetInteger
Case 5
Console.WriteLine("5")
Case 10
Console.WriteLine("10")
Case 15
Console.WriteLine("15!")
Case Else
Console.WriteLine("Value not found")
End Select
End Sub
End Module




Option Strict On
Imports System
Module Module1
Sub Main()

Dim target As String = "Milo"
Select Case target
Case "Alpha" To "Lambda"
Console.WriteLine("Alpha to Lamba executed")
Case "Lambda" To "Zeta"
Console.WriteLine("Lambda to Zeta executed")
Case Else
Console.WriteLine("Else executed")
End Select
End Sub
End Module




Option Strict On
Imports System
Module Module1

Sub Main()
Dim counterVariable As Integer = 0
Do While counterVariable < 10
Console.WriteLine("counterVariable: {0}", counterVariable)
counterVariable = counterVariable + 1
Loop ' While counterVariable < 10
End Sub 'Main
End Module





Option Strict On
Imports System
Module Module1

Sub Main()
Dim counterVariable As Integer = 0
Do Until counterVariable = 10
Console.WriteLine("counterVariable: {0}", counterVariable)
counterVariable = counterVariable + 1
Loop ' until countervariable = 10
End Sub
End Module




Option Strict On
Imports System
Module Module1

Sub Main()
Dim counterVariable As Integer = 100
Do
Console.WriteLine("counterVariable: {0}", counterVariable)
counterVariable = counterVariable + 1
Loop While counterVariable < 10
End Sub
End Module




Sub Main()
Dim loopCounter As Integer
For loopCounter = 0 To 9
Console.WriteLine("loopCounter: {0}", loopCounter)
Next
End Sub




Module Module1
Sub Main()
Dim loopCounter As Single
For loopCounter = 0.5 To 9
Console.WriteLine("loopCounter: {0}", loopCounter)
Next
End Sub
End Module





Option Strict On
Imports System
Module Module1

Sub Main()
Dim loopCounter As Single
For loopCounter = 0.5 To 9 Step 0.5
Console.WriteLine("loopCounter: {0}", loopCounter)
Next
End Sub
End Module





Option Strict On
Imports System
Module Module1

Sub Main()
Dim counter As Integer
'count from 1 to 100
For counter = 1 To 100
'display the value
Console.Write("{0} ", counter)
If counter Mod 10 = 0 Then
Console.WriteLine(vbTab & counter)
End If
Next counter
End Sub 'End of Main() method
End Module





Option Strict On
Imports System
Module Module1
Sub Main()
Dim value As Integer = 6
Dim power As Integer = 3
Console.WriteLine("{0} to the {1}rd power is {2}", value, power, value ^ power)
End Sub
End Module

Monday, August 1, 2011

Monday 8/1/2011


Dim seekString As String = "Visual"
Dim strLocation As Long
strLocation = TextBox1.Text.IndexOf(seekString)
If strLocation > 0 Then
TextBox1.SelectionStart = strLocation
TextBox1.SelectionStart = seekString.Length
End If
TextBox1.ScrollToCaret()




Private Sub EditCopyItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditCopyItem.Click
If txtEditor.SelectionLength > 0 Then
Clipboard.SetText(txtEditor.SelectedText)
End If
End Sub

Private Sub EditCutItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditCutItem.Click
Clipboard.SetText(txtEditor.SelectedText)
txtEditor.SelectedText = ""
End Sub


Private Sub EditPasteItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditPasteItem.Click
If Clipboard.ContainsText Then
txtEditor.SelectedText = Clipboard.GetText
End If
End Sub





Dim ListItem As String
ListItem = InputBox("Enter new item's name")
If ListItem.Trim <> "" Then
sourceList.Items.Add(ListItem)
End If




While sourceList.SelectedIndices.Count > 0
destinationList.Items.Add(sourceList.Items(sourceList.SelectedIndices(0)))
sourceList.Items.Remove(sourceList.Items(sourceList.SelectedIndices(0)))
End While




Private Sub AddElement_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddElement.Click
Dim itm As String
itm = InputBox("Enter new item", "New Item")
If itm.Trim <> "" Then AddElem(itm)
End Sub

Sub AddElem(ByVal newItem As String)
Dim idx As Integer
If ComboBox1.FindString(newItem) > 0 Then
idx = ComboBox1.FindString(newItem)
Else
idx = ComboBox1.Items.Add(newItem)
End If
ComboBox1.SelectedIndex = idx
End Sub




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

Public Class AddressOfWithEvents : Inherits System.Windows.Forms.Form

Dim WithEvents 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

Private Sub btn_click(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("btn_click method", "events demonstration")
End Sub

Private Sub btn_ClickHandles(ByVal sender As Object, ByVal e As EventArgs) Handles btn.Click
MessageBox.Show("btn_ClickHandles method", "Events Demonstration")
End Sub

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

Public Shared Sub Main()
Application.Run(New AddressOfWithEvents())
End Sub
End Class