Friday, September 30, 2011

Friday 9.30.11

Imports System
Imports System.Linq
Imports System.Diagnostics

Namespace Apress.VisualBasicRecipes.Chapter06
Public Class Recipe06_07

Public Shared Sub Main()
'build the query to return the average and total
'physical memory used by all of the processes
'running on the current machine. The data is returned
'as an anonymous type that contains the aggregate data
Dim aggregateData = Aggregate proc In Process.GetProcesses _
Into AverageMemory = Average(proc.WorkingSet64), _
TotalMemory = Sum(proc.WorkingSet64)

'display the formatted results on the console
Console.WriteLine("Average Allocated Physical Memory: {0,6} MB", (aggregateData.AverageMemory / (1024 * 1024)).ToString("#.00"))
Console.WriteLine("Total Allocated Physical Memory: {0,6} MB", (aggregateData.TotalMemory / (1024 * 1024)).ToString("#.00"))

End Sub
End Class
End Namespace


Imports System
Imports System.Linq
Imports System.Diagnostics

Namespace Apress.VisualBasicRecipes.Chapter06
Public Class Recipe06_08

Public Shared Sub Main()

'build the query to return information for all processes running on the current machine
'the process.threads collection for each process will be counted using the Count method
'the data will be returned as anonymous types containing the name of the process
'and the number of threads
Dim query = From proc In Process.GetProcesses _
Order By proc.ProcessName _
Aggregate thread As ProcessThread In proc.Threads _
Into ThreadCount = Count(thread.Id) _
Select proc.ProcessName, ThreadCount

'run the query generated earlier and iterate through the results
For Each proc In query
Console.WriteLine("The {0} process has {1} threads.", proc.ProcessName, proc.ThreadCount.ToString)
Next
End Sub
End Class
End Namespace


Imports System
Imports System.Linq
Imports System.Diagnostics

Namespace Apress.VisualBasicRecipes.Chapter06
Public Class Recipe06_09

Public Shared Sub Main()
'build the query to return the minimum and maximum
'physical memory allocated by all of the processes
'running on the current machine
'the data is returned as an anonymous type that contain the aggregate data.
Dim aggregateData = Aggregate proc In Process.GetProcesses _
Into MinMemory = Min(proc.WorkingSet64), _
MaxMemory = Max(proc.WorkingSet64)
'display the formatted results on the consol
Console.WriteLine("Minimum Allocated Physical Memory: {0,6} MB", (aggregateData.MinMemory / (1024 * 1024)).ToString("#.00"))
Console.WriteLine("Maximum Allocated Physical Memory: {0, 6} MB", (aggregateData.MaxMemory / (1024 * 1024)).ToString("#.00"))


End Sub
End Class
End Namespace


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

'build the query to return information for all processes
'running on the current machine and group them based on the mathematical floor of the allocated physical
'memory. The count, maximum, and minimum values for each group are calculated and returned as properties of the anonymous type.
'data is returned only for groups that have more than one process

Dim query = From proc In Process.GetProcesses _
Order By proc.ProcessName _
Group By MemGroup = Math.Floor((proc.WorkingSet64 / (1024 * 1024))) _
Into Count = Count(), Max = Max(proc.WorkingSet64), Min = Min(proc.WorkingSet64) _
Where Count > 1 Order By MemGroup

'run the query generated earlier and iterate through the results
For Each result In query
Console.WriteLine("Physical Allocated Memory Group: {0} MB", result.MemGroup)
Console.WriteLine("Minimum amount of physical memory" &
" allocated: {0} ({1})", result.Min, (result.Min / (1024 * 1024)).ToString("#.00"))
Console.WriteLine("Maximum amount of physical memory" &
" allocated: {0} ({1})", result.Max, (result.Max / (1024 * 1024)).ToString("#.00"))
Console.WriteLine()
Next


End Sub

End Class
End Namespace


Public Class Recipe06_11

Public Shared Sub Main()
'store a list of processes that will be monitored or that information
'should be gathered for
Dim processesToMonitor = New String() {"explorer", "iexplore", "lsass", "rundll32", "services", "winlogon", "svchost"}

'build the query to return informaton for all of the processes that should be monitored by joining them to
'the list of all processes running on the current computer.
'The count, maximum, and minimum values for each group are calculated and returned as properties of the anonymous type
'data is returned only for groups that have more than one process
Dim query = From proc In Process.GetProcesses _
Order By proc.ProcessName _
Join myProc In processesToMonitor _
On proc.ProcessName Equals myProc _
Select Name = proc.ProcessName, proc.Id, PhysicalMemory = proc.WorkingSet64

'run the query generated earlier and iterate through the results
For Each proc In query
Console.WriteLine("{0, -10} ({1,5}) - Allocated Physical " & _
" Memory: {2,5} MB", proc.Name, proc.Id, (proc.PhysicalMemory / (1024 * 1024)).ToString("#.00"))
Next
End Sub
End Class

Thursday, September 29, 2011

Wednesday 9.29.11

#include
int main(void)
{
float length, width;

printf("Enter the length of the rectangle:\n");
while (scanf("%f", &length) == 1)
{
printf("Length = %0.2f:\n", length);
printf("Enter its width:\n");
if (scanf("%f", &width) != 1)
{
break;
}
printf("Width = %0.2f:\n", width);
printf("Area = %0.2f:\n", length * width);
printf("Enter the length of the rectangle:\n");
}
printf("Done.\n");
return 0;
}

Tuesday, September 27, 2011

Tuesday 9.27.11

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

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


namespace ConsoleApplication1
{
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 data table using DataAdapter
DataTable dt1 = new DataTable();
da.Fill(dt1);

//output the rows from the table
Console.WriteLine("--foreach loop over DataRowCollection (DataTable 1)---");
foreach (DataRow row in dt1.Rows)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", row["ContactID"], row["FirstName"], row["LastName"]);
}
//create and fill the DataRow array
DataRow[] dra = new DataRow[dt1.Rows.Count];
dt1.Rows.CopyTo(dra, 0);

Console.WriteLine("\n--for loop over DataRow array---");
for (int i = 0; i < dra.Length; i++)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", dra[i].Field("ContactID"), dra[i].Field("FirstName"), dra[i].Field("LastName"));
}

//filling a DataTable from the DataRow array using CopyToDataTable()
DataTable dt2 = dra.CopyToDataTable();
//output the rows from the table
Console.WriteLine("\n---foreach loop over DataRowCollection (DataTable 2)---");
foreach (DataRow row in dt2.Rows)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}", row["ContactID"], row["FirstName"], row["LastName"]);
}

//filling a DataTable from the DataRow array using CopyToDataTable(DataTable, LoadOption)
DataTable dt3 = dt1.Clone();
dra.CopyToDataTable(dt3, LoadOption.Upsert);
Console.WriteLine("\n----foreach loop over DataRowCollection (DataTable 3)---");
foreach (DataRow row in dt3.Rows)
{
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName={2}", row["ContactID"], row["FirstName"], row["LastName"]);
}

}
}
}

Monday, September 26, 2011

Monday 9.26.11

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

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

string sqlSelect = @"SELECT * FROM Sales.SalesOrderHeader; SELECT * FROM Sales.SalesOrderDetail";

DataSet ds = new DataSet();

//Fill the dataSet
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.TableMappings.Add("Table", "SalesOrderHeader");
da.TableMappings.Add("Table1", "SalesOrderDetail");
da.Fill(ds);

//relate the header and order tables in the dataset
DataRelation dr = new DataRelation("SalesOrderHeader_SalesORderDetail",
ds.Tables["SalesOrderHeader"].Columns["SalesOrderID"],
ds.Tables["SalesOrderDetail"].Columns["SalesOrderID"]);
ds.Relations.Add(dr);

//add the customer id column from SalesOrderHeader to the SalesOrderDetail table
ds.Tables["SalesOrderDetail"].Columns.Add("CustomerID", typeof(int), "Parent(SalesOrderHeader_SalesOrderDetail).CustomerID");

//output fields from first three header rows with detail
for (int i = 0; i < 3; i++)
{
DataRow rowHeader = ds.Tables["SalesOrderHeader"].Rows[i];
Console.WriteLine("HEADER: OrderID = {0},CustomerID = {1}",
rowHeader["SalesOrderID"], rowHeader["CustomerID"]);

foreach (DataRow rowDetail in rowHeader.GetChildRows(dr))
{
Console.WriteLine("\tDETAIL: OrderID = {0}, DetailID={1}," +
"CustomerID = {2}",
rowDetail["SalesOrderID"], rowDetail["SalesOrderDetailID"],
rowDetail["CustomerID"]);
}
}
Console.WriteLine("\nPress any key to continue");
Console.ReadKey();
}
}
}


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

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

string sqlSelect = @"SELECT * FROM Sales.SalesOrderHeader; SELECT * FROM Sales.SalesOrderDetail;";

DataSet ds = new DataSet();

//fill the data set
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.TableMappings.Add("Table", "SalesOrderHeader");
da.TableMappings.Add("Table1", "SalesOrderDetail");
da.Fill(ds);

//relate the header and order tables in teh dataset
DataRelation dr = new DataRelation("SalesOrderHeader_SalesOrderDetail",
ds.Tables["SalesOrderHeader"].Columns["SalesOrderID"],
ds.Tables["SalesOrderDetail"].Columns["SalesOrderID"]);
ds.Relations.Add(dr);

//add a column to the SalesOrderHeader table summing all LineTotal valeus in SalesOrderDetail
ds.Tables["SalesOrderHeader"].Columns.Add("SumDetailLineTotal", typeof(decimal), "SUM(Child.LineTotal)");

//output fields from the first three header rows with detail
for (int i = 0; i < 3; i++)
{
DataRow rowHeader = ds.Tables["SalesOrderHeader"].Rows[i];
Console.WriteLine("HEADER: OrderID = {0}, CustomerID = {1}, " +
"SumDetailLineTotal = {2}", rowHeader["SalesOrderID"], rowHeader["CustomerID"],
rowHeader["SumDetailLineTotal"]);

foreach (DataRow rowDetail in rowHeader.GetChildRows(dr))
{
Console.WriteLine("\tDetail: OrderID = {0}, DetailID = {1}, " +
"LineTotal = {2}", rowDetail["SalesOrderID"], rowDetail["SalesOrderDetailID"], rowDetail["LineTotal"]);
}
}
}
}
}


public class Customer
{

public int CustomerID { get; set; }
public string Name { get; set; }
public string City { get; set; }


public Customer()
{}

public DataSet GetCustomers()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Customers");
dt.Columns.Add("CustomerId", typeof(System.Int32));
dt.Columns.Add("CustomerName", typeof(System.String));
dt.Columns.Add("CustomerCity", typeof(System.String));

dt.Rows.Add(new object[] { 1, "Test Customer", "Glasgow" });

ds.Tables.Add(dt);
return ds;
}
}

Friday, September 23, 2011

Monday 9.23.11

public partial class StateBagDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblCounter.Text = Counter.ToString();
Counter++;
}

public int Counter
{
get
{
if (ViewState["intCounter"] != null)
{
return ((int)ViewState["intCounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["intCounter"] = value;
}
}
}

Thursday, September 22, 2011

9.22.11

public partial class SessionStateDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
if (rbl.SelectedIndex != -1)
{
string[] Books = new string[3];
Session["cattext"] = rbl.SelectedItem.Text;
Session["catcode"] = rbl.SelectedItem.Value;
switch (rbl.SelectedItem.Value)
{
case "n":
Books[0] = "Programming C#";
Books[1] = "Programming ASP.NET";
Books[2] = "C# Essentials";
break;
case "d":
Books[0] = "Oracle & Open Source";
Books[1] = "SQL in a Nutshell";
Books[2] = "Transact-SQL Programming";
break;
case "h":
Books[0] = "PC Hardware in a Nutshell";
Books[1] = "Dictionary of PC Hardware and Data Communications Terms";
Books[2] = "Linux Device Drivers";
break;
}
Session["books"] = Books;
}
}

protected void btn_Click(object sender, EventArgs e)
{
{
if (rbl.SelectedIndex == -1)
{
lblMessage.Text = "You must select a book category.";
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("You have selected the category ");
sb.Append((string)Session["cattext"]);
sb.Append(" with code \"");
sb.Append((string)Session["catcode"]);
sb.Append("\".");
lblMessage.Text = sb.ToString();

ddl.Visible = true;
string[] CatBooks = (string[])Session["books"];

//populate the dropdownlist
int i;
ddl.Items.Clear();
for (i = 0; i < CatBooks.GetLength(0); i++)
{
ddl.Items.Add(new ListItem(CatBooks[i]));
}
}
}
}
}

Tuesday, September 20, 2011

Tuesday 9.20.11

public partial class PanelDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//first take care of the panel w/ the dynamically generated controls
//show or hide Panel contents
pnlDynamic.Visible = chkVisible.Checked;

//generate label controls.
int numlabels = Int32.Parse(ddlLabels.SelectedItem.Value);
for (int i = 1; i <= numlabels; i++)
{
Label lbl = new Label();
lbl.Text = "Label" + (i).ToString();
lbl.ID = "Label" + (i).ToString();
pnlDynamic.Controls.Add(lbl);
pnlDynamic.Controls.Add(new LiteralControl("
"));

}

//generate textbox controls
int numBoxes = Int32.Parse(ddlBoxes.SelectedItem.Value);
for (int i = 1; i <= numBoxes; i++)
{
TextBox txt = new TextBox();
txt.Text = "TextBox" + (i).ToString();
txt.ID = "TextBox" + (i).ToString();
pnlDynamic.Controls.Add(txt);
pnlDynamic.Controls.Add(new LiteralControl("
"));
}

}
}

Monday, September 19, 2011

Monday 9.19.11

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

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

//build the SaleOrderHeader(Parent) table
DataTable dtHeader = new DataTable("SalesOrderHeader");

//get the collection of columns from the parent table
DataColumnCollection cols = dtHeader.Columns;

//add the identity field
DataColumn col = cols.Add("SalesOrderID", typeof(System.Int32));
col.AutoIncrement = true;
col.AutoIncrementSeed = -1;
col.AutoIncrementStep = -1;
//add other fields
cols.Add("OrderDate", typeof(System.DateTime)).AllowDBNull = false;
cols.Add("SalesOrderNumber", typeof(System.String)).MaxLength = 25;
cols.Add("TotalDue", typeof(System.Decimal));
//set the primary key
dtHeader.PrimaryKey = new DataColumn[] {cols["SalesOrderID"]};
//add the salesorderheader table to the dataset
ds.Tables.Add(dtHeader);

//-----------------------------------------
//build the order details (child) table
DataTable dtDetail = new DataTable("SalesOrderDetail");

cols = dtDetail.Columns;
//add the pk fields
cols.Add("SalesOrderID", typeof(System.Int32)).AllowDBNull = false;

col = cols.Add("SalesOrderDetailID", typeof(System.Int32));
col.AutoIncrement = true;
col.AutoIncrementSeed = -1;
col.AutoIncrementStep = -1;
//add the other fields
cols.Add("UnitPrice", typeof(System.Decimal)).AllowDBNull = false;
cols.Add("OrderQty", typeof(System.Int16)).AllowDBNull = false;
cols.Add("LineTotal", typeof(System.Decimal));
//set the primary key
dtDetail.PrimaryKey = new DataColumn[] {cols["OrderID"], cols["ProductID"]};
//add the order details table to the dataset
ds.Tables.Add(dtDetail);

//----------------
//add the relation between header and detail tables
ds.Relations.Add("SalesOrderHeader_SalesOrderDetail", dtHeader.Columns["SalesOrderID"], dtDetail.Columns["SalesOrderID"]);

//fill the dataset
string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" +
"Integrated Security=SSPI;Initial Catalog=AdventureWorks;";

string sqlSelect = @"SELECT SalesOrderID, OrderDate, SalesOrderNumber, TotalDue
FROM Sales.SalesOrderHeader
SELECT SalesOrderID, SalesOrderDetailID, UnitPrice, OrderQty, LineTotal
FROM Sales.SalesOrderDetail;";

SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
da.TableMappings.Add("Table", "SalesOrderHeader");
da.TableMappings.Add("Table1", "SalesOrderDetail");
da.Fill(ds);

//output the first three orders with details for each
for (int i = 0; i < 3; i++)
{
DataRow row = ds.Tables["SalesOrderHeader"].Rows[i];
Console.WriteLine("{0}\t{1}\t{2}\t{3}", row[0], row[1], row[2], row[3]);

foreach(DataRow rowChild in row.GetChildRows("SalesOrderHeader_SalesOrderDetail"))
{
Console.WriteLine("\t{0}\t{1}\t{2}\t{3}\t{4}", rowChild[0], rowChild[1], rowChild[2], rowChild[3], rowChild[4]);
}
}

Console.ReadLine();
}
}
}


protected void cblItems_Init(object sender, EventArgs e)
{
//create an array of items to add
string[] Genre = { "SciFi", "Fiction", "Computers", "History", "Religion" };
cblItems.DataSource = Genre;
cblItems.DataBind();
}

protected void cblItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (cblItems.SelectedItem == null)
{
lblCategory.Text = "
No genres selected.";
}
else
{
StringBuilder sb = new StringBuilder();

foreach(ListItem li in cblItems.Items)
{
if(li.Selected)
{
sb.Append("
" + li.Value + " - " + li.Text);
}
}
lblCategory.Text = sb.ToString();
}
}


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//build 2 dimensional array for the lists
//first dimension contains bookname
//2nd dimension contains ISBN number
string[,] books = {
{"Learning ASP.NET 2.0 with AJAX", "9780596513976"},
{"Beginning ASP.NET 2.0 with C#", "9780470042583"},
{"Programming C#", "9780596527433"},
{"Programming .NET 3.5", "978059652756X"},
{"Programming .NET Windows Applications", "0596003218"},
{"Programming ASP.NET 3e", "0596001711"},
{"WebClasses From Scratch", "0789721260"},
{"Teach yourself C++ in 21 Days", "067232072X"},
{"Teach Yourself C++ in 10 Minutes", "067231603X"},
{"XML & Java From Scratch", "0789724766"},
};

//now populate the list
for (int i = 0; i < books.GetLength(0); i++)
{
//add both text and value
ddlBooks.Items.Add(new ListItem(books[i, 0], books[i, 1]));
}
}
}

protected void ddlBooks_SelectedIndexChanged(object sender, EventArgs e)
{
//check to verify that something has been selected
if (ddlBooks.SelectedIndex != -1)
{
lblBookInfo.Text = ddlBooks.SelectedItem.Text + "---->IBSN: " + ddlBooks.SelectedValue;
}
}


public partial class BulletedListDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//build 2 dimensional array for the lists
//first dimension contains bookname
//2nd dimension contains ISBN number
string[,] books = {
{"Learning ASP.NET 2.0 with AJAX", "9780596513976"},
{"Beginning ASP.NET 2.0 with C#", "9780470042583"},
{"Programming C#", "9780596527433"},
{"Programming .NET 3.5", "978059652756X"},
{"Programming .NET Windows Applications", "0596003218"},
{"Programming ASP.NET 3e", "0596001711"},
{"WebClasses From Scratch", "0789721260"},
{"Teach yourself C++ in 21 Days", "067232072X"},
{"Teach Yourself C++ in 10 Minutes", "067231603X"},
{"XML & Java From Scratch", "0789724766"},
};

//now populate the list
for (int i = 0; i < books.GetLength(0); i++)
{
//add both text value
bltBooks.Items.Add(new ListItem(books[i, 0], "http://www.amazon.com/gp/product/" + books[i, 1]));
}
}
}

protected void lbxSelectedIndexChanged(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
string strID = lb.ID;
string strValue = lb.SelectedValue;

switch (strID)
{
case "lbxBulletStyle":
BulletStyle style = (BulletStyle)Enum.Parse(typeof(BulletStyle), strValue);
bltBooks.BulletStyle = style;
break;
case "lbxBulletNumber":
bltBooks.FirstBulletNumber = Convert.ToInt32(strValue);
break;
case "lbxDisplayMode":
BulletedListDisplayMode displayMode = (BulletedListDisplayMode)Enum.Parse(typeof(BulletedListDisplayMode), strValue);
bltBooks.DisplayMode = displayMode;
break;

default: break;
}
}


protected void bltBooks_Click(object sender, BulletedListEventArgs e)
{
BulletedList b = (BulletedList)sender;
tdMessage.InnerHtml = "Selected index: " + e.Index.ToString() + "
" + "Selected value: " +
b.Items[e.Index].Value + "
";
}
}

Sunday, September 18, 2011

Sunday 9.18.11

Imports System
Imports System.Linq
Imports System.Diagnostics

Namespace Apress.VisualBasicRecipes.Chapter06
Public Class Recipe06_01

Public Shared Sub Main()
'build the query to return information for all
'processes running on the current machine. The data will be returned
'as instances of the Process class

Dim procsQuery = From proc In Process.GetProcesses

'run the query generated earlier and iterate
'through the results
For Each proc In procsQuery
Console.WriteLine(proc.ProcessName)
Next
'wait to continue
Console.ReadLine()
End Sub
End Class
End Namespace


Imports System
Imports System.Linq
Imports System.Diagnostics

Namespace Apress.VisualBasicRecipes.Chapter06
Public Class Recipe06_03

Public Shared Sub Main()

'Buil the query to return inforamation for all processes
'running on the current machine
'the data will be returned in the form of anonymous
'types with ID, name, and MemUsed properties

Dim procInfoQuery = From proc In Process.GetProcesses Select proc.Id, Name = proc.ProcessName, _
MemUsed = proc.WorkingSet64
'run the query generated earlier and iterate through the results
For Each proc In procInfoQuery
Console.WriteLine("[{0,5}], {1, -20} - {2}", proc.Id, proc.Name, proc.MemUsed)
Next

'wait to continue
Console.ReadLine()
End Sub
End Class
End Namespace


public partial class RadioButtonDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void grpSize_CheckedChanged(object sender, EventArgs e)
{
if (rdoSize10.Checked)
{
lblTime.Font.Size = 10;
}
else if (rdoSize14.Checked)
{
lblTime.Font.Size = 14;
}
else
{
lblTime.Font.Size = 16;
}
}

protected void lblTime_Init(object sender, EventArgs e)
{
lblTime.Font.Name = "Verdana";
lblTime.Font.Size = 20;
lblTime.Font.Bold = true;
lblTime.Font.Italic = true;
lblTime.Text = DateTime.Now.ToString();
}
}


Friday, September 16, 2011

Imports System.Net
Imports System.Net.Sockets

Public Class Tester
Public Shared Sub Main()
Dim aUri As New Uri("http://www.java2s.com/")
Console.WriteLine(aUri.AbsoluteUri)
Console.WriteLine(aUri.AbsolutePath)

End Sub
End Class


Imports System
Imports System.Net.Sockets

Public Class Tester
Public Shared Sub Main()
Dim myURI As New Uri("http://www.java2s.com:8080")

Console.WriteLine(myURI.Host)
Console.WriteLine(myURI.AbsolutePath)
Console.WriteLine(myURI.AbsoluteUri)
Console.WriteLine(myURI.Port.ToString)
Console.WriteLine(myURI.Scheme)

End Sub
End Class

Wednesday, September 14, 2011

Tuesday 9.14.11

using System;
using System.Globalization;

namespace program
{
class mainClass
{

static void Main()
{
string longString = "7654321";
int actualInt = Int32.Parse(longString);
Console.WriteLine(actualInt);

string dblString = "-7654.321";
double actualDbl = Double.Parse(dblString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign);
Console.WriteLine(actualDbl);

//to convert a string containing a Boolean value to a bool type
//this code requries the use of the System namespace
string boolString = "true";
bool actualBool = Boolean.Parse(boolString);
if(actualBool==true)
{
Console.WriteLine(actualBool);
}
}
}
}


static void Main()
{
string testStr = "school";
foreach (char c in testStr)
{
Console.WriteLine("Char: " + c.ToString());
}

testStr = "abc123";
for (int counter = 0; counter < testStr.Length; counter++)
{
Console.WriteLine(testStr[counter]);
}
}


static void Main()
{
string foo = "--TEST--";
Console.WriteLine(foo.Trim(new char[] { '-' }));

foo = ",-TEST-,-";
Console.WriteLine(foo.Trim(new char[] { '-', ',' }));

foo = "--TEST--";
Console.WriteLine(foo.TrimStart(new char[] { '-' }));

foo = ",-TEST-,-";
Console.WriteLine(foo.TrimStart(new char[] { '-', ',' }));

foo = "--TEST--";
Console.WriteLine(foo.TrimEnd(new char[] { '-' }));

foo = ",-TEST-,-";
Console.WriteLine(foo.TrimEnd(new char[] { '-', ',' }));
}


static void Main()
{
StringBuilder sb = new StringBuilder("First line of string");

//terminate teh first line
sb.AppendLine();

//add a second line
sb.AppendLine("Second line of string");
Console.WriteLine(sb.ToString());
}


using System;
using System.Collections;


class Product {
public string name;
double cost;
int onhand;

public Product(string n, double c, int h)
{
name = n;
cost = c;
onhand = h;
}

public override string ToString(){
return String.Format("{0, -10} Cost: {1,6:C} On hand: {2}", name, cost, onhand);
}
}

//create an IComparer for Product objects
class ProductComparer : IComparer
{
//implements the IComparable interface
public int Compare(object obj1, object obj2)
{
Product a, b;
a = (Product)obj1;
b = (Product)obj2;
return a.name.CompareTo(b.name);
}
}

class ICompareDemo
{
public static void Main()
{
ProductComparer comp = new ProductComparer();
ArrayList inv = new ArrayList();

//add elements to the list
inv.Add(new Product("A", 5.5, 3));
inv.Add(new Product("C", 8.9, 2));
inv.Add(new Product("B", 3.0, 4));
inv.Add(new Product("D", 1.8, 8));

Console.WriteLine("Product list before sorting: ");
foreach (Product i in inv)
{
Console.WriteLine(" " + i);
}
Console.WriteLine();

//sort the list using an IComparer
inv.Sort(comp);

Console.WriteLine("Product list after sorting:");
foreach (Product i in inv)
{
Console.WriteLine(" " + i);
}
}
}


using System;

class MainClass
{
public static void Main()
{
int[] nums = new int[10];
int avg = 0;

nums[0] = 99;
nums[1] = 10;
nums[2] = 100;
nums[3] = 18;
nums[4] = 78;
nums[5] = 23;
nums[6] = 63;
nums[7] = 9;
nums[8] = 87;
nums[9] = 49;

for (int i = 0; i < 10; i++)
{
avg = avg + nums[i];
}

avg = avg / 10;

Console.WriteLine("Average: " + avg);
}
}

Tuesday, September 13, 2011

9.13.11

Public Class Recipe05_17

Public Shared Sub Main()

Dim drive As New DriveInfo("C:\")

Console.Write("Free space in {0}-drive (in kilobytes): ", drive.Name)
Console.WriteLine(drive.AvailableFreeSpace / 1024)


End Sub
End Class


Private Sub mnuOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuOpen.Click
Dim dlg As New OpenFileDialog

dlg.Filter = "Rich Text Files (*.rtf)|*.RTF|All Files (*.*)|*.*"
dlg.CheckFileExists = True
dlg.InitialDirectory = Application.StartupPath

If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
rtDoc.LoadFile(dlg.FileName)
rtDoc.Enabled = True
End If
End Sub

Private Sub mnuSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSave.Click
Dim dlg As New SaveFileDialog

dlg.Filter = "Rich Text Files (*.rtf)|*.RTF" & "|All Files (*.*)|*.*"
dlg.InitialDirectory = Application.StartupPath

If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
rtDoc.SaveFile(dlg.FileName)
End If
End Sub

Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
Me.Close()
End Sub


Imports System
Imports System.IO
Imports System.IO.IsolatedStorage

Namespace Apress.VisualBasicRecipes.Chapter05

Public Class Recipe05_19
Public Shared Sub Main()

'create the store for the current user
Using store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly
'create a folder in the root of the isolated store.
store.CreateDirectory("MyFolder")

'create a file in the isolated store.
Using fs As New IsolatedStorageFileStream("MyFile.txt", FileMode.Create, store)
Dim w As New StreamWriter(fs)

'you can now write to the file as normal
w.WriteLine("Test")
w.Flush()
End Using

Using fs As New IsolatedStorageFileStream("OtherFile.txt", FileMode.Create, store)
Dim w As New StreamWriter(fs)

'you can now write to the file as normal
w.WriteLine("Other test")
w.Flush()
End Using

Console.WriteLine("Current size: " & store.CurrentSize.ToString)
Console.WriteLine("Scope: " & store.Scope.ToString)
Console.WriteLine("Contained files include:")

Dim files As String() = store.GetFileNames("*.*")
For Each File As String In files
Console.WriteLine(File)
Next

End Using
End Sub
End Class
End Namespace


Imports System
Imports System.IO
Imports System.Windows.Forms
Imports System.Text

Namespace Apress.VisualBasicRecipes.Chapter05

Public Class Recipe05_20
Public Shared Sub Main()

Using watch As New FileSystemWatcher

watch.Path = Application.StartupPath
watch.Filter = "*.*"
watch.IncludeSubdirectories = True

'attach the event handlers
AddHandler watch.Created, AddressOf OnCreatedOrDeleted
AddHandler watch.Deleted, AddressOf OnCreatedOrDeleted
watch.EnableRaisingEvents = True

Console.WriteLine("Press Enter to create a file")
Console.ReadLine()

If File.Exists("test.bin") Then
File.Delete("test.bin")
End If

'create test.bin file
Using fs As New FileStream("test.bin", FileMode.Create)
Dim info As Byte() = New UTF8Encoding(True).GetBytes("hello world")
fs.Write(info, 0, info.Length)
End Using

End Using
End Sub

Private Shared Sub OnCreatedOrDeleted(ByVal sender As Object, ByVal e As FileSystemEventArgs)
'display the notification information
Console.WriteLine("{0}NOTIFICATION: {1} was {2}", ControlChars.Tab, e.FullPath, e.ChangeType.ToString)
Console.WriteLine()
End Sub

End Class

End Namespace

Monday, September 12, 2011

Monday 9.12.11

using System;
using System.Data;

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


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

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

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


using System;
using System.Data;

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

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

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

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

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

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

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

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

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



using System;
using System.Data;

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

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

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

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

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

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

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

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


Public Class Form1

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

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

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

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

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

End Sub
End Class


Dim numbers As New List(Of Integer)


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


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



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


Imports System
Imports System.IO

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

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

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

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


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

Namespace Apress.VisualBasicRecipes.Chapter05

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

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

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

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

Friday, September 9, 2011

Friday 9.9.11

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

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

End Try

End Sub

Thursday, September 8, 2011

9.8.11

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

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

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

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


Public Class Form1

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


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

newString = UCase(oldString)

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

newString = StrConv(oldString, VbStrConv.ProperCase)

addToString(newString, displayString, counter)

newString = MixedCase(oldString)

addToString(newString, displayString, counter)

'---display results
MsgBox(displayString)

End Sub

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

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

Return Join(textParts, " ")
End Function

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


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

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

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

}


#include
#include

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

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

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

return 0;
}


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

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

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

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

return 0;

}


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

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

return 0;
}

Wednesday, September 7, 2011

Wednesday 9.7.11

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

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

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

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

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

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

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

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

Dim currentRecord As String()

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

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

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

End Class
End Namespace


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

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

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

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

End Sub

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

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


Imports System.Threading

Module Module1
Class MyEventArgs
Inherits System.EventArgs

Public Message As String
Public Time As DateTime

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

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

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

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

End Sub

Sub Main()
Dim i As Integer

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


End Sub

End Module


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

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

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


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

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

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

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

Tuesday, September 6, 2011

Tuesday 9.2.11

Public Shared Sub Main()

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

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


End Sub


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

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

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

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

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

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


Public Class Recipe05_07
Public Shared Sub Main()

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

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

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

End Using
End Using

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


End Sub
End Class


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

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

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

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

if(item == 0)
{
break;
}

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

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

return 0;
}

Monday, September 5, 2011

Monday 9.6.11

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

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

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

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


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

float volume = 0;

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

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


#include
int old_number;
int current_number;
int next_number;

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

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

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

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

}


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

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

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

if (item == 0)
{
break;
}

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

Friday, September 2, 2011

Friday 9.2.11

Option Strict On
Imports System

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

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

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

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

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

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

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

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

End Class
End Namespace


Option Strict On
Imports System
Namespace ReverseAndSort
Class Tester

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

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

Console.WriteLine(ControlChars.Lf)

End Sub 'DisplayArray

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

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

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

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

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

End Sub 'run

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

End Class 'Tester
End Namespace 'Reverse and sort


Option Strict On
Imports System

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

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


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

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

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

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

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

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

Console.WriteLine("After adding strings")

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

'test the access

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

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

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


using System;
using System.Data;

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

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

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

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

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