This shows simple examples of common coding activities. It is a work in progress
and is mainly for my own use, but it may hold the information you want.

Ado.Net

Many are the issues with Ado.Net, and I've not got to the bottom of it yet, but here is an Ado.Net crib sheet all of its own. And also here, the simple high points - all of which are illustrated in the working 'TheMain.cs' file.

SqlConnection and connection string  
SqlConnection dbcon = new SqlConnection();
dbcon.ConnectionString="Server=(local);database=jgtest;Integrated Security=SSPI";
 
Connecting to SqlServer with a named instance (forget the correct terminology)  

Basically the Server=(local) may not work with a named instance or with DNS issues. For named instances use the IP address\instance_name. eg I have a sqlserver instance called JPGPRIV, so the server element of the connection string is:

Server=192.168.0.5\JPGPRIV
 
Typed data set Fill  
String query = "SELECT id, description from CONSource";
DBCONSource dset = new DBCONSource();
SqlDataAdapter da = new SqlDataAdapter(query, dbcon);
da.Fill(dset,0,5,"CONSource");
dbcon.Close();
 
Inserting into a typed data set  
for (int cnt=0; cnt<10; cnt++) {
DataTable tab = dset.CONSource;
dset.CONSource.AddCONSourceRow("example"+cnt);
}
 
Commiting a data set back to the data source  
da = new SqlDataAdapter(query, dbcon);
// Now, to set the commands
SqlCommandBuilder bld = new SqlCommandBuilder(da);
da.InsertCommand = bld.GetInsertCommand();
da.UpdateCommand = bld.GetUpdateCommand();
da.DeleteCommand = bld.GetDeleteCommand(); // note it needs the table name within the db to do the mapping
da.Update(dset, "CONSource");
dbcon.Close();
dset.AcceptChanges();
 
Commiting a dataset and retrieving the real auto inc numbers  

In the data source set seed as 0, increment as -1, and readonly to false for the autoinc column. This allows the local dataset to assign decreasing negative keys, while the server assigns increasing positive keys.

da.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
// note it needs the table name within the db to do the mapping
da.Update(dset, "CONSource"); ... protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args) {
if (args.StatementType == StatementType.Insert) {
SqlConnection con = args.Command.Connection;
Object new_id = 0;
    // sqlserver 2000 version
    SqlCommand id_cmd = new SqlCommand("select scope_identity() as id",          con);
    new_id = id_cmd.ExecuteScalar();
    if (new_id== System.DBNull.Value) {
      // sqlserver earlier version
      id_cmd = new SqlCommand("select @@IDENTITY", con);
      new_id = id_cmd.ExecuteScalar();
      if (new_id== System.DBNull.Value) {
        throw new Exception("Why doesn't it work??!!");
      }
    }
    // Retrieve the identity value and store it in the id column.
    args.Row["id"] = new_id;
  }
} // end of onRowUpdated
       
 
Untyped data set definition  
DataTable tab = dset2.Tables["CONSource"]; 
tab.Columns.Add("id",System.Type.GetType("System.Int32"));
tab.Columns.Add("description", System.Type.GetType("System.String"));
 
Updating untyped data set  
for (int cnt=0; cnt<3; cnt++) {
DataRow anyRow = dset2.Tables["CONSource"].NewRow();
anyRow["id"] = -1;
anyRow["description"] = "example"; dset2.Tables["CONSource"].Rows.Add(anyRow); }
 
Assigning nulls  
  anyRow["description"] = DBNull.Value;
 
Testing nulls
 
if (new_id== System.DBNull.Value) {
 
Transaction - multiple datasets/adaptors  
con.Open();
SqlTransaction my_trans = con.BeginTransaction();
da1.InsertCommand.Transaction=my_trans;
da2.InsertCommand.Transaction=my_trans; try { da1.Update(dset1, "CONSource"); da2.Update(dset2, "CONSource"); my_trans.Commit(); } catch (SqlException ex) { try { my_trans.Rollback(); } catch (SqlException ex1) { if (my_trans.Connection != null) { Console.WriteLine("An exception of type " + ex1.GetType() + " was encountered while attempting to roll back the transaction."); } } Console.WriteLine(ex.ToString()); Console.WriteLine("Update failed."); } con.Close();
 
GUID's  

Now Guid's are nasty, for various reasons, but if you go for them then use the System.Guid class member NewGuid().

Guid val = Guid.NewGuid();
 
SqlCommand and SqlDataReader example  
try {
String query = "select id,desc from a_table"; SqlConnection con = new SqlConnection();
con.ConnectionString="Server=(local);database=jgtest;Integrated Security=SSPI"; con.Open(); SqlCommand cmd = new SqlCommand(query,con); SqlDataReader reader =cmd.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt(0); String desc = reader.GetString(1); } reader.Close(); con.Close(); return ret; } catch (Exception ex) { System.Console.WriteLine(ex.Source); return ret; }
 

Networking

General comment. Attempts to write a threaded web proxy failed dismally because browser socket close events are not detected by the TcpClient and NetworkStream classes within the proxy. The solution is to use Socket classes instead. i.e. use TcpClient for one off comms, not looping comms which you may want to terminate once the read has started.

Listen on a port: Link
TCPListener server = new TCPListener( 23 ); 
server.Start();
Socket accept = server.Accept();
 
Listen on a port take II Link
try {
IPAddress ipAd = IPAddress.Parse("172.21.5.99");
TcpListener myList=new TcpListener(ipAd,8001); myList.Start(); Socket s=myList.AcceptSocket(); Console.WriteLine("Connection accepted from "+s.RemoteEndPoint); byte[] b=new byte[100]; int k=s.Receive(b); for (int i=0;i<k;i++) Console.Write(Convert.ToChar(b[i])); ASCIIEncoding asen=new ASCIIEncoding(); s.Send(asen.GetBytes("The string was recieved by the server.")); s.Close(); myList.Stop(); } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); }
Connect to a port with sockets:  
IPHostEntry ipHostInfo = Dns.Resolve(host);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); serverSoc_ = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
serverSoc_.Connect(remoteEP);
Connect to a port: Link
TCPClient telnet = new TCPClient( "telnet.host.com", 23 );
Stream telnetStream = telnet.GetStream();
StreamWriter output = new StreamWriter( telnetStream );
StreamReader input = new StreamReader( telnetStream );
 
Request a web page Link
WebRequest request = WebRequestFactory.Create( = "http://to.post.to.com"    );
Stream input = request.GetResponse().GetResponseStream();
... read stuff from input ...
input.Close();
 

Error codes from SocketException

Link

No code here, but a .Net horror. All the socket exception thrown include a useless error number which is thrown by the underlying winsock libs. A quick search found a german firewall site which allowed me to work out what the errors actually were. Follow the link for the information - you don't have to read german.

File IO

Create a text file Link
StreamWriter sw File.CreateText( "brand-new-file.txt" );  

Find Disk Size

 
public static void getDiskSize(String drive, 
  out ulong o_size, out ulong o_used, out ulong o_avail) {
  // Check the drive exists
  if (!Directory.Exists(drive+@":\")) 
        throw new DirectoryNotFoundException("No drive info");
  ManagementObject disk = new
  ManagementObject("Win32_LogicalDisk.DeviceID=\""+drive+":\"");
  UInt64 freespace = (UInt64)disk.Properties["FreeSpace"].Value ;
  UInt64 size = (UInt64)disk.Properties["Size"].Value ;
  Console.WriteLine("Harddisk size: "+ size);
  Console.WriteLine("Bytes used: "+ (size - freespace));
  Console.WriteLine("Bytes availlable: "+ freespace);
  o_size = size;
  o_used= ((size - freespace));
  o_avail = freespace;
}
Disk Names  
String [] drives = Directory.GetLogicalDrives();

Strings

Byte array to Strings  
String str = Encoding.ASCII.GetString(buff,0,buff.Length);
 
Strings to byte array  
byte [] end_ln = Encoding.ASCII.GetBytes("\r\n");
 
Strings to number  
try {
String k = headers_.Get(HEAD_CONTENTLENGTH);
int ret = Int32.Parse(k);
return ret;
} catch (FormatException) {
// TODO:
} or System.Convert.ToInt32(some_string);
 
String tokenising  
String [] lines = hdr_str.Split('\n', '\r'); 
int cnt=0;
foreach (String line in lines) {
  if (line==String.Empty) continue;
   ... stuff...
}
 
   
 
 

General

How to get the current time  
DateTime.Now;

Enum

 
public enum RESPONSE_CODES : int {
  OK = 200,
  BadRequest = 400,
  InternalServerError = 500,
};

Threads

All that single thread appartment and multi thread appartment stuff is MS rubbish based upon VB history. Ignore it all, and just use nice, normal java type threads.

Starting a thread  
public void Go(string drive) {
  running_ = true;
  // Note the use of the delegate here.
  myTh_ = new Thread(new ThreadStart(this.Run));
  // Starting the thread invokes the ThreadStart delegate.
  myTh_.Start();
}
 
Stoping a thread  
public void Stop() {
  if (myTh_!=null) {
    running_ = false;
    myTh_.Abort();

    myTh_=null;
  }

}
 
And the main thread loop  
private void Run() {
  try {
    while (running_) {
	 ... do stuff ...
    }
  } catch (ThreadAbortException ) {
    // TODO:
  }
}