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

Thursday, September 4, 2008

using System;
using System.Collections.Generic;
using System.Text;
using wr = System.Console;


namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            //Console.WriteLine(args[0]);
            //this.nonstatic(); //no non static methods are accessable.
            //nstring();
            //extra();
            //stconstr();
            // nstuct();
            ////mypass.run();
            //myparam.run();
            //myprop3.Run();
            //myindex.run();
            //attclass.run();
           // intclass2.run();
            //Pr1.run();
            wr.ReadLine();
        }


        public static void temp()
        { }
        //private variables that are not marked as static cannot be utilised by a static method. 
        public void nonstatic() { } //It is invalid for one static method to directly 
        //call a non-static method or property without first instantiating an object.  


        public static void nmystatic1()
        {
            new mystatic1();
            new mystatic1();
            wr.WriteLine(mystatic1.varstat1);

        }
        public static void stconstr()
        {
            mystatic2 ms = new mystatic2();
            wr.WriteLine("hostname : {0} and ipaddres : {1}", mystatic2.hostname, mystatic2.ipaddr);
        }
        public static void nstring()
        {
            Emp e = new CEmp();
            CEmp x = (CEmp)e;   //write usage 
            // x = (CEmp) new Emp();   //wrong usage
            //    x.Cstring();

        }
        public static void extra()
        {
            Emp e = new Emp();
            wr.WriteLine(e.GetType());
            wr.WriteLine(e.GetHashCode());
            wr.WriteLine(e.ToString());

        }
        public static void nstuct()
        {
            mystruct1 st1;
            st1.e = 1;
            st1.r = 2;
            st1.w = 3;
            mystruct1 st2 = new mystruct1(); //it will initialize all the int types with 0
            Console.WriteLine("{0} {1}", st2.e, st1);


        }
    }

}
class Emp : System.Object
{
    public Emp() { }

}
class CEmp : Emp
{
    public CEmp()
    { Cstring(); }
    public void Cstring()
    {

        string[] str = { "sfsf", "sdf", "sdfsf" };
        //string[] str2 = { "sfsf", 2, 3};
        string[] str1 = new string[1];
        int[] arr1;
        arr1 = new int[10];
        arr1 = new int[20];
        wr.WriteLine(arr1[5]);
        int[,] arr2;
        arr2 = new int[2, 3]; //Multidimensional arrays:
        wr.WriteLine(arr2[0, 1]);
        int[][] arr3; //Array-of-arrays (jagged)
        arr3 = new int[4][];
        for (int i = 0; i <>
            arr3[i] = new int[i + 1];
        string str3 = @"c:\Docs\Source\a.txt";         //@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"
        wr.WriteLine(str3 + "      " + str3[2]);
        str3 = @"sdfsfsf";
        str1[0] = "hello";
        Console.WriteLine(str1[0]);
        // Console.ReadLine();
        //@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

        //ConsoleApplication1.Program.Main(str1); //correct


    }



}

// private class mystatic  { } // no access mofifiers in class



class mystatic1
{
    public mystatic1()
    { varstat1++; }
    public static int varstat1;
}
class mystatic2
{
    /*//A static constructor is used to initialise the static state of a class when 
    //it is first used.  access modifiers private or publiv arent allowed on static 
     * constructors..  A static constructor therefore has no facility to add parameters.
     * It is also not possible to include a static destructor.
    //static constructors are used to initialize static fields, readonly or otherwise.
    //we are not writing any access modifier for static constructor as they are by definition, always public.
     * you can have only one static constructor and it cant access instance members including this pointer.
     * you can provide a non static constructor with the same signature as static constructor and if u 
     * do this then both constructors will get called before the first instance of a class
     * is created with the static version called first.
     */
    static mystatic2()
    {
        System.Net.IPAddress ipad = System.Net.Dns.Resolve(hostname).AddressList[0];
        ipaddr = ipad.ToString();
    }
    public const string hostname = @"www.google.com";
    public static readonly string ipaddr;

}

sealed class mysealed
{
    public mysealed(int x, int y)
    {
        this.x = x;
        this.y = y;

    }

    int x, y;
}

/*like a class, a stuct dont incur the overhead associated with reference objects.
client doesnt have to instantiate the stuct(new keyword). its a value type so is allocated
 once its declared.
 */
public struct mystruct1 //doesnt have a default constructor
{
    public int r, w, e;
    public override string ToString()
    {
        return w.ToString();
    }
}
/* u sue struct when data is very small or it contais few or no methods to access or modify
 * constained data
 * a class is an encapsulation of data and the methods that work on that data. structs can
 * be viewed as simple data.
 */
public struct mystruct2
{
    //public mystruct2() //parameterless constructor of a structure is not allowed.
    public mystruct2(int r, int w, int e)
    {
        this.e = e;
        this.w = w;
        this.r = r;

    }
    public int r, w, e;
}
//passing reference type by reference is same as passing by value.
class mypass
{
    public mypass()
    {
        a = 10;
        b = 20;
        c = 30;
    }

    int a;
    int b;
    int c;
    public void valpass(int a, int b, int c)
    {
        a = 5;
        b = 10;
        c = 15;
        wr.WriteLine("val pass : {0} {1} {2}", a, b, c);
    }
    public void refpass(ref int a, ref int b, ref int c)
    {
        a = this.a;
        b = this.b;
        c = this.c;
        wr.WriteLine("ref pass : {0} {1} {2}", a, b, c);
    }
    public void outpass(out int a, out int b, out int c) //out parameters must be modified in the called method.
    {
        // c = a; can not use out parameter before modifying
        a = this.a + 1;
        b = this.b + 1;
        c = this.c + 1;
        wr.WriteLine("out pass : {0} {1} {2}", a, b, c);
    }

    public void objpass(out mypass m)
    {
        // int x = m.a; can not use m before assigning it to another object
        m = new mypass(); //now u can use it.

    }
    //passing reference type by reference is same as passing by value.
    public void objpass2(ref mypass m1, mypass m2)
    {
        //will work same 
        m1.a = m1.a + 1;
        m2.a = m2.a + 1;
        //will work diff
        m1 = new mypass(); //same ref is passed so value will get changed in the root ref
        m2 = new mypass(); //copy of the reference is passed so root will remain unchanged.
    }
    public static void run()
    {
        int a = 1, b = 2, c = 5; // for ref and val parameter initialization is necessary
        int d = 1, e = 2, f = 5;
        int g = 6, h, i;        // parameter may or may not be initialized for out.
        mypass m = new mypass();
        wr.WriteLine("val pass : {0} {1} {2}", a, b, c);
        m.valpass(a, b, c);
        wr.WriteLine("ref pass : {0} {1} {2}", d, e, f);
        m.refpass(ref d, ref e, ref f);
        //wr.WriteLine("ref pass : {0} {1} {2}", g, h, i);
        m.outpass(out g, out h, out i);
    }

}
/*method overload
 * access modifier and return type doesnt count
 * ref and out are enough
 * you can use either ref or out but not both,
 constructor overloading -
 * its like public func_constructor(int a) : this()
 * where this is default constructor but no longer valid after the explicit use.
 * we can also call other constructor from one constructor like this
 * public func_constructor(int a) : this("hello")
 * overloaded methos is considered an overloaded even if other overloaded versions of the
 * funcitons exist in the base class rather than current class.
 */
class myparam
{
    static void param1(params int[] a)
    {
        foreach (int b in a)
        {
            wr.WriteLine(b);
        }
        //or
        /*  for (int i = 0; i <>
          {
              wr.WriteLine(a[i]);
          }*/
        /* public void func(params object[] a)
         * it can take ny number of parameters of ny type
         */
    }
    public static void run()
    {
        param1(1, 2);
        param1(5, 6, 7);
    }
}

/*method overriding - type of polymorphism
 *in the derived method, wherther we are using 'new' of not, it will be by default to all 
 * the methods with diff name diff arguments or same name same arguments.
 * in the upcast the base reference will always point to the base method.
 * it happpens due to early binding which is binding of method at compile time which is
 * C# looks at the call and determines the address in memory needed to jump to when call
 * is made and in case memory location of the method.
 * late binding means that the compiler doesnt select the method to excute until runtme.
 * for this we must use virtual and override keyword.
 * polymorphic class - using virtual and override
 * non polymorphic class - using new.
 * the point is in virtual function table
 * a constructor cant be virtual.
 * new virtual is also possible - only virtual means new by default.
*/

class myprop1
{
    int salary = -1;
    public virtual int Salary
    {
        // get; allowed only for abstract or extern class
        get
        { return salary; }
        set { }
    }
}
/* only getter - readonly property..only setter - write only property
 * both setter n getter - read-write property
 * cant be used as parameter to methods.
 * static properties doesnt not have virtual abstract or override keywords
 * members defined as abstract within an abstract class must be implemented by any derived class
 * 
*/
class myprop2 : myprop1
{
    int salary = 10;
    public override int Salary
    {
        get
        {
            return salary + 5;
        }

        set
        {
            salary = value;
        }
    }
}
class myprop3 : myprop1
{
    int salary = 20;
    public override int Salary
    {
        get
        {
            return salary + 1;
        }
        set
        {
            salary = value;
        }


    }

    public static void Run()
    {
        myprop1[] m1 = new myprop1[2];
        m1[0] = new myprop2();
        m1[1] = new myprop3();
        wr.WriteLine("1st {0} 2nd {1}", m1[0].Salary, m1[1].Salary);
        m1[0].Salary = 50;
        m1[1].Salary = 100;
        wr.WriteLine("1st {0} 2nd {1}", m1[0].Salary, m1[1].Salary);

    }
}

class myindex
{
    System.Collections.ArrayList a = new System.Collections.ArrayList();
    public object this[int i]
    {
        get
        {
            if (i > -1 && i <>
                return a[i];
            else
                return "error";

        }
        set
        {
            if (i <>
                a[i] = value;
            else if (i == a.Count)
                a.Add(value);
        }
    }
    public static void run()
    {
        myindex m = new myindex();
        m[0] = "asfd";
        m[1] = 2;
        wr.WriteLine(m[0] + "  " + m[1]);
        wr.WriteLine(typeof(myindex));
        //wr.WriteLine(m[0],m[1]);   //error

    }



}

public enum myenum
{
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
class myattribAttribute : Attribute
{
    public myattribAttribute(string name)
    {
        this.Name = name;
    }

    myenum day;
    public myenum Day
    {
        get { return day; }
        set { day = value; }
    }
    string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

}

[myattrib("DayThursday", Day = myenum.thursday)]
class attclass
{
    [myattrib("DayWednesday", Day = myenum.wednesday)]
    public void Method()
    {
    }
    public void method2() { }
    [myattrib("DayFiday", Day = myenum.friday)]
    public int field;
    public int field1;
    public static void run()
    {
        Type type = Type.GetType("attclass");
        foreach (Attribute att in type.GetCustomAttributes(true))
        {
            if (att is myattribAttribute)
            {
                myattribAttribute myat = att as myattribAttribute;
                wr.WriteLine("{0} {1}", myat.Name, myat.Day);
            }
        }
        foreach (System.Reflection.MemberInfo mi in type.GetMethods())
        {
            foreach (Attribute att in mi.GetCustomAttributes(true))
                if (att is myattribAttribute)
                    wr.WriteLine(mi.Name);
                else wr.WriteLine("not {0}", mi.Name);
        }
        foreach (System.Reflection.FieldInfo fi in type.GetFields())
        {
            foreach (Attribute att in fi.GetCustomAttributes(true))
            {
                if (att is myattribAttribute)
                {
                    myattribAttribute myat = att as myattribAttribute;
                    wr.WriteLine(fi.Name);
                    wr.WriteLine("{0} {1}", myat.Name, myat.Day);
                }
            }
        }
    }

}
class intclass1
{
    void printf1()
    {
        wr.WriteLine("print int class1");
    }
}
interface inf1
{
    int count();
    void printf1();
}
interface inf2
{
    void printf2();
}
interface inf3 : inf1, inf2
{ }
interface inf4
{
    int count();
}
class intclass2 : intclass1, inf3, inf4
{
    public void printf2()
    {
        wr.WriteLine("intf3->intf2");
    }
    public void printf1() //new keyword is by default
    {
        wr.WriteLine("intf3->intf1");

    }

    int inf1.count() //inf1 is used instead inf3
    {
        return 2;
    }
    int inf4.count()
    {
        return 3;
    }
    public static void run()
    {
        intclass2 infc2 = new intclass2();
        ((inf3)infc2).printf1();
        // infc2.count-----name hidding

    }

}

class myclock
{
    public delegate void del(Timeargs t1);
    public event del ev;
    int sec, hour, min;
    public void onsecchange(Timeargs ti)
    {
        if (ev != null)
            ev(ti);
    }
    public void run()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(1000);
            DateTime dt = DateTime.Now;
            if (dt.Second != sec)
            {
                Timeargs tm = new Timeargs(dt.Hour, dt.Minute, dt.Second);
                this.sec = dt.Second;
                this.hour = dt.Hour;
                this.min = dt.Minute;
                onsecchange(tm);
            }

        }

    }

}
class logi
{
    public void subscribe(myclock mc)
    {
        mc.ev += new myclock.del(logger);
    }
    public void logger(Timeargs tm)
    {
        Console.Write("\r{2}:{0}:{1}", tm.min, tm.sec, tm.hour);
    }
}
class Timeargs
{
    public Timeargs(int hour, int min, int sec)
    {
        this.hour = hour;
        this.sec = sec;
        this.min = min;
    }
    public readonly int hour, min, sec;
}

class Pr1
{

    
    public static void run()
    {
        string[] a = new string[5];
        myclock mc = new myclock();
        logi lg = new logi();
        lg.subscribe(mc);
        mc.run();
       // Console.ReadLine();




    }
    private static void func1(string message)
    {
        Console.WriteLine(message);

    }
}

C#.Net vs VB.Net

n Visual C# you can document the code you write using XML. C# is the only programming language in Visual Studio .NET with this feature.

.net C#.net and VB.net

ACCESS MODIFIERS
 * Classes and structs that are declared directly within a namespace (in other words, they are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.
 * Nested classes and structs may also be declared as private. Private nested types are not accessible from the containing type.

Derived classes cannot have greater accessibility than their base types. In other words, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
Class members (including nested classes and structs) can be declared with any of the five types of access. Struct
 * members cannot be declared as protected because structs do not support inheritance.

The accessibility of a member can never be greater than the accessibility of its containing type. For example, 
 * a public method declared in an internal type has only internal accessibility.

When a member of a class or struct is a property, field, method, event, or delegate, and that member either is a 
 * type or has a type as a parameter or return value, the accessibility of the member cannot be greater than the 
 * type. For example, you cannot have a public method M that returns a class C unless C is also public. Likewise,
 * you cannot have a protected property of type A if A is declared as private.

User-defined operators must always be declared as public

Interfaces declared directly with a namespace can be declared as public or internal and like classes and structs,
 * interfaces default to internal access. Interface members are always public because the purpose of an interface 
 * is to enable other types to access a class or struct. No access modifiers can be applied to interface members.

Enumeration members are always public, and no access modifiers can be applied.

By default, delegates have internal access.

Any types declared within a namespace or at the top level of a compilation unit (for example, not within 
 * a namespace, class, or struct) are internal by default, but can be made public.
*/

/*
A private constructor is a special instance constructor. It is commonly used in classes that contain static members 
 * only. If a class has one or more private constructors and no public constructors, then other classes
 * (except nested classes) are not allowed to create instances of this class.
 * if you are designing your own type that contains only static members then you should mark the type as Sealed 
 * and define a private parameterless contructor that is never called.
*/

/*
C# doesnt allow a value type to define a parameterless constructor.
 * keep in mind that although C# doesnt allow value types with pareameterless costructors, the CLR does.
 * 
 *     struct point
    {
                public int x=5,y; // cannot have instance field initializers in structs. so x=5 is wrong..
 *                               //becoz there are no default constructors. so int x is correct but int x=5 is wrong...
                public classA a; //an object can be a part of a value type
 * 
 *                public point() // wrong...parameterless constructor is not allowed
 *              public point(int x)
 *              {
 *                  //in a constructor u have to initialize each field else compilation error
 *              this.x=x;
 *              this.y=x;
 *              this.a=new classA();
 *              }
 * }
 * 
 * system.int32 a = new system.int32() and int a = 0 has same code in IL. that mean when we wrote 0 then implicit constructor was called.
 * Any data type that compliler directly supports are called primitive types.   
we do not have instance field initializers in structs....so no objects in value types can be instantiated
*/

/* 
 *a new operator has no complementary delete oerator that is there is no way to explicitly free the memory allocated for an object. 
 * MSCorLib.dll assembly contains the definitions of all the core .NET Framework class Library types, such as Object, int32, String and so on.
 * all the value types of class are allocated in the heap and not on stack, only the value types of the functions are allocated on stack
 * in c#, types declared using struct are value types adn types declared using class are refernce types. 
 * Value types are derived from system.valuetype which is again derived from system.object.system.valuetype overrides
 * the equal method so that it returns true if the values fo the two object's fields match.
 * it also overrides the gethashcode method so that it produces a hash code value using an algorithm that takes into 
 * account the values in the objects instance fields.
 * the reason why a type must define both equals and gethashcode is that the implementation of the 
 * system.collections.hashtable type requires that any two objects that are equal must have same hash code value. 
 * 
 * 
 * someval v1; //someval is a value type.
 * this line produces IL that allocates the instance on the thread stack and zeroes the fields.the only problem is 
 * that C# thinks the instance initialized if u use the new operator or a direct value. so if u try to use it will
 * throw complile time error.
 * 
 * 
 *A READONLY variable can only be assigned in a constructor or variable initializer(repeations are allowed) but
 * cant be declared in a function or constructor.
 * 
 * The compiler saves the CONSTANT value in the module metadata. You can define constant only for types that your
 * compiler considers as primitive types.
 * 
 * A lot of types(System.String) overload the equality (==) and inequality operators.
 * 
 * 
 * An EVENT in C# is a way for a class to provide notifications to clients of that class when some interesting
 * thing happens to an object.
 * DELEGATE is a class that derive from System.MulticastDelegate and includes following  members:
 * EnumConnectionCallback constructor
 * Invoke
 * BeginInvoke
 * EndInvoke
 * 
 * 
 * XML DUCUMENTATION - One of the nice side-effects of setting this configuration value is that documentation 
 * warnings are then enabled:
All overlaoded OPERATOR methods must be defined as public and static.
* should have a return type
* unary operator - single argument, binary operator - 2 arguments.
*
* DELEGATES are reference types that encapsulate a method(either static or instance) with a specified signature.
* CALLBACK methods enable you to pass a function pointer to another function that will then call you back.

Tuesday, August 26, 2008

smtp code

'Web.Mail.SmtpMail.SmtpServer = "Name"

' Dim msg1 As New Web.Mail.MailMessage()

'msg1.From = TextBox1.Text
'msg1.To = TextBox2.Text
'msg1.Subject = TextBox3.Text
'msg1.Body = RichTextBox1.Text
'msg1.BodyFormat = Web.Mail.MailFormat.Html
'Web.Mail.SmtpMail.Send(msg1)
Dim msg2 As New System.Net.Mail.MailMessage(TextBox1.Text, TextBox2.Text, TextBox3.Text, RichTextBox1.Text)
' Dim sd As New System.Net.Mail.SmtpClient()
'System.Net.Mail.smtp
Dim st As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient("inhywexmb1.infor.com")
st.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
st.Send(msg2)

MsgBox("message sent")

Saturday, August 9, 2008

Welcome

For(int =1;i<=101;i++)
{
printf("Welcome");
}