by ashraf
26. October 2008 13:17
.Net Working With Numbers VB#
Dim i As Integer = 0
i += 10 ' add 10 to i
i -= 5 ' subtract 5 from i
i *= 2 ' multiply i by 2
i /= 2 ' divide i by 2
' parse strings as numbers
' all number types have Parse and TryParse shared functions
Try
i = Integer.Parse(Console.ReadLine())
Console.WriteLine("You typed a number")
Catch ex As FormatException
Console.WriteLine("Please type a number")
End Try
If Integer.TryParse(Console.ReadLine(), i) Then
Console.WriteLine("You typed a number")
Else
Console.WriteLine("Please type a number")
End If
' money
Dim price As Decimal = 19.99
price = Decimal.Parse("$39.95" NumberStyles.Currency)
.Net Making Decisions VB#
Dim count As Integer = 10
' simple 1 line if then else
Dim oneHand As Boolean = IIf(count <= 5, True, False)
If count <= 5 Then oneHand = True Else oneHand = False
' multiple conditions
If count = 0 Then
Console.WriteLine("Zero")
ElseIf count > 0 And count < 6 Then
Console.WriteLine("Count on one hand.")
ElseIf count >= 6 And count <= 10 Then
Console.WriteLine("Count on two hands.")
Else
Console.WriteLine("Not enough fi ngers.")
End If
' select case
Select Case count
Case 0 ' simple value expression
Console.WriteLine("Zero.")
Case 1 To 5 ' a range of values
Console.WriteLine("Count on one hand.")
Case 6, 7 To 9, 10 ' multiple expressions
Console.WriteLine("Count on two hands.")
Case Is > 10, Is <= 20 ' use comparison operators
Console.WriteLine("Count on hands and feet.")
Case Else
Console.WriteLine("Not enough fi ngers and toes.")
End Select
.Net Working With Strings VB#
Dim s As String = "Hello World"
Debug.Assert(s.Contains("World"))
Debug.Assert(7 = s.IndexOf("World"))
Debug.Assert(s.StartsWith("Hello"))
Debug.Assert(s.Substring(0, 5) = "Hello")
' combining and formatting strings
s = "Hello" + " " + "World"
s = String.Format("s is: {0}", s)
Dim sb As New StringBuilder()
For i As Integer = 0 To 100
sb.AppendFormat("{0},", i)
Next
s = sb.ToString()
.Net Working With Dates and Times VB#
Dim now As Date = Date.Now ' date and time
Dim today As Date = Date.Today ' just the date
Dim tomorrow As Date = today.AddDays(1)
Dim yesterday As Date = today.AddDays(-1)
' use parse functions to convert from strings
Dim vb1 As Date = Date.Parse("1991-05-01")
' use culture info to parse dates in regional formats
Dim gb As New CultureInfo("en-GB")
vb1 = Date.Parse("01-05-1991", gb.DateTimeFormat)
' format dates as strings
vb1.ToLongDateString() ' Wednesday, May 01, 1991
vb1.ToShortDateString() ' 5/1/1991
vb1.ToLongTimeString() ' 12:00:00 AM
vb1.ToShortTimeString() ' 12:00 AM
vb1.ToString("u") ' 1991-05-01 00:00:00Z
vb1.ToString("yyyy-MM-dd") ' 1991-05-01
' TimeSpan represents differnce between two dates
Dim time As TimeSpan = tomorrow - today
Dim days As Integer = time.Days
Dim hours As Integer = time.Hours
Dim minutes As Integer = time.Minutes
Dim seconds As Integer = time.Seconds
Dim milliseconds As Integer = time.Milliseconds
' Add time using other timespan instances
time.Add(New TimeSpan(days, hours, minutes, seconds,
milliseconds))
' or
time += New TimeSpan(days, hours, minutes, seconds,
milliseconds)
' use a timespan to add time to a date
today.Add(time)
' or
today += time
' timespan represented as Days.Hours:Minutes:Seconds:
' Subseconds
time = TimeSpan.Parse("1.2:3:4:5")
' or
If TimeSpan.TryParse(Console.ReadLine(), time) Then
Console.WriteLine(time)
End If
.Net Making Comparisons VB#
Debug.Assert(1 = 1) ' equal
Debug.Assert(1 <> 2) ' not equal
Debug.Assert(1 <= 2) ' less than or equal
Debug.Assert(1 >= 0) ' greater than or equal
Debug.Assert(1 < 2) ' less than
Debug.Assert(1 > 0) ' greater than
.Net Working With Objects VB#
Dim o As Object = "Hello World"
' check type of object
Debug.Assert(TypeOf o Is String)
' check if reference is not set
Debug.Assert(Not o Is Nothing)
.Net Loops VB#
For i As Integer = 10 To 1 Step -1
Console.WriteLine(i)
If i < 5 Then
Exit For
End If
Next
Dim start As Integer = 5
For i As Integer = start To start + 10
Console.WriteLine(i)
Next
Dim str As String
Do
str = Console.ReadLine()
Console.WriteLine(str)
Loop Until str = ""
Do
str = Console.ReadLine().Trim()
If String.IsNullOrEmpty(str) Then
Exit Do
End If
Console.WriteLine("You typed:{0}", str)
Loop
Dim names As String() = New String() {"Tom", "Daniel"}
For Each name As String In names
Console.WriteLine(name)
Next
.Net Working With Text VB#
Imports System.IO
Imports System.Text
Dim name As String = "Daniel"
Dim hello1 As String = "Hello " + name
Dim hello2 As String = String.Format("Hello {0}", name)
Console.WriteLine("Hello {0}", name)
Dim sb As New StringBuilder("Hello ")
sb.AppendLine(name)
sb.AppendFormat("Goodbye {0}", name)
Console.WriteLine(sb.ToString())
' create a text file
Using w As StreamWriter = File.CreateText("c:\names.txt")
w.WriteLine("Tom")
w.WriteLine("Daniel")
End Using
' read from a text fi le
Using r As StreamReader = File.OpenText("c:\names.txt")
Do While Not r.EndOfStream
Console.WriteLine(r.ReadLine())
Loop
End Using
For Each s As String In File.ReadAllLines("c:\names.txt")
Console.WriteLine(s)
Next
.Net Working With XML VB#
Imports System.IO
Imports System.Xml
' create an xml fi le
Using xw As XmlWriter = XmlWriter.Create("c:\names.xml")
xw.WriteRaw("<names>")
xw.WriteRaw("<name>Tom</name>")
xw.WriteRaw("<name>Daniel</name>")
xw.WriteRaw("</names>")
End Using
' load an xml fi le
Dim doc As New XmlDocument()
doc.Load("c:\names.xml")
For Each node As XmlNode In doc.SelectNodes("//name/text()")
Console.WriteLine(node.Value)
Next
.Net Working With a Database VB#
Imports System.Data
Imports System.Data.SqlClient
Dim cs As String = "Data Source=.\SQLEXPRESS;" + _
"Initial Catalog=NamesDB;" + _
"Integrated Security=True;"
Using con As New SqlConnection(cs)
con.Open()
' insert a record
sql = "INSERT INTO Names(Name) VALUES(@Name)"
Dim cmd1 As New SqlCommand(sql, con)
cmd1.Parameters.Add("@Name", SqlDbType.NVarChar, 100)
cmd1.Parameters("@Name").Value = "Tom"
cmd1.ExecuteNonQuery()
' insert a second record
cmd1.Parameters("@Name").Value = "Daniel"
cmd1.ExecuteNonQuery()
' read records
sql = "SELECT * FROM Names"
Dim cmd2 As New SqlCommand(sql, con)
Using r As SqlDataReader = cmd2.ExecuteReader()
Dim iName As Integer = r.GetOrdinal("Name")
Do While r.Read()
If r.IsDbNull(iName) Then
Console.WriteLine("Null")
Else
Console.WriteLine(r.GetString(iName))
End If
Loop
End Using
' read a single value
sql = "SELECT TOP 1 Name FROM Names"
Dim cmd3 As New SqlCommand(sql, con)
Console.WriteLine(cmd3.ExecuteScalar())
End Using
.Net Classes VB#
' Fields, properties, methods and constructors
Public Class SomeClass
' field
Private mName As String
' read/write property
Public Property Name() As String
Get
Return mName
End Get
Set(ByVal value As String)
mName = value
End Set
End Property
' read only property
Public ReadOnly Property FormattedName() As String
Get
Return String.Format("Hello {0}", mName)
End Get
End Property
' methods/procedures
Public Sub PrintName(ByVal format As String)
Console.WriteLine(format, Me.FormattedName)
End Sub
' constructor
Sub New(ByVal name As String)
mName = name
End Sub
End Class
' Inheritance/Subclassing
Public Class BaseClass
Public Overridable Sub SayHello()
Console.WriteLine("Hello BaseClass")
End Sub
End Class
Public Class DerivedClass
Inherits BaseClass
' override inherited method
Public Overrides Sub SayHello()
' invoke the base class version of the method
MyBase.SayHello()
Console.WriteLine("Hello DerivedClass")
End Sub
End Class
by ashraf
26. October 2008 10:31
.Net Working With Numbers C#
int i = 0;
// convert from a string
int i = int.Parse("1");
// convert froma string and don’t throw exceptions
if (int.TryParse("1", out i)) {}
i++; // increment by one
i--; // decrement by one
i += 10; // add 10
i -= 10; // subtract 10
i *= 10; // multiply by 10
i /= 10; // divide by 10
i = checked(i*2) // check for overfl owerflow
i = unchecked(i*2) // ignore overfl owerflow
.Net Dates and Times C#
DateTime now = DateTime.Now; // date and time
DateTime today = DateTime.Today; // just the date
DateTime tomorrow = today.AddDays(1);
DateTime yesterday = today.AddDays(-1);
TimeSpan time = tomorrow - today;
int days = time.Days;
int hours = time.Hours;
int minutes = time.Minutes;
int seconds = time.Seconds;
int milliseconds = time.Milliseconds;
time += new TimeSpan(days, hours, minutes, seconds,
milliseconds);
.Net Conditional Logic C#
if (i == 0) {}
if (i <= 10) {} else {}
switch (i) {
case 0:
case 1:
break;
case 2:
break;
default:
break;
}
.Net Compare Operators C#
if (i == 0) // equal
if (i != 0) // not equal
if (i <= 0) // less than or equal
if (i >= 0) // greater than or equal
if (i > 0) // greater than
if (i < 0) // less than
if (o is MyClass) // check type of object
if (o == null) // check if reference is null
.Net Loops C#
for (int i=0; i<10; i++) {}
while (i<10) { i++; }
do { i++; } while (i<10);
foreach (ListItem item in list.Items) {}
.Net Define New Types C#
struct MyValueType {} // defi nes a value type
class MyClass { // defi nes a reference type
// fields
const string constName = "DotNetExplorer.com";
static string staticName = "DotNetExplorer.com";
readonly string readOnlyName;
string instName;
// properties
public string Name
{ // read/write
get { return instName; }
set { instName = value; }
}
public string ReadOnlyName { get { return instName; } }
// methods
public void Print() { Console.WriteLine(instName); }
public int Add(int a, int b) { return a + b; }
public static void PrintStatic() {
Console.WriteLine(staticName); }
// constructors
public MyClass() {} // default constructor
public MyClass(string name)
{
readOnlyName = name;
instName = name;
}
}
.Net Inheritance C#
class MyClass : Object {
// override inherited method
public override string ToString() {
// call base class version
string s = base.ToString();
return "Hello " + s;
}
}
.Net Working with XML C#
using System.Xml;
using System.IO;
// Create an XML fi le
using (XmlWriter xw = XmlWriter.Create(@"c:\names.xml"))
{
xw.WriteRaw("<names>");
xw.WriteRaw("<name>Tom</name>");
xw.WriteRaw("<name>Daniel</name>");
xw.WriteRaw("</names>");
}
// Load an XML fi le
XmlDocument doc = new XmlDocument();
doc.Load(@"c:\names.xml");
foreach (XmlNode node in doc.SelectNodes("//name/text()"))
{
Console.WriteLine(node.Value);
}
.Net Working With Text C#
using System.Text;
using System.IO;
string name = "Daniel";
string hello1 = "Hello " + name;
string hello2 = string.Format("Hello {0}", name);
Console.WriteLine("Hello {0}", name);
StringBuilder sb = new StringBuilder("Hello ");
sb.AppendLine(name);
sb.AppendFormat("Goodbye {0}", name);
Console.WriteLine(sb.ToString());
// Create a text file
using (StreamWriter w = File.CreateText(@"c:\names.txt")) {
w.WriteLine("Tom");
w.WriteLine("Daniel");
}
// Read from a text file
using (StreamReader r = File.OpenText(@"c:\names.txt")) {
while (!r.EndOfStream) {
Console.WriteLine(r.ReadLine());
}
}
foreach (string s in File.ReadAllLines(@"c:\names.txt")) {
Console.WriteLine(s);
}
.Net Working With a Database C#
using System.Data;
using System.Data.SqlClient;
string cs = @"Data Source=.\SQLEXPRESS;" +
string cs = @"Initial Catalog=NamesDB;" +
string cs = @"Integrated Security=True;";
using (SqlConnection con = new SqlConnection(cs)) {
con.Open();
string sql = "INSERT INTO Names(Name) VALUES(@Name)";
// insert a record
SqlCommand cmd1 = new SqlCommand(sql, con);
cmd1.Parameters.Add("@Name", SqlDbType.NVarChar, 100);
cmd1.Parameters["@Name"].Value = "Bob";
cmd1.ExecuteNonQuery();
// insert a second record
cmd1.Parameters["@Name"].Value = "David";
cmd1.ExecuteNonQuery();
// read records
sql = "SELECT * FROM Names";
SqlCommand cmd2 = new SqlCommand(sql, con);
using (SqlDataReader r = cmd2.ExecuteReader()) {
int iName = r.GetOrdinal("Name");
while (r.Read()) {
Console.WriteLine(
r.IsDBNull(iName)?"Null":r.GetString(iName)
);
}
}
// read a single value
sql = "SELECT TOP 1 Name FROM Names";
SqlCommand cmd3 = new SqlCommand(sql, con);
Console.WriteLine(cmd3.ExecuteScalar());
}
Powered by BlogEngine.NET 1.4.5.0