Monthly Archives: March 2011

Interesting week

It was an interesting week…. worked overtime all week for an office project… finishing up the built-in bookshelf…. review the Sharepoint 2010 materials etc. I will keep studying and looking forward to learning more.


Chapter 13 – Databases

SAMS CSHARP 4.0 (Page 238)

Create new DB in VS 2010
In server explorer:

Select server instance and enter new DB name:

Add new table:

Set up the table

Connect and Retrieve Data

Chapter 11 – Files and Serialization

SAMS CSHARP 4.0 (Page 194)

* Create, Read and Write Files

Two modes to access files: TEXT and BINARY.

In Text mode, raw contents are converted to System.String. most I/O in .Net are handled with the concept of streams, which are copnceptual buffers of data
that you can read/write in a linear fashion. Some streams allo you to jump to an arbitrary location in the streams, other don’t.

Open a text file to write:
StreamWriter writer = File.CreateText(destFileName);
writer.WriteLine(“text to write”);

Open a text file to read:
StreamReader reader = File.OpenText(destFileName);
String linetext = reader.ReadLine();

Need tro using System.IO;

Delete a File

Use File class’s static method:

Get a File Size

Use FileInfo class:
FileInfo info = new FileInfo(@”C:\myfile.txt”);
long size = info.Length;

Check file and directory Existence

Stirng target=@”D;\Files”;
if (File.Exists(target))
Console.WriteLine(“File exists”);
else if (Directory.Exists(target))
Console.WriteLine(“Directory Exists”);

Enumerate Directories and Files

You want to get a (possibly recursive) list of all directories and files

* DirectoryInfo can retrieve a list of subdirectories and files inside of it.

Create Unique or Temporary FileNames

// Get the faull path of a ramdom file name
string temfilename = Path.GetTempFileName();

// Get the random file name (only)
string filename = Path.GetRandomFileName();


Chapter 11 – Files and Serialization

SAMS CSHARP 4.0 (Page 194)

* Create, Read and Write Files

Two modes to access files: TEXT and BINARY.

In Text mode, raw contents are converted to System.Text.

Chapter 10 — Collections

SAMS CSHARP 4.0 (Page 172) 03/03/2011, 10:43 PM

* Initialize a Connection

List<int> list = new List<int>() {1, 2, 3, 4,5 };

Dictionary<int, string> dict = new Dictionary<int, string> )() {
{1, “one”},
{2, “two”}

* Iterate over a collection independently of its implementation

You want to access all of a collection’s objects independently from how the collection is implemented.

Rather than looping using index or key, use FOREACH.

Chapter 9 – Generics

SAMS CSHARP 4.0 (Page 156)

* Create a Generic List

user List<T> to create a list of T type objects.

class Person {
public string Name {get; set;}
public string Address {get; set; }

static void Main(string[] args) {
List<Person> people = new List<Person>();
// declare a list of Person-typed objects
people.Add(new Person() {Name=”Bruce”, Address=”4007 BB Lane”});

Person p = people[0]; . // No casting is needed

*** Use Generics instead of ArrayList can avoid boxing and unboxing.

* Create Generic Method

You need a method that can be called to perform the same work on different types of arguments.

define a generic method:

private static void Sawsp<T> (ref T a, ref T b) {
T temp = a;
a = b;
b = temp;

to call this method:

Swap<int> (ref aInt, ref bInt); or
Swap<string> (ref aString, ref bString); or

* Create a Generic Interface

//declare generic interface of T

interface IUnique<T> {
T Id { get; }

//implement interface with specific types
class MyObject : IUnique<int>
private int _id;
//implementation of interface’s method
public int Id
get { return _id; }

class MyOtherObject : IUnique<string> {
private string _id;
public string Id
get { return _id; }

TUPLES – New in C# 4

Group multiple values (can be different type) together and use them together.

Example 1:

example 2: (practical use)

Chapter 6 — Enumerations

SAMS CSHARP 4.0 (Page 116)

Enumeration bridge the gap between numbers and objects.

Declare an Enumeration

Enumerations can be defined within an namespace or classes:

enum BookBinding {

You can use the enumeration like:
BookBinding binding = Bookbinding.Hardcover;

Declare an Enumeration with Explicit Values

enum BookLanguage {
English = 0,
Chinese = 1,
Japanese = 2

Declaring Enumeration as Flags

Determine if a Flag is set

To check if the book is of Vampires genra – use HasFlag.
BookGenras genres = BookGenras.Vampire | BookGenres.Fantasy
bool isVampire = genres.HasFlag(Bookgenres.Vampires)

Convert an Enumeration to an Integer

You need to convert an enumeration to its numeric equivalent.

You need to explicitly convert the value:

int Value = (int)


BookLanguage lang=(BookLanguage) Value.

(make sure you validate the converted enumeration is valid – see next)

Determine if an Enumeration is Valid

bool isDefined = Enum.IsDefined(typeof(bookbinding), badBinding)

List All Enumeration Values

foreach (BookGenres genre in Enum.GetValues(typeof(BookGenres))) {
Console.WriteLine(“\t” + Enum.GetName(typeof(BookGenres), genre));

Convert a String to an Enumeration

use TryParse is easier

string hardcoverstring = “hardcover”;
BookBinding goodbinding;
bool canParse = Enum.TryParse(hardcoverstring, out goodBinding) // this is good/true.
canParse = Enum.TryParse(“gargabe”, out goodBinding) // this is false.

Convert a string to a Set of Flags

Enum.TryParse alo works for flags – multiple flags.

string flagstring=”Vampire, Mystery, ScienceFiction, Vampire”;
BookGenres flagEnum = BookGenres.None;

If (Enum.TryParse(flagString, out flagEnum)) {
// print the genres

Enumeration Tips

* If each enumeration must match external values (such as from DB), then explicitly assign a value to each enumeration member.
* Always use [Flags] Enumeration when you need to combine mulripl values into a single fields (such as when using checkboxes)
* Flag enumerations must have values explicitly assigned that are unique powers of 2 (1, 2, 4, 8, 16….) to work correctly.
* An enumeration should have a singular name if it is not used as flags. If it’s flags, then the enum name should be plural.
* Define a None
vlaue in each Enumeration, with value of 0. This is very important when using [Flags].

Chapter 5 — Numbers

SAMS CSHARP 4.0 (Page 94)

Decide between Float, Double and Decimal

Money or finances – use decimal types.

Use Enormous Integers (BigInteger)

BigInteger class is in System.Numerics namespace. Need to add a reference before you can use it.

Format Numbers in a String

Group Digits – N

int number = 12345;
Console.WriteLine(number.ToString(“N“, CultureInfo.InvariantCulture));

You get

Print Leading 0

int number = 12345;
Console.WriteLine(number.ToString(“D8“, CultureInfo.InvariantCulture));

And here’s the output: (total 8 digits)

Specifiy number of decimal places

double number = 12345.6789;
Console.WriteLine(number.ToString(“F3“, CultureInfo.InvariantCulture));

The output is as follows (note the rounding):

Convert a string to a Number

parse a string into a number

Use (1) Parse (willhave exception) or (2) Tryparse (better)

string goodStr = ” -100,000,000.567 “;
double goodVal = 0;
// with C# you need to have “out” keyword
if (double.TryParse(goodStr, out goodVal)){
Console.WriteLine(“Parsed {0} to number {1}”, goodStr, goodVal);

Convert Between Number Bases

base 10 to base 2/8/16

Convert 100 (base-10) to a number that is base-16

Convert.ToString(100, 16)

Generate GUID

Guid g = Guid.NewGuid().

Chapter 4 — Exceptions

SAMS CSHARP 4.0 (Page 80)

Throw an Exception

Catch an Exception

using try… catch….

Catch Multiple Exceptions

You must andle many potential exceptions

Execution with finally

Code in finally will guaranteed to run after try/catch.

Exception: If you use Environment.Exit(),
then the finally will not be executed.

Get Useful Information from an Exception

Message – a brief of the error
Source – the application where the exception occurred
StackTrace – a list of the methods in the current stack. Helpful to retrace the path that caused the exception
targetSite – the method that threw the exception
innerException – exception that caused the current exception. Often, exceptions are wrapped inside other higher-level exceptions.
Data – Exception-specific pairs providing more info

Catch Unhandled Exceptions

Create a custom handler for all exceptions not caught by try/catch….

A thrown exception is passed up the call stack until it finds a catch block that can handle it. If no handler, the process will be shut down.

Trapping ASP.NET app’s exception at an application level: change global.asax, in the Application_Error method.

Chapter 3 – General Coding

SAMS CSHARP 4.0 (P.62) 03/01/2011, 10:27PM

Essential and general C# knowledge that doesn’t fit easily into other chapters

Declare Variables

int x = 13; // declare and define
int y; // declare
y=13; // then define

Use Type Inference (Implicit Typing)
Highly useful in LINQ.
VAR — you want to declare a variable and assign it a value, without having to figure out the type, but still take adv of strong typing. You are merely giving the job of figuring out the type to the compiler. Once done, type can’t change!!!

can use for a local variable but not a class variable!!!

var x=13;
var myObj = new MyType();
// var myNullValue = null; //not allowed to set to NULL
**** but you can set it to NULL after defined
var myNullobj = new MyType();

foreach is a good place to use var.

Defer Type Checking to RunTime (Dynamic Types)

You want to delay type resolution until runtime.
Use the dynamic keyword for your variables and method parameters.

Use Dynamic Typing to Simplify COM Interop

var app=new Excel.Application();
// to avoid casting, use dynamic
dynamic sheet – app.ActiveSheet;

Declare Arrays

(1) int[] array1 = new int[4];
array[0]=13; array[1]=14; array1[2]=15; array1[3]=16;
(2) int[] array1 = new int[4] {13,14,15,16};
(3) int[] array1=new int[] {13,14,15,16};
(4) int[] array1 = {13,14,15,16};
// easiest

Applies to anything that implements IEnumerable

Create Multi-Dimentional Arrays

2D or 3D array

first decide which type of multi-dimentional array you need. (1) rectangular or (2) jagged

rectangular: same size rows

int[,] myarray1 = new int[,] {

float val=myarray1[0,1]; // the value is 2

jagged: like arrays of arrays

int[][] myarray1 = new int[3][];
myarray1[0]=new int[] {1,2,3};
myarray1[1]=new int[] {4,5,6,7,8};
myarray1[2]=new int[] {9,10,11,12};

int val = myarray1[0][1]; // the value is 2

Alias a NameSpace

to abbreviate the namespace in the using section; good for intellisense

using WPFControls = System.Windows.Controls;
using Acme = Acme.Widget.Controls;

Use the Conditional Operator (? 🙂

bool condition = true;
int x = condition? 13:14;


int x = y > 3 ? 5:6;

*** You can also use it to execute method, e.g.:

bool condition = true;
condition ? ExecuteSucceed() : ExecuteFail();

It will execute a method depending on the condition.

Use the Null-Coalescing Operator (??)

k can be null; if n != null, then k=n; else k=-1
int? k = n ?? -1;

Add Methods to Existing Types with Extension Methods (P.71)

static class, static method, and this keyword.In this example, a method is deined for the type integer.

Call Methods with Default Parameters

you want to avoid creating many overloads of a method by specifying default values for some parameters

ShaowFolders(string root = @”C:\”, bool showFullPAth = false)

ShowFolders();// method will take it as using the default: “C:\” and false
ShowFolders(@”C:\”);// “C:\” and false
ShowFolders(false);// not working this way!!!! Can’t just supply the second param.

Not recommended as it’s confusing.

parameter that has default value must appear before others, e.g.,
ShowFolders(string root=@”C:\”, bool showFullPath)

Call Method with Named Parameter

In last example, you need to do this to call the method:

ShowFolders(“C:\”, false)

but you can also do this with named parameters – order of the parameters does not masster in this case.

(add a ParameterName :
in front of the value being passed over)

false, root:

Enforce Code Contracts

Use contract to add constraints to your methods.

Static Checker integrated with VS can interactively notify you of contract violations in your code.

Implement Contracts on Interfaces

You want to implement contracts on every class that implements an interface. Because interfaces don’t have method bodies, you need to create a surrogate implementation
of the interface and add the contracts there. You tie them together using attributes.