Wednesday, August 31, 2011

8.31.11

Dim Customer As New Customer

Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnContinue.Click
If chkMail.Checked Then
Customer.Mail = True
Else
Customer.Mail = False
End If

If rdoEmail.Checked Then
Customer.MailType = "Email"
ElseIf rdoPostal.Checked Then
Customer.MailType = "Postal"
End If
End Sub


Protected Sub btnUpload_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnUpload.Click
Dim iSizeLimit As Integer = 5242880 '5mb
If uplCustList.HasFile Then
If uplCustList.PostedFile.ContentLength <= iSizeLimit Then
Dim sPath As String = "C:\uploads\" & uplCustList.FileName
uplCustList.SaveAs(sPath)
lblMessage.Text = "File uploaded to " & sPath
Else
lblMessage.Text = "File exceeds size limit."
End If
End If
End Sub


Option Strict On
Imports System
Namespace ArrayDemo
'a simple class to store ni the array
Public Class Employee
Private empID As Integer

'constructor
Public Sub New(ByVal empID As Integer)
Me.empID = empID
End Sub 'new

Public Overrides Function ToString() As String
Return empID.ToString()
End Function 'toString
End Class 'Employee

Class Tester

Public Sub Run()
Dim intArray() As Integer
Dim empArray() As Employee
intArray = New Integer(5) {}
empArray = New Employee(3) {}

'populate the array
Dim i As Integer
For i = 0 To empArray.Length - 1
empArray(i) = New Employee(i + 5)
Next i

Console.WriteLine("The integer array...")
For i = 0 To intArray.Length - 1
Console.WriteLine(intArray(i).ToString())
Next i

Console.WriteLine(ControlChars.Lf + "The employee array...")
For i = 0 To empArray.Length - 1
Console.WriteLine(empArray(i).ToString())
Next i

End Sub 'Run

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

End Class 'Tester

End Namespace 'ArrayDemo


Public Sub Run()
Dim intArray As Integer() = {2, 4, 6, 8, 19}
Dim empArray As Employee() = _
{New Employee(5), New Employee(7), New Employee(8), New Employee(12)}

Console.WriteLine("The Integer array...")
Dim theInt As Integer
For Each theInt In intArray
Console.WriteLine(theInt.ToString())
Next

Console.WriteLine("The employee array...")
Dim e As Employee
For Each e In empArray
Console.WriteLine(e.ToString())
Next e

End Sub 'Run


Namespace ArrayDemo

Class Tester

Public Sub Run()
Dim a As Integer = 5
Dim b As Integer = 6
Dim c As Integer = 7
Console.WriteLine("Calling with three Integers")
DisplayVals(a, b, c)


Console.WriteLine("Calling with four integers")
DisplayVals(5, 6, 7, 8)

Console.WriteLine("Calling with an array of four Integers")
Dim explicitArray() As Integer = {5, 6, 7, 8}
DisplayVals(explicitArray)

End Sub 'Run

Public Sub DisplayVals(ByVal ParamArray intVals() As Integer)
Dim i As Integer
For Each i In intVals
Console.WriteLine("DisplayVals {0}", i)
Next i
End Sub 'DisplayVals

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

End Class
End Namespace


Public Sub Run()
Const rowsUB As Integer = 4
Const columnsUB As Integer = 3

' define and initialize the array
Dim rectangularArray As Integer(,) = _
{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}}

'report the contents of the array
Dim i As Integer
For i = 0 To rowsUB - 1
Dim j As Integer
For j = 0 To columnsUB - 1
Console.WriteLine("rectangularArray[{0},{1}] = {2}", _
i, j, rectangularArray(i, j))
Next
Next
End Sub 'Run

Tuesday, August 30, 2011

Tuesday 8.30.11

Imports System.Data

Partial Class Orders
Inherits System.Web.UI.Page

Private SelectedProduct As Product

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlProducts.DataBind()
End If
SelectedProduct = Me.GetSelectedProduct()
lblName.Text = SelectedProduct.Name
lblShortDescription.Text = SelectedProduct.ShortDescription
lblLongDescription.Text = SelectedProduct.LongDescription
lblUnitPrice.Text = FormatCurrency(SelectedProduct.UnitPrice)
imgProduct.ImageUrl = "Images\Products\" _
& SelectedProduct.ImageFile
End Sub

Private Function GetSelectedProduct() As Product
Dim dvTable As DataView = CType(AccessDataSource1.Select( _
DataSourceSelectArguments.Empty), DataView)
dvTable.RowFilter = "ProductID = '" & ddlProducts.SelectedValue & "'"
Dim drvRow As DataRowView = dvTable(0)

Dim Product As New Product
Product.ProductID = drvRow("ProductID").ToString
Product.Name = drvRow("Name").ToString
Product.ShortDescription = drvRow("ShortDescription").ToString
Product.LongDescription = drvRow("LongDescription").ToString
Product.UnitPrice = CDec(drvRow("UnitPrice"))
Product.ImageFile = drvRow("ImageFile").ToString
Return Product

End Function

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If Page.IsValid Then
Dim CartItem As New CartItem
CartItem.Product = SelectedProduct
CartItem.Quantity = CType(txtQuantity.Text, Integer)
Me.AddToCart(CartItem)
Response.Redirect("Cart.aspx")
End If
End Sub

Private Sub AddToCart(ByVal CartItem As CartItem)
Dim Cart As SortedList = GetCart()
Dim sProductID As String = SelectedProduct.ProductID
If Cart.ContainsKey(sProductID) Then
CartItem = CType(Cart(sProductID), CartItem)
CartItem.Quantity += CType(txtQuantity.Text, Integer)
Else
Cart.Add(sProductID, CartItem)
End If
End Sub

Private Function GetCart() As SortedList
If Session("Cart") Is Nothing Then
Session.Add("Cart", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function

End Class



Partial Class Cart
Inherits System.Web.UI.Page

Private Cart As SortedList

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Cart = GetCart()
If Not IsPostBack Then
Me.DisplayCart()
End If
End Sub

Private Function GetCart() As SortedList
If Session("Cart") Is Nothing Then
Session.Add("Cart", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function

Private Sub DisplayCart()
firstCart.Items.Clear()
Dim CartItem As CartItem
Dim CartEntry As DictionaryEntry
For Each CartEntry In Cart
CartItem = CType(CartEntry.Value, CartItem)
firstCart.Items.Add(CartItem.Display)
Next
End Sub

Protected Sub btnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If firstCart.SelectedIndex > -1 And Cart.Count > 0 Then
Cart.RemoveAt(firstCart.SelectedIndex)
Me.DisplayCart()
End If
End Sub

Protected Sub btnEmpty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEmpty.Click
Cart.Clear()
firstCart.Items.Clear()
lblMessage.Text = ""
End Sub

Protected Sub btnCheckOut_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckOut.Click
lblMessage.Text = "Sorry, that function hasn't been implemented yet."
End Sub
End Class

Monday, August 29, 2011

Monday 8.29.11

Imports MVB = Microsoft.VisualBasic

Public Class Form1

Private Declare Auto Function GetPrivateProfileString _
Lib "kernel32" _
(ByVal AppName As String, _
ByVal KeyName As String, _
ByVal DefaultValue As String, _
ByVal ReturnedString As System.Text.StringBuilder, _
ByVal BufferSize As Integer, _
ByVal FileName As String) As Integer

Private Sub MenuExitProgram_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MenuExitProgram.Click
'exit the program
Me.Close()
End Sub


Private Sub BuildFavorites(ByVal whichMenu As ToolStripMenuItem, ByVal fromPath As String)
'--given a starting directory, add all files
'--and direcories in it to the specified menu
'recurse for subordinate directores
Dim oneEntry As String
Dim menuEntry As ToolStripMenuItem
Dim linkPath As String
Dim displayName As String

'start with any directories
For Each oneEntry In My.Computer.FileSystem.GetDirectories(fromPath)
'--create the parent menu
'but don't attach it yet
menuEntry = New ToolStripMenuItem(My.Computer.FileSystem.GetName(oneEntry))
' ---recurse to build the sub directory brach
BuildFavorites(menuEntry, oneEntry)

' if that folder contained items, then attach it
If (menuEntry.DropDownItems.Count > 0) Then
whichMenu.DropDownItems.Add(menuEntry)
End If
Next oneEntry

'---next build the actual file links. Only look at '.url' files.
For Each oneEntry In My.Computer.FileSystem.GetFiles(fromPath, FileIO.SearchOption.SearchTopLevelOnly, "*.url")
'build a link based on this file. these files are old-style INI files
linkPath = GetINIEntry("InternetShortcut", "URL", oneEntry)
If (linkPath <> "") Then
'---foudn the link add it to the menu
displayName = My.Computer.FileSystem.GetName(oneEntry)
displayName = MVB.Left(displayName, displayName.Length - 4)
menuEntry = New ToolStripMenuItem(displayName)
menuEntry.Tag = linkPath
whichMenu.DropDownItems.Add(menuEntry)

'connect this entry to the event handler
AddHandler menuEntry.Click, AddressOf RunFavoritesLink
End If
Next oneEntry
End Sub

Private Sub RunFavoritesLink(ByVal sender As System.Object, ByVal e As System.EventArgs)
'---run the link
Dim whichMenu As ToolStripMenuItem
whichMenu = CType(sender, ToolStripMenuItem)
Process.Start(whichMenu.Tag)
End Sub


Private Function GetINIEntry(ByVal sectionName As String, ByVal keyName As String, ByVal whichFile As String) As String
'extract a value from an INI-style file
Dim resultLength As Integer
Dim targetBuffer As New System.Text.StringBuilder(500)

resultLength = GetPrivateProfileString(sectionName, keyName, "", targetBuffer, targetBuffer.Capacity, whichFile)
Return targetBuffer.ToString()
End Function


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim favoritesPath As String

'--determine the location of the 'favorites' folder.
favoritesPath = Environment.GetFolderPath(Environment.SpecialFolder.Favorites)
If (favoritesPath = "") Then Return
If (My.Computer.FileSystem.DirectoryExists(favoritesPath) = False) Then Return

'call the recurvsive routine that builds the menu.
BuildFavorites(MenuFavorites, favoritesPath)

'---if no favories were added, hide the 'no favorites' item
If (MenuFavorites.DropDownItems.Count > 1) Then _
MenuNoFavorites.Visible = False
End Sub

End Class


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim workText As New System.Text.StringBuilder

'---build a basic text block
workText.Append("The important")
workText.Append(vbNewLine)
workText.Append("thing is not")
workText.AppendLine()
workText.AppendLine("to stop questioning.")
workText.Append("--Albert Einstein")
MsgBox(workText.ToString())

'---delete the trailing text
Dim endSize As Integer = "--Albert Einstein".Length
MsgBox(endSize.ToString())

workText.Remove(workText.Length - endSize, endSize)
MsgBox(workText.ToString())

'perform a search and replace
workText.Replace("not", "never")
MsgBox(workText.ToString())

'--truncate the existing text
workText.Length = 3
MsgBox(workText.ToString())

End Sub


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim fancyString As New System.Text.StringBuilder
For counter As Integer = 1 To 35
fancyString.Append("+~")
Next counter
MsgBox(fancyString.ToString())
End Sub


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim messageText As New StringBuilder
messageText.Append("The important thing is not to stop questioning.")
MsgBox(messageText.ToString())
Dim obfuscated As String = Obfuscate(messageText.ToString())
messageText.AppendLine(obfuscated)
messageText.AppendLine(DeObfuscate(obfuscated))
MsgBox(messageText.ToString())
End Sub

Public Function Obfuscate(ByVal origText As String) As String
'---make a string unreadable, but retrievable
Dim textBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(origText)
For counter As Integer = 0 To textBytes.Length - 1
If (textBytes(counter) > 31) And (textBytes(counter) < 127) Then
textBytes(counter) += CByte(counter Mod 31 + 1)
If (textBytes(counter) > 126) Then
textBytes(counter) -= CByte(95)
End If
End If
Next counter
Return System.Text.Encoding.UTF8.GetChars(textBytes)
End Function


Public Function DeObfuscate(ByVal origText As String) As String
'--restore a previously obfuscated string.
Dim textBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(origText)
For counter As Integer = 0 To textBytes.Length - 1
If (textBytes(counter) > 31) And (textBytes(counter) < 127) Then
textBytes(counter) -= CByte(counter Mod 31 + 1)
End If
If (textBytes(counter) < 32) Then
textBytes(counter) += CByte(95)
End If
Next
Return System.Text.Encoding.UTF8.GetChars(textBytes)
End Function

Friday, August 26, 2011

Friday 8.26.11

#include
int main(void)
{
const int FREEZING = 0;
float temperature;
int cold_days = 0;
int all_days = 0;

printf("Enter the list of daily lowe temperatures.\n");
printf("Use Celsius, and enter q to quit.\n");
while (scanf("%f", &temperature)==1)
{
all_days++;
if (temperature < FREEZING)
{
cold_days++;
}
}
if (all_days != 0)
{
printf("%d days total: %.1f%% were below freezing.\n", all_days, 100.0 * (float) cold_days / all_days);
}
if (all_days ==0)
{
printf("No data entered!\n");
}

return 0;
}


#include
#define SPACE ' '
int main(void)
{
char ch;

ch=getchar();
while (ch != '\n')
{
if (ch==SPACE)
{
putchar(ch);
} else {
putchar(ch + 1);
}
ch = getchar(); //get next character
}
putchar(ch);

return(0);
}



Imports System
Imports System.IO

Namespace Apress.VisualBasicRecipes.Chapter05

Public Class Recipe05_03 'expanded by me somewhat using http://msdn.microsoft.com/en-us/library/dd997370.aspx

Public Shared Sub Main()

Dim dirPath As String = "C:\inetpub\wwwroot\"
Dim dirs = From folder In Directory.EnumerateDirectories(dirPath)
Dim folderArray(20, 1) As String

Dim i As Integer = 0
For Each folder In dirs
folderArray(i, 0) = folder.Substring(folder.LastIndexOf("\") + 1)
folderArray(i, 1) = folder
Console.WriteLine("[{0}] {1}", i, folderArray(i, 0))
i = i + 1
Next
Console.WriteLine("select a directory to copy")
Dim sourceDirNum = Console.ReadLine()
Dim sourceDirName = folderArray(sourceDirNum, 0)
Dim sourceDirPath = folderArray(sourceDirNum, 1)


displayNamePath(sourceDirName, sourceDirPath)

Console.WriteLine("Please enter the name of the new directory to create")
Dim destDirName = Console.ReadLine()
Dim destDirPath = sourceDirPath.Substring(0, sourceDirPath.LastIndexOf(sourceDirName)) + destDirName
displayDestPath(destDirName, destDirPath)

CopyDirectory(sourceDirPath, destDirPath)

End Sub

Shared Sub displayNamePath(ByVal arg1, ByVal arg2)
Console.WriteLine("-> You will copy the {0} directory", arg1)
Console.WriteLine("-> located at {0}", arg2)
End Sub

Shared Sub displayDestPath(ByVal arg1, ByVal arg2)
Console.WriteLine("-> You will create a directory named {0} ", arg1)
Console.WriteLine("-> located at {0}", arg2)
End Sub

Shared Sub CopyDirectory(ByVal sourceDirPath, ByVal destDirPath)
Dim source As New DirectoryInfo(sourceDirPath)
Dim destination As New DirectoryInfo(destDirPath)

If Not destination.Exists Then
Console.WriteLine("Creating the destination folder {0}", destination.FullName)
destination.Create()
End If

'Copy all files
Dim files As FileInfo() = source.GetFiles

For Each File As FileInfo In files
Console.WriteLine("Copying the {0} file...", File.Name)
File.CopyTo(Path.Combine(destination.FullName, File.Name))
Next

'Process subdirectories
Dim dirs As DirectoryInfo() = source.GetDirectories

'unfortunately could not figure out how to copy subs.


End Sub

End Class
End Namespace


Imports System
Imports System.IO

Public Class Test
Public Shared Sub Main()
'specifiy the directories you want to manipulate
Dim di As DirectoryInfo = New DirectoryInfo("C:\new\MyDir")
Try
'determine whether the directory exists
If di.Exists Then
Console.WriteLine("That directory exists already")
Return
End If

'try to create that directory
di.Create()
Console.WriteLine("the directory was created successfully")

'delete the directory
di.Delete()
Console.WriteLine("The directory was deleted successfully")

Catch ex As Exception
Console.WriteLine("The process failed: {0}", ex.ToString())
End Try
End Sub

End Class

Wednesday, August 24, 2011

Tuesday 8.24.11

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

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

string sqlSelect = "SELECT TOP 10 EmployeeID, Title, Gender, HireDate FROM HumanResources.Employee";

SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);

//create a dtable mapping to map the default table name 'Table'
DataTableMapping dtm = da.TableMappings.Add("Table", "mappedContact");

//create column mappings
dtm.ColumnMappings.Add("EmployeeID", "mappedEmployeeID");
dtm.ColumnMappings.Add("Title", "mappedTitle");
dtm.ColumnMappings.Add("Gender", "mappedGender");
dtm.ColumnMappings.Add("HireDate", "mappedHireDate");

//create and fill the DataSet
DataSet ds = new DataSet();
da.Fill(ds);

Console.WriteLine("DataTable name = {0}", ds.Tables[0].TableName);

foreach (DataColumn col in ds.Tables["mappedContact"].Columns)
{
Console.WriteLine("\tDataColumn {0} name = {1}", col.Ordinal, col.ColumnName);
}

Console.WriteLine();

foreach (DataRow row in ds.Tables["mappedContact"].Rows)
{
Console.WriteLine("EmployeeID = {0} \t Title = {1} \n Gender = {2} \t HireDate = {3} ", row["mappedEmployeeID"], row["mappedTitle"], row["mappedGender"],
row["mappedHireDate"]);
Console.WriteLine();
}
}
}
}


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

namespace MappingDataTypes
{
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 ContactID, FirstName, MiddleName, LastName FROM Person.Contact";

int contactID;
string firstName, middleName, lastName;

//create the connection and the command
SqlConnection connection = new SqlConnection(sqlConnectString);
SqlCommand command = new SqlCommand(sqlSelect, connection);

//Open the connection and build the DataReader
connection.Open();

using (SqlDataReader dr = command.ExecuteReader())
{
Console.WriteLine("--Cast value retrieved by Ordinal---");
while (dr.Read())
{
contactID = Convert.ToInt32(dr[0]);
firstName = Convert.ToString(dr[1]);
middleName = Convert.ToString(dr[2]);
lastName = Convert.ToString(dr[3]);

Console.WriteLine("{0}\t{1}, {2} {3}", contactID, lastName, firstName, middleName);
}
}

using (SqlDataReader dr = command.ExecuteReader())
{
//Get values from the DataReader using generic typed accessors.
Console.WriteLine("\n----Generic typed accessors----");
while (dr.Read())
{
contactID = dr.GetInt32(0);
firstName = dr.GetString(1);
middleName = dr.IsDBNull(2) ? null : dr.GetString(2);
lastName = dr.GetString(3);

Console.WriteLine("{0}\t{1}, {2} {3}", contactID, lastName, firstName, middleName);
}
}

using (SqlDataReader dr = command.ExecuteReader())
{
//get values from the DataReader using SQL Server
//specific typed accessors
Console.WriteLine("\n---SQL Server specific typed accessors---");
while (dr.Read())
{
contactID = (int)dr.GetSqlInt32(0);
firstName = (string)dr.GetSqlString(1);
middleName = dr.IsDBNull(2) ? null : (string)dr.GetSqlString(2);
lastName = (string)dr.GetSqlString(3);

Console.WriteLine("{0}\t{1}, {2} {3}", contactID, lastName, firstName, middleName);
}
}

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


Public Class Recipe02_07

Public Shared Sub Main(ByVal args As String())
'1st January 1975 at 00:00:00
Dim dt1 As DateTime = DateTime.Parse("Jan 1975")

'12th January 1975 at 18:19:00
Dim dt2 As DateTime = DateTime.Parse("Sunday 12 January 1975 18:19:00")

'12th January 1975 at 00:00:00
Dim dt3 As DateTime = DateTime.Parse("1,12,1975")

'12th January 1975 at 18:19:00
Dim dt4 As DateTime = DateTime.Parse("1/12/1975 18:19:00")

'Current Date at 18:19 showitng UTC offset for local time zone
Dim dt5 As DateTimeOffset = DateTimeOffset.Parse("6:19 PM")

'Current Date at 18:19 showing an offset of -8 hours from UTC
Dim dt6 As DateTimeOffset = DateTimeOffset.Parse("6:19 PM -8")

'Date set to minvalue to be used later by TryPares
Dim dt7 As DateTime = DateTime.MinValue

'Display the converted DateTime objects
Console.WriteLine("Jan 1975")
Console.WriteLine(dt1)
Console.WriteLine()
Console.WriteLine("Sunday 12 January 1975 18:19:00")
Console.WriteLine(dt2)
Console.WriteLine()
Console.WriteLine("1,12,1975")
Console.WriteLine(dt3)
Console.WriteLine()
Console.WriteLine("1/12/1975 18:19:00")
Console.WriteLine(dt4)
Console.WriteLine()
Console.WriteLine(dt5)
Console.WriteLine()
Console.WriteLine(dt6)
Console.WriteLine()

'try to parse a nondatetime string.
If Not DateTime.TryParse("THis is an invalid date", dt7) Then
Console.WriteLine("Unable to parse.")
Else
Console.WriteLine(dt7)
End If

'Parse only string scontaining LongTimePattern
Dim dt8 As DateTime = DateTime.ParseExact("6:19:00 PM", "h:mm:ss tt", Nothing)


'Parse only strings containing MonthDayPattern.
Dim dt10 As DateTime = DateTime.ParseExact("January 12", "MMMM dd", Nothing)

'display the cnoverted DateTime objects.
Console.WriteLine(dt8)
'Console.WriteLine(dt9)
Console.WriteLine(dt10)

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


End Sub

End Class



Imports System
Imports System.IO

Namespace Apress.VisualBasicRecipes.Chapter05
Public Class Recipe05_01

Public Shared Sub Main()
Dim keepGoing = 1

Do
Console.WriteLine("Please enter a file name, or enter Q to exit")

Dim entry = Console.ReadLine()

If (entry <> "Q") Then
Dim File As FileInfo = New FileInfo(entry)


Console.WriteLine("Checking file: " & File.Name)
Console.WriteLine("File exists: " & File.Exists.ToString)

If File.Exists Then
Console.WriteLine("File created: ")
Console.WriteLine(File.CreationTime.ToString)
Console.Write("File last updated: ")
Console.WriteLine(File.LastWriteTime.ToString)
Console.Write("File last accessed: ")
Console.WriteLine(File.LastAccessTime.ToString)
Console.Write("File size: ")
Console.WriteLine(File.Length.ToString)
Console.Write("File attribute list: ")
Console.WriteLine(File.Attributes.ToString)
End If
Console.WriteLine()

'Display directory information
Dim dir As DirectoryInfo = File.Directory

Console.WriteLine("Checking directory: " & dir.Name)
Console.WriteLine("In directory: " & dir.Parent.Name)
Console.Write("Directory exists: ")
Console.WriteLine(dir.Exists.ToString)

If dir.Exists Then
Console.Write("Directory created: ")
Console.WriteLine(dir.CreationTime.ToString)
Console.Write("Directory last updated: ")
Console.WriteLine(dir.LastWriteTime.ToString)
Console.Write("Directory last accessed: ")
Console.WriteLine(dir.LastAccessTime.ToString)
Console.Write("Directory attribute list: ")
Console.WriteLine(File.Attributes.ToString)
Console.Write("Directory contains: ")
Console.WriteLine(dir.GetFiles().Length.ToString & " files")
End If
Console.WriteLine("Press any key to continue")

'display drive information.
Dim drv As DriveInfo = New DriveInfo(File.FullName)

Console.WriteLine("Drive: ")
Console.WriteLine(drv.Name)

If drv.IsReady Then
Console.Write("Drive type: ")
Console.WriteLine(drv.DriveType.ToString)
Console.Write("Drive format: ")
Console.WriteLine(drv.DriveFormat.ToString)
Console.Write("Drive free space: ")
Console.WriteLine(drv.AvailableFreeSpace.ToString)
End If


Console.ReadLine()
Else
keepGoing = 0
End If
Loop Until (keepGoing = 0)
End Sub

End Class
End Namespace

Tuesday, August 23, 2011

Tuesday 8.23.11

#include

int term;
int main()
{
term = 3 * 5;
printf("Twice %d is %d\n", term, 2*term);
printf("Three times %d is %d\n", term, 3*term);
return (0);
}


#include
float answer; //the result of our calculation

int main()
{
//wrong
answer = 1/3;
printf("The value of 1/3 is %f\n", answer);

//right
answer = 1.0/3.0;
printf("The value of 1/3 is %f\n", answer);

//return 0 if program runs
return(0);
}



#include

float result;

int main()
{
result = 7.0/22.0;

printf("The result is %d\n", result);

//right

printf("The result is %f\n", result);
return(0);
}


#include
char char1;
char char2;
char char3;

int main()
{
char1 = 'A';
char2 = 'B';
char3 = 'C';

printf("%c%c%c reversed is %c%c%c\n", char1, char2, char3, char3, char2, char1);

return(0);

}


#include

float data[5];
float total;
float average;

int main()
{
data[0] = 34.0;
data[1] = 27.0;
data[2] = 45.0;
data[3] = 82.0;
data[4] = 22.0;

total = data[0] + data[1] + data[2] + data[3] + data[4];

average = total / 5.0;

printf("Total %f Average %f\n", total, average);
return(0);
}


#include
#include
char name[30];
int main()
{
strcpy(name, "Sam");
printf("The name is %s\n", name);
return(0);
}


#include
#include

char first[100];
char last[100];

char full_name[200];

int main()
{
strcpy(first, "Steve");
strcpy(last, "Oualline");

strcpy(full_name, first);
//strcat not strcpy!!!
strcat(full_name, " ");
strcat(full_name, last);

printf("The full name is %s\n", full_name);
return (0);
}


#include
#include

char line[100];

int main()
{
printf("Enter a line: ");
fgets(line, sizeof(line), stdin);

printf("The length of the line is: %d\n", strlen(line));
return (0);
}


#include
#include

char line[100];

int main()
{
printf("Enter a line: ");
fgets(line, sizeof(line), stdin);

printf("The length of the line is: %d\n", strlen(line));
return (0);
}


#include
#include

char first[100];
char last[100];

char full[200];

int main() {
printf("Enter first name: ");
fgets(first, sizeof(first), stdin);
//trim off last character
first[strlen(first)-1] = '\0';

printf("Enter last name: ");
fgets(last, sizeof(last), stdin);
//trim off last character
last[strlen(last)-1] = '\0';

strcpy(full, first);
strcat(full, " ");
strcat(full, last);

printf("The name is %s\n", full);
return(0);
}


#include
#define SIZE 10
#define PAR 72
int main(void)
{
int index, score[SIZE];
int sum = 0;
float average;

printf("Enter %d golf scores:\n", SIZE);
for(index = 0; index < SIZE; index++)
{
scanf("%d", &score[index]);
}
printf("The scores read in area as follows:\n");
for (index=0; index {
printf("%5d", score[index]); //verify input
}
printf("\n");
for (index = 0; index < SIZE; index++)
{
sum += score[index];
}
average = (float) sum / SIZE;
printf("Sum of scores = %d, average = %.2f\n", sum, average);
printf("That's a handicap of %.0f.\n", average - PAR);

return 0;
}


#include
double power(double n, int p);
int main(void)
{
double x, xpow;
int exp;

printf("Enter a number and the positive integer power");
printf(" to which \n the number will be raised. Enter q to quit.\n");
while (scanf("%lf%d", &x, &exp) == 2)
{
xpow = power(x, exp); //function call
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("Enter next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed this power trip -- bye!\n");

return 0;
}

double power(double n, int p) //function definition
{
double pow = 1;
int i;
for (i = 1; i <= p; i++)
{
pow *= n;
}
return pow;
}


Sub Main()
Dim arr As Array
Dim int() As Integer = {12, 16, 20, 24, 28, 32}
arr = CType(int, Array)

Dim byFours() As Integer = {12, 24, 36, 48}
Dim names() As String = {"K", "S", "S", "D", "N"}
Dim miscData() As Object = {"this", 12D, 16UI, "a"}
Dim objArray() As Object

miscData = names

Dim myArray2(10) As Integer

Dim Employees1(,) As Object
Dim Employees(200, 2) As Object

Dim jagged1(9)() As String
Dim jagged2()() As String = New String(9)() {}

Dim myArray1arr As Array
Dim myArray2a As Array = Array.CreateInstance(GetType(Integer), 10)
Dim members() As Integer = {3, 10}
Dim myArray3a As Array = Array.CreateInstance(GetType(Integer), members)

End Sub


Module Tester
Sub Main()
PrintSub(40, 10.5)
PrintSub(38, 21.75)
PrintSub(20, 13)
PrintSub(50, 14)
End Sub

Sub PrintSub(ByVal hours As Double, ByVal wage As Decimal)
Console.WriteLine("The payment is {0:C}", hours * wage)
End Sub
End Module


Class Job

Public Event Meeting()
Public Event Testing(ByVal Temp As Integer)
Public Event Coding(ByVal Room As String, ByVal Duration As Integer)

Public Sub GenerateEvents()
RaiseEvent Meeting()
RaiseEvent Testing(212)
RaiseEvent Coding("VB.NET", 25)
End Sub

End Class

Class MainClass

Shared WithEvents Alarms As New Job()

Shared Sub MyMeeting() Handles Alarms.Meeting
Console.WriteLine("MyMeeting alarm occurred.")
End Sub

Shared Sub MyTesting(ByVal Temp As Integer) Handles Alarms.Testing
Console.WriteLine("MyTesting alarm occurred: Temp : " & Temp)
End Sub

Shared Sub MyCoding(ByVal Room As String, ByVal Duration As Integer) Handles Alarms.Coding
Console.WriteLine("MyCoding alarm occurred: " & Room & " " & Duration)
End Sub

Public Shared Sub Main()
Alarms.GenerateEvents()
End Sub

End Class


<?xml version="1.0"?>
<pet>
<name>Polly Parrot</name>
<age>3</age>
<species>parrot</species>
<parents>
<mother>Pia Parrot</mother>
<father>Peter Parrot</father>
</parents>
</pet>


<?php
if(file_exists('pet.xml'))
{
$xml =simplexml_load_file('pet.xml');
print_r($xml);
} else {
exit('failed to open pet.xml');
}

?>

Monday, August 22, 2011

Monday 8.22.11

//use the math.h header file, handy for floating-point tests
#include
#include
int main(void)
{
const double ANSWER = 3.14159;
double response;

printf("What is the value of pi?\n");
scanf("%lf", &response);
while (fabs(response - ANSWER) > 0.0001)
{
printf("Try again!\n");
scanf("%lf", &response);
}
printf("Close enough!\n");

return 0;
}


#include
int main(void)
{
long num;
long sum = 0L;
_Bool input_is_good;
printf("Please enter an integer to be summed ");
printf("(q to quit): ");
//the parentheses enclosing the == expression are not needed
//but make the code easier to read
input_is_good = (scanf("%ld", &num) == 1);
while(input_is_good)
{
sum = sum + num;
printf("Please enter next integer (q to quit): ");
input_is_good = (scanf("%ld", &num) == 1);
}
printf("Those integers sum to %ld.\n", sum);

return 0;
}


<#include
int main(void)
{
const int NUMBER = 22;
int count = 1;

while (count <= NUMBER)
{
printf("Be my Valentine!\n");
count++;
}
return 0;

}


#include
int main(void)
{
const int NUMBER = 22;
int count;

for (count = 1; count <= NUMBER; count++)
{
printf("Be my Valentine!\n");
}
return 0;
}


#include
int main(void)
{
const int FIRST_OZ = 37;
const int NEXT_OZ = 23;
int ounces, cost;

printf(" ounces cost\n");
for (ounces=1, cost=FIRST_OZ; ounces <= 16; ounces++, cost += NEXT_OZ)
{
printf("%5d $%4.2f\n", ounces, cost/100.0);
}

return 0;
}



#include
int main(void)
{
const int secret_code = 13;
int code_entered;

do
{
printf("To enter the triskaidekaphobia therapy club, \n");
printf("please enter the secret code number: ");
scanf("%d", &code_entered);
} while (code_entered != secret_code);
printf("Congratulations! You are cured!\n");

return 0;
}


#include
int main(void)
{
const int secret_code = 13;
int code_entered;

do
{
printf("To enter the triskaidekaphobia therapy club, \n");
printf("please enter the secret code number: ");
scanf("%d", &code_entered);
} while (code_entered != secret_code);
printf("Congratulations! You are cured!\n");

return 0;
}


#include
#define ROWS 6
#define CHARS 10
int main(void)
{
int row;
char ch;

for (row = 0; row < ROWS; row++)
{
for (ch = 'A'; ch < ('A' + CHARS); ch++)
{
printf("%c", ch);
}
printf("\n");
}
return 0;
}

here are some vb tutorials


Option Strict On

Public Module TimerFunction
Public Sub Main()
Dim starttime, endtime As Integer
starttime = Environment.TickCount
For ctr As Integer = 0 To 100000000

Next
endtime = Environment.TickCount
Console.WriteLine("Ellapsed time is {0} milliseconds", endtime - starttime)
End Sub
End Module


Module Module1

Dim WithEvents ValueInfo As New Value()

Class Value
Public Event ValueUp(ByVal amount As Double)
Public Event ValueDown(ByVal amount As Double)
Public Event Result(ByVal amount As Double, ByVal announceDate As DateTime)

Public Sub GenerateEvents()
RaiseEvent ValueUp(2)
RaiseEvent ValueDown(-5.5)
RaiseEvent Result(1.25, Now())
End Sub
End Class

Sub PriceGoingUp(ByVal Price As Double)
Console.WriteLine("Up: " & Price)
End Sub

Sub PriceGoingDown(ByVal Price As Double)
Console.WriteLine("Down: " & Price)
End Sub

Sub ResultAnnouncement(ByVal Amount As Double, ByVal AnnounceDate As DateTime)
Console.WriteLine("Result: " & Amount & " " & AnnounceDate)
End Sub


Sub Main()
AddHandler ValueInfo.ValueUp, AddressOf PriceGoingUp
AddHandler ValueInfo.ValueDown, AddressOf PriceGoingDown
AddHandler ValueInfo.Result, AddressOf ResultAnnouncement

ValueInfo.GenerateEvents()
End Sub

End Module


Module Module1

Dim WithEvents ColorInfo As New Color()

Class Color
Public Event ColorChange(ByVal color As String)
Public Event ToneChange(ByVal tone As String)

Public Sub GetColor()
Console.WriteLine("What color?")
Dim newColor = Console.ReadLine()
RaiseEvent ColorChange(newColor)
End Sub

Public Sub GetTone()
Console.WriteLine("What tone?")
Dim newTone = Console.ReadLine()
RaiseEvent ToneChange(newTone)
End Sub


End Class

Sub ColorChanging(ByVal color As String)
Console.WriteLine("Color is now: " & color)
End Sub

Sub ToneChanging(ByVal tone As String)
Console.WriteLine("Tone is now: " & tone)
End Sub

Sub Main()


AddHandler ColorInfo.ColorChange, AddressOf ColorChanging
AddHandler ColorInfo.ToneChange, AddressOf ToneChanging
ColorInfo.GetColor()
ColorInfo.GetTone()

End Sub

End Module


Module Module1
Class DailyJob
Public Event Coding(ByVal Item As String, ByVal StartTime As DateTime)
Public Event Testing(ByVal Item As String, ByVal StartTime As DateTime)
Public Event Meeting(ByVal Item As String, ByVal StartTime As DateTime)

Public Sub GenerateEvents()
RaiseEvent Coding("Coding", Now())
RaiseEvent Testing("Testing", Now().AddMinutes(5.0))
RaiseEvent Meeting("Meeting", Now().AddMinutes(10.0))
End Sub
End Class

Dim WithEvents ThisDailyJob As New DailyJob()

Sub DoJob(ByVal Item As String, ByVal StartTime As DateTime)
Console.WriteLine("Starting " & Item & "at : " & StartTime)
End Sub

Sub Main()
AddHandler ThisDailyJob.Coding, AddressOf DoJob
AddHandler ThisDailyJob.Testing, AddressOf DoJob
AddHandler ThisDailyJob.Meeting, AddressOf DoJob

ThisDailyJob.GenerateEvents()

End Sub

End Module


using System;
using System.Data;

namespace CreateDataColumnAddDataTable
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();

//Add the column to the Data Table to create
DataColumn col1 = dt.Columns.Add();
//configure the column -- integer with a default = 0 that
//does not allow nulls
col1.ColumnName = "Column-1";
col1.DataType = typeof(int);
col1.DefaultValue = 0;
col1.Unique = true;
col1.AllowDBNull = false;

//create and configure the column
DataColumn col2 = new DataColumn();
//configure the colum -- string with max length = 50
col2.ColumnName = "Column-2";
col2.DataType = typeof(string);
col2.MaxLength = 50;
//add the column to the DataTable
dt.Columns.Add(col2);

//add a column directly using an overload of the Add()
//method of the DataTable.Columns collection -- the column
//is a string with max length = 50
dt.Columns.Add("Column-3", typeof(string)).MaxLength = 50;

//add multiple existing columns to the DataTable
DataColumn col4 = new DataColumn("Column-4");
//...configure column 4
DataColumn col5 = new DataColumn("Column-5", typeof(int));
//add columns 4 and 5 to the DataTable
dt.Columns.AddRange(new DataColumn[] { col4, col5 });

//Output the columns in the dataTable to the console
Console.WriteLine("DataTable has {0} DataColumns named: ", dt.Columns.Count);
foreach (DataColumn col in dt.Columns)
{
Console.WriteLine("\t{0}", col.ColumnName);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}


using System;
using System.Data;

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

//add a DataTable named Table-1 directly
DataTable dt1 = ds.Tables.Add("Table-1");
//configure the DataTable...add some columns etc.
DataColumn col1 = dt1.Columns.Add();
col1.ColumnName = "PrimaryKey";
col1.DataType = typeof(int);
col1.Unique = true;
col1.AutoIncrement = true;

//add a DataTable named Table-2 by creating the table
//and adding it to the DataSet

DataTable dt2 = new DataTable("Table-2");
//configure the DataTable, add some columns, etc.
DataColumn col2 = new DataColumn();
col2.ColumnName = "CompanyName";
ds.Tables.Add(dt2);
//add multiple DataTables to the DataSet
DataTable dt3 = new DataTable("Table-3");
DataTable dt4 = new DataTable("Table-4");
//configure the DataTable -- add some columns, etc.
ds.Tables.AddRange(new DataTable[] {dt3, dt4});

//output the tables in the DataSet to the console.
Console.WriteLine("DataSet has {0} DataTables named: ", ds.Tables.Count);
foreach (DataTable dt in ds.Tables)
Console.WriteLine("\t{0}", dt.TableName);

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

Friday, August 19, 2011

Friday 8.18.11

using System;
using System.Windows.Forms;

public class MainClass : System.Windows.Forms.Form
{
public MainClass()
{
Application.ApplicationExit += new EventHandler(Form_OnExit);
}
[STAThread]
static void Main()
{
Application.Run(new MainClass());
}

private void Form_OnExit(object sender, EventArgs evArgs)
{
Console.WriteLine("Exit");
}
}


using System;
using System.Threading;
using System.Windows.Forms;

public class BlockLeftMouseButtonMessageFilter : IMessageFilter
{
const int WM_LEFTBUTTONDOWN = 0x201;

public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LEFTBUTTONDOWN)
{
Exception LeftButtonDownException;

LeftButtonDownException = new Exception("The left mouse button was pressed.");
Application.OnThreadException(LeftButtonDownException);
return true;
}
return false;
}
}


public class ApplicationEventHandlerClass
{
public void OnThreadException(object sender, ThreadExceptionEventArgs e)
{
Exception LeftButtonDownException;
LeftButtonDownException = e.Exception;
Console.WriteLine(LeftButtonDownException.Message);
}
}

public class MainForm : Form
{
public static void Main()
{
ApplicationEventHandlerClass AppEvents = new ApplicationEventHandlerClass();
MainForm myForm = new MainForm();
BlockLeftMouseButtonMessageFilter MsgFilter = new BlockLeftMouseButtonMessageFilter();

Application.AddMessageFilter(MsgFilter);
Application.ThreadException += new ThreadExceptionEventHandler(AppEvents.OnThreadException);
Application.Run(myForm);
}


public MainForm()
{
Text = "Application Exception Test";
}
}




Module Module1

Sub Main()
Console.Title = "Custom Command Window"
Console.BackgroundColor = ConsoleColor.White
Console.ForegroundColor = ConsoleColor.DarkBlue
Console.WindowHeight = Console.LargestWindowHeight - 15
Console.WindowWidth = Console.LargestWindowWidth - 15

Console.Clear()
Console.ReadLine()

End Sub

End Module



Module Module1

Sub Main(ByVal cmdArgs() As String)
Dim strArg As String

If cmdArgs.Length > 0 Then
For Each strArg In cmdArgs
Select Case strArg.Substring(0, 3)
Case "/a1"
Console.WriteLine("Processsing arg1: Value is {0}.", strArg.Substring(3, strArg.Length - 3))
Case "/a2"
Console.WriteLine("Processing arg1: Value is {0}.", strArg.Substring(3, strArg.Length - 3))
End Select
Next
End If

End Sub

End Module


Namespace MyApp.Info


Public Class Utilities
'Run time application
Public Sub DisplayData()
Console.WriteLine(Environment.MachineName)
Console.WriteLine(Environment.SystemDirectory)
Console.WriteLine(Environment.GetLogicalDrives())
Console.WriteLine(Environment.Version.ToString())
End Sub
End Class

Module Main

Sub Main()
Dim objHW As New MyApp.Info.Utilities
objHW.DisplayData()
End Sub

End Module

End Namespace


Sub Main(ByVal cmdArgs() As String)
If Environment.GetCommandLineArgs.Length > 0 Then
For Each strArg As String In Environment.GetCommandLineArgs
'process the arguments here
Console.WriteLine(strArg)
Next strArg
End If
End Sub


Public Class Tester
Public Shared Sub Main()
Console.WriteLine("Enter the numerator")
Dim a As Integer = Console.ReadLine()
Console.WriteLine("Enter the denominator")
Dim b As Integer = Console.ReadLine()


Try
Dim numerator As Integer = Convert.ToInt32(a)
Dim denominator As Integer = Convert.ToInt32(b)

Dim result As Integer = numerator \ denominator

Catch formattingException As FormatException
Console.WriteLine("You must enter two integers")
Catch dividingException As DivideByZeroException
Console.WriteLine(dividingException.Message)


End Try
End Sub

End Class


Imports System
Imports System.IO
Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_03

'create a byte array from a decimal
Public Shared Function DecimalToByteArray(ByVal src As Decimal) As Byte()
'Create a MemoryStream as a buffer to hold the binary data.
Using Stream As New MemoryStream
'Create a BinaryWriter to write binary data to the stream
Using writer As New BinaryWriter(Stream)
'write the decimal to the BinaryWriter/MemoryStream
writer.Write(src)
'return the byte representation of the decimal
Return Stream.ToArray
End Using
End Using

End Function

'create a decimal from a byte array
Public Shared Function ByteArrayToDecimal(ByVal src As Byte()) As Decimal
'create a MemoryStream containing the byte array.
Using Stream As New MemoryStream(src)
'create a binaryReader to read the decimal from the stream.
Using reader As New BinaryReader(Stream)
'Read and return the decimal from the
'BinaryReader/MemoryStream
Return reader.ReadDecimal
End Using
End Using

End Function


Public Shared Sub Main()

Dim b As Byte() = Nothing

'Convert a boolean to a byte array and display
b = BitConverter.GetBytes(True)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a boolean and display
Console.WriteLine(BitConverter.ToBoolean(b, 0))

'convert and interger to a byte array and display
b = BitConverter.GetBytes(3678)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to integer and display
Console.WriteLine(BitConverter.ToInt32(b, 0))

'convert a decimal to a byte array and display
b = DecimalToByteArray(285998345545.563846696D)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a decimal and display
Console.WriteLine(ByteArrayToDecimal(b))

'Wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter.")
Console.ReadLine()

End Sub


End Class
End Namespace


Imports System
Imports System.Text.RegularExpressions

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_05

Public Shared Function ValidateInput(ByVal expression As String, ByVal input As String) As Boolean

'Create a new Regex based on the specified regular expression.
Dim r As New Regex(expression)

'Test if the specified input matches the regular expression
Return r.IsMatch(input)

End Function


Sub New(ByVal args As String())

'Test the input frm the command line. The first argument is the regular expression, and the second is the input
Console.WriteLine("Regular Expressions: {0}", args(0))
Console.WriteLine("Input: {0}", args(1))
Console.WriteLine("Valued = {0}", ValidateInput(args(0), args(1)))

'Wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter")
Console.ReadLine()

End Sub

End Class

Public Class MainClass

''must be shared if you define it inside a class
Public Shared Sub Main()
Console.WriteLine("Enter regex here")
Dim a = Console.ReadLine()
Console.WriteLine("Enter test string here")
Dim b = Console.ReadLine()

Dim stringArray(1) As String
stringArray(0) = a
stringArray(1) = b

Dim ex As New Recipe02_05(stringArray)


End Sub

End Class

End Namespace


#include
int main(void)
{
long num;
long sum = 0l;
int status;

printf("Please enter an integer to be summed");
printf("(q to quit): ");
status = scanf("%ld", &num);
while (status == 1) //means 'is equal to'
{
sum = sum +num;
printf("please enter next integer (q to quit): ");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);

return 0;
}


#include
int main(void)
{
int n = 5;

while(n < 7)
{
printf("n = %d\n", n);
n++;
printf("Now n = %d\n", n);
}
printf("The loop has finished.\n");

return 0;
}


using System;
using System.Data;

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

//add a DataTable named Table-1 directly
DataTable dt1 = ds.Tables.Add("Table-1");
//configure the DataTable...add some columns etc.
DataColumn col1 = dt1.Columns.Add();
col1.ColumnName = "PrimaryKey";
col1.DataType = typeof(int);
col1.Unique = true;
col1.AutoIncrement = true;

//add a DataTable named Table-2 by creating the table
//and adding it to the DataSet

DataTable dt2 = new DataTable("Table-2");
//configure the DataTable, add some columns, etc.
DataColumn col2 = new DataColumn();
col2.ColumnName = "CompanyName";
ds.Tables.Add(dt2);
//add multiple DataTables to the DataSet
DataTable dt3 = new DataTable("Table-3");
DataTable dt4 = new DataTable("Table-4");
//configure the DataTable -- add some columns, etc.
ds.Tables.AddRange(new DataTable[] {dt3, dt4});

//output the tables in the DataSet to the console.
Console.WriteLine("DataSet has {0} DataTables named: ", ds.Tables.Count);
foreach (DataTable dt in ds.Tables)
Console.WriteLine("\t{0}", dt.TableName);

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

Thursday, August 18, 2011

Thursday 8.18.11


//modulus
#include
#define SEC_PER_MIN 60
int main(void)
{
int sec, min, left;

printf("Convert seconds to minutes and seconds!\n");
printf("Enter the number of seconds (<=0 to quit):\n");
scanf("%d", &sec);
while (sec>0)
{
min = sec / SEC_PER_MIN; //truncated number of minutes
left = sec % SEC_PER_MIN; //number of seconds left over
printf("%d seconds is %d minutes, %d seconds.\n", sec, min, left);
printf("Enter next value (<=0 to quit):\n");
scanf("%d", &sec);
}
printf("Done!\n");

return 0;
}





#include
int main(void)
{
int ultra = 0, super = 0;

while (super < 5)
{
super++;
++ultra;
printf("super = %d, ultra = %d \n", super, ultra);
}

return 0;
}





#include
int main(void)
{
int a = 1, b = 1;
int aplus, plusb;

aplus = a++;
plusb = ++b;
printf("a aplus b plusb \n");
printf("%1d %5d %5d %5d\n", a, aplus, b, plusb);

return 0;
}




#include
int main(void)
{
int count, sum; //declaration statement

count = 0; //assignment statement
sum = 0; //assignment statement
while (count++ < 20) //while statement (structured statement)
{
sum = sum + count;
printf("sum = %d\n", sum); //function statement
}
return 0

}




#include
int main(void)
{
char ch;
int i;
float f1;

f1 = i = ch = 'C';
printf("ch = %c, i = %d, f1 = %2.2f\n", ch, i, f1);
ch = ch + 1;
i = f1 + 2 * ch;
f1 = 2.0 * ch + i;
printf("ch = %c, i = %d, f1 = %2.2f\n", ch, i, f1);
ch = 5212205.17;
printf("Now ch = %c\n", ch);

return 0;
}




#include
void pound(int n);

int main(void)
{
int times = 5;
char ch = '!'; //ASCII code is 33
float f = 6.0;

pound(times); //int argument
pound(ch); //char automatically -> int
pound((int) f); //cast forces f -> int

return 0;
}

void pound(int n)
{
while (n-- > 0)
{
printf("#");
}
printf("\n");
}




#include
const int S_PER_M = 60;
const int S_PER_H = 3600;
const double M_PER_K = 0.62137;

int main(void)
{
double distk, distm; //distance run in km and in miles
double rate; //average speed in mph
int min, sec; // minutes and seconds of running time
int time; //running time in seconds only
double mtime; //time in seconds for one mile
int mmin, msec; //minutes and seconds for one mile

printf("This program converts your time for a metric race\n");
printf("to a time for running a mile and to your average\n");
printf("speed in miles per hour.\n");
printf("Please enter, in kilometeres, the distance run.\n");
scanf("%lf", &distk); //%lf for type double
printf("Next, enter the time in minutes and seconds.\n");
printf("Begin by entering the minutes.\n");
scanf("%d", &min);
printf("Now enter the seconds.\n");
scanf("%d", &sec);
//converts time to pure seconds
time = S_PER_M * min + sec;
//convers kilometers to miles
distm = M_PER_K * distk;
//miles per sec x sec per hour = mph
rate = distm / time * S_PER_H;
// time/distance - time per mile
mtime = (double) time / distm;
//using the cast operator
mmin = (int) mtime / S_PER_M; //find whole minutes
msec = (int) mtime % S_PER_M; //find remain seconds
printf("Your ran %1.2f km (%1.2f miles) in %d min, %d sec.\n", distk, distm, min, sec);
printf("That pace corresponds to running a mile in %d min, ", mmin);
printf("%d sec.\n Your average speed was %1.2f mph.\n", msec, rate);

return 0;
}




using System;
using System.Windows.Forms;

public class MainClass : System.Windows.Forms.Form
{
public MainClass()
{
Console.WriteLine("Company: " + Application.CompanyName);
Console.WriteLine("App Name: " + Application.ProductName);
Console.WriteLine("I live here: " + Application.StartupPath);
}
[STAThread]
static void Main()
{
Application.Run(new MainClass());
}
}




Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface 'IStorable

'here's the new interface
Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'Document implements both interfaces
Public Class Document
Implements ICompressible, IStorable

'hold teh data for IStorable's Status property
Private myStatus As Integer = 0

'the Document constructor
Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'new

Public Sub Compress() Implements ICompressible.Compress
Console.WriteLine("Implementing Compress")
End Sub

Public Sub Decompress() Implements ICompressible.Decompress
Console.WriteLine("Implementing Decompress")
End Sub

Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set
End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub
End Class

Class Tester
Public Sub Run()
Dim doc As New Document("Test Document")
doc.Status = -1
doc.Read()
doc.Compress()
Console.WriteLine("Document Status: {0}", doc.Status)
End Sub 'Run

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

End Namespace




Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface 'IStorable

'the compressible interface is now the base for ICompressible2
Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'extend ICompressible to log the bytes saved
Interface ICompressible2
Inherits ICompressible
Sub LogSavedBytes()
End Interface 'ICompressible2


'Document implements both interfaces
Public Class Document
Implements ICompressible2, IStorable

Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with: {0}", s)
End Sub 'New

Public Sub LogSavedBytes() Implements ICompressible2.LogSavedBytes
Console.WriteLine("Implementing LogSavedBytes")
End Sub


Public Sub Decompress() Implements ICompressible2.Decompress
Console.WriteLine("Implementing decompress for ICompresible")
End Sub

Public Sub Compress() Implements ICompressible2.Compress
Console.WriteLine("Implementing compress for ICompressible")
End Sub


Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set

End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub

Private myStatus As Integer = 0

End Class

Class Tester
Public Sub Run()
Dim doc As New Document("Test Document")
If TypeOf doc Is IStorable Then
Dim isDoc As IStorable = doc
isDoc.Read()
Else
Console.WriteLine("Could not cast to IStorable")
End If

If TypeOf doc Is ICompressible2 Then
Dim ilDoc As ICompressible2 = doc
Console.Write("Calling both ICOmpressible And ")
Console.WriteLine("ICompressible2 methods...")
ilDoc.Compress()
ilDoc.LogSavedBytes()
Else
Console.WriteLine("Could not cast to ICompressible2")
End If
End Sub

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

End Class
End Namespace




Imports System
Imports System.Text

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_01

Public Shared Function ReverseString(ByVal str As String) As String

'Make sure we have a reversible string.
If str Is Nothing Or str.Length <= 1 Then
Return str
End If

'create a stringBuilder object with the required capacity.
Dim revStr As StringBuilder = New StringBuilder(str.Length)

'Convert the string to a character array so we can easily loop through it
Dim chars As Char() = str.ToCharArray()

'Loop backward through the soruce string one character ata time
'and append each characer to the StringBuilder
For count As Integer = chars.Length - 1 To 0 Step -1
revStr.Append(chars(count))
Next

Return revStr.ToString()

End Function

Public Shared Sub Main()
Console.WriteLine(ReverseString("Madam Im Adam"))

Console.WriteLine(ReverseString("The quick brown fox jumped over the lazy dog."))

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


End Class

End Namespace




Imports System
Imports System.IO
Imports System.Text.Encoding

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_02

Public Shared Sub Main()

'Create a file to hold the output.
Using output As New StreamWriter("C:\inetpub\output.txt")
'Create and Write a string containing the symbol for pi.
Dim srcString As String = String.Format("Area = {0}r^2", ChrW(&H3A0))
output.WriteLine("Source Text: " & srcString)

'write the UTF-15 encoded bytes of the source string.
Dim utf16String As Byte() = Unicode.GetBytes(srcString)
output.WriteLine("UTF-16 Bytes: {0}", BitConverter.ToString(utf16String))

'Convert the UTF-15 encoded source string to UTF-8 and ASCII
Dim utf8String As Byte() = UTF8.GetBytes(srcString)
Dim asciiString As Byte() = ASCII.GetBytes(srcString)

'write teh UTF-8 and ASCII encoded byte arrays.
output.WriteLine("UTF-8 Bytes: {0}", BitConverter.ToString(utf8String))
output.WriteLine("ASCII Bytes: {0}", BitConverter.ToString(asciiString))

'Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded string
'and write to the output file
output.WriteLine("UTF-8 Text: {0}", UTF8.GetString(utf8String))
output.WriteLine("ASCII Text: {0}", ASCII.GetString(asciiString))

End Using

'Wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press enter.")
Console.ReadLine()

End Sub
End Class
End Namespace





Imports System
Imports System.IO

Namespace Apress.VisualBasicRecipes.Chapter02

Public Class Recipe02_03
Public Shared Function DecimalToByteArray(ByVal src As Decimal) As Byte()
'Create a MemoryStream as a buffer to holdthe binary data.
Using Stream As New MemoryStream
'Create a BinaryWriter to write binary data to the stream
Using writer As New BinaryWriter(Stream)
'write the decimal to the BinaryWriter/MemoryStream.
writer.Write(src)

'return the byte representation of the decimal.
Return Stream.ToArray
End Using
End Using

End Function

'create a decimal from a byte array.
Public Shared Function ByteArrayToDecimal(ByVal src As Byte()) As Decimal
'create a MemoryStream containing the byte array.
Using Stream As New MemoryStream(src)
'create a binaryReader to read the decimal from teh stream.
Using reader As New BinaryReader(Stream)
'read and return the decimal from teh BinaryReader/MemoryStream.
Return reader.ReadDecimal
End Using
End Using
End Function

Public Shared Sub Main()

Dim b As Byte() = Nothing

' Convert a boolean to a byte array and display.
b = BitConverter.GetBytes(True)
Console.WriteLine(BitConverter.ToString(b))

' Convert a byte array to a boolean and display
Console.WriteLine(BitConverter.ToBoolean(b, 0))

'convert an interger to a byte array and display
b = BitConverter.GetBytes(3678)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to integer and display
Console.WriteLine(BitConverter.ToInt32(b, 0))

'convert a decimal to a byte array and display
b = DecimalToByteArray(28599834554.563846696D)
Console.WriteLine(BitConverter.ToString(b))

'convert a byte array to a decimal and display
Console.WriteLine(ByteArrayToDecimal(b))

'Wait to continue
Console.WriteLine(vbCrLf & "Main method complete. Press Enter.")
Console.ReadLine()

End Sub

End Class

End Namespace




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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//remove a substring from a string
string name = "Doe, John";
Console.WriteLine(name);
name = name.Remove(3, 1);
Console.WriteLine(name);

string name2 = "Johnson, Don";
Console.WriteLine(name2);
name2 = name2.Remove(7, 5);
Console.WriteLine(name2);

//if performance is critical, and particularly if the string removal operation occurs in a loop
//so that the operation is performed multiple times, you can instead use the Remove method of the
//stringbuilder object

StringBuilder str = new StringBuilder("1234abc5678", 12);
str.Remove(4, 3);
Console.WriteLine(str);

//to replace a delimiting character within a string, use the following code

string commaDelimitedString = "100,200,300,400,500";
Console.WriteLine(commaDelimitedString);
commaDelimitedString = commaDelimitedString.Replace(',', ':');
Console.WriteLine(commaDelimitedString);
commaDelimitedString = commaDelimitedString.Replace(':', '-');
Console.WriteLine(commaDelimitedString);

string theName = "Mary";
string theObject = "car";
string ID = "This is the property of .";
ID = ID.Replace("", theObject);
ID = ID.Replace("", theName);
Console.WriteLine(ID);


}
}
}

Wednesday, August 17, 2011

Wednesday 8.17.11

using System;
using System.IO;

public class MainClass
{
public static void Main()
{
FileInfo MyFile = new FileInfo(@"C:\inetpub\Test2.txt");
MyFile.Create();
}
}




using System;
using System.IO;

public class MainClass
{
public static int Main(string[] args)
{
FileInfo f = new FileInfo(@"C:\inetpub\test3.txt");
FileStream fs = f.Create();

Console.WriteLine("Creation: {0}", f.CreationTime);
Console.WriteLine("Full name: {0}", f.FullName);
Console.WriteLine("Full atts: {0}", f.Attributes.ToString());

fs.Close();
f.Delete();

return 0;
}
}


using System;
using System.IO;

public class MainClass
{
static void Main(string[] args)
{
FileInfo MyFile = new FileInfo(@"C:\inetpub\Testing3.txt");

MyFile.Delete();
}
}



using System;
using System.IO;

class MainClass
{

static void createFile()
{
FileInfo MyFile = new FileInfo(@"C:\inetpub\inputFile.txt");
MyFile.Create();
}

public static void Main(string[] args)
{

int i;
FileStream fin;
FileStream fout;



try
{
fin = new FileStream(@"C:\inetpub\inputFile.txt", FileMode.Open);
}
catch (FileNotFoundException exc)
{
Console.WriteLine(exc.Message + "\nInput File Not Found");
Console.WriteLine("Creating file now.");
createFile();
return;
}

try
{
fout = new FileStream(@"C:\inetpub\outputFile.txt", FileMode.Create);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + "\nError Opening Output File");
return;
}

try
{

do
{
i = fin.ReadByte();
if (i != -1)
{
fout.WriteByte((byte)i);
}
} while (i != -1);
}
catch (IOException exc)
{
Console.WriteLine(exc.Message + " File Error");
}

fin.Close();
fout.Close();
}
}



using System;
using System.IO;

class MainClass
{
public static void Main()
{
string[] aFiles = Directory.GetFiles(@"C:\inetpub\");

foreach (string s in aFiles)
{
Console.WriteLine(s);
}
}
}

OK, back to C. Classes start next week!


#include
int main(void)
{
int bph2o = 212;
int rv;

rv = printf("%d F is water's boiling point.\n", bph2o);
printf("The printf() function printed %d characters.\n", rv);
return 0;
}




#include
int main(void)
{
printf("Here's one way to print a ");
printf("long string.\n");
printf("Here's another way to print a \ long string.\n");
printf("Here's the newest way to print a "
"long string.\n");
return 0;
}




#include
int main(void)
{
unsigned width, precision;
int number = 256;
double weight = 242.5;

printf("What field width?\n");
scanf("%d", &width);
printf("The number is : %d:\n", width, number);
printf("Now enter a width and a precision:\n");
scanf("%d %d", &width, &precision);
printf("Width = %*.*f\n", width, precision, weight);
printf("Done!\n");

return 0;
}




#include
#define ADJUST 7.64
#define SCALE 0.325
int main(void)
{
double shoe, foot;

printf("Shoe size (men's) foot length\n");
shoe = 3.0;
while (shoe < 18.5)
{
foot = SCALE*shoe + ADJUST;
printf("%10.1f %15.2f inches\n", shoe, foot);
shoe = shoe + 1.0;
} //end while
printf("If the shoe fits, wear it.\n");

return 0;
}




#include
int main(void)
{
int num = 1;
while (num < 21)
{
printf("%4d %6d\n", num, num * num);
num = num + 1;
}
}




#include
#define SQUARES 64
#define CROP 1E15
int main(void)
{
double current, total;
int count = 1;

printf("square grains total ");
printf("fraction of \n");
printf(" added grains ");
printf("US total\n");
total = current = 1.0; //start with one grain
printf("%4d %13.2e %12.2e %12.2e\n", count, current, total, total/CROP);
while (count < SQUARES)
{
count = count + 1;
current = 2.0 * current;
total = total + current;
printf("%4d %13.2e %12.2e %12.2e\n", count, current, total, total/CROP);
}
printf("That's all.\n");

return 0;
}




#include
int main(void)
{
printf("integer division: 5/4 is %d \n", 5/4);
printf("integer division: 6/3 is %d \n", 6/3);
printf("integer division: 7/4 is %d \n", 7/4);
printf("floating division: 7./4. is %1.2f \n", 7./4.);
printf("mixed division: 7./4 is %1.2f \n", 7./4);

return 0;
}




#include
int main(void)
{
int n = 0;
size_t intsize;
intsize = sizeof (int);
printf("n = %d, n has %zd bytes; all ints have %zd bytes.\n", n, sizeof n, intsize);

return 0;
}




#include
#define SEC_PER_MIN 60
int main(void)
{
int sec, min, left;

printf("Convert seconds to minutes and seconds!\n");
printf("Enter the number of seconds (<=0 to quit:\n);
scanf("%d", &sec);
while (sec > 0)
{
min = sec / SEC_PER_MIN;
left = sec % SEC_PER_MIN;
printf("%d seconds is %d minutes, %d seconds.\n", sec, min, left);
printf("Enter next value (<=0 to quit:\n");
scanf("%d", &sec);
}
printf("Done!\n");
return 0;
}




#include
#define MAX 100
int main(void)
{
int count = MAX +1;
while(--count > 0) {
printf("%d bottles of beer on the wall, "
"%d bottles of beer!\n", count, count);
printf("Take one down and pass it around, \n");
printf("%d bottles of beer~\n\n", count - 1);
}

return 0;
}

Tuesday, August 16, 2011

Tuesday 8.16.11


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

namespace SetConnectionPoolingOptions
{
class Program
{

static void connection_StateChange(object sender, StateChangeEventArgs e)
{
Console.WriteLine("\tConnection.StateChange event occurred.");
Console.WriteLine("\tOriginalState = {0}", e.OriginalState.ToString());
Console.WriteLine("\tCurrentState = {0}", e.CurrentState.ToString());
}

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

SqlConnection connection = new SqlConnection();

//set up the event handler to detect connection state change
connection.StateChange += new StateChangeEventHandler(connection_StateChange);

//set the connection string with pooling options
connection.ConnectionString = sqlConnectString + "Connection Timeout=15;Connection Lifetime=0;" +
"Min Pool Size=0;Max Pool Size=100;Pooling=true;";

//output the connection string and open/close the connection
Console.WriteLine("Connection string = {0}", connection.ConnectionString);
Console.WriteLine("-> Open connection.");
Console.OpenStandardError();
Console.WriteLine("-> Close connection.");
connection.Close();

//Set the connection string with new pooling options
connection.ConnectionString = sqlConnectString + "Connection Timeout=30;Connection Lifetime=0;" + "Min Pool Size=0;Max Pool Size=200;Pooling=true;";

//output the connection string and open/close the conncetion
Console.WriteLine("\nConnection string = {0}", connection.ConnectionString);
Console.WriteLine("-> Open connection.");
connection.Open();
Console.WriteLine("-> Close connection.");
connection.Close();

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




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace DisplayConnectionPropertyDialog
{
public partial class Form1 : Form
{
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();

public Form1()
{
InitializeComponent();
propertyGrid1.SelectedObject = scsb;
}



private void Form1_Load(object sender, EventArgs e)
{

}

private void onPropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
connectString.Text = scsb.ConnectionString;
}

}
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace ConsoleApplication1
{
class Program
{
//makes the program thread safe for COM
//in a multi-threaded program several threads execute simultaneously
//in a shared address space
[STAThread]
static void Main(string[] args)
{
OpenFileDialog dlgOpen = new OpenFileDialog();

if (dlgOpen.ShowDialog() == DialogResult.OK)
{
string s = dlgOpen.FileName;
Console.WriteLine("Filename " + s);
Console.WriteLine("Created at " + File.GetCreationTime(s));
Console.WriteLine("Accessed at " + File.GetLastAccessTime(s));
}
}
}
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;


namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
OpenFileDialog dlgOpen = new OpenFileDialog();
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
FileInfo fi = new FileInfo(dlgOpen.FileName);
Console.WriteLine("Filename " + fi.FullName);
Console.WriteLine("Created at " + fi.CreationTime);
Console.WriteLine("Accessed at " + fi.LastAccessTime);
}
}
}
}




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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter(@"C:\inetpub\myfile.txt");
for (int i = 0; i < 5; i++)
{
writer.Write(i.ToString());
}
writer.Flush();
writer.Close();
foreach(string line in File.ReadAllLines(@"C:\inetpub\myfile.txt"))
{
Console.WriteLine(line);
}
}
}
}





using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

class MainClass
{
static void Main(string[] args)
{
string[] lines = new string[10];
for (int i = 0; i < 10; i++)
{
lines[i] = string.Format("This is line number {0}", i);
}

File.WriteAllLines(@"C:\inetpub\test.txt", lines);

foreach(string line in File.ReadAllLines(@"C:\inetpub\test.txt"))
{
Console.WriteLine(line);
}
}
}




#include
int main(void)
{
int age;
float assets;
char pet[30];

printf("Enter your age, assets, and favorite pet.\n");
scanf("%d %f", &age, &assets);
scanf("%s", pet);
printf("%d $%.2f %s\n", age, assets, pet);
return 0;
}