Monday, December 19, 2011

Monday 12/19/11

#include
#include //must include !

int main()
{
using namespace std;
string myName = "Alfred Jensen";
string myStreet = "5127 S. 95th E. Ave";
string myCityStreet = "Tulsa, OK";

cout << myName << endl;
cout << myStreet << endl;
cout << myCityStreet << endl;


return 0;
}


#include
#include

int main()
{
using namespace std;
cout << "Please enter the distance in furlongs" << endl;
int furlong = 0;
cin >> furlong;
int yard = furlong * 220;
cout << endl << "That is " << yard << " yards long";

}


#include
#include

int twoTimes()
{
using namespace std;
string s = "Three blind mice";
cout << s << endl;
cout << s << endl;

return 0;
}

int twice()
{
using namespace std;
string s = "See how they run";
cout << s << endl;
cout << s << endl;

return 0;
}

int main()
{
twoTimes();
twice();

}


#include
#include

int main()
{
using namespace std;
cout << "Please enter the temp. in Celsius" << endl;
double celsius = 0.0;
cin >> celsius;
double fahrenheit = celsius * 1.8 + 32.0;
cout << "That is " << fahrenheit << " in Fahrenheit degrees";
}


#include
#include

int calculateAU(double);

int main(){
double lightYears = 0.0;

using namespace std;
cout << "Enter the distance in light years: " << endl;
cin >> lightYears;
calculateAU(lightYears);
}

int calculateAU(double lightYears)
{
double au = lightYears * 265608;
std::cout << "That is " << au << " in astronomical units." << std::endl;
return 0;
}


#include
#include

int main()
{
using namespace std;
int n_int = INT_MAX;
short n_short = SHRT_MAX;
long n_long = LONG_MAX;

//sizeof operator yileds size of type or of variables
cout << "int is " << sizeof(int) << " bytes." << endl;
cout << "short is " << sizeof n_short << " bytes." << endl;
cout << "long is " << sizeof n_long << " bytes." << endl;

cout << "Maximum Values: " << endl;
cout << " Int: " << n_int << endl;
cout << " Short: " << n_short << endl;
cout << " Long: " << n_long << endl << endl;

cout << "Minimum int value=" << INT_MIN << endl;
cout << "Bits per byte=" << CHAR_BIT << endl;

return 0;
}


#include
#define ZERO 0
#include
int main()
{
using namespace std;
short sam = SHRT_MAX;
unsigned short sue = sam;

cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl;
cout << "Add $1 to each account." << endl << "Now.";
sam = sam + 1;
sue = sue + 1;
cout << "Same has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited.\nPoor Sam!" << endl;
sam = ZERO;
sue = ZERO;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl;
cout << "Take $1 from each account." << endl << "Now";
sam = sam - 1;
sue = sue - 1;
cout << "Sam has " << sam << "dollars and Sue has " << sue;
cout << " dollars deposited. " << endl << "Lucky Sue!" << endl;

return 0;
}

Friday, December 16, 2011

Friday 12/16/11

#include
#include

int main()
{
using namespace std;

double area;
cout << "Enter the floor area, in square feet, of your house.";
cout << endl;
cin >> area;
double side;
side = sqrt(area);

cout << "That's the equivalent of a square " << side;
cout << " feet to the side. " << endl;
cout << "How Fascinating!" << endl;
return 0;

}


#include
void simon(int); //function prototype simon()

int main()
{
using namespace std;
simon(3);
cout << " Pick an integer: ";
int count;
cin >> count;
simon(count); //call it again
cout << "Done!" << endl;
return 0;
}

void simon(int n)
{
using namespace std;
cout << "Simon says touch your toes " << n << " times " << endl;
//void functions don't need return statements
}


#include
int stonetolb(int);
int main()
{
using namespace std;
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << " stone = ";
cout << pounds << " pounds. " << endl;
return 0;
}

int stonetolb(int sts)
{
return 14*sts;
}

Thursday, December 15, 2011

Thursday 12.15.11

#include
int main()
{
using namespace std;
cout << "Come up and see me some time.";
cout << endl;
cout << "You won't regret it!" << endl;
return 0;
}


///carrots.cpp food processing program
//use and display a program

#include

int main()
{
using namespace std;

int carrots; //declare an integer variable
carrots = 25;
cout << "I have ";
cout << carrots;
cout << " carrots. ";
cout << endl;
carrots = carrots - 1;
cout << "crunch, crunch, crunch now I have " << carrots << " carrots " << endl;
return 0;
}

Wednesday, December 14, 2011

Wednesday 12.14.11

Imports System
Imports System.Security.Cryptography

Module Module1

Sub Main()
Apress.VisualBasicRecipes.Chapter12.Recipe12_12.Main()
End Sub

End Module

Namespace Apress.VisualBasicRecipes.Chapter12
Public Class Recipe12_12
Public Shared Sub Main()
'create a byte array to hold the random data
Dim number As Byte() = New Byte(32) {}
'instantiate the default random number generator
Dim rng As RandomNumberGenerator = RandomNumberGenerator.Create

'generate 32 bytes of random data
rng.GetBytes(number)

'display the random number
Console.WriteLine(BitConverter.ToString(number))

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


Imports System
Imports System.Text

Imports System.Security.Cryptography

Module Module1

Sub Main()
Dim args As String() = {"SHA384CryptoServiceProvider", "nasal7Spray"}
Recipe12_13.Main(args)

End Sub

End Module

Public Class Recipe12_13

Public Shared Sub Main(ByVal args As String())
'create a hashalgorithm of the type specified by the first command-line argument
Dim hashAlg As HashAlgorithm = Nothing

'some of the lcasses cannot be instantiated using the factory method so they must be directly created
Select Case args(0).ToUpper()
Case "SHA1MANAGED"
hashAlg = New SHA1Managed
Case "SHA256CRYPTOSERVICEPROVIDER"
hashAlg = New SHA256CryptoServiceProvider
Case "SHA384CRYPTOSERVICEPROVIDER"
hashAlg = New SHA384CryptoServiceProvider
Case "SHA512CRYPTOSERVICEPROVIDER"
hashAlg = New SHA512CryptoServiceProvider
Case Else
hashAlg = HashAlgorithm.Create(args(0))
End Select

Using hashAlg
'convert the password string, provided as the second command-line arguemnt
'to an array of bytes
Dim pwordData As Byte() = Encoding.Default.GetBytes(args(1)) 'imports system.text
'generate the has code of the password
Console.WriteLine("Generate the hash code of the password")
Dim hash As Byte() = hashAlg.ComputeHash(pwordData)

'display the hash code of the password to the console
Console.WriteLine(BitConverter.ToString(hash))

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


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

Module Module1

Sub Main()
Dim args As String() = {"SHA1Managed", "C:/new/VBDotNet.txt"}
Recipe12_14.Main(args)

End Sub

End Module

Public Class Recipe12_14

Public Shared Sub Main(ByVal args As String())
'create a hash algorith of the tpye specified by the first command-line argument
Dim hashAlg As HashAlgorithm = Nothing
'the sha1 managed algorithm cannot be implemented using the
'factory approach it must be instantiated directly
If args(0).CompareTo("SHA1Managed") = 0 Then
hashAlg = New SHA1Managed
Else
hashAlg = HashAlgorithm.Create(args(0))
End If

'open a FileStream to teh file specified by the second command-line argument
Using fileArg As New FileStream(args(1), FileMode.Open, FileAccess.Read)
'generate the hash code of the password
Dim hash As Byte() = hashAlg.ComputeHash(fileArg)
'display the hash code fo the password to the console
Console.WriteLine(BitConverter.ToString(hash))
'wait to continue
Console.ReadLine()
End Using
End Sub
End Class


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

Module Module1

Sub Main()
Dim args As String() = {"SHA1Managed", "C:/new/VBDotNet.txt"}
Recipe12_14.Main(args)

End Sub

End Module

Public Class Recipe12_14

Public Shared Sub Main(ByVal args As String())
'create a hash algorith of the tpye specified by the first command-line argument
Dim hashAlg As HashAlgorithm = Nothing
'the sha1 managed algorithm cannot be implemented using the
'factory approach it must be instantiated directly
If args(0).CompareTo("SHA1Managed") = 0 Then
hashAlg = New SHA1Managed
Else
hashAlg = HashAlgorithm.Create(args(0))
End If

readHash(args(1), hashAlg)

Dim myFileStream As System.IO.FileStream

Try
myFileStream = New System.IO.FileStream(args(1), FileMode.Append, FileAccess.Write, FileShare.None)
Try
Dim myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine("Hello World!")
'flush before we close
myWriter.Flush()
myWriter.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Catch ex As Exception
MsgBox(ex.ToString())
Finally
myFileStream.Close()
End Try

readHash(args(1), hashAlg)
End Sub

Public Shared Sub readHash(ByVal fileName, ByVal hashAlg)
'open a FileStream to teh file specified by the second command-line argument
Using fileArg As New FileStream(fileName, FileMode.Open, FileAccess.Read)
'generate the hash code of the password
Dim hash As Byte() = hashAlg.ComputeHash(fileArg)
'display the hash code fo the password to the console
Console.WriteLine(BitConverter.ToString(hash))
'wait to continue
Console.WriteLine()
Console.ReadLine()
End Using
End Sub
End Class



namespace practice
{
class Program
{
static void Main(string[] args)
{
EntryPoint ep = new EntryPoint();
ep.Run();
Console.ReadLine();
}
}

public struct Coordinate //this is a value type
{
public int x;
public int y;
}

public class EntryPoint //this is a reference type
{
public static void AttemptToModifyCoord(Coordinate coord)
{
coord.x = 1;
coord.y = 1;
}

public static void ModifyCoord(ref Coordinate coord)
{
coord.x = 10;
coord.y = 10;
}

public void Run()
{
Coordinate location;
location.x = 50;
location.y = 50;

AttemptToModifyCoord(location);
System.Console.WriteLine("({0}, {1} )", location.x, location.y);

ModifyCoord(ref location);
System.Console.WriteLine("({0}, {1} )", location.x, location.y);
}
}
}


class Program
{
[Flags]
public enum AccessFlags
{
NoAccess = 0x0,
ReadAccess = 0x1,
WriteAccess = 0x2,
ExecuteAccess = 0x4
}

static void Main(string[] args)
{
AccessFlags access = AccessFlags.ReadAccess | AccessFlags.WriteAccess;
System.Console.WriteLine("Access is {0}", access);
}
}


static void Main(string[] args)
{
var myList = new List();

myList.Add(1);
myList.Add(2);
myList.Add(3);

foreach (var i in myList)
{
Console.WriteLine(i);
}
}


Imports System
Imports System.Reflection
Imports System.Security.Policy


Module ADSetupInformation

Sub Main()
'create the application domain setup information
Dim domainInfo As New AppDomainSetup()
domainInfo.ApplicationBase = System.Environment.CurrentDirectory
'create evidence for a new AppDomain
Dim adevidence As Evidence = AppDomain.CurrentDomain.Evidence

'create the new application domain using setup information
Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain", adevidence, domainInfo)

'write out the domain information
Console.WriteLine("Host Domain: " + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine("New child domain: " + domain.FriendlyName)
Console.WriteLine()
Console.WriteLine("Application base is: " + domain.SetupInformation.ApplicationBase)

AppDomain.Unload(domain)
Console.ReadLine()
End Sub

End Module

Tuesday, December 13, 2011

Tuesday 12.13.11

Public Interface IAppFunctionality
Sub DoIt()
End Interface

_
Public NotInheritable Class CompanyInfoAttribute
Inherits System.Attribute

Private companyName As String
Private companyUrl As String

Public Sub New()
End Sub
Public Property Name() As String
Get
Return companyName
End Get
Set(ByVal value As String)
companyName = value
End Set
End Property

Public Property Url() As String
Get
Return companyUrl
End Get
Set(ByVal value As String)
companyUrl = value
End Set
End Property

End Class

Imports System.Windows.Forms
Imports CommonSnappableTypes


Module Module1

Sub Main()
Dim s As New VbNetSpanInModule()
s.DoIt()
End Sub

End Module

_
Public Class VbNetSpanInModule
Implements IAppFunctionality

Public Sub New()

End Sub

Public Sub DoIt() Implements CommonSnappableTypes.IAppFunctionality.DoIt
MessageBox.Show("You have just used the VB 2008 snap in!")
End Sub
End Class




Imports System.Reflection
Imports CommonSnappableTypes

Public Class Form1

Private Sub SnapInModuleToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SnapInModuleToolStripMenuItem.Click
'allow user to select an assemnly to load
Dim dlg As New OpenFileDialog()

If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
If dlg.FileName.Contains("CommonSnappableTypes") Then
MessageBox.Show("CommonSnappableTypes has no snap-ins!")
ElseIf LoadExternalModule(dlg.FileName) = False Then
MessageBox.Show("nothing implements IAppFunctionality!")
End If
End If
End Sub

Private Function LoadExternalModule(ByVal path As String) As Boolean
Dim foundSnapin As Boolean = False
Dim itfAppFx As IAppFunctionality
Dim theSnapInAsm As Assembly = Nothing

'try to dynamically load the selected assembly
Try
theSnapInAsm = Assembly.LoadFrom(path)
Catch ex As Exception
MessageBox.Show(ex.Message)
Return foundSnapin
End Try

'get all IAppFunctionality compatible classes in assembly using a LINQ query and implicity typed data
Dim classTypes = From t In theSnapInAsm.GetTypes() Where t.IsClass And (t.GetInterface("IAppFunctionality") IsNot Nothing) Select t

For Each c As Object In classTypes
foundSnapin = True
'use late binding to create the type
Dim o As Object = theSnapInAsm.CreateInstance(c.FullName)

'call DoIt() off the interface
itfAppFx = CType(o, IAppFunctionality)
itfAppFx.DoIt()
lstLoadedSnapIns.items.add(c.FullName)

Next
Return foundSnapin


End Function


Module Module1

Sub Main()
ListAllRunningProcesses()
Console.ReadLine()

Dim theProc As Process
Try
theProc = Process.GetProcessById(987)
'manipulate the process handle...
Catch ex As Exception
Console.WriteLine("-> Sorry...bad PID!")
End Try
Console.ReadLine()
'Prompt user for a PID and print out the set of active threads
Console.WriteLine("***** Enter PID of process to investigate *****")
Console.Write("PID: ")
Dim pID As String = Console.ReadLine()
Try
Dim theProcID As Integer = Integer.Parse(pID)
EnumThreadsForPid(theProcID)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
Dim proc As Process() = Process.GetProcessesByName("ListAllProcesses")
For Each p In proc
Console.WriteLine("Proc name is {0}", p.ProcessName)
Console.WriteLine("Proc id is {0}", p.Id)
EnumModsForPid(p.Id)
Next
StartAndKillProcess()

End Sub


Public Sub ListAllRunningProcesses()
'get all the processes on the local machine
Dim runningProcs As Process() = Process.GetProcesses(".")

'print out each PID and name of each process
For Each p As Process In runningProcs
Dim info As String = String.Format("-> PID: {0}" & Chr(9) & "Name: {1}", p.Id, p.ProcessName)
Console.WriteLine(info)
Next
Console.WriteLine("*****************************")
Console.WriteLine()
End Sub

Public Sub EnumThreadsForPid(ByVal pID As Integer)
Dim theProc As Process
Try
theProc = Process.GetProcessById(pID)
Catch ex As Exception
Console.WriteLine("-> Sorry...bad PID!")
Console.WriteLine("***********************")
Console.WriteLine()
Return
End Try
Console.WriteLine("Here are the threads used by: {0}", theProc.ProcessName)

'list out stats for each thread in the specified process
Dim theThreads As ProcessThreadCollection = theProc.Threads
For Each pt As ProcessThread In theThreads
Dim info As String = String.Format("-> Thread ID: {0}" & Chr(9) & "Start Time {1}" & _
Chr(9) & "Priority {2}", _
pt.Id, pt.StartTime.ToShortTimeString(), pt.PriorityLevel)
Console.WriteLine(info)
Next
Console.WriteLine("*************************")
Console.WriteLine()
End Sub

Public Sub EnumModsForPid(ByVal pID As Integer)
Dim theProc As Process
Try
theProc = Process.GetProcessById(pID)

Catch ex As Exception
Console.WriteLine("->Sorry...bad PID!")
Console.WriteLine("********************")
Console.WriteLine()
Return
End Try
Console.WriteLine("Here are the loaded modules for: {0}", theProc.ProcessName)
Try
Dim theMods As ProcessModuleCollection = theProc.Modules
For Each pm As ProcessModule In theMods
Dim info As String = String.Format("-> Mod Name: {0}", pm.ModuleName)
Console.WriteLine(info)
Next
Console.WriteLine("******************")
Console.WriteLine()
Catch ex As Exception
Console.WriteLine("No mods!")
End Try
End Sub

Public Sub StartAndKillProcess()
'launch internet explorer
Console.WriteLine("--> Hit a key to launch IE")
Console.ReadLine()
Dim ieProc As Process = Process.Start("IExplorer.exe", "www.intertech.com")
Console.WriteLine("--> Hit a key to kill {0}...", ieProc.ProcessName)
Console.ReadLine()
'kill the iexplorer.exe process
Try
ieProc.Kill()
Catch 'in case the user already killed it...
End Try
End Sub
End Module

Monday, December 12, 2011

Monday 12/12/11

Imports System.Reflection

Module Module1

Sub Main()
Console.WriteLine("***** Welcome to MyTypeViewer *****")
Dim typeName As String = String.Empty

Do
Console.WriteLine()
Console.WriteLine("Enter a type name to evaluate")
Console.Write("or enter Q to quit: ")

'get name of type
typeName = Console.ReadLine()
'does user want to quit?
If typeName.ToUpper() = "Q" Then
Exit Do
End If

'try to display type
Try
Dim t As Type = Type.GetType(typeName)
Console.WriteLine()
ListVariousStats(t)
ListFields(t)
ListProps(t)
ListMethods(t)
ListInterfaces(t)
Catch ex As Exception
Console.WriteLine("Sorry, cant' find {0}.", typeName)
End Try
Loop
End Sub


Public Sub ListMethods(ByVal t As Type)
Console.WriteLine("***** Methods *****")
Dim mi As MethodInfo() = t.GetMethods()
For Each m As MethodInfo In mi
Dim retVal As String = m.ReturnType.FullName()
Dim paramInfo As String = "( "
For Each pu As ParameterInfo In m.GetParameters()
paramInfo &= String.Format("{0} {1} ", pu.ParameterType, pu.Name)
Next
paramInfo &= " )"
Console.WriteLine("->{0} {1} {2}", retVal, m.Name, paramInfo)
Next
Console.WriteLine()

End Sub
'display field names of type
Public Sub ListFields(ByVal t As Type)
Console.WriteLine("***** Field *****")
Dim fi As FieldInfo() = t.GetFields()
For Each field As FieldInfo In fi
Console.WriteLine("->{0}", field.Name)
Next
Console.WriteLine()
End Sub

'display property names of type
Public Sub ListProps(ByVal t As Type)
Console.WriteLine("***** Properties *****")
Dim pi As PropertyInfo() = t.GetProperties()
For Each prop As PropertyInfo In pi
Console.WriteLine("->{0}", prop.Name)
Next
Console.WriteLine()
End Sub

'print out th enames of any interfaces
'supported on the incoming type
Public Sub ListInterfaces(ByVal t As Type)
Console.WriteLine("***** Interfaces *****")
Dim ifaces As Type() = t.GetInterfaces()
For Each i As Type In ifaces
Console.WriteLine("->{0}", i.Name)
Next
Console.WriteLine()
End Sub

Public Sub ListVariousStats(ByVal t As Type)
Console.WriteLine("***** Various Statistics *****")
Console.WriteLine("Base class is: {0}", t.BaseType)
Console.WriteLine("Is type abstract? {0}", t.IsAbstract)
Console.WriteLine("Is type sealed? {0}", t.IsSealed)
Console.WriteLine("Is type generic? {0}", t.IsGenericTypeDefinition)
Console.WriteLine("Is type a class type? {0}", t.IsClass)
Console.WriteLine()
End Sub
End Module


'demonstrates dynamic laoding
Imports System.Reflection

Module Module1

Sub Main()
Console.WriteLine("***** External Assemly Viewer *****")
Dim asmName As String = String.Empty
Dim asm As Assembly = Nothing
Do
Console.WriteLine()
Console.WriteLine("Enter an assembly to evaluate")
Console.Write("or enter Q to quit: ")

'get name of assembly
asmName = Console.ReadLine()

'does user want to quit?
If asmName.ToUpper = "Q" Then
Exit Do
End If

Try 'try to load assembly
asm = Assembly.Load(asmName)
DisplayTypesInAsm(asm)
Catch ex As Exception
Console.WriteLine("Sorry, can't find assembly named {0}.", asmName)
End Try
Loop

End Sub

Sub DisplayTypesInAsm(ByVal asm As Assembly)
Console.WriteLine()
Console.WriteLine("***** Types in Assembly *****")
Console.WriteLine("->{0}", asm.FullName)
Dim types As Type() = asm.GetTypes()
For Each t As Type In types
Console.WriteLine("Type: {0}", t)
Next
Console.WriteLine()
End Sub

End Module

Saturday, December 10, 2011

Saturday 12/10/2011

'this type is in the root namespace,
' which is (by default) the same name
'as the initial project

Public Class SomeClass
End Class

'this naemspace is nested within the root. therefore the fully
'qualified name of this class is MyCodeLibrary.MyTypes.SomeClass
Namespace MyTypes
Public Class SomeClass
End Class

'it is possible to nest namespaces within other namespaces to gain a greater level of structure
'thus the fully qualified name of this enum is
'MyCodeLibary.MyTypes.MyEnums.TestEnum
Namespace MyEnums
Public Enum TestEnum
TestValue
End Enum
End Namespace
End Namespace

Imports System.Windows.Forms

Public Class SportsCar
Inherits Car

Public Sub New()
End Sub

Public Sub New(ByVal carName As String, ByVal max As Short, ByVal curr As Short)
MyBase.New(carName, max, curr)
End Sub


Public Overrides Sub TurboBoost()
MessageBox.show("Ramming speed!", "Faster is better...")
End Sub
End Class

Public Class MiniVan
Inherits Car

Public Sub New()

End Sub

Public Sub New(ByVal carName As String, ByVal max As Short, ByVal curr As Short)
MyBase.New(carName, max, curr)
End Sub

Public Overrides Sub TurboBoost()
'minivans have poor turbo capabilities!
egnState = EngineState.engineDead
MessageBox.Show("Time to call AAA", "Your car is dead")
End Sub
End Class