Monday, October 31, 2011

Monday 10.31.11

Imports Microsoft.VisualBasic
Imports System
Imports System.Xml

Namespace DrWhoLib

Public Class DrWhoQuotes
Private quoteDoc As XmlDocument
Private quoteCount As Integer

Public Sub New(ByVal fileName As String)
quoteDoc = New XmlDocument()
quoteDoc.Load(fileName)
quoteCount = quoteDoc.DocumentElement.ChildNodes.Count
End Sub

Public Function GetRandomQuote() As Quotation
Dim i As Integer
Dim x As New Random()
i = x.Next(quoteCount - 1)
Return New Quotation(quoteDoc.DocumentElement.ChildNodes(i))
End Function
End Class

Public Class Quotation

Private qSource As String

Public Property Source() As String
Get
Return qSource
End Get
Set(ByVal value As String)
qSource = value
End Set
End Property

Private dteDate As String
Public Property MyDate() As String
Get
Return dteDate
End Get
Set(ByVal value As String)
dteDate = value
End Set
End Property

Private strQuotation As String
Public Property QuotationText() As String
Get
Return strQuotation
End Get
Set(ByVal value As String)
strQuotation = value
End Set
End Property

Public Sub New(ByVal quoteNode As XmlNode)
If quoteNode.SelectSingleNode("source") IsNot Nothing Then
qSource = quoteNode.SelectSingleNode("source").InnerText
End If

If quoteNode.Attributes.GetNamedItem("date") IsNot Nothing Then
dteDate = quoteNode.Attributes.GetNamedItem("date").Value
End If

strQuotation = quoteNode.FirstChild.InnerText
End Sub
End Class

End Namespace

Partial Class DrWhoQuotes
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim quotes As New DrWhoLib.DrWhoQuotes(Server.MapPath("~/doctorWho.xml"))
Dim quote As DrWhoLib.Quotation = quotes.GetRandomQuote()
Response.Write(" " & quote.Source & " ( " & quote.MyDate & ")")
Response.Write("
" & quote.QuotationText & "
")
End Sub
End Class


Protected Sub btnCmd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCmd.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Northwind").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
Dim sql As String = "DELETE FROM Employees WHERE EmployeeID = " & empID.Text
Dim cmd As New SqlCommand(sql, con)

Try
con.Open()
Dim numAff As Integer = cmd.ExecuteNonQuery()
HtmlContent.Text &= String.Format("
Deleted {0} record(s)
", numAff)
Catch ex As Exception
HtmlContent.Text &= String.Format("Error: {0}

", ex.Message)
Finally
con.Close()
End Try
End Sub


CREATE PROCEDURE InsertEmployee(
@TitleOfCourtesy varchar(25),
@LastName varchar(20),
@FirstName varchar(10),
@EmployeeID int OUTPUT)
AS
INSERT INTO Employees
(TitleOfCourtesy, LastName, FirstName, HireDate)
VALUES (@TitleOfCourtesy, @LastName, @FirstName, GETDATE());

SET @EmployeeID = @@IDENTITY
GO

Wednesday, October 26, 2011

#include
void up_and_down(int);

int main(void)
{
up_and_down(1);
return 0;
}

void up_and_down(int n)
{
printf("Level %d: n location %p\n", n, &n);
if (n < 4)
up_and_down(n+1);
printf("LEVEL %d: n location %p\n", n, &n);
}


#include
#define MONTHS 12

int main(void)
{
int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int index;
for (index = 0; index < MONTHS; index++)
printf("Month %d has %2d days.\n", index +1, days[index]);
return 0;
}



#include
#define MONTHS 12
int main(void)
{
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31};
int index;

for (index = 0; index < sizeof days / sizeof days[0]; index++)
printf("Month %2d has %d days.\n", index +1, days[index]);

return 0;
}


#include
#define MONTHS 12 //number of months in a year
#define YEARS 5 //number of years of data
int main(void)
{
//..initializing rainfall data for 2000-2004
const float rain[YEARS][MONTHS] =
{
{4.3, 4.3, 4.3, 3.0, 2.0, 1.2, 0.2, 0.2, 0.4, 2.4, 3.5, 6.6},
{8.5, 8.2, 1.2, 1.6, 2.4, 0.0, 5.2, 0.9, 0.3, 0.9, 1.4, 7.3},
{9.1, 8.5, 6.7, 4.3, 2.1, 0.8, 0.2, 0.2, 1.1, 2.3, 6.1, 8.4},
{7.2, 9.9, 8.4, 3.3, 1.2, 0.8, 0.3, 0.0, 0.6, 1.7, 4.3, 6.2},
{7.6, 5.6, 3.8, 2.8, 3.8, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 5.2}
};
int year, month;

float subtot, total;

printf("YEAR RAINFALL (inches)\n");
for (year = 0, total=0; year < YEARS; year++)
{
//for each year, sum rainfall for each month
for (month = 0, subtot = 0; month < MONTHS; month++)
subtot += rain[year][month];
printf("%5d %15.1f\n", 2000 + year, subtot);
total += subtot; //total for all years
}

printf("\nThe yearly average is %.1f inches.\n\n", total/YEARS);
printf("MONTHLY AVERAGES:\n\n");
printf(" JAN FEB MAR APR MAY JUN JUL AUG SEP OCT");
printf(" NOV DEC \n");

for (month = 0; month < MONTHS; month++)
{
//for each month, sum rainfall over years
for (year = 0, subtot = 0; year < YEARS; year++)
{
subtot += rain[year][month];
}
printf("%4.1f ", subtot/YEARS);
}
printf("\n");
return 0;
}


#include
#define SIZE 4
int main(void)
{
short dates[SIZE];
short *pti;
short index;
double bills[SIZE];
double *ptf;

pti = dates;
ptf = bills;
printf("%23s %10s\n", "short", "double");
for (index = 0; index < SIZE; index++)
{
printf("pointers + %d: %10p %10p\n", index, pti + index, ptf + index);
}

return 0;

}


#include
#define MONTHS 12

int main(void)
{
int days[MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int index;

for (index = 0; index < MONTHS; index++)
{
printf("Month %2d has %d days.\n", index +1, *(days + index)); //same as days[index]


}

return 0;
}


#include
#define SIZE 10
int sump(int * start, int * end);
int main(void)
{
int marbles[SIZE] = {20, 10, 5, 39, 4, 16, 19, 26, 31, 20};
long answer;

answer = sump(marbles, marbles + SIZE);
printf("The total number of marbles is %ld.\n", answer);

return 0;
}

//use pointer arithmetic
int sump(int * start, int * end)
{
int total = 0;

while (start < end)
{
total += *start;
start++;
}

return total;
}

Tuesday, October 25, 2011

Tuesday 10.25.11

#include
void display(char cr, int lines, int width);
int main(void)
{
int ch;
int rows, cols;

printf("Enter a character and two integers:\n");
while ((ch = getchar()) != '\n')
{
if (scanf("%d %d", &rows, &cols) != 2)
break;
display(ch, rows, cols);
while (getchar() != '\n')
continue;
printf("Enter another character and two integers;\n");
printf("Enter a newline to quit.\n");
}
printf("Bye.\n");

return 0;
}

void display(char cr, int lines, int width)
{
int row, col;

for (row = 1; row <= lines; row++)
{
for (col = 1; col <= width; col++)
putchar(cr);
putchar('\n');

}


#include

//validate that input is an integer
int get_int(void);
//validate that range limits are valid
int bad_limits(int begin, int end, int low, int high);
//calculate the sum of the squares of teh two integers
//a through b
double sum_squares(int a, int b);
int main(void)
{
const int MIN = -1000; //lower limit to range
const int MAX = +1000; //upper limit to range
int start; //start of range
int stop; //end of range
double answer;

printf("This program computes the sum of the squares of integerrs in a range.\n");
printf("The lower bound should not be less than -1000 and \n the upper bound should not be more than +1000.\n");
printf("Enter the limits (enter 0 for both limits to quit):\nlower limit: ");
start = get_int();
printf("upper limit: ");
stop = get_int();
while (start != 0 || stop != 0)
{
if (bad_limits(start, stop, MIN, MAX))
printf("Please try again.\n");
else
{
answer = sum_squares(start, stop);
printf("The sum of the squares of the integers ");
printf("from %d to %d is %g\n", start, stop, answer);
}
printf("Enter the limits (enter 0 for both limits to quit):\n");
printf("lower lmit: ");
start = get_int();
printf("upper limit: ");
stop = get_int();
}
printf("Done.\n");
return 0;
}

int get_int(void)
{
int input;
char ch;

while (scanf("%d", &input) != 1)
{
while ((ch = getchar()) != 1)
putchar(ch); //dispose of bad input
printf(" is not an integer.\n Please enter an ");
printf("integer value, such as 25, -178, or 3: ");
}
return input;
}

double sum_squares(int a, int b)
{
double total = 0;
int i;

for (i = a; i <= b; i++)
total += i * i;
return total;
}

int bad_limits(int begin, int end, int low, int high)
{
int not_good = 0;
if (begin > end)
{
printf("%d isn't smaller than %d.\n", begin, end);
not_good = 1;
}
if (begin < low || end < low)
{
printf("Values must be %d or greater.\n", low);
not_good = 1;
}
if (begin > high || end > high)
{
printf("Values must be %d or less.\n", high);
not_good = 1;
}

return not_good;
}


#include
char get_choice(void);
char get_first(void);
int get_int(void);
void count(void);
int main(void)
{
int choice;
void count(void);

while ((choice = get_choice()) != 'q')
{
switch (choice)
{
case 'a' : printf("Buy low, sell high.\n");
break;
case 'b' : putchar('\a'); //ansi
break;
case 'c' : count();
break;
default: printf("Program error!\n");
break;
}
}
printf("Bye.\n");

return 0;
}

void count(void)
{
int n, i;
printf("Count how far? Enter an integer:\n");
n = get_int();
for (i = 1; i <= n; i++)
{
printf("%d\n", i);
}
while (getchar() != '\n')
continue;
}

char get_choice(void)
{
int ch;

printf("Enter the letter of your choice:\n");
printf("a. advice b. bell\n");
printf("c. count q.quit\n");
ch = get_first();
while ((ch < 'a' || ch > 'c') && ch!= 'q')
{
printf("Please respond with a, b, c or q.\n");
ch = get_first();
}
return ch;
}

char get_first(void)
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;

return ch;
}

int get_int(void)
{
int input;
char ch;

while (scanf("%d", &input) != 1)
{
putchar(ch);
}
printf(" is not an integer.\nPlease enter an ");
printf("integer value; such as 25, -178, of 3:");
return input;
}


#include
#define NAME "GIGATHINK, INC."
#define ADDRESS "101 Megabuck Plaza"
#define PLACE "Megapolis, CA 94904"
#define WIDTH 40

void starbar(void);

int main(void)
{
starbar();
printf("%s\n", NAME);
printf("%s\n", ADDRESS);
printf("%s\n", PLACE);
starbar();

return 0;
}

void starbar(void)
{
int count;

for (count = 1; count <= WIDTH; count++)
putchar('*');
putchar('\n');
}



#include
#include
#define NAME "GIGATHINK, INC."
#define ADDRESS "101 Megabuck Plaza"
#define PLACE "Megapolis, CA 94904"
#define WIDTH 40
#define SPACE ' '

void show_n_char(char ch, int num);

int main(void)
{
int spaces;
show_n_char('*', WIDTH);
putchar('\n');
show_n_char(SPACE, 12);
printf("%s\n", NAME);

spaces = (WIDTH - strlen(ADDRESS)) / 2;
//let the program calculate how many spaces to skip
show_n_char(SPACE, spaces);
printf("%s\n", ADDRESS);
show_n_char(SPACE, (WIDTH - strlen(PLACE)) / 2);
printf("%s\n", PLACE);
show_n_char('*', WIDTH);
putchar('\n');

return 0;
}

//show_n_char() definition
void show_n_char(char ch, int num)
{
int count;

for (count = 1; count <= num; count++)
putchar(ch);
}

Friday, October 21, 2011

Friday 10.21.11

using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

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

string sqlSelect = "SELECT TOP 5 FirstName, LastName FROM Person.Contact";

//create a data adapter
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);

//fill a data table using DataAdapter and output to console
DataTable dt = new DataTable();
da.Fill(dt);

Console.WriteLine("---DataTable---");
foreach (DataRow row in dt.Rows)
Console.WriteLine("{0} {1}", row[0], row["LastName"]);

//fill a DataSet using DataAdapter and output to console
DataSet ds = new DataSet();
da.Fill(ds, "Contact");

Console.WriteLine("\n---DataSet; DataTable count = {0}---", ds.Tables.Count);
Console.WriteLine("[TableName = {0}]", ds.Tables[0].TableName);
foreach (DataRow row in ds.Tables["Contact"].Rows)
Console.WriteLine("{0} {1}", row[0], row[1]);

}
}
}


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


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

string sqlSelect = "SELECT ContactID, FirstName, LastName FROM Person.Contact " +
"WHERE ContactID BETWEEN 10 AND 14";

//create a data adapter
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);

//fill a DataTable using DataAdapter and output to console
DataTable dt = new DataTable();
da.Fill(dt);

//accessing rows using indexer
Console.WriteLine("---Index loop over DataRowCollection---");
for (int i = 0; i < 5; i++)
{
DataRow row = dt.Rows[i];
Console.WriteLine("Row = {0}\tContactID = {1}\tFirstName = {2}\tLastName={3}", i, row[0], row["FirstName"], row[2, DataRowVersion.Default]);
}

//accessing rows using foreach loop
Console.WriteLine("\n--foreach loop over DataRowCollection---");
int j = 0;
foreach (DataRow row in dt.Rows)
{
j++;
Console.WriteLine("Row = {0}\tContactID = {1}\tFirstName = {2}\tLastName = {3}", j, row[0], row["FirstName"], row["LastName", DataRowVersion.Default]);
}

//accessing DataTable values directly
Console.WriteLine("\n---Accessing FirstName value in row 3 (ContactID = 12) directly ----");
Console.WriteLine("FirstName = {0}", dt.Rows[2][1]);
Console.WriteLine("FirstName = {0}", dt.Rows[2]["FirstName"]);
Console.WriteLine("FirstName = {0}", dt.Rows[2]["FirstName", DataRowVersion.Default]);
Console.WriteLine("FirstName = {0}", dt.Rows[2][dt.Columns[1]]);
Console.WriteLine("FirstName = {0}", dt.Rows[2][dt.Columns["FirstName"]]);
Console.WriteLine("FirstName = {0}", dt.Rows[2].Field(1));
Console.WriteLine("FirstName = {0}", dt.Rows[2].Field("FirstName"));
Console.WriteLine("FirstName = {0}", dt.Rows[2].Field(dt.Columns[1]));

}
}
}


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

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

string sqlSelect = "SELECT * FROM Person.Contact";
string sqlSelectEmpty = "SELECT * FROM Person.Contact WHERE ContactID = 0";

Console.WriteLine("---QUERY RETURNS NON-EMPTY RESULT SET---");
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
DataTable dt = new DataTable();
da.Fill(dt);
Console.WriteLine("DataTable has records = {0}", dt.Rows.Count > 0);

using (SqlConnection connection = new SqlConnection(sqlConnectString))
{
SqlCommand command = new SqlCommand(sqlSelect, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();

Console.WriteLine("DataReader has records using HasRows property = {0}", dr.HasRows);

Console.WriteLine("DataReader has records using Read() method = {0}", dr.Read());

dr.Close();
}

Console.WriteLine();
Console.WriteLine("---QUERY RETURNS EMPTY RESULT SET---");
da = new SqlDataAdapter(sqlSelectEmpty, sqlConnectString);
dt = new DataTable();
da.Fill(dt);
Console.WriteLine("DataTable has records = {0}", dt.Rows.Count > 0);

using (SqlConnection connection = new SqlConnection(sqlConnectString))
{
SqlCommand command = new SqlCommand(sqlSelectEmpty, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();

Console.WriteLine("DataReader has records using HasRows property = {0}", dr.HasRows);

Console.WriteLine("DataReader has records using Read() method = {0}", dr.Read());

dr.Close();
}

}
}
}


Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration

Partial Class DataReader
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'create the command and the connection objects
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("NorthWind").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim sql As String = "SELECT * FROM Employees"
Dim cmd As New SqlCommand(sql, con)

con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()

'the read method also returns a Boolean value indicating whether there are more rows to read

Dim htmlStr As New StringBuilder("")
Do While reader.Read()
htmlStr.Append("
  • ")
    ' htmlStr.Append(reader("Title of Courtesy"))
    htmlStr.Append(" ")
    htmlStr.Append(reader.GetString(1))
    htmlStr.Append("
    ")
    htmlStr.Append(reader.GetString(2))
    htmlStr.Append(" - employee from ")
    htmlStr.Append(reader.GetDateTime(6).ToString("d"))
    htmlStr.Append("
  • ")
    Loop

    reader.Close()
    con.Close()
    HtmlContent.Text = htmlStr.ToString()
    End Sub
    End Class


    Imports System.Web.Configuration
    Imports System.Data
    Imports System.Data.SqlClient

    Partial Class ExecuteScalar
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Northwind").ConnectionString
    Dim con As New SqlConnection(connectionString)
    Dim sql As String = "SELECT COUNT(*) FROM Employees"
    Dim cmd As New SqlCommand(sql, con)

    'open the connection & get the COUNT(*) value
    con.Open()
    Dim numEmployees As Integer = CInt(cmd.ExecuteScalar())
    con.Close()

    'display the information
    HtmlContent.Text = "Total Employees: " & numEmployees.ToString() & "

    "

    End Sub
    End Class

    Thursday, October 20, 2011

    Wednesday 10.20.11

    #include

    int main(void)
    {
    char CurrentChar;
    int Spaces = 0;
    int NewLines = 0;
    int Others = 0;

    for(;;)
    {
    CurrentChar = getchar();

    switch(CurrentChar)
    {
    case '#':
    getchar(); //eat the cr
    goto Report; //exits the loop
    case ' ':
    Spaces++;
    break;
    case '\n':
    NewLines++;
    break;
    default:
    Others++;
    break;
    }
    }

    Report: //label
    printf("\n");
    printf("Spaces %d\n", Spaces);
    printf("NewLines %d\n", NewLines);
    printf("Others %d\n", Others);
    getchar();
    return 0;

    }

    Wednesday, October 19, 2011

    Wednesday 10.19.11

    #include
    int main(void)
    {
    char ch;

    while ((ch = getchar()) != '#')
    putchar(ch);

    return 0;
    }


    #include
    int main(void)
    {
    int ch;

    while ((ch = getchar()) != EOF)
    putchar(ch);

    return 0;
    }


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

    printf("Pick an integer from 1 to 100. I will try to guess ");
    printf("it.\nRespond with a y if my guess is right and with");
    printf("\nan n if it is wrong.\n");
    printf("Uh...is your number %d?\n", guess);
    while (getchar() != 'y')
    {
    printf("Well, then, is it %d?\n", ++guess);
    while (getchar() != '\n')
    continue; //skip rest of input line
    }
    printf("I knew I could do it!\n");

    return 0;
    }


    #include
    void display(char cr, int lines, int width);
    int main(void)
    {
    int ch;
    int rows, cols;
    printf("enter a character and two integers:\n");
    while ((ch = getchar()) != '\n')
    {
    scanf("%d %d", &rows, &cols);
    display(ch, rows, cols);
    printf("Enter another character and two integers;\n");
    printf("Enter a newline to quit.\n");
    }
    printf("Bye.\n");

    return 0;
    }

    void display(char cr, int lines, int width)
    {
    int row, col;

    for (row = 1; row <= lines; row++)
    {
    for (col = 1; col <= width; col++)
    {
    putchar(cr);
    }
    putchar('\n');s
    }
    }


    #include
    void display(char cr, int lines, int width);
    int main(void)
    {
    int ch; //character to be printed
    int rows, cols; //number of rows and columns

    printf("Enter a character and two integers:\n");
    while ((ch = getchar()) != '\n')
    {
    if (scanf("%d %d", &rows, &cols) != 2)
    break;
    display(ch, rows, cols);
    while (getchar() != '\n')
    continue;
    printf("Enter another character and two integers;\n");
    printf("Enter a newline to quit.\n");
    }
    printf("Bye.\n");

    return 0;
    }

    void display(char cr, int lines, int width)
    {
    int row, col;

    for (row = 1; row <= lines; row++)
    {
    for (col = 1; col <= width; col++)
    {
    putchar(cr);
    }
    putchar('\n'); //end line and start a new one
    }
    }

    Tuesday, October 18, 2011

    Tuesday 10/18/11

    protected void gvwCustomers_SelectedIndexChanged(object sender, EventArgs e)
    {
    StringBuilder info = new StringBuilder();
    info.AppendFormat("You are viewing record {0} of {1} (SelectedIndex)
    ", gvwCustomers.SelectedIndex.ToString(), gvwCustomers.Rows.Count.ToString());
    info.AppendFormat("You are viewing record {0} of {1} (DataKeys)
    ", gvwCustomers.SelectedIndex.ToString(), gvwCustomers.DataKeys.Count);
    info.AppendFormat("You are viewing page {0} of {1} (PageCount)
    ", gvwCustomers.PageIndex.ToString(), gvwCustomers.PageCount.ToString());

    info.AppendFormat("

    Using SelectedRow, Email Address= {0}
    ", gvwCustomers.SelectedRow.Cells[4].Text);

    info.Append("Using SelectedDataKey
    ");

    for (int i = 0; i < gvwCustomers.DataKeyNames.Length; i++)
    {
    info.AppendFormat("{0} : {1}
    ", gvwCustomers.DataKeyNames[i], gvwCustomers.SelectedDataKey.Values[i]);
    }
    info.AppendFormat("Selected Value: {0}", gvwCustomers.SelectedValue.ToString());

    lblInfo.Text = info.ToString();
    }



    Imports System
    Imports System.Data
    Imports System.Threading
    Imports System.Data.SqlClient

    Namespace Apress.VisualBasicRecipes.Chapter08
    Public Class Recipe08_09
    'a method to handle asynchronous completion using callbacks
    Public Shared Sub CallBackHandler(ByVal result As IAsyncResult)
    'obtain a reference to the SqlCommand used to initiate the asynchronous operation
    Using cmd As SqlCommand = TryCast(result.AsyncState, SqlCommand)
    'obtain the result of the stored procedure.
    Using reader As SqlDataReader = cmd.EndExecuteReader(result)
    'display the results of the stored procedure to the console.
    'to ensure the program is thread safe, SyncLock is used to stop
    'more than one thread from accessing the console at the same time.
    SyncLock Console.Out
    Console.WriteLine("Bill of Materials:")
    Console.WriteLine("ID \t DESCRIPTION \t QUANTITY \t LISTPRICE")
    While reader.Read
    'display the record details
    Console.WriteLine("{0} {1} {2} {3}", reader("ComponentID"), reader("ComponentDesc"), reader("TotalQuantity"), reader("ListPrice"))
    End While
    End SyncLock
    End Using
    End Using

    End Sub

    Public Shared Sub Main()
    'create a new SqlConnection object
    Using con As New SqlConnection
    'configure teh SqlConnection object's connection string
    'you must specify Asynchronous Processing=True to support
    'asynchronous operations over the connection
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress; Database=AdventureWorks; Integrated Security=SSPI;Asynchronous Processing=True;"
    'create and configure a new command to run a stored procedure
    Using cmd As SqlCommand = con.CreateCommand

    cmd.CommandType = CommandType.StoredProcedure
    cmd.CommandText = "uspGetBillOfMaterials"

    'create the required SqlParameter objects
    cmd.Parameters.Add("@StartProductID", SqlDbType.Int).Value = 771
    cmd.Parameters.Add("@CheckDate", SqlDbType.DateTime).Value = DateTime.Parse("07/10/2000")

    'open the database connection and execute the command
    'asynchronously. Pass the reference to the SqlCommand used to initiate the asynchronous operation
    con.Open()
    cmd.BeginExecuteReader(AddressOf CallBackHandler, cmd)
    End Using
    'continue with other processing
    For count As Integer = 1 To 10
    SyncLock Console.Out
    Console.WriteLine("{0} : Continue processing...", DateTime.Now.ToString("HH:mm:ss.ffff"))
    End SyncLock
    Thread.Sleep(500)
    Next

    'close the database connection
    con.Close()

    End Using

    End Sub
    End Class

    End Namespace


    Imports System
    Imports System.Net.NetworkInformation

    Namespace Apress.VisualBasicRecipes.Chapter11
    Public Class Recipe11_01

    Public Shared Sub Main()

    'only proceed if there is a network available
    If NetworkInterface.GetIsNetworkAvailable Then
    'get the set of all NetworkInterface objects for the local machine
    Dim interfaces As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces
    'iterate through the interfaces and display information
    For Each ni As NetworkInterface In interfaces
    'report basic interface information
    Console.WriteLine("Interface Name: {0}", ni.Name)
    Console.WriteLine("Description: {0}", ni.Description)
    Console.WriteLine("ID: {0}", ni.Id)
    Console.WriteLine("Type: {0}", ni.NetworkInterfaceType)
    Console.WriteLine("Speed: {0}", ni.Speed)
    Console.WriteLine("Status: {0}", ni.OperationalStatus)

    'report physical address
    Console.WriteLine("Physical Address: {0}", ni.GetPhysicalAddress().ToString)

    'report network statistics for the interface
    Console.WriteLine("Bytes Sent: {0}", ni.GetIPv4Statistics().BytesSent)
    Console.WriteLine("Bytes Received: {0}", ni.GetIPv4Statistics.BytesReceived)

    'report IP configuration
    Console.WriteLine("IP Addresses:")
    For Each addr As UnicastIPAddressInformation In ni.GetIPProperties.UnicastAddresses
    Console.WriteLine(" - {0} (lease expires {1})", addr.Address, DateTime.Now.AddSeconds(addr.DhcpLeaseLifetime))
    Next
    Console.WriteLine(Environment.NewLine)
    Next
    Else
    Console.WriteLine("No network available")
    End If
    End Sub
    End Class
    End Namespace


    Imports System
    Imports System.IO
    Imports System.Net
    Imports System.Text.RegularExpressions

    Namespace Apress.VisualBasicRecipes.Chapter11
    Public Class Recipe11_03

    Public Shared Sub Main()


    'specify the URI of the resource to parse
    Dim remoteUri As String = "http://www.msdn.com"

    'create a webclient to perform the download
    Dim client As New WebClient

    Console.WriteLine("Downloading {0}", remoteUri)

    'perform the donload getting the resource as a string
    Dim str As String = client.DownloadString(remoteUri)

    'use a regular expression to extract all fully qualified URIs that refer to GIF files
    Dim matches As MatchCollection = Regex.Matches(str, "http\S+[^-,;:?]\.gif")

    'try to download each referenced GIF file
    For Each expMatch As Match In matches
    For Each grp As Group In expMatch.Groups
    'determine the local filename
    Dim downloadedFile As String = grp.Value.Substring(grp.Value.LastIndexOf("/") + 1)
    Try
    'download and store the file
    Console.WriteLine("Donlowading {0} to file {1}", grp.Value, downloadedFile)
    client.DownloadFile(New Uri(grp.Value), downloadedFile)
    Catch ex As Exception
    Console.WriteLine("Failed to download {0}", grp.Value)
    End Try
    Next
    Next

    End Sub

    End Class
    End Namespace


    Imports System
    Imports System.IO
    Imports System.Net
    Imports System.Text
    Imports System.Threading

    Namespace Apress.VisualBasicRecipes.Chapter11
    Public Class Recipe11_05

    'configure the maximum number of requests that can be handled concurrently
    Private Shared maxRequestHandlers As Integer = 5

    'an integer used to assign each HTTP request handler a unique identifier
    Private Shared requestHandlerID As Integer = 0

    'the HttpListener is the class that provides all the capabilities to receive and process HTTP requests
    Private Shared listener As HttpListener

    Public Shared Sub Main()
    'quit gracefully if this feature is not supported
    If Not HttpListener.IsSupported Then
    Console.WriteLine("You must be running this example on Windows XP SP2, Windows Server 2003, or higher to create an HttpListener.")
    Exit Sub
    End If

    'create the HttpListener
    listener = New HttpListener
    'configure the URI prefixes that will map to the HttpListener
    listener.Prefixes.Add("http://localhost:19080/VisualBasicRecipes/")
    listener.Prefixes.Add("http://localhost:20000/Recipe11-05/")

    'Start the HttpListener before listening for incoming requests.
    Console.WriteLine("Starting HTTP Server")
    listener.Start()
    Console.WriteLine("HTTP Server started")
    Console.WriteLine(Environment.NewLine)

    'create a number of asynchronous request handlers up to the configurable maximum
    'give each a unique identifier
    For count As Integer = 1 To maxRequestHandlers
    listener.BeginGetContext(AddressOf RequestHandler, "RequestHandler_" & Interlocked.Increment(requestHandlerID))
    Next

    'wait for the user to stop the HttpListener
    Console.WriteLine("Press Enter to stop the HTTP Server.")
    Console.ReadLine()

    'stop accepting new requests
    listener.Stop()

    'Terminate the HttpListener without procesing current requests
    listener.Abort()
    End Sub

    'a method to asynchronously process individual requests and send responses
    Private Shared Sub RequestHandler(ByVal result As IAsyncResult)
    Console.WriteLine("{0}: Activated.", result.AsyncState)
    Try
    'obtain the HttpListenerContext for the new request
    Dim context As HttpListenerContext = listener.EndGetContext(result)

    Console.WriteLine("{0}: Processing HTTP Request from {1} ({2}).", result.AsyncState, context.Request.UserHostName, context.Request.RemoteEndPoint)

    'Build the response using a StreamWriter feeding the Response.OutputStream
    Dim sw As New StreamWriter(context.Response.OutputStream, Encoding.UTF8)
    sw.WriteLine("")
    sw.WriteLine("")
    sw.WriteLine("title>Visual Basic Recipes")
    sw.WriteLine("")
    sw.WriteLine("")
    sw.WriteLine("Recipe 11-05: " & result.AsyncState)
    sw.WriteLine("")
    sw.WriteLine("")
    sw.Flush()

    'configure th response
    context.Response.ContentType = "text/html"
    context.Response.ContentEncoding = Encoding.UTF8

    'close the response to send it to the client
    context.Response.Close()

    Console.WriteLine("{0}: Sent HTTP response.", result.AsyncState)

    Catch ex As ObjectDisposedException
    Console.WriteLine("{0}: HttpListener disposed--shutting down.", result.AsyncState)
    Finally
    'start another handler unless the HttpListener is closing.
    If listener.IsListening Then
    Console.WriteLine("{0}: Creating new request handler.", result.AsyncState)
    listener.BeginGetContext(AddressOf RequestHandler, "RequestHandler_" & Interlocked.Increment(requestHandlerID))
    End If

    End Try
    End Sub
    End Class
    End Namespace

    Monday, October 17, 2011

    Monday 10.17.11

    Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Calendar1.SelectionChanged
    lblDates.Text = "You selected" & Calendar1.SelectedDate.ToLongDateString()
    End Sub

    Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs) Handles Calendar1.DayRender
    If e.Day.IsWeekend Then
    e.Cell.BackColor = System.Drawing.Color.Green
    e.Cell.ForeColor = System.Drawing.Color.Yellow
    e.Day.IsSelectable = False
    End If
    End Sub



    Partial Class ViewStateTest
    Inherits System.Web.UI.Page

    Protected Sub cmdSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSave.Click
    'save the current text
    SaveAllText(Page.Controls, True)
    End Sub


    Private Sub SaveAllText(ByVal controls As ControlCollection, ByVal saveNested As Boolean)
    For Each Control As Control In controls
    If TypeOf Control Is TextBox Then
    'store the text using the unique control id
    ViewState(Control.ID) = (CType(Control, TextBox)).Text
    End If

    If (Control.Controls IsNot Nothing) AndAlso saveNested Then
    SaveAllText(Control.Controls, True)
    End If
    Next
    End Sub

    Protected Sub cmdRestore_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRestore.Click
    RestoreAllText(Table1.Controls, True)
    End Sub

    Private Sub RestoreAllText(ByVal controls As ControlCollection, ByVal saveNested As Boolean)
    For Each Control As Control In controls
    If TypeOf Control Is TextBox Then
    If ViewState(Control.ID) IsNot Nothing Then
    CType(Control, TextBox).Text = CStr(ViewState(Control.ID))
    End If
    End If
    If (Control.Controls IsNot Nothing) AndAlso saveNested Then
    RestoreAllText(Control.Controls, True)
    End If
    Next
    End Sub
    End Class


    public partial class DetailsView : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (IsPostBack)
    {
    StringBuilder info = new StringBuilder();
    info.AppendFormat("You are viewing record {0} of {1}
    ",
    CustomerDetails.DataItemIndex.ToString(),
    CustomerDetails.DataItemCount.ToString());

    for (int i = 0; i < CustomerDetails.DataKeyNames.Length; i++)
    {
    info.AppendFormat("{0} : {1}
    ", CustomerDetails.DataKeyNames[i], CustomerDetails.DataKey.Values[i]);
    }

    info.AppendFormat("Selected Value: {0}", CustomerDetails.SelectedValue.ToString());

    lblInfo.Text = info.ToString();
    }
    }

    Saturday, October 15, 2011

    Saturday 10.15.11

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

    'index on string
    Default Public Property Item(ByVal index As String) As String
    Get
    If index.Length = 0 Then
    'handle bad index
    Else
    Return strings(findString(index))
    End If
    End Get
    Set(ByVal value As String)
    strings(findString(index)) = value
    End Set
    End Property

    'helper method given a string find first matchign record that starts with the target
    Private Function findString(ByVal searchString As String) As Integer
    Dim i As Integer
    For i = 0 To strings.Length - 1
    If strings(i).StartsWith(searchString) Then
    Return i
    End If
    Next
    Return -1
    End Function

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

    Public Class tester


    Public Sub Run()
    'craete 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
    'add a few strings
    lbt.Add("Who")
    lbt.Add("Is")
    lbt.Add("John")
    lbt.Add("Galt")

    Console.WriteLine(vbCrLf & "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
    lbt("Hel") = "GoodBye"

    'access all the strings
    Console.WriteLine(vbCrLf & "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


    Partial Class SelectableList
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    If (Not Page.IsPostBack) Then
    For i As Integer = 3 To 5
    ListBox1.Items.Add("Option " & i.ToString())
    DropdownList1.Items.Add("Option " & i.ToString())
    CheckboxList1.Items.Add("Option " & i.ToString())
    RadiobuttonList1.Items.Add("Option " & i.ToString())
    Next i
    End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Response.Write("<b>Selected items for Listbox1:</b><br />")
    For Each li As ListItem In ListBox1.Items
    If li.Selected Then
    Response.Write("- " & li.Text & "<br />")
    End If
    Next
    Response.Write("<b>Selected item for DropdownList1:</b><br/>")
    Response.Write("- " & DropdownList1.SelectedItem.Text & "<br />")

    Response.Write("<b>selected items for CheckboxList1:</b><br />")
    For Each li As ListItem In CheckboxList1.Items
    If li.Selected Then
    Response.Write("- " & li.Text & "<br />")
    End If
    Next
    End Sub

    End Class

    Friday, October 14, 2011

    Friday 10.14.11

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

    namespace RetrieveSingleValueFromQuery
    {
    class Program
    {
    //the ExecuteScalar() method of the Command object returns a single value from the dta soruce rather than a collection of records as
    //a table or data stream
    static void Main(string[] args)
    {
    string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress; Integrated security=SSPI; Initial Catalog=AdventureWorks;";

    string sqlSelect = "SELECT COUNT(*) FROM Person.Contact";

    SqlConnection connection = new SqlConnection(sqlConnectString);

    //create the scalar command and open the connection
    SqlCommand command = new SqlCommand(sqlSelect, connection);
    connection.Open();

    //execute the scalar SQl statement and store resuts.
    int count = Convert.ToInt32(command.ExecuteScalar());
    connection.Close();

    Console.WriteLine("Record count in Person.Contact = {0}", count);

    Console.WriteLine();
    Console.ReadLine();
    }
    }
    }


    using System;
    using System.Data.SqlClient;

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

    string sqlSelect = "SELECT ContactID, FirstName, LastName FROM Person.Contact " +
    "WHERE ContactID BETWEEN 10 and 14";


    SqlConnection connection = new SqlConnection(sqlConnectString);

    //create the command and open the conneciton
    SqlCommand command = new SqlCommand(sqlSelect, connection);
    connection.Open();

    //create the DataReader to retrieve data
    using (SqlDataReader dr = command.ExecuteReader())
    {
    while (dr.Read())
    {
    //output fields from DataReader row
    Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", dr["ContactID"], dr["LastName"], dr["FirstName"]);
    }
    }
    connection.Close();
    }
    }
    }


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

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

    string sqlSelect = @"SELECT ContactID, NameStyle, Title, FirstName, MiddleName, LastName, Suffix, EmailAddress, EmailPromotion, Phone, PasswordHash, PasswordSalt FROM Person.Contact";

    SqlConnection connection = new SqlConnection(sqlConnectString);

    //create the command and open the connection
    SqlCommand command = new SqlCommand(sqlSelect, connection);
    connection.Open();

    SqlDataReader dr = command.ExecuteReader();
    dr.Read();

    //output fields from the first DataRow reader using different techniques
    Console.WriteLine("ContactID = {0}", dr[0]);
    Console.WriteLine("Title = {0}", dr["Title"]);
    Console.WriteLine("FirstName = {0}", dr.IsDBNull(3) ? "NULL" : dr.GetString(3));
    Console.WriteLine("MiddleName = {0}", dr.IsDBNull(4) ? "NULL" : dr.GetSqlString(4));
    Console.WriteLine("LastName = {0}", dr.IsDBNull(5) ? "NULL" : dr.GetSqlString(5).Value);
    Console.WriteLine("EmailAddress = {0}", dr.GetValue(7));
    Console.WriteLine("EmailPromotion = {0}", int.Parse(dr["EmailPromotion"].ToString()));

    //get the column ordinal for the Phone attribute and use it to output the column
    int coPhone = dr.GetOrdinal("Phone");
    Console.WriteLine("Phone = {0}", dr[coPhone]);

    //get the column name for the PasswordHash attribute
    //and use it to output the column
    string cnPasswordHash = dr.GetName(10);
    Console.WriteLine("PasswordHash = {0}", dr[cnPasswordHash]);

    //create an object array and load the row into it
    object[] o = new object[dr.FieldCount];
    //output the passwordsalt attribute from the object array
    dr.GetValues(o);
    Console.WriteLine("PasswordSalt = {0}", o[11].ToString());
    }
    }
    }

    Wednesday, October 12, 2011

    Wednesday 10.12.11

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

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

    string sqlDelete = "DELETE FROM ExecuteQueryNoResultSet " +
    "WHERE Id = 2";

    //create and execute a command to delete the record with Id=2 from the table ExecuteQueryNoResultSet
    SqlConnection connection = new SqlConnection(sqlConnectString);
    SqlCommand command = new SqlCommand(sqlDelete, connection);
    connection.Open();
    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine("{0} row(s) affected.", rowsAffected);
    Console.WriteLine("Record with Id = 2 deleted.");
    connection.Close();

    Console.ReadKey();
    }
    }
    }

    Tuesday, October 11, 2011

    Tuesday 10.11.11

    Imports System
    Imports System.Data
    Imports System.Data.SqlClient

    Namespace Apress.VisualBasicRecipes.Chapter08

    Public Class Recipe08_07

    Public Shared Sub Main()
    'create a new SqlConnection object
    Using con As New SqlConnection

    'configure the SqlConnection object's connection string.
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;Integrated Security=SSPI"

    'create and configure a new command
    Using com As SqlCommand = con.CreateCommand
    com.CommandType = CommandType.Text
    com.CommandText = "SELECT e.BirthDate, c.FirstName, c.LastName FROM HumanResources.Employee e INNER JOIN Person.Contact c ON e.EmployeeID = c.ContactID " & _
    " ORDER BY e.BirthDate; SELECT * FROM humanResources.Employee"

    'open the database connection and execute the example commands through the conneciton
    con.Open()

    'execute the command and obtain a DataReader
    Using reader As SqlDataReader = com.ExecuteReader

    Console.WriteLine("Employee Birthdays (By Age).")
    While reader.Read
    'process the first set of results and display the content of the result set
    Console.WriteLine("{0,18:D} - {1} {2}", reader.GetDateTime(0), reader("FirstName"), reader(2))
    End While
    Console.WriteLine(Environment.NewLine)
    'process the second set of results and display details
    'abotu the columns and data types in the result set.


    End Using
    con.Close()
    End Using
    End Using
    End Sub
    End Class

    End Namespace


    Imports System
    Imports System.Xml
    Imports System.Data
    Imports System.Data.SqlClient

    Namespace Apress.VisualBasicRecipes.Chapter08

    Public Class Recipe08_08

    Public Shared Sub ConnectedExample()
    'create a new SqlConnection object
    Using con As New SqlConnection
    'configure the SqlConnection object's connection strin.
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;Integrated Security=SSPI;"
    'create and configure a new command that includes the FOR XML AUTO clause.
    Using com As SqlCommand = con.CreateCommand

    com.CommandType = CommandType.Text
    com.CommandText = "SELECT DepartmentID, [Name], " & _
    "GroupName FROM HumanResources.Department FOR XML AUTO"
    'open the database connection
    con.Open()

    'execute the command and retrieve and XmlReader to access the results
    Using reader As XmlReader = com.ExecuteXmlReader
    'loop through the reader
    While reader.Read
    'make sure we are dealing with an actual element of some type
    If reader.NodeType = XmlNodeType.Element Then
    'create an XElement object based on the current contents of the reader
    Dim currentEle As XElement = XElement.ReadFrom(reader)
    'display the anme of the current element and list any attributes that it may have
    Console.WriteLine("Element: {0}", currentEle.Name)
    If currentEle.HasAttributes Then
    For i As Integer = 0 To currentEle.Attributes.Count - 1
    Console.Write("{0}: {1}", currentEle.Attributes()(i).Name, currentEle.Attributes()(i).Value)
    Next
    End If
    End If
    End While
    End Using
    'close the database conneciton
    con.Close()
    End Using
    End Using
    End Sub

    Public Shared Sub DisconnectedExample()

    'thsi will be used to create the new XML document
    Dim doc As New XDocument
    'create a new SqlConnection object
    Using con As New SqlConnection

    'configure the SqlConnection object's connection string
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress; Database=AdventureWorks;Integrated Security=SSPI;"

    'create and configure a new command that includes the FOR XML AUTO clause
    Using com As SqlCommand = con.CreateCommand


    com.CommandType = CommandType.Text
    com.CommandText = "SELECT DepartmentID, [Name], GroupName FROM HumanResources.Department FOR XML AUTO;"

    'open the database connection
    con.Open()

    'Execute the command and retrieve and XmlReader to access the results
    Using reader As XmlReader = com.ExecuteXmlReader
    'create the parent element for the results
    Dim root As XElement =
    'loop through the reader and add each node as a child to the root
    While reader.Read

    'we need to make sur ewe are only dealing with some form of an element
    If reader.NodeType = XmlNodeType.Element Then
    Dim newChild As XNode = XElement.ReadFrom(reader)
    root.Add(newChild)
    End If

    End While

    'finally add the root element (and all of it its children
    'to the new xml document.
    doc.Add(root)
    End Using


    End Using
    'close the database connection
    con.Close()
    End Using
    End Sub

    Public Shared Sub Main()
    ConnectedExample()
    Console.WriteLine(Environment.NewLine)
    DisconnectedExample()
    Console.WriteLine(Environment.NewLine)
    End Sub
    End Class
    End Namespace

    Monday, October 10, 2011

    Monday 10.10.11

    Imports System
    Imports System.Linq
    Imports System.Diagnostics

    Namespace Apress.VisualBasicRecipes.Chapter06
    Public Class Recipe06_14
    Public Shared Sub Main()

    'array to hold a set of strings
    Dim myWishList = New String() {"XBox 360", "Rolex", "Serenity", "iPod iTouch", "Season 3 of BSG", "Dell XPS", "Halo 3"}

    'an array holding a second set of strings
    Dim myShoppingCart = New String() {"Shrek", "Swatch (Green)", "Sony Walkman", "XBox 360", "Season 3 of the Golden Girls", "Serenity"}

    ' returns elemnts from myWishList that are NOT in myShoppingCart
    Dim result1 = myWishList.Except(myShoppingCart)

    Console.WriteLine("Items in the wish list that were not in the shopping cart:")
    For Each item In result1
    Console.WriteLine(item)
    Next
    Console.WriteLine()

    'returns elements that are common in both myWishList and myShoppingCart
    Dim result2 = myWishList.Intersect(myShoppingCart)

    Console.WriteLine("Matching items from both lists:")
    For Each Item In result2
    Console.WriteLine(Item)
    Next
    Console.WriteLine()

    'returns all elements from myWishList and myShoppingCart without duplicates
    Dim result3 = myWishList.Union(myShoppingCart)

    Console.WriteLine("All items from both lists (no duplicates):")
    For Each item In result3
    Console.WriteLine(item)
    Next

    Console.WriteLine()

    'returns all elements from myWishList and myShoppingCart including duplicates
    Dim result4 = myWishList.Concat(myShoppingCart)

    Console.WriteLine("All items from both lists (with duplicates):")
    For Each item In result4
    Console.WriteLine(item)
    Next

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


    End Sub

    End Class
    End Namespace


    Imports System
    Imports System.Linq
    Imports System.Diagnostics

    Namespace Apress.VisualBasicRecipes.Chapter06
    Public Class Recipe06_15
    Public Class Tool
    Public Name As String
    End Class

    Public Class Clothes
    Public Name As String
    End Class

    Public Shared Sub Main()
    'from example - nongeneric collection

    Dim employeeList As New ArrayList
    employeeList.Add("Todd")
    employeeList.Add("Alex")
    employeeList.Add("Joe")
    employeeList.Add("Todd")
    employeeList.Add("Ed")
    employeeList.Add("David")
    employeeList.Add("Mark")

    'you can't normall use standard query operators on an ArrayList (IEnumberable) unless you strongly type the From clause
    'Strongly typeing the From clause creates a call to the Cast function, shown below.
    Dim queryableList = employeeList.Cast(Of String)()
    Dim query = From name In queryableList

    For Each name In query
    Console.WriteLine(name)
    Next

    Dim shoppingCart As New ArrayList

    shoppingCart.Add(New Clothes With {.Name = "Shirt"})
    shoppingCart.Add(New Clothes With {.Name = "Socks"})
    shoppingCart.Add(New Tool With {.Name = "Hammer"})
    shoppingCart.Add(New Clothes With {.Name = "Hat"})
    shoppingCart.Add(New Tool With {.Name = "Screw Driver"})
    shoppingCart.Add(New Clothes With {.Name = "Pants"})
    shoppingCart.Add(New Tool With {.Name = "Drill"})

    'attempting to iterate through the results would generate
    ' an InvalidCastException because some items cannot be cast
    ' to the appropriate type. However, some items maybe becast prior to hitting the exception.
    Dim queryableList2 = shoppingCart.Cast(Of Clothes)()

    Console.WriteLine("Cast (using Cast) all items to 'clothes':")
    Try
    For Each item In queryableList2
    Console.WriteLine(item.Name)
    Next
    Catch ex As Exception
    Console.WriteLine(ex.Message)
    End Try
    Console.WriteLine()

    'oftype is similar to cast but wouldn't cause thet exception as shown in the previous example
    'only the items that can be successfully cast will be returned
    Dim queryableList3 = shoppingCart.OfType(Of Clothes)()

    Console.WriteLine("Cast (using OfType) all items to 'Clothes':")
    For Each item In queryableList3
    Console.WriteLine(item.Name)
    Next
    End Sub



    End Class
    End Namespace


    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Data.OleDb

    Namespace Apress.VisualBasicRecipes.Chapter08

    Public Class Recipe08_01

    Public Shared Sub SqlConnectionExample()

    'Configure an empty SqlConnectino object
    Using con As New SqlConnection
    'Configure the SqlConnection object's connection string.
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;Integrated Security=SSPI;"
    'open the database connection
    con.Open()

    'display the information about the connection

    If con.State = ConnectionState.Open Then
    Console.WriteLine("SqlConnection Information:")
    Console.WriteLine(" Connection State = " & con.State)
    Console.WriteLine(" Connection String = " & con.ConnectionString)
    Console.WriteLine(" Database Source = " & con.DataSource)
    Console.WriteLine(" Database = " & con.Database)
    Console.WriteLine(" Server Version = " & con.ServerVersion)
    Console.WriteLine(" Workstation Id = " & con.WorkstationId)
    Console.WriteLine(" Timeout = " & con.ConnectionTimeout)
    Console.WriteLine(" Packet Size = " & con.PacketSize)
    Else
    Console.WriteLine("SqlConnection failed to open.")
    Console.WriteLine("Conenction State = " & con.State)
    End If

    con.Close()
    End Using
    End Sub


    Public Shared Sub OleDbConnectionExample()
    Using con As New OleDbConnection
    'configue the SqlConnection object's connection string.
    con.ConnectionString = "Provider=SQLOLEDB; Data Source=Alfred-PC\SQLExpress;Initial Catalog=AdventureWorks; Integrated Security=SSPI;"
    'open the database conncetion
    con.Open()

    'display the information about the connection
    If con.State = ConnectionState.Open Then
    Console.WriteLine("OleDbConnection Information:")
    Console.WriteLine(" Connection State = " & con.State)
    Console.WriteLine(" Connection String = " & con.ConnectionString)
    Console.WriteLine(" Database Source = " & con.DataSource)
    Console.WriteLine(" Database = " & con.Database)
    Console.WriteLine(" Server Version = " & con.ServerVersion)
    Console.WriteLine(" Timeout = " & con.ConnectionTimeout)
    Else
    Console.WriteLine("OleDbConnection failed to open.")
    Console.WriteLine(" Connection State = " & con.State)
    End If

    con.Close()

    End Using
    End Sub
    Public Shared Sub Main()
    'open the connection using SqlConnection
    SqlConnectionExample()
    Console.WriteLine()
    'open conneciton using OleDbConnection
    OleDbConnectionExample()
    Console.WriteLine(Environment.NewLine)



    End Sub

    End Class

    End Namespace


    Imports System
    Imports System.Data.SqlClient

    Namespace Apress.VisualBasicRecipes.Chapter08
    Public Class Recipe08_02

    Public Shared Sub Main()

    'obtain a pooled connection
    Using con As New SqlConnection
    'configue the SqlConnection object's connection string.
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;" & _
    "Integrated Security=SSPI;Min Pool Size=5;Max Pool Size=15;" & _
    "Connection Reset=True;Connection Lifetime=600;Pooling=True;"

    'open the database conenction.
    con.Open()



    'access the database

    'close the database connection
    'this returns the connection to the pool for reuse.
    con.Close()

    'at the end of the using block, the Dispose class Close
    'which returns the connection back to the pool for reuse

    End Using
    'Obtain a nonpooled connection
    Using con As New SqlConnection
    'configure the SqlConnection object's connection string.
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;Integrated Security=SSPI;Pooling=False;"
    'open the database connection
    con.Open()

    'access the database
    con.Close()
    End Using


    End Sub

    End Class

    End Namespace


    Imports System
    Imports System.Data.SqlClient

    Namespace Apress.VisualBasicRecipes.Chapter08
    Public Class Recipe08_03

    Public Shared Sub Main()
    'configure the SqlConnection object's connection string
    Dim conString As String = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;Integrated Security=SSPI;Min Pool Size=5;Max Pool Size=15;" & _
    "Connection Lifetime=600;"

    'parse the SQL Server connection string an display the component configuration parameters
    Dim sb1 As New SqlConnectionStringBuilder(conString)

    Console.WriteLine("Parsed SQL Connection String Parameters:")
    Console.WriteLine(" Database Source = " & sb1.DataSource)
    Console.WriteLine(" Database = " & sb1.InitialCatalog)
    Console.WriteLine(" Use Integrated Security = " & sb1.IntegratedSecurity)

    Console.WriteLine(" Min Pool SIze = " & sb1.MinPoolSize)
    Console.WriteLine(" Max Pool Size = " & sb1.MaxPoolSize)
    Console.WriteLine(" LIfetime = " & sb1.LoadBalanceTimeout)

    'build a connection string frmo component parameters and display it
    Dim sb2 As New SqlConnectionStringBuilder(conString)

    sb2.DataSource = "Alfred-PC\SQLExpress"
    sb2.InitialCatalog = "AdventureWorks"
    sb2.IntegratedSecurity = True
    sb2.MinPoolSize = 5
    sb2.MaxPoolSize = 15
    sb2.LoadBalanceTimeout = 700

    Console.WriteLine()
    Console.WriteLine("Constructed connection string:")
    Console.WriteLine(" " & sb2.ConnectionString)

    'wait to continue
    Console.WriteLine()
    Console.ReadLine()


    End Sub

    End Class

    End Namespace


    Imports System
    Imports System.Data
    Imports System.Data.SqlClient

    Namespace Apress.VisualBasicRecipes.Chapter08

    Public Class Recipe08_05

    Public Shared Sub ExecuteNonQueryExample(ByVal con As IDbConnection)

    'create and configure a new command.
    Dim com As IDbCommand = con.CreateCommand
    com.CommandType = CommandType.Text
    com.CommandText = "UPDATE HumanResources.Employee SET Title = " & _
    "'Production Supervisor' WHERE EmployeeID = 24;"

    'execute the command and process the result.
    Dim result As Integer = com.ExecuteNonQuery
    If result = 1 Then
    Console.WriteLine("Employee Title updated.")
    ElseIf result > 1 Then
    Console.WriteLine("{0} employee titles updated.", result)
    Else
    Console.WriteLine("Emploee title not updated.")
    End If
    End Sub


    Public Shared Sub ExecuteReaderExample(ByVal con As IDbConnection)
    'create and configure a new command
    Dim com As IDbCommand = con.CreateCommand
    com.CommandType = CommandType.Text
    com.CommandText = "SET ROWCOUNT 10; SELECT " & _
    "Production.Product.Name, Production.Product.ListPrice FROM " & _
    "Production.Product ORDER BY Production.Product.ListPrice DESC; SET ROWCOUNT 0;"

    'execute the command and process the results
    Using reader As IDataReader = com.ExecuteReader

    While reader.Read
    'display the product details.
    Console.WriteLine(" {0} = {1}", reader("Name"), reader("ListPrice"))
    End While
    End Using
    End Sub

    Public Shared Sub ExecuteScalarExample(ByVal con As IDbConnection)
    'create and configure a new command
    Dim com As IDbCommand = con.CreateCommand
    com.CommandType = CommandType.Text
    com.CommandText = "SELECT COUNT(*) FROM HumanResources.Employee;"

    'execute the command and cast the result
    Dim result As Integer = CInt(com.ExecuteScalar)

    Console.WriteLine("Employee count = " & result)
    End Sub

    'the example in this recipe demonstrates hwo to use a command object to execute a few different
    'sql statements against a database.

    Public Shared Sub Main()
    'create a new SqlConnection object
    Using con As New SqlConnection
    'configure the SqlConnection object's connection string
    con.ConnectionString = "Data Source=Alfred-PC\SQLExpress;Database=AdventureWorks;Integrated Security=SSPI;"

    'open the database connection and execute the example commands through the connection
    con.Open()

    ExecuteNonQueryExample(con)
    Console.WriteLine(Environment.NewLine)
    ExecuteReaderExample(con)
    Console.WriteLine(Environment.NewLine)
    ExecuteScalarExample(con)
    Console.WriteLine(Environment.NewLine)

    'close the database connection.
    con.Close()
    End Using
    End Sub

    End Class
    End Namespace

    Friday, October 7, 2011

    October 7th 2011 Friday

    Partial Class ServerControls
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim table1 As New HtmlTable()
    'set the table's formatting-related properties
    table1.Border = 1
    table1.CellPadding = 3
    table1.CellSpacing = 3
    table1.BorderColor = "red"

    'start adding content to the table
    Dim row As HtmlTableRow
    Dim cell As HtmlTableCell
    For i As Integer = 1 To 5
    'create a new row, and set its background color.
    row = New HtmlTableRow()
    If i Mod 2 = 0 Then
    row.BgColor = ("lightyellow")
    Else
    row.BgColor = ("lightcyan")
    End If

    For j As Integer = 1 To 4
    'create a cell and set its text
    cell = New HtmlTableCell()
    cell.InnerHtml = "Row: " & i.ToString() & "
    Cell: " & j.ToString()

    'add the cell to the current row
    row.Cells.Add(cell)
    Next j
    'add teh rows to the table
    table1.Rows.Add(row)
    Next i
    'add the table to the apge.
    Me.Controls.Add(table1)
    End Sub
    End Class


    Partial Class ServerSideEvents
    Inherits System.Web.UI.Page


    Protected Sub Ctrl_ServerChange(ByVal sender As Object, ByVal e As System.EventArgs) Handles Textbox1.ServerChange
    Response.Write("
  • SeverChange detected for " & (CType(sender, Control)).ID & "
  • ")
    End Sub

    Public Sub List1_ServerChanage(ByVal sender As Object, ByVal e As System.EventArgs) Handles List1.ServerChange
    Response.Write("
  • ServerChange detected for List1." & " The selected items are:

  • ")
    For Each li As ListItem In List1.Items
    If li.Selected Then
    Response.Write(" - " & li.Value & "
    ")
    End If
    Next
    End Sub

    Protected Sub Submit1_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.ServerClick
    Response.Write("
  • ServerClick ddetected for Submit1.
  • ")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If (Not Page.IsPostBack) Then
    List1.Items.Add("Option 3")
    List1.Items.Add("Option 4")
    List1.Items.Add("Option 5")
    End If
    End Sub
    End Class


    Imports System
    Imports System.Linq
    Imports System.Diagnostics

    Namespace Apress.VisualBasicRecipes.Chapter06
    Public Class Recipe06_13
    'this field holds the size of our pages.
    Private Shared pageSize As Integer = 10
    Private Const Five_MB = 3 * (1024 * 1024)
    Public Shared Sub Main()
    'use LINQ to retrieve a List(Of Process) List of processes that are using more
    'than 5MB of memory. The ToList method is used to force the query to execute immediately
    'and save the results in the procs variable so they can be reused
    Dim procs = (From proc In Process.GetProcesses.ToList _
    Where proc.WorkingSet64 > Five_MB _
    Order By proc.ProcessName _
    Select proc).ToList

    Dim totalPages As Integer

    'determine the exact number of pages of information
    'available for display
    totalPages = Math.Floor(procs.Count / pageSize)
    If procs.Count Mod pageSize > 0 Then totalPages += 1

    Console.WriteLine("List of processes with memory usage over 5 MB:")
    Console.WriteLine("")

    'Loop and Display Each Page of Data
    For i = 0 To totalPages - 1
    Console.WriteLine("PAGE {0} OF {1}", i + 1.ToString(), totalPages.ToString())
    'query the procs collection and return a single page
    'of proceses using the Skip and Take clauses.
    Dim currentPage = From proc In procs _
    Skip i * pageSize Take pageSize

    'loop through all the process records for the current page
    For Each proc In currentPage
    Console.WriteLine("{0,-20} - {1,5} MB", proc.ProcessName, (proc.WorkingSet64 / (1024 * 1024)).ToString("#.00"))
    Next
    'check whether there are any more pages.
    If Not i = totalPages - 1 Then
    Console.WriteLine("Press Enter for the next page.")
    Console.ReadLine()
    End If
    Next
    Console.WriteLine("No more data available. Press Enter to end.")
    Console.ReadLine()



    End Sub
    End Class
    End Namespace

    Wednesday, October 5, 2011

    Wednesay 8.05.11

    Partial Class SettingStyleAttributes
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'perform the initialization only the first time the page is requested
    'after that, this information is tracked in view state
    If (Not Page.IsPostBack) Then
    'set the style attributes to configure appearance
    TextBox1.Style("font-size") = "20px"
    TextBox1.Style("color") = "red"
    'use a slightly different but equivalent syntax
    'for setting a style attribute
    TextBox1.Style.Add("background-color", "lightyellow")
    'set the default text.
    TextBox1.Text = ""
    'set other nonstandard attributes.
    TextBox1.Attributes("onfocus") = "alert(TextBox1.value)"
    End If

    End Sub
    End Class

    Tuesday, October 4, 2011

    October 4th 2011

    Partial Class PageFlow
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    lblInfo.Text &= "Page.Load event handled.
    "
    If Page.IsPostBack Then
    lblInfo.Text &= "This is the second time you've seen this page.
    "
    End If
    End Sub

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    lblInfo.Text &= "Page.Init event handled.
    "
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    lblInfo.Text &= "Page.PreRender event handled.
    "
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs)
    'this text never appears because the html is already rendered for the page at this point
    lblInfo.Text &= "Page.Unload event handled.
    "
    End Sub
    End Class


    Partial Class MyControls
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'start examining all the controls.
    DisplayControl(Page.Controls, 0)
    'add the closing horizontal line
    Response.Write("
    ")
    End Sub

    Private Sub DisplayControl(ByVal controls As ControlCollection, ByVal depth As Integer)
    For Each cControl As Control In controls
    'use the depth parameter to indent the control tree.
    Response.Write(New String("-"c, depth * 4) & "> ")
    'display this control
    Response.Write(cControl.GetType().ToString() & " - " _
    & cControl.ID & "

    ")
    If cControl.Controls IsNot Nothing Then
    DisplayControl(cControl.Controls, depth + 1)
    End If
    Next
    End Sub
    End Class

    Monday, October 3, 2011

    Monday 10.03.11

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

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

    string sqlSelect =
    "SELECT ContactID, FirstName, LastName FROM Person.Contact " +
    "WHERE ContactID BETWEEN 10 AND 13";

    //create a data adapter
    SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);

    //fill a DataTable using DataAdapter
    DataTable dt = new DataTable();
    da.Fill(dt);

    //create and fill the DataRow array
    DataRow[] dra = new DataRow[dt.Rows.Count];
    dt.Rows.CopyTo(dra, 0);

    //access DataRow array FirstName value in row 3
    //using different techniques

    Console.WriteLine("FirstName = {0}", dra[2][1]);
    Console.WriteLine("FirstName = {0}", dra[2]["FirstName"]);
    Console.WriteLine("FirstName = {0}", dra[2]["FirstName", DataRowVersion.Default]);
    Console.WriteLine("FirstName = {0}", dra[2].Field(1));
    Console.WriteLine("FirstName = {0}", dra[2].Field("FirstName"));
    Console.WriteLine("Firstname = {0}", dra[2].Field("FirstName", DataRowVersion.Default));

    Console.ReadKey();
    }
    }
    }


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

    namespace CreateStronglyTypedDataSetXsd
    {
    class Program
    {
    static void Main(string[] args)
    {
    string xsdFileName = @"..\..\AdventureWorks.xsd";

    string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" +
    "Integrated security=SSPI; Initial Catalog=AdventureWorks;";

    string sqlText = "SELECT * FROM Sales.SalesOrderHeader;" +
    "SELECT * FROM Sales.SalesOrderDetail;";

    //create and fill a DataSet schema using a data adapter
    SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConnectString);
    da.TableMappings.Add("Table", "SalesOrderHeader");
    da.TableMappings.Add("Table1", "SalesOrderDetail");
    DataSet ds = new DataSet("AdventureWorks");
    da.FillSchema(ds, SchemaType.Mapped);
    //add the data relation
    ds.Relations.Add("SalesOrderHeader_SalesOrderDetail",
    ds.Tables["SalesOrderHeader"].Columns["SalesOrderID"],
    ds.Tables["SalesOrderDetail"].Columns["SalesOrderID"]);

    //output teh XSD schema for the DataSet
    ds.WriteXmlSchema(xsdFileName);

    Console.WriteLine("File: {0} created.", xsdFileName);
    Console.WriteLine("\n{ress any key to continue.");
    Console.ReadKey();
    }
    }
    }