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!";
}
?>

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')