Monday, October 25, 2010

Reading & Writing Text File One Line at a Time

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();





// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

Sunday, October 24, 2010

Paging in SQL Server

declare @PageIndex int
declare @pageSize int
declare @startindex int
declare @endindex int



set @PageIndex = 1
set @pageSize = 10



set @startindex = @pageindex
set @endindex = @pagesize



if
(@pageindex > 1)
begin
set @endindex = @pageSize * @PageIndex
set @startindex = (@endindex - @pageSize ) + 1
end


Declare @totalrows int
select @totalrows =count(company_code) from tbl_CMT_Company
select *,@totalrows as totalRecords from
(
select Company_code,name,Arabic_name,
Row_number() over (order by Company_code) as rowindex
from tbl_CMT_Company
) as pageresult
where rowindex >=@startindex and rowindex <=@endindex

Friday, October 22, 2010

how to search value in Array

using System;

class Program
{
static void Main()
{
//
// Example integer array is declared.
//
int[] array = new int[6];
array[0] = 1;
array[1] = 3;
array[2] = 5;
array[3] = 7;
array[4] = 8;
array[5] = 5;

//
// Find index of element with value 5.
//
int index1 = Array.IndexOf(array, 5);

//
// Find index of value 3.
//
int index2 = Array.IndexOf(array, 3);

//
// Find last index of 5.
//
int index3 = Array.LastIndexOf(array, 5);

//
// Write the results.
//
Console.WriteLine(index1);
Console.WriteLine(index2);
Console.WriteLine(index3);
}
}

=== Output of the program ===

2
1
5





if (Array.IndexOf("StringArray", "ValueToFind") != -1)
{
//If found
//your code goes here
}
else
// Not found

Thursday, October 21, 2010

Flagging Unsaved Data

*script language="javascript" type="text/javascript"&
var myarray;
window.onload = function(e)
{
myarray=new Array(document.forms["aspnetForm"].elements.length)
for (var j=0; j < document.forms["aspnetForm"].elements.length; j++)
myarray[j]=new Array(3)

for (var i = 0; i < document.forms["aspnetForm"].elements.length; i++)
{
var element = document.forms["aspnetForm"].elements[i];
var type = element.type;

myarray[i][0] = element;
myarray[i][1] = type;

if (type == "checkbox" || type == "radio")
{
if (element.checked)
myarray[i][2] = true;
else
myarray[i][2] = false;
}
else if (type == "password" || type == "text" ||
type == "textarea")
{
// if( type == "textarea")
// {
// var textDesc = this.editor_getHTML('ctl00_ContentPlaceHolder1_txtBodyMessage');
// if(textDesc != undefined || textDesc != null)
// myarray[i][2] = textDesc;
// else
// {
// if(element.value != "")
// myarray[i][2] = element.value;
// else
// myarray[i][2] = "";
// }
// }
// else
if(element.value != "")
myarray[i][2] = element.value;
else
myarray[i][2] = "";

}
else if (type == "select-one" || type == "select-multiple")
{
for (var j = 0; j < element.options.length; j++)
{
if (element.options[j].selected)
myarray[i][2] = j;
}
}
else
myarray[i][2] = "";
}
};

window.onbeforeunload = function(e)
{

e = e || window.event;

var hdnButton = document.getElementById("hdnClicked");
if( hdnButton != null && hdnButton != '' && hdnButton != undefined)
{
if(hdnButton.value != "save")
{
if (formIsDirty(document.forms["aspnetForm"]))
{
if (e)
e.returnValue = "You have unsaved data on this page and are attempting to navigate away without saving.";
}
}
}
else
{
if (formIsDirty(document.forms["aspnetForm"]))
{
if (e)
e.returnValue = "You have unsaved data on this page and are attempting to navigate away without saving.";
}
}
};
function formIsDirty(form)
{
for (var i = 0; i < form.elements.length; i++)
{
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio")
{
if(myarray[i][2] != undefined)
{
if (element.checked != myarray[i][2])
return true;
}
}
else if (type == "password" || type == "text" ||
type == "textarea")
{
if( myarray[i][2] != undefined)
{
// if(type =="textarea")
// {
// if(element.value != "

 

")
// {
// if (element.value != myarray[i][2])
// return true;
// }
// }
// else
if (element.value != myarray[i][2])
return true;
}
}
else if (type == "select-one" || type == "select-multiple")
{
for (var j = 0; j < element.options.length; j++)
{
if (element.options[j].selected)
{
if( j != myarray[i][2])
return true;
}
}
}
}
return false;
}

function GetClicked()
{

var hdnButton = document.getElementById("hdnClicked");
if( hdnButton != null && hdnButton != '' && hdnButton != undefined)
hdnButton.value = "save";
}

*/script*

OnClick="btnSave_Click" ValidationGroup="vldSave" OnClientClick="GetClicked();" />




CS


ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
scriptManager.RegisterPostBackControl(btnCancel);

Yield

using System;
using System.Collections.Generic;
using System.Text;

namespace Yield
{
class Yield
{
public static class NumberList
{
// Create an array of integers.
public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };

// Define a property that returns only the even numbers.
public static IEnumerable GetEven()
{
// Use yield to return the even numbers in the list.
foreach (int i in ints)
if (i % 2 == 0)
yield return i;
}

// Define a property that returns only the even numbers.
public static IEnumerable GetOdd()
{
// Use yield to return only the odd numbers.
foreach (int i in ints)
if (i % 2 == 1)
yield return i;
}
}

static void Main(string[] args)
{

// Display the even numbers.
Console.WriteLine("Even numbers");
foreach (int i in NumberList.GetEven())
Console.WriteLine(i);

// Display the odd numbers.
Console.WriteLine("Odd numbers");
foreach (int i in NumberList.GetOdd())
Console.WriteLine(i);
}
}
}

Conversion

//Copyright (C) Microsoft Corporation. All rights reserved.

// conversion.cs
using System;

struct RomanNumeral
{
public RomanNumeral(int value)
{
this.value = value;
}
// Declare a conversion from an int to a RomanNumeral. Note the
// the use of the operator keyword. This is a conversion
// operator named RomanNumeral:
static public implicit operator RomanNumeral(int value)
{
// Note that because RomanNumeral is declared as a struct,
// calling new on the struct merely calls the constructor
// rather than allocating an object on the heap:
return new RomanNumeral(value);
}
// Declare an explicit conversion from a RomanNumeral to an int:
static public explicit operator int(RomanNumeral roman)
{
return roman.value;
}
// Declare an implicit conversion from a RomanNumeral to
// a string:
static public implicit operator string(RomanNumeral roman)
{
return("Conversion not yet implemented");
}
private int value;
}

class Test
{
static public void Main()
{
RomanNumeral numeral;

numeral = 10;

// Call the explicit conversion from numeral to int. Because it is
// an explicit conversion, a cast must be used:
Console.WriteLine((int)numeral);

// Call the implicit conversion to string. Because there is no
// cast, the implicit conversion to string is the only
// conversion that is considered:
Console.WriteLine(numeral);

// Call the explicit conversion from numeral to int and
// then the explicit conversion from int to short:
short s = (short)numeral;

Console.WriteLine(s);
}
}






// structconversion.cs
using System;

struct RomanNumeral
{
public RomanNumeral(int value)
{
this.value = value;
}
static public implicit operator RomanNumeral(int value)
{
return new RomanNumeral(value);
}
static public implicit operator RomanNumeral(BinaryNumeral binary)
{
return new RomanNumeral((int)binary);
}
static public explicit operator int(RomanNumeral roman)
{
return roman.value;
}
static public implicit operator string(RomanNumeral roman)
{
return("Conversion not yet implemented");
}
private int value;
}

struct BinaryNumeral
{
public BinaryNumeral(int value)
{
this.value = value;
}
static public implicit operator BinaryNumeral(int value)
{
return new BinaryNumeral(value);
}
static public implicit operator string(BinaryNumeral binary)
{
return("Conversion not yet implemented");
}
static public explicit operator int(BinaryNumeral binary)
{
return(binary.value);
}

private int value;
}

class Test
{
static public void Main()
{
RomanNumeral roman;
roman = 10;
BinaryNumeral binary;
// Perform a conversion from a RomanNumeral to a
// BinaryNumeral:
binary = (BinaryNumeral)(int)roman;
// Performs a conversion from a BinaryNumeral to a RomanNumeral.
// No cast is required:
roman = binary;
Console.WriteLine((int)binary);
Console.WriteLine(binary);
}
}

Threading

using System;
using System.Threading;

// The Fibonacci class provides an interface for using an auxiliary
// thread to perform the lengthy Fibonacci(N) calculation.
// N is provided to the Fibonacci constructor, along with an
// event that the object signals when the operation is complete.
// The result can then be retrieved with the FibOfN property.
public class Fibonacci
{
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}

// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...", threadIndex);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}

// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}
else
{
return Calculate(n - 1) + Calculate(n - 2);
}
}

public int N { get { return _n; } }
private int _n;

public int FibOfN { get { return _fibOfN; } }
private int _fibOfN;

ManualResetEvent _doneEvent;
}

public class ThreadPoolExample
{
static void Main()
{
const int FibonacciCalculations = 10;

// One event is used for each Fibonacci object
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();

// Configure and launch threads using ThreadPool:
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20,40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
}

// Wait for all threads in pool to calculation...
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("Calculations complete.");

// Display the results...
for (int i= 0; i {
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}





using System;
using System.Threading;

public class Worker
{
// This method will be called when the thread is started.
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
}

public class WorkerThreadExample
{
static void Main()
{
// Create the thread object. This does not start the thread.
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);

// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");

// Loop until worker thread activates.
while (!workerThread.IsAlive);

// Put the main thread to sleep for 1 millisecond to
// allow the worker thread to do some work:
Thread.Sleep(1);

// Request that the worker thread stop itself:
workerObject.RequestStop();

// Use the Join method to block the current thread
// until the object's thread terminates.
workerThread.Join();
Console.WriteLine("main thread: Worker thread has terminated.");
}
}





using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;

// The thread synchronization events are encapsulated in this
// class to allow them to easily be passed to the Consumer and
// Producer classes.
public class SyncEvents
{
public SyncEvents()
{
// AutoResetEvent is used for the "new item" event because
// we want this event to reset automatically each time the
// consumer thread responds to this event.
_newItemEvent = new AutoResetEvent(false);

// ManualResetEvent is used for the "exit" event because
// we want multiple threads to respond when this event is
// signaled. If we used AutoResetEvent instead, the event
// object would revert to a non-signaled state with after
// a single thread responded, and the other thread would
// fail to terminate.
_exitThreadEvent = new ManualResetEvent(false);

// The two events are placed in a WaitHandle array as well so
// that the consumer thread can block on both events using
// the WaitAny method.
_eventArray = new WaitHandle[2];
_eventArray[0] = _newItemEvent;
_eventArray[1] = _exitThreadEvent;
}

// Public properties allow safe access to the events.
public EventWaitHandle ExitThreadEvent
{
get { return _exitThreadEvent; }
}
public EventWaitHandle NewItemEvent
{
get { return _newItemEvent; }
}
public WaitHandle[] EventArray
{
get { return _eventArray; }
}

private EventWaitHandle _newItemEvent;
private EventWaitHandle _exitThreadEvent;
private WaitHandle[] _eventArray;
}

// The Producer class asynchronously (using a worker thread)
// adds items to the queue until there are 20 items.
public class Producer
{
public Producer(Queue q, SyncEvents e)
{
_queue = q;
_syncEvents = e;
}
public void ThreadRun()
{
int count = 0;
Random r = new Random();
while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
{
lock (((ICollection)_queue).SyncRoot)
{
while (_queue.Count < 20)
{
_queue.Enqueue(r.Next(0, 100));
_syncEvents.NewItemEvent.Set();
count++;
}
}
}
Console.WriteLine("Producer thread: produced {0} items", count);
}
private Queue _queue;
private SyncEvents _syncEvents;
}

// The Consumer class uses its own worker thread to consume items
// in the queue. The Producer class notifies the Consumer class
// of new items with the NewItemEvent.
public class Consumer
{
public Consumer(Queue q, SyncEvents e)
{
_queue = q;
_syncEvents = e;
}
public void ThreadRun()
{
int count = 0;
while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
{
lock (((ICollection)_queue).SyncRoot)
{
int item = _queue.Dequeue();
}
count++;
}
Console.WriteLine("Consumer Thread: consumed {0} items", count);
}
private Queue _queue;
private SyncEvents _syncEvents;
}

public class ThreadSyncSample
{
private static void ShowQueueContents(Queue q)
{
// Enumerating a collection is inherently not thread-safe,
// so it is imperative that the collection be locked throughout
// the enumeration to prevent the consumer and producer threads
// from modifying the contents. (This method is called by the
// primary thread only.)
lock (((ICollection)q).SyncRoot)
{
foreach (int i in q)
{
Console.Write("{0} ", i);
}
}
Console.WriteLine();
}

static void Main()
{
// Configure struct containing event information required
// for thread synchronization.
SyncEvents syncEvents = new SyncEvents();

// Generic Queue collection is used to store items to be
// produced and consumed. In this case 'int' is used.
Queue queue = new Queue();

// Create objects, one to produce items, and one to
// consume. The queue and the thread synchronization
// events are passed to both objects.
Console.WriteLine("Configuring worker threads...");
Producer producer = new Producer(queue, syncEvents);
Consumer consumer = new Consumer(queue, syncEvents);

// Create the thread objects for producer and consumer
// objects. This step does not create or launch the
// actual threads.
Thread producerThread = new Thread(producer.ThreadRun);
Thread consumerThread = new Thread(consumer.ThreadRun);

// Create and launch both threads.
Console.WriteLine("Launching producer and consumer threads...");
producerThread.Start();
consumerThread.Start();

// Let producer and consumer threads run for 10 seconds.
// Use the primary thread (the thread executing this method)
// to display the queue contents every 2.5 seconds.
for (int i = 0; i < 4; i++)
{
Thread.Sleep(2500);
ShowQueueContents(queue);
}

// Signal both consumer and producer thread to terminate.
// Both threads will respond because ExitThreadEvent is a
// manual-reset event--so it stays 'set' unless explicitly reset.
Console.WriteLine("Signaling threads to terminate...");
syncEvents.ExitThreadEvent.Set();

// Use Join to block primary thread, first until the producer thread
// terminates, then until the consumer thread terminates.
Console.WriteLine("main thread waiting for threads to finish...");
producerThread.Join();
consumerThread.Join();
}
}

Struct

//Copyright (C) Microsoft Corporation. All rights reserved.

// struct1.cs
using System;
struct SimpleStruct
{
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
xval = value;
}
}
public void DisplayX()
{
Console.WriteLine("The stored value is: {0}", xval);
}
}

class TestClass
{
public static void Main()
{
SimpleStruct ss = new SimpleStruct();
ss.X = 5;
ss.DisplayX();
}
}





// struct2.cs
using System;

class TheClass
{
public int x;
}

struct TheStruct
{
public int x;
}

class TestClass
{
public static void structtaker(TheStruct s)
{
s.x = 5;
}
public static void classtaker(TheClass c)
{
c.x = 5;
}
public static void Main()
{
TheStruct a = new TheStruct();
TheClass b = new TheClass();
a.x = 1;
b.x = 1;
structtaker(a);
classtaker(b);
Console.WriteLine("a.x = {0}", a.x);
Console.WriteLine("b.x = {0}", b.x);
}
}

Suppress Security

// SuppressSecurity.cs
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;

class NativeMethods
{
// This is a call to unmanaged code. Executing this method requires
// the UnmanagedCode security permission. Without this permission,
// an attempt to call this method will throw a SecurityException:
/* NOTE: The SuppressUnmanagedCodeSecurityAttribute disables the
check for the UnmanagedCode permission at runtime. Be Careful! */
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("msvcrt.dll")]
internal static extern int puts(string str);
[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
}

class MainClass
{
// The security permission attached to this method will remove the
// UnmanagedCode permission from the current set of permissions for
// the duration of the call to this method.
// Even though the CallUnmanagedCodeWithoutPermission method is
// called from a stack frame that already calls
// Assert for unmanaged code, you still cannot call native code.
// Because this method is attached with the Deny permission for
// unmanaged code, the permission gets overwritten. However, because
// you are using SuppressUnmanagedCodeSecurityAttribute here, you can
// still call the unmanaged methods successfully.
// The code should use other security checks to ensure that you don't
// incur a security hole.
[SecurityPermission(SecurityAction.Deny, Flags =
SecurityPermissionFlag.UnmanagedCode)]
private static void CallUnmanagedCodeWithoutPermission()
{
try
{
// The UnmanagedCode security check is disbled on the call
// below. However, the unmanaged call only displays UI. The
// security will be ensured by only allowing the unmanaged
// call if there is a UI permission.
UIPermission uiPermission =
new UIPermission(PermissionState.Unrestricted);
uiPermission.Demand();

Console.WriteLine("Attempting to call unmanaged code without UnmanagedCode permission.");
NativeMethods.puts("Hello World!");
NativeMethods._flushall();
Console.WriteLine("Called unmanaged code without UnmanagedCode permission.");
}
catch (SecurityException)
{
Console.WriteLine("Caught Security Exception attempting to call unmanaged code.");
}
}

// The security permission attached to this method will add the
// UnmanagedCode permission to the current set of permissions for the
// duration of the call to this method.
// Even though the CallUnmanagedCodeWithPermission method is called
// from a stack frame that already calls
// Deny for unmanaged code, it will not prevent you from calling
// native code. Because this method is attached with the Assert
// permission for unmanaged code, the permission gets overwritten.
// Because you are using SuppressUnmanagedCodeSecurityAttribute here,
// you can call the unmanaged methods successfully.
// The SuppressUnmanagedCodeSecurityAttribute will let you succeed,
// even if you don't have a permission.
[SecurityPermission(SecurityAction.Assert, Flags =
SecurityPermissionFlag.UnmanagedCode)]
private static void CallUnmanagedCodeWithPermission()
{
try
{
Console.WriteLine("Attempting to call unmanaged code with permission.");
NativeMethods.puts("Hello World!");
NativeMethods._flushall();
Console.WriteLine("Called unmanaged code with permission.");
}
catch (SecurityException)
{
Console.WriteLine("Caught Security Exception attempting to call unmanaged code. Whoops!");
}
}

public static void Main()
{
SecurityPermission perm = new
SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// The method itself is attached with the security permission Deny
// for unmanaged code, which will override the Assert permission in
// this stack frame. However, because you are using
// SuppressUnmanagedCodeSecurityAttribute, you can still call the
// unmanaged methods successfully.
// The code should use other security checks to ensure that you
// don't incur a security hole.
perm.Assert();
CallUnmanagedCodeWithoutPermission();

// The method itself is attached with the security permission
// Assert for unmanaged code, which will override the Deny
// permission in this stack frame. Because you are using
// SuppressUnmanagedCodeSecurityAttribute, you can call the
// unmanaged methods successfully.
// The SuppressUnmanagedCodeSecurityAttribute will let you succeed,
// even if you don't have a permission.
perm.Deny();
CallUnmanagedCodeWithPermission();
}
}

Declarative Security

// DeclarativeSecurity.cs
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;

class NativeMethods
{
// This is a call to unmanaged code. Executing this method requires
// the UnmanagedCode security permission. Without this permission,
// an attempt to call this method will throw a SecurityException:
[DllImport("msvcrt.dll")]
public static extern int puts(string str);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
}

class MainClass
{
// The security permission attached to this method will deny the
// UnmanagedCode permission from the current set of permissions for
// the duration of the call to this method:
// Even though the CallUnmanagedCodeWithoutPermission method is
// called from a stack frame that already calls
// Assert for unmanaged code, you still cannot call native code.
// Because this function is attached with the Deny permission for
// unmanaged code, the permission gets overwritten.
[SecurityPermission(SecurityAction.Deny, Flags =
SecurityPermissionFlag.UnmanagedCode)]
private static void CallUnmanagedCodeWithoutPermission()
{
try
{
Console.WriteLine("Attempting to call unmanaged code without permission.");
NativeMethods.puts("Hello World!");
NativeMethods._flushall();
Console.WriteLine("Called unmanaged code without permission. Whoops!");
}
catch (SecurityException)
{
Console.WriteLine("Caught Security Exception attempting to call unmanaged code.");
}
}

// The security permission attached to this method will force a
// runtime check for the unmanaged code permission whenever
// this method is called. If the caller does not have unmanaged code
// permission, then the call will generate a Security Exception.
// Even though the CallUnmanagedCodeWithPermission method is called
// from a stack frame that already calls
// Deny for unmanaged code, it will not prevent you from calling
// native code. Because this method is attached with the Assert
// permission for unmanaged code, the permission gets overwritten.
[SecurityPermission(SecurityAction.Assert, Flags =
SecurityPermissionFlag.UnmanagedCode)]
private static void CallUnmanagedCodeWithPermission()
{
try
{
Console.WriteLine("Attempting to call unmanaged code with permission.");
NativeMethods.puts("Hello World!");
NativeMethods._flushall();
Console.WriteLine("Called unmanaged code with permission.");
}
catch (SecurityException)
{
Console.WriteLine("Caught Security Exception attempting to call unmanaged code. Whoops!");
}
}

public static void Main()
{
SecurityPermission perm = new
SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// The method itself is attached with the security permission
// Deny for unmanaged code, which will override
// the Assert permission in this stack frame.
perm.Assert();
CallUnmanagedCodeWithoutPermission();

// The method itself is attached with the security permission
// Assert for unmanaged code, which will override the Deny
// permission in this stack frame.
perm.Deny();
CallUnmanagedCodeWithPermission();
}
}

Imperative Security

// ImperativeSecurity.cs
using System;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;

class NativeMethods
{
// This is a call to unmanaged code. Executing this method requires
// the UnmanagedCode security permission. Without this permission
// an attempt to call this method will throw a SecurityException:
[DllImport("msvcrt.dll")]
public static extern int puts(string str);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
}

class MainClass
{
private static void CallUnmanagedCodeWithoutPermission()
{
// Create a security permission object to describe the
// UnmanagedCode permission:
SecurityPermission perm =
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// Deny the UnmanagedCode from our current set of permissions.
// Any method that is called on this thread until this method
// returns will be denied access to unmanaged code.
// Even though the CallUnmanagedCodeWithPermission method
// is called from a stack frame that already
// calls Assert for unmanaged code, you still cannot call native
// code. Because you use Deny here, the permission gets
// overwritten.
perm.Deny();

try
{
Console.WriteLine("Attempting to call unmanaged code without permission.");
NativeMethods.puts("Hello World!");
NativeMethods._flushall();
Console.WriteLine("Called unmanaged code without permission. Whoops!");
}
catch (SecurityException)
{
Console.WriteLine("Caught Security Exception attempting to call unmanaged code.");
}
}

private static void CallUnmanagedCodeWithPermission()
{
// Create a security permission object to describe the
// UnmanagedCode permission:
SecurityPermission perm =
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);

// Check that you have permission to access unmanaged code.
// If you don't have permission to access unmanaged code, then
// this call will throw a SecurityException.
// Even though the CallUnmanagedCodeWithPermission method
// is called from a stack frame that already
// calls Assert for unmanaged code, you still cannot call native
// code. Because you use Deny here, the permission gets
// overwritten.
perm.Assert();

try
{
Console.WriteLine("Attempting to call unmanaged code with permission.");
NativeMethods.puts("Hello World!");
NativeMethods._flushall();
Console.WriteLine("Called unmanaged code with permission.");
}
catch (SecurityException)
{
Console.WriteLine("Caught Security Exception attempting to call unmanaged code. Whoops!");
}
}

public static void Main()
{
// The method itself will call the security permission Deny
// for unmanaged code, which will override the Assert permission
// in this stack frame.
SecurityPermission perm = new
SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
perm.Assert();
CallUnmanagedCodeWithoutPermission();

// The method itself will call the security permission Assert
// for unmanaged code, which will override the Deny permission in
// this stack frame.
perm.Deny();
CallUnmanagedCodeWithPermission();
}
}

Properties

// person.cs
using System;
class Person
{
private string myName ="N/A";
private int myAge = 0;

// Declare a Name property of type string:
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}

// Declare an Age property of type int:
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}

public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}

public static void Main()
{
Console.WriteLine("Simple Properties");

// Create a new Person object:
Person person = new Person();

// Print out the name and the age associated with the person:
Console.WriteLine("Person details - {0}", person);

// Set some values on the person object:
person.Name = "Joe";
person.Age = 99;
Console.WriteLine("Person details - {0}", person);

// Increment the Age property:
person.Age += 1;
Console.WriteLine("Person details - {0}", person);
}
}





// shapes.cs
// compile with: /target:library /reference:abstractshape.dll
public class Square : Shape
{
private int mySide;

public Square(int side, string id) : base(id)
{
mySide = side;
}

public override double Area
{
get
{
// Given the side, return the area of a square:
return mySide * mySide;
}
}
}

public class Circle : Shape
{
private int myRadius;

public Circle(int radius, string id) : base(id)
{
myRadius = radius;
}

public override double Area
{
get
{
// Given the radius, return the area of a circle:
return myRadius * myRadius * System.Math.PI;
}
}
}

public class Rectangle : Shape
{
private int myWidth;
private int myHeight;

public Rectangle(int width, int height, string id) : base(id)
{
myWidth = width;
myHeight = height;
}

public override double Area
{
get
{
// Given the width and height, return the area of a rectangle:
return myWidth * myHeight;
}
}
}





// shapetest.cs
// compile with: /reference:abstractshape.dll;shapes.dll
public class TestClass
{
public static void Main()
{
Shape[] shapes =
{
new Square(5, "Square #1"),
new Circle(3, "Circle #1"),
new Rectangle( 4, 5, "Rectangle #1")
};

System.Console.WriteLine("Shapes Collection");
foreach(Shape s in shapes)
{
System.Console.WriteLine(s);
}

}
}

Operator Overloading

// complex.cs
using System;

public struct Complex
{
public int real;
public int imaginary;

public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}

// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
// Override the ToString method to display an complex number in the suitable format:
public override string ToString()
{
return(String.Format("{0} + {1}i", real, imaginary));
}

public static void Main()
{
Complex num1 = new Complex(2,3);
Complex num2 = new Complex(3,4);

// Add two Complex objects (num1 and num2) through the
// overloaded plus operator:
Complex sum = num1 + num2;

// Print the numbers and the sum using the overriden ToString method:
Console.WriteLine("First complex number: {0}",num1);
Console.WriteLine("Second complex number: {0}",num2);
Console.WriteLine("The sum of the two numbers: {0}",sum);

}
}





// dbbool.cs
using System;

public struct DBBool
{
// The three possible DBBool values:
public static readonly DBBool dbNull = new DBBool(0);
public static readonly DBBool dbFalse = new DBBool(-1);
public static readonly DBBool dbTrue = new DBBool(1);
// Private field that stores -1, 0, 1 for dbFalse, dbNull, dbTrue:
int value;

// Private constructor. The value parameter must be -1, 0, or 1:
DBBool(int value)
{
this.value = value;
}

// Implicit conversion from bool to DBBool. Maps true to
// DBBool.dbTrue and false to DBBool.dbFalse:
public static implicit operator DBBool(bool x)
{
return x? dbTrue: dbFalse;
}

// Explicit conversion from DBBool to bool. Throws an
// exception if the given DBBool is dbNull, otherwise returns
// true or false:
public static explicit operator bool(DBBool x)
{
if (x.value == 0) throw new InvalidOperationException();
return x.value > 0;
}

// Equality operator. Returns dbNull if either operand is dbNull,
// otherwise returns dbTrue or dbFalse:
public static DBBool operator ==(DBBool x, DBBool y)
{
if (x.value == 0 || y.value == 0) return dbNull;
return x.value == y.value? dbTrue: dbFalse;
}

// Inequality operator. Returns dbNull if either operand is
// dbNull, otherwise returns dbTrue or dbFalse:
public static DBBool operator !=(DBBool x, DBBool y)
{
if (x.value == 0 || y.value == 0) return dbNull;
return x.value != y.value? dbTrue: dbFalse;
}

// Logical negation operator. Returns dbTrue if the operand is
// dbFalse, dbNull if the operand is dbNull, or dbFalse if the
// operand is dbTrue:
public static DBBool operator !(DBBool x)
{
return new DBBool(-x.value);
}

// Logical AND operator. Returns dbFalse if either operand is
// dbFalse, dbNull if either operand is dbNull, otherwise dbTrue:
public static DBBool operator &(DBBool x, DBBool y)
{
return new DBBool(x.value < y.value? x.value: y.value);
}

// Logical OR operator. Returns dbTrue if either operand is
// dbTrue, dbNull if either operand is dbNull, otherwise dbFalse:
public static DBBool operator |(DBBool x, DBBool y)
{
return new DBBool(x.value > y.value? x.value: y.value);
}

// Definitely true operator. Returns true if the operand is
// dbTrue, false otherwise:
public static bool operator true(DBBool x)
{
return x.value > 0;
}

// Definitely false operator. Returns true if the operand is
// dbFalse, false otherwise:
public static bool operator false(DBBool x)
{
return x.value < 0;
}

// Overload the conversion from DBBool to string:
public static implicit operator string(DBBool x)
{
return x.value > 0 ? "dbTrue"
: x.value < 0 ? "dbFalse"
: "dbNull";
}

// Override the Object.Equals(object o) method:
public override bool Equals(object o)
{
try
{
return (bool) (this == (DBBool) o);
}
catch
{
return false;
}
}

// Override the Object.GetHashCode() method:
public override int GetHashCode()
{
return value;
}

// Override the ToString method to convert DBBool to a string:
public override string ToString()
{
switch (value)
{
case -1:
return "DBBool.False";
case 0:
return "DBBool.Null";
case 1:
return "DBBool.True";
default:
throw new InvalidOperationException();
}
}
}

class Test
{
static void Main()
{
DBBool a, b;
a = DBBool.dbTrue;
b = DBBool.dbNull;

Console.WriteLine( "!{0} = {1}", a, !a);
Console.WriteLine( "!{0} = {1}", b, !b);
Console.WriteLine( "{0} & {1} = {2}", a, b, a & b);
Console.WriteLine( "{0} | {1} = {2}", a, b, a | b);
// Invoke the true operator to determine the Boolean
// value of the DBBool variable:
if (b)
Console.WriteLine("b is definitely true");
else
Console.WriteLine("b is not definitely true");
}
}

OleDb

// OleDbSample.cs
// To build this sample from the command line, use the command:
// csc oledbsample.cs

using System;
using System.Data;
using System.Data.OleDb;
using System.Xml.Serialization;

public class MainClass
{
public static void Main ()
{
// Set Access connection and select strings.
// The path to BugTypes.MDB must be changed if you build the sample
// from the command line:
#if USINGPROJECTSYSTEM
string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\..\\BugTypes.MDB";
#else
string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BugTypes.MDB";
#endif
string strAccessSelect = "SELECT * FROM Categories";

// Create the dataset and add the Categories table to it:
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;
try
{
myAccessConn = new OleDbConnection(strAccessConn);
}
catch(Exception ex)
{
Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
return;
}

try
{

OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect,myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

myAccessConn.Open();
myDataAdapter.Fill(myDataSet,"Categories");

}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
myAccessConn.Close();
}

// A dataset can contain multiple tables, so let's get them all
// into an array:
DataTableCollection dta = myDataSet.Tables;
foreach (DataTable dt in dta)
{
Console.WriteLine("Found data table {0}", dt.TableName);
}

// The next two lines show two different ways you can get the
// count of tables in a dataset:
Console.WriteLine("{0} tables in data set", myDataSet.Tables.Count);
Console.WriteLine("{0} tables in data set", dta.Count);
// The next several lines show how to get information on a
// specific table by name from the dataset:
Console.WriteLine("{0} rows in Categories table", myDataSet.Tables["Categories"].Rows.Count);
// The column info is automatically fetched from the database, so
// we can read it here:
Console.WriteLine("{0} columns in Categories table", myDataSet.Tables["Categories"].Columns.Count);
DataColumnCollection drc = myDataSet.Tables["Categories"].Columns;
int i = 0;
foreach (DataColumn dc in drc)
{
// Print the column subscript, then the column's name and its
// data type:
Console.WriteLine("Column name[{0}] is {1}, of type {2}",i++ , dc.ColumnName, dc.DataType);
}
DataRowCollection dra = myDataSet.Tables["Categories"].Rows;
foreach (DataRow dr in dra)
{
// Print the CategoryID as a subscript, then the CategoryName:
Console.WriteLine("CategoryName[{0}] is {1}", dr[0], dr[1]);
}

}
}

Nullable Basics, Boxing, Nullable Operator

using System;

class NullableBasics
{
static void DisplayValue(int? num)
{
if (num.HasValue == true)
{
Console.WriteLine("num = " + num);
}
else
{
Console.WriteLine("num = null");
}

// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
Console.WriteLine("value = {0}", num.Value);
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
}

static void Main()
{
DisplayValue(1);
DisplayValue(null);
}
}





using System;

class NullableBoxing
{
static void Main()
{
int? a;
object oa;

// Assigns a to Nullable (value = default(int), hasValue = false).
a = null;

// Assigns oa to null (because x==null), not boxed "int?".
oa = a;

Console.WriteLine("Testing 'a' and 'boxed a' for null...");
// Nullable variables can be compared to null.
if (a == null)
{
Console.WriteLine(" a == null");
}

// Boxed nullable variables can be compared to null
// because boxing a nullable where HasValue==false
// sets the reference to null.
if (oa == null)
{
Console.WriteLine(" oa == null");
}

Console.WriteLine("Unboxing a nullable type...");
int? b = 10;
object ob = b;

// Boxed nullable types can be unboxed
int? unBoxedB = (int?)ob;
Console.WriteLine(" b={0}, unBoxedB={0}", b, unBoxedB);

// Unboxing a nullable type set to null works if
// unboxed into a nullable type.
int? unBoxedA = (int?)oa;
if (oa == null && unBoxedA == null)
{
Console.WriteLine(" a and unBoxedA are null");
}

Console.WriteLine("Attempting to unbox into non-nullable type...");
// Unboxing a nullable type set to null throws an
// exception if unboxed into a non-nullable type.
try
{
int unBoxedA2 = (int)oa;
}
catch (Exception e)
{
Console.WriteLine(" {0}", e.Message);
}
}

}





using System;

class NullableOperator
{
static int? GetNullableInt()
{
return null;
}

static string GetStringValue()
{
return null;
}

static void Main()
{
// ?? operator example.
int? x = null;

// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
Console.WriteLine("y == " + y);

// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);
Console.WriteLine("i == " + i);

// ?? also works with reference types.
string s = GetStringValue();
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine("s = {0}", s ?? "null");


Console.ReadLine();
}
}

Indexer

// indexer.cs
// arguments: indexer.txt
using System;
using System.IO;

// Class to provide access to a large file
// as if it were a byte array.
public class FileByteArray
{
Stream stream; // Holds the underlying stream
// used to access the file.
// Create a new FileByteArray encapsulating a particular file.
public FileByteArray(string fileName)
{
stream = new FileStream(fileName, FileMode.Open);
}

// Close the stream. This should be the last thing done
// when you are finished.
public void Close()
{
stream.Close();
stream = null;
}

// Indexer to provide read/write access to the file.
public byte this[long index] // long is a 64-bit integer
{
// Read one byte at offset index and return it.
get
{
byte[] buffer = new byte[1];
stream.Seek(index, SeekOrigin.Begin);
stream.Read(buffer, 0, 1);
return buffer[0];
}
// Write one byte at offset index and return it.
set
{
byte[] buffer = new byte[1] {value};
stream.Seek(index, SeekOrigin.Begin);
stream.Write(buffer, 0, 1);
}
}

// Get the total length of the file.
public long Length
{
get
{
return stream.Seek(0, SeekOrigin.End);
}
}
}

// Demonstrate the FileByteArray class.
// Reverses the bytes in a file.
public class Reverse
{
public static void Main(String[] args)
{
// Check for arguments.
if (args.Length != 1)
{
Console.WriteLine("Usage : Indexer ");
return;
}

// Check for file existence
if (!System.IO.File.Exists(args[0]))
{
Console.WriteLine("File " + args[0] + " not found.");
return;
}

FileByteArray file = new FileByteArray(args[0]);
long len = file.Length;

// Swap bytes in the file to reverse it.
for (long i = 0; i < len / 2; ++i)
{
byte t;

// Note that indexing the "file" variable invokes the
// indexer on the FileByteStream class, which reads
// and writes the bytes in the file.
t = file[i];
file[i] = file[len - i - 1];
file[len - i - 1] = t;
}

file.Close();
}
}

Indexed Property

using System;

public class Document
{
// Type allowing the document to be viewed like an array of words:
public class WordCollection
{
readonly Document document; // The containing document

internal WordCollection(Document d)
{
document = d;
}

// Helper function -- search character array "text", starting at
// character "begin", for word number "wordCount." Returns false
// if there are less than wordCount words. Sets "start" and
// length" to the position and length of the word within text:
private bool GetWord(char[] text, int begin, int wordCount,
out int start, out int length)
{
int end = text.Length;
int count = 0;
int inWord = -1;
start = length = 0;

for (int i = begin; i <= end; ++i)
{
bool isLetter = i < end && Char.IsLetterOrDigit(text[i]);

if (inWord >= 0)
{
if (!isLetter)
{
if (count++ == wordCount)
{
start = inWord;
length = i - inWord;
return true;
}
inWord = -1;
}
}
else
{
if (isLetter)
inWord = i;
}
}
return false;
}

// Indexer to get and set words of the containing document:
public string this[int index]
{
get
{
int start, length;
if (GetWord(document.TextArray, 0, index, out start,
out length))
return new string(document.TextArray, start, length);
else
throw new IndexOutOfRangeException();
}
set
{
int start, length;
if (GetWord(document.TextArray, 0, index, out start,
out length))
{
// Replace the word at start/length with the
// string "value":
if (length == value.Length)
{
Array.Copy(value.ToCharArray(), 0,
document.TextArray, start, length);
}
else
{
char[] newText =
new char[document.TextArray.Length +
value.Length - length];
Array.Copy(document.TextArray, 0, newText,
0, start);
Array.Copy(value.ToCharArray(), 0, newText,
start, value.Length);
Array.Copy(document.TextArray, start + length,
newText, start + value.Length,
document.TextArray.Length - start
- length);
document.TextArray = newText;
}
}
else
throw new IndexOutOfRangeException();
}
}

// Get the count of words in the containing document:
public int Count
{
get
{
int count = 0, start = 0, length = 0;
while (GetWord(document.TextArray, start + length, 0,
out start, out length))
++count;
return count;
}
}
}

// Type allowing the document to be viewed like an "array"
// of characters:
public class CharacterCollection
{
readonly Document document; // The containing document

internal CharacterCollection(Document d)
{
document = d;
}

// Indexer to get and set characters in the containing document:
public char this[int index]
{
get
{
return document.TextArray[index];
}
set
{
document.TextArray[index] = value;
}
}

// Get the count of characters in the containing document:
public int Count
{
get
{
return document.TextArray.Length;
}
}
}

// Because the types of the fields have indexers,
// these fields appear as "indexed properties":
public WordCollection Words;
public CharacterCollection Characters;

private char[] TextArray; // The text of the document.

public Document(string initialText)
{
TextArray = initialText.ToCharArray();
Words = new WordCollection(this);
Characters = new CharacterCollection(this);
}

public string Text
{
get
{
return new string(TextArray);
}
}
}

class Test
{
static void Main()
{
Document d = new Document(
"peter piper picked a peck of pickled peppers. How many pickled peppers did peter piper pick?"
);

// Change word "peter" to "penelope":
for (int i = 0; i < d.Words.Count; ++i)
{
if (d.Words[i] == "peter")
d.Words[i] = "penelope";
}

// Change character "p" to "P"
for (int i = 0; i < d.Characters.Count; ++i)
{
if (d.Characters[i] == 'p')
d.Characters[i] = 'P';
}

Console.WriteLine(d.Text);
}
}

Generic

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Generics_CSharp
{
//Type parameter T in angle brackets.
public class MyList : IEnumerable
{
protected Node head;
protected Node current = null;

// Nested type is also generic on T
protected class Node
{
public Node next;
//T as private member datatype.
private T data;
//T used in non-generic constructor.
public Node(T t)
{
next = null;
data = t;
}
public Node Next
{
get { return next; }
set { next = value; }
}
//T as return type of property.
public T Data
{
get { return data; }
set { data = value; }
}
}

public MyList()
{
head = null;
}

//T as method parameter type.
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}

// Implement GetEnumerator to return IEnumerator to enable
// foreach iteration of our list. Note that in C# 2.0
// you are not required to implement Current and MoveNext.
// The compiler will create a class that implements IEnumerator.
public IEnumerator GetEnumerator()
{
Node current = head;

while (current != null)
{
yield return current.Data;
current = current.Next;
}
}

// We must implement this method because
// IEnumerable inherits IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}


public class SortedList : MyList where T : IComparable
{
// A simple, unoptimized sort algorithm that
// orders list elements from lowest to highest:
public void BubbleSort()
{
if (null == head || null == head.Next)
return;

bool swapped;
do
{
Node previous = null;
Node current = head;
swapped = false;

while (current.next != null)
{
// Because we need to call this method, the SortedList
// class is constrained on IEnumerable
if (current.Data.CompareTo(current.next.Data) > 0)
{
Node tmp = current.next;
current.next = current.next.next;
tmp.next = current;

if (previous == null)
{
head = tmp;
}
else
{
previous.next = tmp;
}
previous = tmp;
swapped = true;
}

else
{
previous = current;
current = current.next;
}

}// end while
} while (swapped);
}
}

// A simple class that implements IComparable
// using itself as the type argument. This is a
// common design pattern in objects that are
// stored in generic lists.
public class Person : IComparable
{
string name;
int age;

public Person(string s, int i)
{
name = s;
age = i;
}

// This will cause list elements
// to be sorted on age values.
public int CompareTo(Person p)
{
return age - p.age;
}

public override string ToString()
{
return name + ":" + age;
}

// Must implement Equals.
public bool Equals(Person p)
{
return (this.age == p.age);
}
}

class Generics
{
static void Main(string[] args)
{
//Declare and instantiate a new generic SortedList class.
//Person is the type argument.
SortedList list = new SortedList();

//Create name and age values to initialize Person objects.
string[] names = new string[] { "Franscoise", "Bill", "Li", "Sandra", "Gunnar", "Alok", "Hiroyuki", "Maria", "Alessandro", "Raul" };
int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };

//Populate the list.
for (int x = 0; x < names.Length; x++)
{
list.AddHead(new Person(names[x], ages[x]));
}

Console.WriteLine("Unsorted List:");
//Print out unsorted list.
foreach (Person p in list)
{
Console.WriteLine(p.ToString());
}

//Sort the list.
list.BubbleSort();

Console.WriteLine(String.Format("{0}Sorted List:", Environment.NewLine));
//Print out sorted list.
foreach (Person p in list)
{
Console.WriteLine(p.ToString());
}

Console.WriteLine("Done");
}
}

}

Explicit Interface

// explicit1.cs
interface IDimensions
{
float Length();
float Width();
}

class Box : IDimensions
{
float lengthInches;
float widthInches;

public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit interface member implementation:
float IDimensions.Length()
{
return lengthInches;
}
// Explicit interface member implementation:
float IDimensions.Width()
{
return widthInches;
}

public static void Main()
{
// Declare a class instance "myBox":
Box myBox = new Box(30.0f, 20.0f);
// Declare an interface instance "myDimensions":
IDimensions myDimensions = (IDimensions) myBox;
// Print out the dimensions of the box:
/* The following commented lines would produce compilation
errors because they try to access an explicitly implemented
interface member from a class instance: */
//System.Console.WriteLine("Length: {0}", myBox.Length());
//System.Console.WriteLine("Width: {0}", myBox.Width());
/* Print out the dimensions of the box by calling the methods
from an instance of the interface: */
System.Console.WriteLine("Length: {0}", myDimensions.Length());
System.Console.WriteLine("Width: {0}", myDimensions.Width());
}
}





// explicit2.cs
// Declare the English units interface:
interface IEnglishDimensions
{
float Length();
float Width();
}
// Declare the metric units interface:
interface IMetricDimensions
{
float Length();
float Width();
}
// Declare the "Box" class that implements the two interfaces:
// IEnglishDimensions and IMetricDimensions:
class Box : IEnglishDimensions, IMetricDimensions
{
float lengthInches;
float widthInches;
public Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicitly implement the members of IEnglishDimensions:
float IEnglishDimensions.Length()
{
return lengthInches;
}
float IEnglishDimensions.Width()
{
return widthInches;
}
// Explicitly implement the members of IMetricDimensions:
float IMetricDimensions.Length()
{
return lengthInches * 2.54f;
}
float IMetricDimensions.Width()
{
return widthInches * 2.54f;
}
public static void Main()
{
// Declare a class instance "myBox":
Box myBox = new Box(30.0f, 20.0f);
// Declare an instance of the English units interface:
IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
// Declare an instance of the metric units interface:
IMetricDimensions mDimensions = (IMetricDimensions) myBox;
// Print dimensions in English units:
System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
// Print dimensions in metric units:
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
}
}

Events

using System;
namespace MyCollections
{
using System.Collections;

// A delegate type for hooking up change notifications.
public delegate void ChangedEventHandler(object sender, EventArgs e);

// A class that works just like ArrayList, but sends event
// notifications whenever the list changes.
public class ListWithChangedEvent: ArrayList
{
// An event that clients can use to be notified whenever the
// elements of the list change.
public event ChangedEventHandler Changed;

// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}

// Override some of the methods that can change the list;
// invoke event after each
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(EventArgs.Empty);
return i;
}

public override void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}

public override object this[int index]
{
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
}
}

namespace TestEvents
{
using MyCollections;

class EventListener
{
private ListWithChangedEvent List;

public EventListener(ListWithChangedEvent list)
{
List = list;
// Add "ListChanged" to the Changed event on "List".
List.Changed += new ChangedEventHandler(ListChanged);
}

// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}

public void Detach()
{
// Detach the event and delete the list
List.Changed -= new ChangedEventHandler(ListChanged);
List = null;
}
}

class Test
{
// Test the ListWithChangedEvent class.
public static void Main()
{
// Create a new list.
ListWithChangedEvent list = new ListWithChangedEvent();

// Create a class that listens to the list's change event.
EventListener listener = new EventListener(list);

// Add and remove items from the list.
list.Add("item 1");
list.Clear();
listener.Detach();
}
}
}

Delegates

// compose.cs
using System;

delegate void MyDelegate(string s);

class MyClass
{
public static void Hello(string s)
{
Console.WriteLine(" Hello, {0}!", s);
}

public static void Goodbye(string s)
{
Console.WriteLine(" Goodbye, {0}!", s);
}

public static void Main()
{
MyDelegate a, b, c, d;

// Create the delegate object a that references
// the method Hello:
a = new MyDelegate(Hello);
// Create the delegate object b that references
// the method Goodbye:
b = new MyDelegate(Goodbye);
// The two delegates, a and b, are composed to form c,
// which calls both methods in order:
c = a + b;
// Remove a from the composed delegate, leaving d,
// which calls only the method Goodbye:
d = c - a;

Console.WriteLine("Invoking delegate a:");
a("A");
Console.WriteLine("Invoking delegate b:");
b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
Console.WriteLine("Invoking delegate d:");
d("D");
}
}

Delegates

// bookstore.cs
using System;

// A set of classes for handling a bookstore:
namespace Bookstore
{
using System.Collections;

// Describes a book in the book list:
public struct Book
{
public string Title; // Title of the book.
public string Author; // Author of the book.
public decimal Price; // Price of the book.
public bool Paperback; // Is it paperback?

public Book(string title, string author, decimal price, bool paperBack)
{
Title = title;
Author = author;
Price = price;
Paperback = paperBack;
}
}

// Declare a delegate type for processing a book:
public delegate void ProcessBookDelegate(Book book);

// Maintains a book database.
public class BookDB
{
// List of all books in the database:
ArrayList list = new ArrayList();

// Add a book to the database:
public void AddBook(string title, string author, decimal price, bool paperBack)
{
list.Add(new Book(title, author, price, paperBack));
}

// Call a passed-in delegate on each paperback book to process it:
public void ProcessPaperbackBooks(ProcessBookDelegate processBook)
{
foreach (Book b in list)
{
if (b.Paperback)
// Calling the delegate:
processBook(b);
}
}
}
}

// Using the Bookstore classes:
namespace BookTestClient
{
using Bookstore;

// Class to total and average prices of books:
class PriceTotaller
{
int countBooks = 0;
decimal priceBooks = 0.0m;

internal void AddBookToTotal(Book book)
{
countBooks += 1;
priceBooks += book.Price;
}

internal decimal AveragePrice()
{
return priceBooks / countBooks;
}
}

// Class to test the book database:
class Test
{
// Print the title of the book.
static void PrintTitle(Book b)
{
Console.WriteLine(" {0}", b.Title);
}

// Execution starts here.
static void Main()
{
BookDB bookDB = new BookDB();

// Initialize the database with some books:
AddBooks(bookDB);

// Print all the titles of paperbacks:
Console.WriteLine("Paperback Book Titles:");
// Create a new delegate object associated with the static
// method Test.PrintTitle:
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));

// Get the average price of a paperback by using
// a PriceTotaller object:
PriceTotaller totaller = new PriceTotaller();
// Create a new delegate object associated with the nonstatic
// method AddBookToTotal on the object totaller:
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));
Console.WriteLine("Average Paperback Book Price: ${0:#.##}",
totaller.AveragePrice());
}

// Initialize the book database with some test books:
static void AddBooks(BookDB bookDB)
{
bookDB.AddBook("The C Programming Language",
"Brian W. Kernighan and Dennis M. Ritchie", 19.95m, true);
bookDB.AddBook("The Unicode Standard 2.0",
"The Unicode Consortium", 39.95m, true);
bookDB.AddBook("The MS-DOS Encyclopedia",
"Ray Duncan", 129.95m, false);
bookDB.AddBook("Dogbert's Clues for the Clueless",
"Scott Adams", 12.00m, true);
}
}
}

Conditional Method

// CondMethod.cs
// compile with: /target:library /d:DEBUG
using System;
using System.Diagnostics;
namespace TraceFunctions
{
public class Trace
{
[Conditional("DEBUG")]
public static void Message(string traceMessage)
{
Console.WriteLine("[TRACE] - " + traceMessage);
}
}
}





// TraceTest.cs
// compile with: /reference:CondMethod.dll
// arguments: A B C
using System;
using TraceFunctions;

public class TraceClient
{
public static void Main(string[] args)
{
Trace.Message("Main Starting");

if (args.Length == 0)
{
Console.WriteLine("No arguments have been passed");
}
else
{
for( int i=0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] is [{1}]",i,args[i]);
}
}

Trace.Message("Main Ending");
}
}

Collection Classes

using System;
using System.Collections;

public class Tokens: IEnumerable
{
private string[] elements;

Tokens(string source, char[] delimiters)
{
elements = source.Split(delimiters);
}

// IEnumerable Interface Implementation:

public TokenEnumerator GetEnumerator() // non-IEnumerable version
{
return new TokenEnumerator(this);
}

IEnumerator IEnumerable.GetEnumerator() // IEnumerable version
{
return (IEnumerator) new TokenEnumerator(this);
}

// Inner class implements IEnumerator interface:

public class TokenEnumerator: IEnumerator
{
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t)
{
this.t = t;
}

public bool MoveNext()
{
if (position < t.elements.Length - 1)
{
position++;
return true;
}
else
{
return false;
}
}

public void Reset()
{
position = -1;
}

public string Current // non-IEnumerator version: type-safe
{
get
{
return t.elements[position];
}
}

object IEnumerator.Current // IEnumerator version: returns object
{
get
{
return t.elements[position];
}
}
}

// Test Tokens, TokenEnumerator

static void Main()
{
Tokens f = new Tokens("This is a well-done program.",
new char [] {' ','-'});
foreach (string item in f) // try changing string to int
{
Console.WriteLine(item);
}
}
}

Collection Classes

using System;
using System.Collections;

// Declare the Tokens class:
public class Tokens : IEnumerable
{
private string[] elements;

Tokens(string source, char[] delimiters)
{
// Parse the string into tokens:
elements = source.Split(delimiters);
}

// IEnumerable Interface Implementation:
// Declaration of the GetEnumerator() method
// required by IEnumerable
public IEnumerator GetEnumerator()
{
return new TokenEnumerator(this);
}

// Inner class implements IEnumerator interface:
private class TokenEnumerator : IEnumerator
{
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t)
{
this.t = t;
}

// Declare the MoveNext method required by IEnumerator:
public bool MoveNext()
{
if (position < t.elements.Length - 1)
{
position++;
return true;
}
else
{
return false;
}
}

// Declare the Reset method required by IEnumerator:
public void Reset()
{
position = -1;
}

// Declare the Current property required by IEnumerator:
public object Current
{
get
{
return t.elements[position];
}
}
}

// Test Tokens, TokenEnumerator

static void Main()
{
// Testing Tokens by breaking the string into tokens:
Tokens f = new Tokens("This is a well-done program.",
new char[] {' ','-'});
foreach (string item in f)
{
Console.WriteLine(item);
}

Console.ReadLine();
}
}

Attributes

using System;
using System.Reflection;
using System.Collections;

// The IsTested class is a user-defined custom attribute class.
// It can be applied to any declaration including
// - types (struct, class, enum, delegate)
// - members (methods, fields, events, properties, indexers)
// It is used with no arguments.
public class IsTestedAttribute : Attribute
{
public override string ToString()
{
return "Is Tested";
}
}

// The AuthorAttribute class is a user-defined attribute class.
// It can be applied to classes and struct declarations only.
// It takes one unnamed string argument (the author's name).
// It has one optional named argument Version, which is of type int.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class AuthorAttribute : Attribute
{
// This constructor specifies the unnamed arguments to the attribute class.
public AuthorAttribute(string name)
{
this.name = name;
this.version = 0;
}

// This property is readonly (it has no set accessor)
// so it cannot be used as a named argument to this attribute.
public string Name
{
get
{
return name;
}
}

// This property is read-write (it has a set accessor)
// so it can be used as a named argument when using this
// class as an attribute class.
public int Version
{
get
{
return version;
}
set
{
version = value;
}
}

public override string ToString()
{
string value = "Author : " + Name;
if (version != 0)
{
value += " Version : " + Version.ToString();
}
return value;
}

private string name;
private int version;
}

// Here you attach the AuthorAttribute user-defined custom attribute to
// the Account class. The unnamed string argument is passed to the
// AuthorAttribute class's constructor when creating the attributes.
[Author("Joe Programmer")]
class Account
{
// Attach the IsTestedAttribute custom attribute to this method.
[IsTested]
public void AddOrder(Order orderToAdd)
{
orders.Add(orderToAdd);
}

private ArrayList orders = new ArrayList();
}

// Attach the AuthorAttribute and IsTestedAttribute custom attributes
// to this class.
// Note the use of the 'Version' named argument to the AuthorAttribute.
[Author("Jane Programmer", Version = 2), IsTested()]
class Order
{
// add stuff here ...
}

class MainClass
{
private static bool IsMemberTested(MemberInfo member)
{
foreach (object attribute in member.GetCustomAttributes(true))
{
if (attribute is IsTestedAttribute)
{
return true;
}
}
return false;
}

private static void DumpAttributes(MemberInfo member)
{
Console.WriteLine("Attributes for : " + member.Name);
foreach (object attribute in member.GetCustomAttributes(true))
{
Console.WriteLine(attribute);
}
}

public static void Main()
{
// display attributes for Account class
DumpAttributes(typeof(Account));

// display list of tested members
foreach (MethodInfo method in (typeof(Account)).GetMethods())
{
if (IsMemberTested(method))
{
Console.WriteLine("Member {0} is tested!", method.Name);
}
else
{
Console.WriteLine("Member {0} is NOT tested!", method.Name);
}
}
Console.WriteLine();

// display attributes for Order class
DumpAttributes(typeof(Order));

// display attributes for methods on the Order class
foreach (MethodInfo method in (typeof(Order)).GetMethods())
{
if (IsMemberTested(method))
{
Console.WriteLine("Member {0} is tested!", method.Name);
}
else
{
Console.WriteLine("Member {0} is NOT tested!", method.Name);
}
}
Console.WriteLine();
}
}

Arrays

using System;
class DeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];

// Multidimensional array
string[,] names = new string[5,4];

// Array-of-arrays (jagged array)
byte[][] scores = new byte[5][];

// Create the jagged array
for (int i = 0; i < scores.Length; i++)
{
scores[i] = new byte[i+3];
}

// Print length of each row
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
}
}
}

Anonymous Delegate

using System;
using System.Collections.Generic;
using System.Text;

namespace AnonymousDelegate
{

// Define the delegate method.
delegate decimal CalculateBonus(decimal sales);

// Define an Employee type.
class Employee
{
public string name;
public decimal sales;
public decimal bonus;
public CalculateBonus calculation_algorithm;
}

class Program
{

// This class will define two delegates that perform a calculation.
// The first will be a named method, the second an anonymous delegate.

// This is the named method.
// It defines one possible implementation of the Bonus Calculation algorithm.

static decimal CalculateStandardBonus(decimal sales)
{
return sales / 10;
}

static void Main(string[] args)
{

// A value used in the calculation of the bonus.
// Note: This local variable will become a "captured outer variable".
decimal multiplier = 2;

// This delegate is defined as a named method.
CalculateBonus standard_bonus = new CalculateBonus (CalculateStandardBonus);

// This delegate is anonymous - there is no named method.
// It defines an alternative bonus calculation algorithm.
CalculateBonus enhanced_bonus = delegate(decimal sales) { return multiplier * sales / 10; };

// Declare some Employee objects.
Employee[] staff = new Employee[5];

// Populate the array of Employees.
for (int i = 0; i < 5; i++)
staff[i] = new Employee();

// Assign initial values to Employees.
staff[0].name = "Mr Apple";
staff[0].sales = 100;
staff[0].calculation_algorithm = standard_bonus;

staff[1].name = "Ms Banana";
staff[1].sales = 200;
staff[1].calculation_algorithm = standard_bonus;

staff[2].name = "Mr Cherry";
staff[2].sales = 300;
staff[2].calculation_algorithm = standard_bonus;

staff[3].name = "Mr Date";
staff[3].sales = 100;
staff[3].calculation_algorithm = enhanced_bonus;

staff[4].name = "Ms Elderberry";
staff[4].sales = 250;
staff[4].calculation_algorithm = enhanced_bonus;

// Calculate bonus for all Employees
foreach (Employee person in staff)
PerformBonusCalculation(person);

// Display the details of all Employees
foreach (Employee person in staff)
DisplayPersonDetails(person);


}

public static void PerformBonusCalculation(Employee person)
{

// This method uses the delegate stored in the person object
// to perform the calculation.
// Note: This method knows about the multiplier local variable, even though
// that variable is outside the scope of this method.
// The multipler varaible is a "captured outer variable".
person.bonus = person.calculation_algorithm(person.sales);
}

public static void DisplayPersonDetails(Employee person)
{
Console.WriteLine(person.name);
Console.WriteLine(person.bonus);
Console.WriteLine("---------------");
Console.ReadLine();
}
}
}