Friday, December 19, 2008

Enum and bit flag

Enum
enum Color{
red, //0
blue, //1
orange, //3
}

Instead of hardcoding the numbers..use enum.
* symbolic name is used throughout the code, just change the number and recompile when ever necessary
* enumeration are strongly types..cant pass orange instead of wood.
* cant define an methods, properties or events.
* after compilation, each symbol is replaced by a constant field.
* enumerated type is just a structure that has a bunch of constant fields defined in it.
* After compilation, assembly that defined the enumerated type doesnt have to available at run time.
* fields can be byte, sbyte, short, ushort, uint,long, or ulong..int is default.

enum Color : byte{
Red,
Green,
Blue,
}
Console.WriteLine(Enum.GetUnderlyingType(typeof(Color)) ); //system.byte
Color co = Color.Green;
Console.WriteLine(co) //Green
Console.WriteLine(co.ToString()) //Green
Console.WriteLine(co.ToString("D")) 1
Console.WriteLine(Enum.Format(typeof(Color),(Byte)2,"G")); //Blue
Color[] cm = (Color[])Enum.GetValues(typeof(Color));
foreach(Color m in cm)
Console.WriteLine(m);

[Flags] attribute is applied so that a symbol matching each 1 bit islooked up and concatenated to a string; each symbol is separated by comma.


File Flags
* System.IO.File and System.IO.FileAttributes
*
* String fl = @"c:\YServer.txt";
System.IO.FileAttributes at=System.IO.File.GetAttributes(fl);
Console.WriteLine(at);

Text

STRING
* String type is derived immediately from object, making it a reference type.
* Implements several interfaces like Icomparable, Icloneable, Iconvertible, IEnumerable
* primitive type
* immutable - once created, a string can never get longer, get shorter, or have any of its characters changed.
Equals - checks if same object and returns true otherwise checks if all characters are same n return true

STRINGBUILDER
* Internally , a stringbuilder object has a field that refers to an array of char structures.
* performs dynamic operations with strings and characters to create a string.
* convert the stringbuilder's character array into a string by calling tostring. it will return the refernce to string field of stringbuilder
* string returned is immutable.
* attempt to edit stringbuilder after tostring was called will return a new stringbuilder object
* mutable string

Encoding: conversion between characters and bytes
* In CLR, all characters are represented as 16-bit Unicode code values and all strings are composed of 16-bit Unicode code values.
* transmitting 16th bit value isnt very efficient as half of the bytes written would contain zeros.
* Better encode it to compress it in array of bytes..transmit it then again decode back to 16th bit values
* encoding is done for system.IO.binarywriter and streamwriter and decoding is done for system.io.binaryreader or streamreader.
* no encoding then default is UTF-8

Most frequently used encoding are UTF-16 and UTF-8
UTF-16
* encode 16-bit character as 2 bites.
* no compression
* excellent performance
* also known as Unicode Encoding.

UTF-8
* encodes some as 1 byte,2byte,3byte and four byte.
* less useful than UTF-16 when encoding for 4byte is done mostly.

UTF-7
* for characters expressed using 7-bit values.
* rather avoid as its ends with expanding data instead of compressing.

ASCII
* encodes 16 bit characters in ASCII characters.
* any values less than 256 can be converted into single byte
* for greater the value is lost
* compressed data in half

to encode or decode ..create instance of class derived from system.text.encoding.

Comparing Strings
* Equals - calls CompareOrdinal method- check for same ref first then compare the characters.
* CompareOrdinal - checks for same characters.- always case sensitive - fast
* Compare - culture specific - logically equal strings

Delegates and Events

DELEGATES
* CLR's eventing model is based on delegates.
* DELEGATE is a type-safe way to invoke a callback method.
* They are just function pointers, That is, they hold references to functions.
* A Delegate is a class. When you create an instance of it, you pass in the function name (as a parameter for the delegate's constructor) to which this delegate will refer.
* Delegates also intergrate the ability to call multiple methods serially and support the calling of static methods as well as instance methods.
*All delegate types are derived from MulticastDelegate which itself is derived from System.Delegate class which itself is derived from System.Object.
* The implementation of Equals compares two delegate objects to see whether their target is same or not.



class classdelg
{static int i=1;
public delegate void del(int a, string b);
public void delfunc(del d)
{
if (d != null)
d(i++, "success");
}
}
class funcdelg
{
public void outfunc(int a, string B)
{
Console.WriteLine("OUTFUNC {0},{1}",a,B);
}
}
class p1isas
{
static void infunc(int a, string b) //not a public function
{
Console.WriteLine("INFUNC {0},{1}", a, b);
}
static void Main()
{

classdelg cd = new classdelg();
funcdelg fd= new funcdelg();
classdelg.del d = null; //delegates are type property
d += new classdelg.del(infunc);
d += new classdelg.del(fd.outfunc);
cd.delfunc(d);
Console.Read();
}
}


Delegate Chains -

Feedback fb1 =new Feedback(Func1);
Feedback fb2= new Feedback(Func2);
Feedback fbchain= (Feedback) Delegate.Combine(fb1,fb2);
fb2 function will get invoke first.

EVENTS
* Event programming model that is popular in asynchronous programming.
* Delegate usefulness does not just lie in the fact that it can hold the references to functions but in the fact that it can define and use function names at runtime and not at compile time. A large goal of design delegates is their applicability in events model of .Net

Removing Delegates
Feedback fb1 =new Feedback(Func1);
Feedback fb2= new Feedback(Func2);
Feedback fbchain= (Feedback) Delegate.Combine(fb1,fb2);
Feedback fbchain= (Feedback) Delegate.Remove(fbchain, new Feedback(Func2) );

C# provides overloads of the += and -= for Delegate.Combine and Delegate.Remove

Event Example

using System;
using System.Threading;

namespace SecondChangeEvent
{
/* ======================= Event Publisher =============================== */

// Our subject -- it is this class that other classes
// will observe. This class publishes one event:
// SecondChange. The observers subscribe to that event.

public class Clock
{
// Private Fields holding the hour, minute and second
private int _hour;
private int _minute;
private int _second;

// The delegate named SecondChangeHandler, which will encapsulate
// any method that takes a clock object and a TimeInfoEventArgs
// object as the parameter and returns no value. It's the
// delegate the subscribers must implement.

public delegate void SecondChangeHandler (
object clock,
TimeInfoEventArgs timeInformation
);


// The event we publish
public event SecondChangeHandler SecondChange;

// The method which fires the Event
protected void OnSecondChange(
object clock,
TimeInfoEventArgs timeInformation
)
{
// Check if there are any Subscribers
if (SecondChange != null)
{
// Call the Event
SecondChange(clock,timeInformation);
}
}


// Set the clock running, it will raise an
// event for each new second

public void Run()
{
for(;;)
{
// Sleep 1 Second
Thread.Sleep(1000);

// Get the current time
System.DateTime dt = System.DateTime.Now;

// If the second has changed
// notify the subscribers

if (dt.Second != _second)
{
// Create the TimeInfoEventArgs object
// to pass to the subscribers

TimeInfoEventArgs timeInformation =
new TimeInfoEventArgs(
dt.Hour,dt.Minute,dt.Second);

// If anyone has subscribed, notify them
OnSecondChange (this,timeInformation);
}

// update the state
_second = dt.Second;
_minute = dt.Minute;
_hour = dt.Hour;

}
}
}

// The class to hold the information about the event
// in this case it will hold only information
// available in the clock class, but could hold
// additional state information

public class TimeInfoEventArgs : EventArgs
{
public TimeInfoEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public readonly int hour;
public readonly int minute;
public readonly int second;
}

/* ======================= Event Subscribers =============================== */

// An observer. DisplayClock subscribes to the
// clock's events. The job of DisplayClock is
// to display the current time

public class DisplayClock
{
// Given a clock, subscribe to
// its SecondChangeHandler event

public void Subscribe(Clock theClock)
{
theClock.SecondChange +=
new Clock.SecondChangeHandler(TimeHasChanged);

}

// The method that implements the
// delegated functionality

public void TimeHasChanged(
object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine("Current Time: {0}:{1}:{2}",
ti.hour.ToString(),
ti.minute.ToString(),
ti.second.ToString());
}
}

// A second subscriber whose job is to write to a file
public class LogClock
{
public void Subscribe(Clock theClock)
{
theClock.SecondChange +=
new Clock.SecondChangeHandler(WriteLogEntry);

}

// This method should write to a file
// we write to the console to see the effect

// this object keeps no state
public void WriteLogEntry(
object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine("Logging to file: {0}:{1}:{2}",
ti.hour.ToString(),
ti.minute.ToString(),
ti.second.ToString());
}
}

/* ======================= Test Application =============================== */

// Test Application which implements the
// Clock Notifier - Subscriber Sample

public class Test
{
public static void Main()
{
// Create a new clock
Clock theClock = new Clock();

// Create the display and tell it to
// subscribe to the clock just created

DisplayClock dc = new DisplayClock();
dc.Subscribe(theClock);

// Create a Log object and tell it
// to subscribe to the clock

LogClock lc = new LogClock();
lc.Subscribe(theClock);

// Get the clock started
theClock.Run();
}
}

}

Monday, December 8, 2008

DESIGNING TYPES

OPERATOR OVERLOAD methods are not part of the Common Language Specification.

EVENTS - used to send notification to a listening type or a listening object.

Attributes for Types
* Abstract - abstract - MustInherit
* Sealed - sealed - NotInheritable

Use of Sealed and private constructor - when creating your own type that contains only static members.

Attributes for fields
* Static - static - Shared - allocated when class loads - first time it is JIT compiled.
* InitOnly - readonly - ReadOnly - The field can be written to only by code contained in a construtor method.

Method Predifined attributes
* Static - Static - Shared - can't access instance fields or methods defined within the type.
* Virtual - virtual - Overridable - default type - applies only to non static methods
* Newslot - new - shadows - default type - should not override a virtual method of base and hides the inherited method. applies only to virtual methods.
* Abstract - abstract - MustOverride - must be implemented by derived type. applies only to virtual methods.
* Override - override - Overrides - explicitly states that the method is overiding virtual method of base.
* Final - sealed - NotOverridable - Cant be override. applies only to virtual method

Constants -
* saves value in metadata determined at compile time -
* applies only to primitive types -
* part of type - implicity static
* cant be passed by reference

Create a constant at run time use - public static readonly int32 value = 50

Creation of ref type object - all fields are zeroed out then constructor is called.

Create a instance of a type without calling its constructor - Use memberwiseclone method or deserialize an object

Value type constructor -
* C# doesnt allow parameterless constructot but CLR allows
* Constructor must initialize all the type fields otherwise complile time error.

Type Constructors or static constructors -
* should be marked as static
* always implicitly private
* parameterless
* CLR is responsible to call type constructor
* will never call base constructor or fields
* static fields are never inherited or shared



reference type passing by value - new ref type created and pointing to the same object
reference type passing by ref or out- same ref type copied.
Variables passed by reference to a method must be the same type. This is to ensure the type safety so type casting doesnt happen.



Variable parameter
* should always be the last parameter
* even pass null or no parameter to param

static void Main(string[] str)
{
variableparam("saurabh", true, 1, 2, 3, 4, 4, 4);
variableparam("no param", false);
Console.Read();
}
static void variableparam(string a, Boolean b,params int[] c)
{
Console.WriteLine("a={0}, b={1}, c={2} ", a, b,c[2]);
}

Properties
* smart fields
* static, instance and virtual properties
* defined within an interface
* overload not possible
* readonly - set method is absent
* writeonly - get method is absent
* C# calls it indexers and vb defalult properties
* indexers can have atleast one or more than one parameters
* C# indexers only on instance of objects - no static indexers but CLR does.
* indexers is kind of overloading of [] operator

Friday, December 5, 2008

Type Fundamentals

All types implicitly derived from System.Object

Public Methods
* Equals - Return true if two objects have the same value.
Reference types - objects - Return true if two references returned point to same object.
System.ValueType overrides the Equals method so that it returns true is the value of two object's fields match.

* GetHashcode - Return Hash code for this objects value. - implementation of the system.collections.Hashtable type requires that any two objects that are equal must have the same hash code value.
System.ValueType overrides the GetHashCode method so that it produces a hash code using an algorithm which takes into account the value of object's field.


* ToString - returns this.GetType().FullName.ToString() - int32, boolean etc override to return string of their value
* GetType - Non Virtual method - derived class cant override it - type safety.

Protected Methods
* MemberwiseClone - nonvirtual method - returns new instance of the type and sets the current object identical fields. first it allocated memory, initializes the objects overhead fields and then copies the source object's bytes to the new object.
* Finalize - automatically called just before relaclaming memory after garbage collecter is called. - types required cleanup is added in the override of this method.

No delete operator - No way explicitly free the memory allocated for an object

Initialize object overhead member - 2 members
* Object's pointer to the types method table
* SyncBlockIndex - multiple threads synchronize their access to the instance using the methods of the System.Threading.Monitor type

IS and AS

* IS returns boolean value after checking the compatibility of the object
* AS returns the object reference if found compatible else returns null



Object o1 = new Object();
Object o2 = new test1();
if (o1 is test1) //false
{
test1 t1 = (test1) o1;
Console.WriteLine("t1 success");
}
if (o2 is test1) //true
{
test1 t2 = (test1) o2;
Console.WriteLine("t2 success");
}
test1 t3= o1 as test1;
test1 t4 = o2 as test1;
if (t3 == null)
{Console.WriteLine("t3 is null");} //null
if (t4 == null)
{Console.WriteLine("t3 is null");} //not null


// x allocated to stack
Int32 x = 5;
// memory equal to size of x + method table pointer + SyncBlockIndex is allocated in heap and value copied then ref is returned
Object o = x;
//unboxing
Int16 y = (Int16)(Int32) o;

IL generated for the below is same
* System.Int32 a
* int a = 0

Primitive types - Any data types the compiler directly supports.

C# allows implicit casts if the conversion is "safe",that is no loss of data is possible such as converting int32 to an int64. But C# requires explicit casts if the conversin is potentially unsafe.For numeric types, "unsafe" means that you could lose precision or magnitude as a result of the conversion.

CHECKED AND UNCHECKED is used to check the overflow

System.Object -> System.ValueType -> System.Int32 or System.Boolean
System.Object -> System.ValueType -> System.Enum -> System.FontStyle or System.IO.FileAttributes
* All value types are either structures or enumerations inherit System.Object and thats why allocated on stack.
* CLR doesnt allow a value type to be used as a base type for any new types.

When any of the inherited methods of value type is called. It is first boxed and then method is accessed via table method pointer

ICloneable interface - The class should implement this interface if it wants instances of itself to be cloneable.

Public interface ICloneable{
Object Clone();
}

Wednesday, December 3, 2008

.NET Concepts

.NET Frame work consist of two parts
* Common language runtime(CLR)
* Framework Class Library(FCL)

Advantage of CLR and FCL

* Consistent programming model - oops
* Simplified programming model - frees developer from knowledge of registry, GUIDS, AddRef..
* Run once - run always
* Simplified Deployement
* Wide platform reach - ny machine that has CLR installed.
* Programming language integration - ny language
* Automatic Memory Management - garbage collection
* Type safety
* Rich debugging support
* Exeption handling
* Security
* Interoperability - access existing COM and win32 func in existing Dlls

What is the advantage of using one programming language over other ?

i think of compilers as syntax checkers and correct code analyzers. Expressing your logic
is very important. different developers had different background before switching to .NET
so inorder to make them more comfortable with programming languages.

A MANAGED MODULE is a standard windows protable executable(PE) file that requires the CLR
to execute.

Parts of Managed Module

* PE Header - type of file-dll,exe,gui,cui, modified,access,creation time
* CLR Header - entry point, CLR target version, location size of resources, metadata and flags
* Metadata - mainly 2 tables-tables that describe the types and members defined/referenced in ur source code
* IL code - code produced by compiler

5 Uses of Metadata

* Intellisense
* Removes the need of Header files and Library files
* Garbage coller to track the life time of object
* Use during serialization and deserialization of an object
* By Code verfication process to ensure type safe operations

Multiple Managed modules + resource files = 1 Assembly file(modules + Manifest)

.NET Framework installed or not check for MSCoreEE.dll file in system32 folder.

MSCorEE.dll - Microsoft Component Object Runtime Execution Engine.

Click exe file - read PE header - 6 byte x86 stub function - JMP _CorExeMain/JMP _CorDllMain - loads MSCorEE.dll - executes _CorExeMain - initialize CLR - read CLR Header - locate Main entry point

6-byte x86 stub functions are ignored on machines running Windows XP and the Windows .NET Server Family

IL Assembler - ILAsm.exe
IL Disassembler - ILDasm.exe

New function - JITCompiler - searches assembly metadata for methods IL- compiles it.

Managed Code outperforms unmanaged code when -:

* JIT complier could detect that the application is running on a pentium 4 and produce
* native code that takes advantage of any special instructions offered by the pentium-4.

* NGen.exe tool - compiles assembly IL code into native code and saves resulting code
* to a file in the disk.

Verification - safe - throw exception System.Security.VerifierException- also tool PEVerify.exe

CTS - describs how types are defined and how they behave

Property - validate input parameters and object state before accessing the value and calculate
* a value only when necessary

IL defines 6 visibles types
* Private - same class
* Family - protected - derived class
* Public - any class
* Assembly - internal - Friend - any class same assembly
* Family or assembly - protected internal - Protected Friend same assembly or derived types in diff assembly
* Family and assembly - derived type in same assembly - not supported

if an unnested type isn't explicitly marked, C# and VB both default to Assembly(internal/Friend)

CLS - Minimum set of features that a compiler must support to target CLR.

Windows - security is based around a users identity
.NET Framework - code access security - based around an assembly's identity

MSCorLib.dll - it contains the definitions of all the core .NET Framework class Library (FCL) types, such as Object, Int32, String and so on.

Assembly - An assembly is a collection of one or more files containing type definitions and resource files.
Manifest - it is another set of metadata tables that basically contain the name of the files that are part of the assembly and makes the assembly self describing.
CLR always loads the file that contains the manifest metadata talbes first and then uses the manifest to get the names of the other files that are in the assembly.
/t:exe, /t:winexe, /t:library - assembly is produced
/t:module - DLL PE file without manifest, must be added to assembly to access its types

AL.exe - Assembly Linker Utility - creates assembly consisting of modules built from different compilers or to build resource only assembly(satellite assembly)

AssemblyInfo.cs - assembly specific information.

3 custom attribute for versioning - AssemblyVersion is main - CLR uses this version number when binding to strongly named assemblies.
* uniquely identify an assembly. format of version number - 4 fields.
* Major Number
* Minor Number
* Build Number - increments with every build
* Revision Number

Culture attribute - for a specific language - 2 fields - Primary Tag and secondary Tag - en (none) and en US
* Culture Neutral - Assembly that isnt assigned a culture
* Satellite Assembly - Assemblies that contain only culture specific resources and no code - AL.exe tool
* you access the satellite assembly's resources using the System.Resources.ResourceManager
* you can also specify the Culture using the System.Reflection.AssemblyCultureAttribute custom attribute [assembly:AssemblyCulture("en-US")]

Two kinds of Assemblies - Weakly named assemblies and strong named assemblies.
* Difference - strong named assembly is signed with publisher's public/private key pair that uniquely identfies the assemblies publisher.

Two ways of deployment
* Privately deployed assemblies - Assemblies deployed to the same application directory - both weak and strong named assembly
* Globally deployed - assemblies deployed the CLR known location - stong named assembly

A strong named assembly consist of four attributes that uniquely indentify the asembly
* FileName(without extention)
* VersionNumber
* culture identity
* Public key token

SN.exe - Strong Name Utility - generate public/private key pair
* Public key Token is 64 bit hash of public key
to create strong named assembly - use System.Reflection.AssemblyKeyFileAttribute in ur source code
* [assembly:AssemblyKeyFile("Mycompany.Keys)]
* signs assembly with private key and embeds public key in the manifest - SHA-1 algorithm - PE file's entire contents are hashed after built

GAC - C:\Windows\Assembly\GAC
* Use always GACUtil.exe to install a strong name assembly into GAC.

CLR compares hash value when assembly is loaded other than GAC - performance hit

Delayed Signing - developing and testing ur assembly , gaining access to secure private key can be hassle - always copying in GAC
* it allows you to build an assembly using only public key - extract public key in a file - use both keys which packaging n installing
* DelaySignAttribute