Monday, March 15, 2010

ASP.NET 3.5 Training Course Notes(1)

1. this.Request.QueryString[null]
this.Request.QueryString["varName"] - - ?varName=...

2.You need manually input event handler Page_Init( object sender , EventArgs e) ;

3.Page Event order
PreInit() -> Page_Init() ->Page_PreLoad() -> Page_Load() -> Page_Unload()

Sunday, February 21, 2010

.Net Framework Application Development Foundation(3)--Sample


1. Graphics sample
WinForm Sample: ( ColorDialog Control , fontDialog Constrol used)

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Pen aPen = new Pen(Color.Navy, 3);
private int? lastX = null;
private int? lastY = null;
// store last line drawn
private class myPath
{
public Pen newPen;
public float lastX, lastY, currentX, CurrentY;
}
List paths = new List();

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
var g = this.CreateGraphics();
g.SmoothingMode = SmoothingMode.HighQuality;

if (e.Button == MouseButtons.Left)
{
if (lastX.HasValue && lastY.HasValue)
{
g.DrawLine(aPen, (float) lastX, (float) lastY, e.X, e.Y);
paths.Add(new myPath()
{
newPen = aPen,
currentX = e.X,
CurrentY = e.Y,
lastX = (float) lastX,
lastY = (float) lastY
});
}
else
{
g.DrawRectangle(aPen, e.X, e.Y, 1, 1);
}
lastX = e.X;
lastY = e.Y;
}
else
{
lastX = null;
lastY = null;
}
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
var g = this.CreateGraphics();
g.SmoothingMode = SmoothingMode.HighQuality;
// when clear the graphics , keep the color white
this.BackColor = Color.White;
foreach (var s in paths)
{
g.DrawLine(s.newPen , s.lastX , s.lastY , s.currentX,s.CurrentY);
}
}

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
var g = this.CreateGraphics();
if( e.Button == System.Windows.Forms.MouseButtons.Right)
{
g.Clear(Color.White);
paths.Clear();
}
}

private void button1_Click(object sender, EventArgs e)
{
if(colorDialog1.ShowDialog(this) == DialogResult.OK)
{
aPen = new Pen(colorDialog1.Color);
button1.BackColor = colorDialog1.Color;
}
}

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
aPen = new Pen(aPen.Color, (float)numericUpDown1.Value);
}

private void button2_Click(object sender, EventArgs e)
{
var g = this.CreateGraphics();

Font font;

if( fontDialog1.ShowDialog() == DialogResult.OK)
{
font = fontDialog1.Font;
}
else
{
font = new Font("Arial" , 60 , FontStyle.Bold | FontStyle.Underline);
}

g.DrawString(textBox1.Text ,font ,Brushes.Navy , 100f , 100f);
}

}

2. Multiple threading programming
class Program
{
static void Main(string[] args)
{
//utilize the automatical threading method
ThreadPool.QueueUserWorkItem(DemoThreading.Proc);
ThreadPool.QueueUserWorkItem(DemoThreading.ProcWithArgument, 5);

Thread.Sleep(2000);// have backgroud thread finished first
int anum, cnum;
ThreadPool.GetMaxThreads(out anum , out cnum);
;
Console.WriteLine("The Main thread exist. The threadPool has {0} threads availabe. {1} completionPortThreads.",
anum , cnum);
}
}

public class DemoThreading
{
//show how many days from 2000 to 2010
public static void Proc(object input) //input is uesless only to meet the satisfaction of signature
{
DateTime oldTime = new DateTime(2000, 1 , 1);
DateTime newTime = new DateTime(2010 , 1 , 1);
TimeSpan ts = newTime - oldTime;

Console.WriteLine("There are total {0} days from 2000 to 2010" , ts.TotalDays);

}
//return the factorial of a
public static void ProcWithArgument( object input )
{
int a = Convert.ToInt32(input);
int fab = 1;

if (a == 1)
fab = 1;
else
{
checked
{
int i;
for (i = 1; i <= a; i++) { fab = fab * i; } } } Console.WriteLine("The factorial of number {0} is {1} .", a , fab); } }

2.2 managing threads
class Program
{
static void Main(string[] args)
{
//managing threads methods
var thread = new Thread(new ParameterizedThreadStart(DemoThreading.Proc));
var another = new Thread(new ParameterizedThreadStart(DemoThreading.ProcWithArgument));

another.Priority = ThreadPriority.Highest;
thread.Priority = ThreadPriority.BelowNormal;
thread.Start();
another.Start(5);

Thread.Sleep(2000);
Console.WriteLine("The main thread is ending.");
}
}

public class DemoThreading
{
//show how many days from 2000 to 2010
public static void Proc(object input) //input is uesless only to meet the satisfaction of signature
{
DateTime oldTime = new DateTime(2000, 1 , 1);
DateTime newTime = new DateTime(2010 , 1 , 1);
TimeSpan ts = newTime - oldTime;

Console.WriteLine("There are total {0} days from 2000 to 2010" , ts.TotalDays);

}
//return the factorial of a
public static void ProcWithArgument( object input )
{
int a = Convert.ToInt32(input);
int fab = 1;

if (a == 1)
fab = 1;
else
{
checked
{
int i;
for (i = 1; i <= a; i++)
{
fab = fab * i;
}
}
}

Console.WriteLine("The factorial of number {0} is {1} .", a , fab);
}

private string _file = "Hello";//private field
private ReaderWriterLock rwl = new ReaderWriterLock();//syn lock

public void WriteFile()
{
lock (_file)
{
_file += " It's good.";
}

}

public void ReadFile()
{
rwl.AcquireReaderLock(10000);
for( int i=1; i<=3 ; i++)
{
Console.WriteLine(_file);
Thread.Sleep(1000);
}
rwl.ReleaseReaderLock();
}
}

Friday, February 19, 2010

.Net Framework Application Development Foundation(2)--Samples

1. FileSystemWatcher Sample:
class Program
{
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher(@"d:\");


fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;
fsw.IncludeSubdirectories = true;

fsw.Created += new FileSystemEventHandler(fsw_SthHappened);
fsw.Deleted += new FileSystemEventHandler(fsw_SthHappened);
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
fsw.EnableRaisingEvents = true;
while( true )
{
Thread.Sleep(100);
}
}

static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine(e.Name + " => "+ e.ChangeType + " => " + e.OldName + " => " + e.FullPath + " -- " + DateTime.Now.ToLongTimeString());
}

static void fsw_SthHappened(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "=> "+ e.ChangeType + " => " + e.FullPath + " -- " + DateTime.Now.ToLongTimeString());
}
}

2. Serialization
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO.Compression;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security.Permissions;
using System.Text;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Serialization;

namespace ExplainNotes4
{
class Program
{
static void Main(string[] args)
{
//FileStream fs = new FileStream(@"d:\home\serializeDate.data", FileMode.Create, FileAccess.Write);
//Invoice aTax = new Invoice() {ItemName = "For DIY", ReleaseDate = DateTime.Now, Number = 100, Price = 12.8M};
//aTax.SetTotal();
//BinaryFormatter bf = new BinaryFormatter();
//bf.Serialize( fs , aTax);
//fs.Close();
//**************************************** using soapFormatter ****************
//FileStream fs = new FileStream(@"d:\home\serializeDate.xml", FileMode.Create, FileAccess.Write);
//Invoice aTax = new Invoice() { ItemName = "For DIY", ReleaseDate = DateTime.Now, Number = 100, Price = 12.8M };
//aTax.SetTotal();
//SoapFormatter sf = new SoapFormatter();
//sf.Serialize(fs, aTax);
//fs.Close();

//FileStream fs = new FileStream(@"d:\home\serializeDate.data", FileMode.Open , FileAccess.Read);
//Invoice another = new Invoice();
//BinaryFormatter bf = new BinaryFormatter();
//another = (Invoice) bf.Deserialize(fs);
//fs.Close();

//Console.WriteLine(another.Total);
FileStream fs = new FileStream(@"d:\home\serializeDate.xml", FileMode.Create, FileAccess.Write);
Invoice aTax = new Invoice() { ItemName = "For DIY", ReleaseDate = DateTime.Now, Number = 100, Price = 12.8M };
aTax.SetTotal();
XmlSerializer xs = new XmlSerializer(typeof(Invoice));
xs.Serialize(fs, aTax);
fs.Close();
}
}

[Serializable]
class Invoice : IDeserializationCallback
{
public string ItemName { set; get; }
public DateTime ReleaseDate { set; get; }
public int Number { set; get; }
public decimal Price { set; get; }

public decimal Total { get; private set; }

public void Sumary()
{ Console.WriteLine("this is an invoice.");}

public void SetTotal()
{
if (Price != 0 && Number != 0)
Total = Price*Number;
else
{
throw new NotSupportedException();
}
}

public void OnDeserialization(object sender)
{
Console.WriteLine("i make it");
}
public Invoice(){}
}

}

Wednesday, February 17, 2010

.Net Framework Application Development Foundation(2)

Code Explanation of C# Languege:

1. object (base method )
class Program
{
static void Main(string[] args)
{
// any object class includes 4 methods : Equals() ,ToString() ,GetType() , GetHashCode() ;
Student aStud = new Student(){ Age = 20, Name = "Jim Parson",Subject = "History"};
Student bStud = new Student() { Age = 20, Name = "Jim Parson", Subject = "History" };

Console.WriteLine(aStud.GetType());// reflection base method
Console.WriteLine(aStud.Equals(bStud));
Console.WriteLine(aStud == bStud);
Console.WriteLine( aStud.GetHashCode());
aStud.Age = 25;
aStud.Name = "tom";
aStud.Subject = "English";
Console.WriteLine(aStud.GetHashCode());
Console.WriteLine(bStud.GetHashCode());
Console.WriteLine(aStud.ToString());
return;
}

class Student
{
// automatical property
public string Name { set; get; }
public int Age { set; get; }
public string Subject { set; get; }

public override bool Equals(object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");

var other = obj as Student;// obj should be Student class object
return (other != null && other.Age == Age && other.Name == Name && other.Subject == Subject);
}

public override int GetHashCode()
{
return (Name +":" + Age +":"+ Subject).GetHashCode();
}

public static bool operator ==( Student a , Student b)
{
if( ReferenceEquals(a,b))// Object.ReferenceEquals( a , b)
return true;

if ((object)a == null || (object)b == null)
return false;

return a.Equals((b));

}

public static bool operator !=(Student a, Student b)
{
return !(a == b);
}

public override string ToString()
{
return Name + " : " + Age + " : " + Subject;
}
}

2. var keyword ( I love using it)
//*** C# support double type number reminder ***
//Console.WriteLine(7.2%2.4);
//return;

//*** C# Definite Assignement Rule ***
// int aNum;
//Console.WriteLine(aNum);
// or using out keyword
//var afloat = 12f;
//var adouble = 24.5;
//var money = 21.35m;
//Console.WriteLine("{0} {1} {2} {3} {4}" , num , str, afloat,adouble,money);

//Console.WriteLine( "this is a nice day." + "that is right.");
//string input = Console.ReadLine();
//int another;
//if( int.TryParse( input, out another ))
// Console.WriteLine(another);
// int aNum = int.Parse(input);

//*** C# is case-sensitive language ***
//int integer = 100, integEr = 200;
//Console.WriteLine( "{0} -- {1}" , integer , integEr)

3. List , Array , Lambda ,ForEach()
// list has ForEach() , linq to object always uses list
int[] arr = {10, 40, 43, 55, 67, 35, 6, 78, 9};
var alist = arr.ToList();
alist.ForEach(Console.WriteLine);// == alist.ForEach( item=>Console.WriteLine(item));

4.Switch Statement

string input = Console.ReadLine();
switch (input) // input could int type , char or string , no float , double
{
case "1" :
Console.WriteLine("input is 1");
break;
case "2": // can fall-through
case "3":
Console.WriteLine("input is 2 or 3");
break;
case "4":
Console.WriteLine("input is 4");
break;
default :
Console.WriteLine("default input");
break;
}
4. Overflow Exception : checked and unchecked
int n = int.MaxValue;
try
{
checked // or unchecked
{
n += 1;
Console.WriteLine("overflow?");

}
}
catch (OverflowException e)
{
Console.WriteLine("overflow found");
}

byte test = 240;
byte another = 120;
test = unchecked((byte)(test + another));
Console.WriteLine(test);
test = 240;
test = checked((byte)(test+ another) );

5. Class Student -- Constructors
///
/// all kinds of constuctors
///

///
///
///
public Student( string _name , int _age , string _sub)
{
Name = _name;
Age = _age;
Subject = _sub;
}
public Student( string _name , int _age):this(_name ,_age , "N/A")
{

}

public Student( string _name):this(_name , 18)
{
}

public Student( int age):this("noName" , age )
{
}
public Student():this("unknown")
{
}

6. Const and Readonly (the same use but readonly type can be used in run time
class Media
{
public const int Month = 12;
// error => public const DateTime Current = DateTime.Now.Year;
public readonly DateTime Current = DateTime.Now;
}

7. Static Class in C#
public static class Shape
{
public static int Area { set; get; } //property

private static int _field; // field

public static void Show()
{
throw new NotImplementedException();
}
}

8.Anonymous Class
var anonymousClass = new {Name = "Tom", Age = 20};
Console.WriteLine(anonymousClass);
or
string atr = "this is a good movie." ;
var other = atr.split( new [] { " "}) ;
or In Linq Application

9. Nullable and Nullable<T>  --we always use generics one
Nullable<int> num = null; // or int? num = null or Enumeration Type
num = 100;
if(num.HasValue)
Console.WriteLine(num);
Console.WriteLine(num.GetType());

10. Boxing and unboxing
int one = 100;
object other = one; // boxing
one = (int) other; // unboxing
Console.WriteLine(one);

11. Is and As Operator ( in Type Cast )
Student aStud = new Student(){ Age = 20, Name = "Jim Parson",Subject = "History"};
object obj2 = aStud; //
var other2 = obj2 as Student;//
if( other2 != null )//
Console.WriteLine("it is Student Type");//
return;
or
Student aStud = new Student(){ Age = 20, Name = "Jim Parson",Subject = "History"};
object obj = aStud;
var other = obj;
if( other is Student)
Console.WriteLine("yes");

12.Enumeration
enum Days :byte { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri }; // not be defined in a method

13. Array copy
int[] arr = {5, 9, 2, 4, 8};
var another = (int[]) arr.Clone();
//var another = new int[arr.Length];
//Array.Copy(arr, another, arr.Length);
//arr.CopyTo(another , 0);
another.ToList().ForEach(Console.WriteLine);

14. extension method
static class MyClass
{
public static int IntegerPart( this double a)
{
return Convert.ToInt32(a);
}
}
class Program
{  
  static void Main(string[] args)
{
double num = 6.5;
Console.WriteLine(num.IntegerPart());
   return ;
}
}

15. Interface ( explicitly and implicitly)
internal interface ITalk
{
void Talk();
bool WantToTalk();
}

internal interface ISpeak
{
void Speak();
bool WantToTalk();
}

internal class AClass : ITalk , ISpeak
{
public void Talk()
{
Console.WriteLine("method Talk called");
}
bool ITalk.WantToTalk()
{
Console.WriteLine("method ITalk.WantToTalk called");
return true;
}
bool ISpeak.WantToTalk()
{
Console.WriteLine("method ISpeak.WantToTalk called");
return false;
}
public virtual void Speak()
{
Console.WriteLine("method speak called");
}

public void PrintAll()
{
Console.WriteLine("All Information.");
}
}

class Program
{
static void Main(string[] args)
{
AClass anotherOne = new AClass();

anotherOne.Speak();// object cannot call explicitly interface methods
anotherOne.Talk();

ITalk anInter = anotherOne; // the interface variable can only call its own methods
anInter.Talk();
anInter.WantToTalk();

ISpeak anInter2 = anotherOne;
anInter2.Speak();
anInter2.WantToTalk();
}}

16. Abstract Class
class Library where T : Media
{
public List Items { get; set; }
}

abstract class Media
{
public string ISBN { get; set; }
}

class Book : Media
{
}

class Dvd : Media
{
}

17. Property
public class InterClass
{
public string Name { set; get; }
public int ID { get; private set; } //read only property
public string Score { set; private get; } // write only
}
static void Main(string[] args)
{
InterClass anotherOne = new InterClass() { Name = "Tom", Score = "30"};
}

18.Generic Class
class Media
{
public string ISDN { set; get; }
}
class Book:Media{}
class DVD : Media{}
class Library<T> where T:Media
{
public List
<T> Item { get; set; }
}

19. LINQ to Objects
var addresses = new[]
{
new {CompanyName = "ASK", City = "Tokyo", Country = "Japan"},
new {CompanyName = "TPG", City = "Sydney", Country = "Australia"},
new {CompanyName = "Nissan", City = "Osaka", Country = "Japan"},
new {CompanyName = "Toshiba", City = "Tokyo", Country = "Japan"},
new {CompanyName = "ALG", City = "New York", Country = "USA"}
};

var customers = new [] // anonymous array
{
new { CID = 1,FName = "Tim", SName = "Anderson", Age = 23 , CompanyName="ASK"},
new { CID =2,FName = "Loly", SName = "Green", Age = 22,CompanyName="TPG"},
new{ CID =3,FName = "Tom" ,SName="Lee" , Age=21 ,CompanyName="ALG"} ,
new{ CID =4,FName = "Bob" ,SName="Camp" , Age=23,CompanyName="Toshiba"} ,
new{ CID =5 ,FName = "Jason" ,SName="Troops" , Age=24,CompanyName="ALG"} ,
};// like a table

//var firstnames = customers.Select(name => name.FName + " " + name.SName +"--"+ name.Age);//Select statement
var firstnames = from name in customers select new {name.FName, name.SName, name.Age};
//var fullItems = customers.Select(item => new {FullName = item.FName + " " + item.SName, Age = item.Age});
//var filter = customers.Where(age => int.Equals(age.Age, 23)).Select(aname => aname.FName);//where statement
var filter = from age in customers where int.Equals(age.Age, 23) select age.FName;
//var orderBy = customers.OrderByDescending(order=>order.Age).Select(aname => aname.FName);//order by statement
var orderBy = from order in customers orderby order.Age descending select order.FName;
//var joins = customers.Select(c => new {c.FName, c.SName, c.CompanyName}).Join(addresses,
// cust => cust.CompanyName,
// addr => addr.CompanyName,
// (cust, addr) =>
// new
// {
// cust.FName,
// cust.SName,
// addr.City
// });
var joins = from c in customers
join a in addresses on c.CompanyName equals a.CompanyName
select new {c.FName, c.SName, a.City};
foreach (var item in firstnames)
{
Console.WriteLine(item);
}
Console.WriteLine();
//foreach (var item in fullItems)
//{
// Console.WriteLine(item);
//}
Console.WriteLine();
foreach (var e in filter)
{
Console.WriteLine(e);
}
Console.WriteLine();
foreach (var o in orderBy)
{
Console.WriteLine(o);
}
Console.WriteLine();
Console.WriteLine(customers.Select(cust => cust.Age).Distinct().Count());
foreach (var j in joins)
{
Console.WriteLine(j);
} }

20.IEnumerable , IEnumerator and yield statement
class Program
{
static void Main(string[] args)
{
AClass app = new AClass();

foreach (var @class in app.ShowMe())
{
Console.WriteLine(@class);
}

var iterator = app.GetEnumerator();
while( iterator.MoveNext())
{
Console.WriteLine(iterator.Current);
}
// iterator.Reset();reset method not implemented
return;

}
}

class AClass
{
private int[] arrInt = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public IEnumerator GetEnumerator()
{
foreach (var i in arrInt)
{
if( i == 6)
yield break;

yield return i;
}
}
public IEnumerable ShowMe()
{
foreach (var i in arrInt)
{
yield return i;
}
}
}

21.delegate , Event , covariance and contravariance
class Program
{
public static void Show()
{
Console.WriteLine("show something to me.");
}
public static void Handler( object sender , EventArgs args)// subscriber
{
Console.WriteLine("yes , I subscribed this event.");
}

static void Main(string[] args)
{
BClass another = new BClass() {Name = "James", SCode = 939483};
BClass.AHandler del = another.PrintName;
del += another.PrintSCode;
del += Show;

//del();
del -= another.PrintName;//remove a delegation
del += another.PrintName;//add it again
del.Invoke();

Console.WriteLine( );
foreach (var s in del.GetInvocationList())
{
Console.WriteLine(s.Method.Name);
}
del = null;

another.MyEvent += Handler;
another.AMethod();//invoke event

}
}

class BClass
{
public delegate void AHandler();
// define an event
public event EventHandler MyEvent;

public string Name { set; get; }
public int SCode { set; get; }

public void PrintName()
{
Console.WriteLine(this.Name);
}
public void PrintSCode()
{
Console.WriteLine(this.SCode);
}
// invoke an event
public void AMethod()
{
if (this.MyEvent != null)
MyEvent(null, null);
}
}

Sunday, February 7, 2010

.Net Framework Application Development Foundation(1)

Week One Notes:
Date: 7 /Feb/ 2009

About .Net Framework software: 3.5 SP1 , Visual Studio 2008 SP1 , an optimized tool for VS 2008-> VS Resharper ;
Free download student edition VS 2008 Pro Edition :
https://www.dreamspark.com/Products/Product.aspx?ProductId=1

Reference Books:
1. Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition ( Apress)
2. MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework Application
Development Foundation, Second edition ( Microsoft Press)

Notes:
1. About .NET:
.NET is their foundation for future application developments. ‘.NET’ is a set of technologies that are aimed at enabling development over the internet as well as aimed at enabling devices to be connected together via a common platform (.NET). This includes Mobile devices, personal computers and other electronic devices.
DLL Hell -- no more in .Net( versioning issues) via version forwarding
Security -- more secure in .Net ( by using managed code)

2. About VC++ and J++ , VB
VC++ -- there are too many compatibility issue( driver issue)
VJ++ -- rarely used ( not popular)
VB -- too basic

3. About .Net Versions
.Net 1.0 no more use ( using CLR 1.0)
.Net 1.1 still works and widely used in legacy applications ( shipped with Windows
Server 2003 and Visual Studio 2003 , using CLR 1.0 )
.Net 2.0 popular and shipped with visual studio 2005 and Windows Server 2003 R2 , SQL
Server 2005 ; full 64bit support; using CLR 2.0
.Net 3.0 better integrated in Vista and server 2008 ; still using CLR 2.0 ; new components:
WCF , WPF , WFF , WCardspace( bad , rarely used)
.Net 3.5 came withVisual Studio 2008 . Shipped with Server 2008 R2 and Windows 7;
still using CLR 2.0 ; Linq included .
.Net 4.0 coming with Visual Studio 2010 ( still in Beta)

So, .Net 2.0 includes WinForms , Web Service and ASP.Net
.Net 3.0 includes .net 2.0 and WFF , WPF , WCF and CardSpace
.Net3.5 includes .net 3.0 and LINQ , AJAX and REST( rarely used , some web service)

4. Common Type System(C#)
Actually , some types are never used in production environment:
uint , ulong , ushort , float
Always using : byte , int , long , bool and double

5. Constant and read only variable
Const in C# : the value must be assigned in source code.
E.G. const int a = DateTime.Today.Year ; ( Error) the right side is a variable actually

Use keyword readonly if value can only be assigned at runtime ; can be set only once. After that, it behaves as a constant

6. Types
value types ( value type , enumeration and structure type ) -- object types( class and interface , array)

Each of the numerical types map to a corresponding structure in the System namespace. Structures are “value types” allocated on the stack.
String and object are “reference types,” meaning the variable is allocated on the managed heap (garbage-collected).
Value types can be allocated into memory very quickly and have a very
fixed and predictable lifetime.

7. Indexer ( extension method , properties)
public MyType this [int index]
{
set{} ; get{} ;
}

8. Practice:
a. decimal money = 12.45m ;
cw( money.toString("c")) or cw( "{0:c}" , money); -- 'C' means format currency

b. int.MinValue , int.MaxValue , ....
c. char input = (char) Console.Read() ; -- default int type returned
d. Utilities method : char.isDigit() , isLetter() , isLower() , isUpper() ;
e. type convert or cast
string str = 12 ; int num ; if( int.TryParse(str , out num)) ...
d. Checked keyword -- only check overflow exception
e. Nullable a = null or int? a = null ; a.HasValue , a.Value.ToString()
a ?? -1 if a is null , return -1 when a is int type or return a.Value
equals a.HasValue ? a.Value.ToString() : "N/A"

f. var type is good utility.
g. string , str.Split( new []{','} ) ; array.toList() and then we can use foreach with iterator
h. Linq to object is good . ( toList , select, lambda expression)

9.Debugging
Stopwatch class ; sw.Start() , Stop() , sw.Elapsed ; return execution duration ;

10 . DateTime and TimeSpan are of value types and structures defined by system.


=============================================================
Some Code
==============================================================
class Program
{
static void Main(string[] args)
{
///
/// Excercise one
/// About DateTime and TimeSpan structures ( value types)
/// ITIC Training Course -- Week One
/// Trainee : Tonny Yan
/// Instructor: Bing Xie
/// Date: 10/02/2010
///

DateTime birth = DateTime.Now;
TimeSpan interval = new TimeSpan();
TimeSpan interval2 = new TimeSpan(2, 14, 28); // using values explicitly

Console.WriteLine(interval.Equals(TimeSpan.Zero));// true
Console.WriteLine(TimeSpan.MinValue);
Console.WriteLine(TimeSpan.MaxValue);
Console.WriteLine(interval2.ToString());

// duration of a trip
// the order is year , month , day , hour , min and second ;
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime);

// excercise for Property of a class
Student aSt = new Student("tonny", "Yan");
Console.WriteLine(aSt.ToString());

}
}

// define a class with auto-implemented properties
public class Student
{
public string Fullname { get; private set; }// readonly
public string Firstname { private get; set; }// write only
public string Lastname { private get; set; }

public Student(string firstname, string lastname)
{
this.Firstname = firstname;
this.Lastname = lastname;
this.Fullname = firstname + " " + lastname;
}

public override string ToString()
{
return Fullname;
}

}

Wednesday, December 30, 2009

SQL Server 2008 Implementation and Maintenance (3)

Schema , Table , View and Index

1.exec sp_spaceused 'tableName' -- show the disk space which data occupied
2. rename
sp_rename 'oldTableName' , 'NewTableName' ;

3. view all indexes
select * from sys.indexes ;

4. sp_who -- view all user session

Monday, December 28, 2009

SQL Server 2008 Implementation and Maintenance (2)

SQL SERVER 2008 T-SQL Management Commands(system procedures)

1. sp_help -- show all sys proc names , object type , owner name ...
2.select name from sys.databases ; -- show all databases in one instance
3.sp_helpdb 'database name' ; -- show the information and properties of a database

4.sp_dboption ; -- settable database options == alter database clause
5. function DB_Id("database Name") -- return database ID

6. Fulltext Search
select * from sys.fulltext_languages -- show the languages which are supported
select * from sys.fulltext_document_types -- show document format supported

7. Security
select * from sys.fn_builtin_permissions(default) ; ( view all permissions which can be granted for objects)
e.g. select * from sys.fn_builtin_permissions('login') (or ' database' )

select has_perms_by_name( 'databasename' , 'database ' , 'any' ) ; -- to view if the current user is granted any permission of using database )

execute as user='someone'
go
select has_perms_by_name('databaseName' ,'database' , 'any') ;
go
( check user someone has permissions )

Visual Studio 2005/2008/2010 Notes

1. VS 2008 does not support connecting to SQL Server 2008 initially .
VS 2008 Service pack 1 is needed .

Windows Server 2003 Notes

In win server 03 , some functions and services are not available after the system is installed, such as Internet Access , remote desktop , telnet and so on.
1. startup Telnet service( must be running Windows Server 2003 SP1. )
run-> cmd -> input : tlntsvr /service ( to install telnet service utility)
to do some settings: go->start -> administrative tools -> services -> found Telnet
( startup : automatic ; start service ; input telnet username and password ; OK)

Sunday, December 27, 2009

SQL Server 2008 Implementation and Maintenance (1)

1. Command-line utilities
Windows PowerShell -> SQL Server PowerShell
( Running cmdlet commands)
c:\ sqlps
PS SQLSERVER:\ get-command ( view all commands under the shell)
/*******************************************************/
use Tab key to input the complete command automatically
/*******************************************************/
PS SQLSERVER:\ get-help cmdName -detailed ( view the information about every command)
e.g. PS SQLSERVER:\get-help get-host -detailed
PS SQLSERVER:\get-help sqlserver | more ( view sql server information , more is UNIX-like command . Pipeline process is used , so that you view information page by page)

2. use stored procedure to configure SSMS(Master database)
sp_configure -> to config standard configuration parameters and advanced ones.
e.g. :
use master
go
exec sp_configure 'show advanced options' , 1 -- so that you can set advanced system parameters)
go
reconfigure
go
exec sp_configure -- to view the information of all parameters

3. View the information of database in a instance of SQL Server 08
Select name , database_id from sys.databases ;

Saturday, December 26, 2009

ADO.Net 2.0 Notes(part four)

Using Class DataSet to process data from database( offline data)

1. DataSet contains Class DataTable and Class DataRelation.
DataSet object can include more than one table . There is one relationship at least if two tables are contained in DataSet object .

2. DataTable contains DataRow , DataColumn and Constraint.

Friday, December 25, 2009

ADO.Net 2.0 Notes(part three)

Query of Database with SqlCommand class and SqlDataReader Class

1. create command
a. SqlCommand cmd = new SqlCommand()
cmd.Connection = cn; // cn is the instance of SqlConnection
cmd.CommandText = "SQL ... " ;
b. SqlCommand cmd ;
cmd = cn.createCommand() ;
cmd.CommandText = "SQL ..." ;
c. SqlCommand cmd = new SqlCommand( SQL , cn ) ;

2. SqlDataReader reader = cmd.ExecuteReader() ; ( cmd is the instance of SqlCommand class)
reader.read() ;


ADO.Net 2.0 Notes(part two)

Connection of database
SqlConnection class
-> connection string -> ConnectionStringBuilder class

1. connection pool ( about connection close() issues)

2. SqlConnection class -> create SqlCommand instance ( class SqlCommand)
SqlConnection class -> SqlTransaction
SqlConnection class -> getSchema information ( about architecture of the database )
e.g. cn.GetSchema()

2. methods of Class SqlConnection

BeginTransaction() ;
ChangeDatabase() ; --> like " use databasename" in SSMS

ADO.Net 2.0 Notes(part one)




the whole view:( Only for SQL Server 200X)


Section A :( Request of Connection )
1. Connection class ( SqlConnection, used to connect with database or data source)
Before connection , connection string is needed.
Class ConnectionStringBuilder -> connection string -> Class SqlConnection
e.g.
ConnectionStringBuilder strcon = new ConnectionStringBuilder() ;
strcon.DataSource = ...
strcon.IntegratedSecurity=True;
strcon.InitialCatalog= ...
SqlConnection cn = new SqlConnection( strcon ) ;
cn.open() ; ( or using(sqlConnection cn = new SqlConnection(strcon)){} )
...
cn.close() ;

==============
SqlConnection Class
1. ConnectionStringBuilder (create connectionString)
2. SqlTransaction Class
3. SqlDataAdapter Class
4. SqlCommand Class
===============
||
||
\/
2. Database Query( SqlCommand class and SqlDataReader , to query database or data source)
===================
SqlCommand class :
1. SqlParameter
2.SqlDataReader
===================
||
||
\/
3. Class SqlDataAdapter ( a bridge of online data and offline data )
connection -> SqlCommand->SqlDataReader ( an active connection with database )
/\
||
Class SqlDataAdapter
||
\/
Class DataSet ( Offline data manipulation )


Section B:( Offline data manipulation and processing)
1. Class DataSet
A=> Class DataTable(Class DataView) B=> Class DataColumn (Class DataRowView)
B=> Class DataRow
B=> Class Constraint
A=> Class DataRelation

Wednesday, December 23, 2009

SQL Server 2008 internals notes (CHAPTER ONE)

1. select serverproperty( 'Edition') ------------ e.g. Enterprise Edition ( or others)
select serverproperty('EngineEdition') ---------- e.g. 3 ( means edtion is either Enterprise , enterprise Evaluation or Developer. These three have exactly the same features and functionality.

2. Exec SP_help ( to view all system base tables with a system administrator privilege)

3. execute sys.objects to see the names of all system tables
use master ;
select name from sys.objects where type_desc = 'System_table' ;

4. Catalog Views in SQL Server 2008
( all are in sys schema)
sys.bojects , sys.database , sys.indexes , sys.databases

5. View the description of a table ( columns)
to use stored procedure (system procedures) sp_columns
e.g. exec sp_columns @table_name=N'tablename' , @table_owner=N'tableschema' ;

6. We can use function object_definition(object_id( 'some_object') or system procedure sp_helptext 'some_object' to view the definitions of views , procedures , triggers and user-defined functions(UDFs)
e.g. select object_definition(object_id('some_object')) ; --- unavailable for table definitions
exec sp_helptext 'some_object'

7. View the schema of a database in one of instances in SQL 2008
checking Information_schema
e.g. select table_name from information_schema.tables ; ( all tables and views returned)
select table_name from information_schema.tables where table_type='Base Table'; ( only tables returned)

8. View Server Version -> select @@version ;
In ADO.net , Sqlconnection cn = ... ; cn.ServerVersion;(property)