CSharp

Introduction
C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create traditional Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more. Visual C# 2008 provides an advanced code editor, convenient user interface designers, integrated debugger, and many other tools to make it easier to develop applications based on version 3.0 of the C# language and version 3.5 of the .NET Framework.

Links

 * Visual C# Develop Center
 * Project Mono (C# for Unix systems

The “Line Feed” or “New Line” constant
You can use the command or declare a public static variable like this:

public static string CRLF = Environment.NewLine;

Application Path
One possibility is to get the CodeBase of the executing assembly:

Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly.GetName.CodeBase); String curPath = System.IO.Path.GetDirectoryName(uri.LocalPath);

Other possibility is to use the following commands below:

/// /// Returns the application Path. /// /// The application path. public static String ApplicationPath { 	get { 			try { 				// .NET Compact Framework // String curPath = System.IO.Path.GetDirectoryName( 				//	   System.Reflection.Assembly.GetExecutingAssembly.GetName.CodeBase ); // 				// OR  				// // String curPath = System.IO.Path.GetDirectoryName( 				//	   System.Reflection.Assembly.GetExecutingAssembly.GetName.FullyQualifiedName ); // windows application String curPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath); return curPath; } 			catch (Exception ex) { 				MessageError (ex); } 			return ""; } } // getApplicationPath

Opening a Database
There are other properties that could be very helpful. Try to execute the following code and find out yourself :

try { 	moCon = new OleDbConnection(ConnectionString); moCon.Open; } catch (OleDbException e) { Sky4Main.MessageError("The database could not be opened.\nError:" + e.ToString); return false; }

The problem with location and country configuration
You can see the actual culture using the following command:

Console.WriteLine("Current culture before : " + System.Threading.Thread.CurrentThread.CurrentCulture.NativeName);

Then you can change anytime the culture of the current thread to another culture:

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");

Filling a combobox with database values
/// /// Fills a combobox with database values. /// /// The combobox to be filled. /// The source table used to fill the combobox. /// String that specifies the property of the data source whose contents you want to display. /// String that specifies the property of the data source from which to draw the value. public static void FillCombobox (System.Windows.Forms.ComboBox pCombobox, 	string TableName,  	string DisplayMember,  	string ValueMember) { 	DataSet dataset = new DataSet; OleDbCommand command = Sky4DB.Connection.CreateCommand; command.CommandText="SELECT " + ValueMember + ", " + DisplayMember + " FROM " + TableName; OleDbDataAdapter adapter = new OleDbDataAdapter(command); adapter.Fill(dataset, TableName); pCombobox.DataSource = dataset.Tables[TableName]; pCombobox.DisplayMember = DisplayMember; pCombobox.ValueMember = ValueMember; }

Setting focus to a control
MyControl.Focus;

To set the focus to a TabPage object, you need to call the method or. Example:

tabControl1.SelectedTab = tabPageData;

Conditional operator
Here is an example how to use the conditional operator ?.

((ListBox)mControls[i]).BackColor = bEnabled ? Color.White : mDisabledColor;

Copying arrays to arrays
Use the method like this:

ArrayList PKList = new ArrayList; for (int i=0; i < mGridColumnTypes.Count; i++) { 	// insert the field into the list PKList.Add (mDataSet.Tables[msTableName].Columns[i]); } 	DataColumn[] dc = new DataColumn[PKList.Count]; PKList.CopyTo(dc); }

Changing the combobox height
See below, you have to change the property DrawMode to OwnerDrawFixed or OwnerDrawVariable. Then change the property ItemHeight as you want.



Characters Escape
Most of the important regular expression language operators are unescaped single characters. The escape character \ (a single backslash) signals to the regular expression parser that the character following the backslash is not an operator. For example, the parser treats an asterisk (*) as a repeating quantifier and a backslash followed by an asterisk (\*) as the Unicode character 002A.

The character escapes listed in this table are recognized both in regular expressions and in replacement patterns.

Note: The escaped character \b is a special case. In a regular expression, \b denotes a word boundary (between \w and \W characters) except within a [] character class, where \b refers to the backspace character. In a replacement pattern, \b always denotes a backspace.

Switch case
The governing type of a statement is established by the  expression. If the type of the expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the  statement.

switch (i) { case 0: CaseZero; goto case 1; case 1: CaseZeroOrOne; goto default; default: CaseAny; break; }

Adding object manually to a Combobox
To add one object at time use the command and to add many objects at once use this:

this.comboBox1.Items.AddRange(new object[] {“Item 1”, 			“Item 2”, 			“Item 3”, 			“Item 4”, 			“Item 5”});

Forcing DoEvents
should be called if you are having problems with intern events that must be executed before the executiuon of your code. In this case use

Application.DoEvents;

Comparing a data type
You can compare data types using two approaches:

1) is operator

if (myClass is ComboBox) { // code here }

2) GetType and typeof 

if (myClass.GetType == typeof(ComboBox)) { // code here }

Changing the cursor
Use the sealed classes Cursor and Cursors like this:

try { 	// change the cursor Cursor.Current = Cursors.WaitCursor; } finally { 	// resotre the cursor Cursor.Current = Cursors.Default; }

Changing a font of some control
Because the Font object is immutable (meaning that you cannot adjust any of it's properties), you can only assign the Font property to a new Font object. However, you can create the new font based on an existing font.

The code below is an example of how to adjust the existing font to make it bold: myControl.Font = new Font(myControl.Font, myControl.Font.Style | FontStyle.Bold);

Formating numbers
Use a mask like "##.#" or "000.0" to format numbers

float result = 6.25f; result.ToString(“##.0”);     // result : 6.3 result.ToString(“000.0”);    // result : 006.3

Comparing dates
Use the method of the DateTime class. Example:

if (dtpFrom.DateTimeValue.CompareTo(dtpTo.DateTimeValue) > 0) {   control = dtpFrom; msg = “The From date must be less than the To date.”; }

Verifiying the focus of a control
Verify the property containFocus of the control like this:

// Disable the menu item if the text box does not have focus. this.menuItemEditInsertCustomerInfo.Enabled = this.textBox1.containFocus;

Logging
FileStream moLogFile = new FileStream(“C:\log.txt”, FileMode.Create); TextWriterTraceListener myListener = new TextWriterTraceListener(moLogFile); Trace.Listeners.Add(myListener); // flushs the stream after every write. Trace.AutoFlush=true; // write the text into the log file. Trace.WriteLine(sText + “\r\n”);

Writing to a file
The following example opens a file or creates it if it does not already exist, and appends information to the end of the file.

FileStream fs=new FileStream(“c:\\Variables.txt”, FileMode.Append, FileAccess.Write,   FileShare.Write); fs.Close; StreamWriter sw=new StreamWriter(“c:\\Variables.txt”, true, Encoding.ASCII); string NextLine=“This is the appended line.”; sw.Write(NextLine); sw.Close;

Reading from a file
//Open the stream and read it back. using (FileStream fs = File.OpenRead(path)) {      byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b,0,b.Length) > 0) {      	Console.WriteLine(temp.GetString(b)); } }

Closing an MDI Application
We have to catch the window message WM_CLOSE before it is processed. So you prevent that this message be sent to MDI children.

protected override void WndProc(ref Message m) { switch (m.Msg) { 		case 0x010: // WM_CLOSE if (Sky4Main.Message(“Quit the application?” ,MessageBoxButtons.YesNo ,MessageBoxIcon.Question ,MessageBoxDefaultButton.Button2)==DialogResult.Yes) { 				// change the general flag // to inform all the windows and threads // that the application is closing Sky4Main.IsApplicationClosing = true; // process the message base.WndProc (ref m); } 			// otherwise the message will be ignored break; default: base.WndProc (ref m); break; } }

Opening a table for CRUD
You have to use an Adapter and a DataSet object to insert, update and delete records of a table in the database.

A FillSchema operation adds a DataTable to the destination DataSet. It then adds columns to the DataColumnCollection of the DataTable, and configures the following DataColumn properties if they exist at the data source: FillSchema does not return any rows. Use the method to add rows to a DataTable.
 * AllowDBNull
 * AutoIncrement. You must set AutoIncrementStep and AutoIncrementSeed separately.
 * MaxLength
 * ReadOnly
 * Unique

The OleDbDataAdapter does not automatically generate the SQL statements required to reconcile changes made to a DataSet with the associated data source. However, you can create an OleDbCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of the OleDbDataAdapter. Then, any additional SQL statements that you do not set are generated by the OleDbCommandBuilder.

DataSet mDataSet = new DataSet; String msSelect = “SELECT * FROM USER”; mDataAdapter = new OleDbDataAdapter ( msSelect ,Sky4DB.Connection); OleDbCommandBuilder custCB = new OleDbCommandBuilder(mDataAdapter); mDataAdapter.FillSchema(mDataSet, SchemaType.Mapped, msTableName); mDataAdapter.Fill(mDataSet, msTableName);

Adding rows with AutoIncrement Primary key
Use the following code:

mDataSet.Tables[msTableName].Columns[i].AutoIncrement = true; mDataSet.Tables[msTableName].Columns[i].AutoIncrementSeed = -1; mDataSet.Tables[msTableName].Columns[i].AutoIncrementStep = -1;

Clearing error icons
Try to find methods to get a error array and then clear the object error with empty strings like this:

// clear the errors foreach(DataRow row in mDataSet.Tables[msTableName].GetErrors) { 	row.RowError = ““; foreach(DataColumn col in mDataSet.Tables[msTableName].Columns) row.SetColumnError(col, ““); }

Events
1.	Define a class that provides data for the event. This class must derive from System.EventArgs, which is the base class for event data. An example follows.

Note: This step is not needed if an event data class already exists for the event or if there is no data associated with your event. If there is no event data, use the base class System.EventArgs.

public class AlarmEventArgs : EventArgs { private readonly int nrings = 0; private readonly bool snoozePressed = false; //Properties. public string AlarmText { ...   }    public int NumRings { ...   }    public bool SnoozePressed{ ...   }    ... } 2.	Declare a delegate for the event, as in the following example.

Note: You do not have to declare a custom delegate if the event does not generate data. In that case, use the base event handler System.ComponentModel.EventHandler.

public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);

3.	Define a public event member in your class using the event keyword whose type is an event delegate, as in the following example. public class AlarmClock { ...  public event AlarmEventHandler Alarm; } In the AlarmClock class the Alarm event is a delegate of type AlarmEventHandler. When the compiler encounters an event keyword, it creates a private member such as private AlarmEventHandler al = null; and the two public methods add_Alarm and remove_Alarm. These methods are event hooks that allow delegates to be combined or removed from the event delegate al. The details are hidden from the programmer.

Note: In languages other than C# and Visual Basic .NET, the compiler might not automatically generate the code corresponding to an event member, and you might have to explicitly define the event hooks and the private delegate field.

4.	Provide a protected method in your class that raises the event. This method must be named OnEventName. The OnEventName method raises the event by invoking the delegates. The code example at the end of this topic shows an implementation of OnEventName.

Note: The protected OnEventName method also allows derived classes to override the event without attaching a delegate to it. A derived class must always call the OnEventName method of the base class to ensure that registered delegates receive the event.

public class AlarmClock {   ...    public event AlarmHandler Alarm; protected virtual void OnAlarm(AlarmEvent e){...} }

The following code fragment puts together all of the elements discussed in this section. //Step 1. Class that defines data for the event // public class AlarmEventArgs : EventArgs {         private readonly bool snoozePressed = false; private readonly int nrings = 0; // Constructor. public AlarmEventArgs(bool snoozePressed, int nrings) {...} // Properties. public int NumRings{ get { return nrings;}} public bool SnoozePressed { get { return snoozePressed;}} public string AlarmText { get {...}} } //Step 2. Delegate declaration. // public delegate void AlarmEventHandler(object sender, AlarmEventArgs e); // Class definition. // public class AlarmClock { //Step 3. The Alarm event is defined using the event keyword. //The type of Alarm is AlarmEventHandler. public event AlarmEventHandler Alarm; // //Step 4. The protected OnAlarm method raises the event by invoking //the delegates. The sender is always this, the current instance of //the class. //   protected virtual void OnAlarm(AlarmEventArgs e)     { if (Alarm != null) {       //Invokes the delegates. Alarm(this, e); }   } }

Searching for Rows in DataTables
/* This code sample illustrates assigning primary key columns to a data table and then selecting against the data table using the primary key column */ DataSet ds = new DataSet(“TestDS”); SqlDataAdapter sda = new SqlDataAdapter(“...”, “...”); sda.Fill(ds); DataTable dt = ds.Tables[0]; dt.PrimaryKey = new DataColumn[] { dt.Columns[0], dt.Columns[1] }; DataRow[] rows = dt.Rows.Find(““); foreach(DataRow row in rows) {    Response.WriteLine(row[“col1”] + “ - “ + row[“col2”]); }

Opening a ADODB.Recordset
OleDbDataAdapter custDA = new OleDbDataAdapter; DataSet custDS = new DataSet; //Use ADO objects from ADO library (msado15.dll) imported // as .NET library ADODB.dll using TlbImp.exe ADODB.Connection adoConn = new ADODB.Connection; ADODB.Recordset adoRS = new ADODB.Recordset; adoConn.Open(“Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;”, ““, ““, -1); adoRS.Open(“SELECT * FROM Customers”, adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1); custDA.Fill(custDS, adoRS, “Customers”); adoConn.Close;

How to open and read a DataReader
OleDbCommand myCommand = Sky4Lib.Sky4DB.Connection.CreateCommand; myCommand.CommandText = “SELECT * FROM Standard”; OleDbDataReader myReader = myCommand.ExecuteReader; while (myReader.Read) { 	DataRow myRow = mDataTable.NewRow; myRow[“stID”] = myReader[“stID”]; myRow[“Standard”] = myReader[“Standard”]; mDataTable.Rows.Add(myRow); }

Getting the application version
lblVersion.Text = System.Reflection.Assembly.GetExecutingAssembly.GetName.Version;

Getting a File from Resource
System.IO.StreamReader mySR = new System.IO.StreamReader(    Assembly.GetEntryAssembly.GetManifestResourceStream(“Kuringa_Alarm.Images.CLOCK03.ICO”)); //        ' read the resource from the returned stream notifyIcon1.Icon = new System.Drawing.Icon(mySR.BaseStream);

Copying Text to Clipboard
Clipboard.SetText(MyText);

Change the mouse pointer
// set the cursor to hour glass Cursor.Current = Cursors.WaitCursor; // set the default cursor Cursor.Current = Cursors.Default;

Working with Enumerator
IEnumerator EmpEnumerator=EmpList.GetEnumerator; //Getting the Enumerator EmpEnumerator.Reset; //Position at the Beginning While(EmpEnumerator.MoveNext) //Till not finished do print {     Console.WriteLine((Employee)EmpEnumerator.Current); }

How to close a window when ESC is pressed
Set the property to true and then add the following code to your Form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { 	if ( (keyData & Keys.Escape) == Keys.Escape ) { 		this.Close; return true; } 	else { 		return base.ProcessCmdKey (ref msg, keyData); } } // ProcessCmdKey

How to center a Form
this.StartPosition=FormStartPosition.CenterScreen;

How to use KeyDown Event
private void txtText_KeyDown(object sender, KeyEventArgs e) { // CTRL+F was pressed ? if (e.Modifiers.Equals(Keys.Control) && e.KeyCode.Equals(Keys.F)) { 		txtFind.SelectionStart = 0; txtFind.SelectionLength = txtFind.Text.Length; txtFind.Focus; } 	else if (e.KeyCode.Equals(Keys.F2)) { 		SearchString(false); } 	else if (e.KeyCode.Equals(Keys.F3)) { 		SearchString(true); } 	else if (e.Modifiers.Equals(Keys.Control) && e.KeyCode.Equals(Keys.A)) { 		txtText.SelectAll; } }

How to share .NET code cross-platform
This section describes how to share common .NET code cross-platform. For example, you want to share the same source code, functionalities and types between a smart device project and a windows project.

Some solutions are proposed here:
 * http://msdn.microsoft.com/msdnmag/issues/07/07/ShareCode/
 * http://www.danielmoth.com/Blog/2004/09/share-code-if-fullframe_17.html
 * http://www.danielmoth.com/Blog/2004/09/retargetable-256.html

The solution is:
 * You have to share the code not the binary
 * Create a shared directory to put all common classes and resources between two or more .NET projects
 * In each project, right click on the project and select the option menu "Add existing item..."
 * Select the shared items and click on the button Add and select the option "Add as link"

If you want to separate in any .NET class some instructions/commands for smart device (windows mobile, pocket pc, etc.) and windows projects use the solution below:
 * Right click on the project, select "Properties"
 * Under the Build tab add a new "Conditional compilation symbol" named DESKTOP_APP
 * Save it. Now in any part of your code you can distinguish between the Dekstop project or Smart device project. For example:

if (c != null) c.Cursor = defaultOrWait; Cursor.Current = defaultOrWait;
 * 1) if DEKTOP_APP
 * 1) else
 * 1) endif

C# most used commands and common situations. This document works also as CSharp reference and problems and solutions in the language CSharp. 