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.");
}
}
}

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