C# mini tutorial

Presentation outline

What is C#?

In June 2000, Microsoft announced a new strongly-typed object-oriented language: C#. It is designed with the hindsight of many languages, most notably Java and C++, to give the optimum blend of simplicity, expressiveness and performance. Although initially symbiotic with the .NET framework, open source support (e.g. Mono) has allowed it to migrate to non-Windows platforms.

Why C#?

C# takes the simplicity of Java, with its automatic garbage collection, monolithic inheritance (single root object hierarchy), and standard class library, and adds a number of advanced features, such as properties, delegates, and attributes. Interestingly , many of these features have ended up in the latest versions of Java, e.g. enumerations and the foreach statement in Java 1.5.

C# was also developed very much with the Web foremost in mind, and whilst some say that C# is more expressive than Java and is more suited to performance-critical code, when it comes to web services both C# and Java are much better than C++.

How do I do C#?

On Windows platforms, C# can used with the .NET Framework; however, a more platform agnostic option is to use the open source implementation of Mono, which is what we focus on in this mini tutorial.

To compile a C# code, we use the mcs compiler:

>mcs SomeFile.cs

This will create an executable file called SomeFile.exe. To run this, we use the mono program:

>mono SomeFile.exe

C# example code 1: Handling XML

The first example code will load a specified XML document, apply a specified XPath string against it and print out the results. The source code, which can be found in $NVOSS_CSHARP_HOME/examples/XPathExample.cs, is:

using System;
using System.Xml;

public class XPathExample {
public static void Main(string[] args) {
string filename = args[0];
string query = args[1];

XmlDocument document = new XmlDocument();
document.Load(filename);
XmlNodeList nodes = document.SelectNodes(query);
Console.WriteLine("{0} nodes match the query {1}",
nodes.Count, query);
foreach (XmlNode node in nodes) {
Console.WriteLine(node.Value);
}
}
}

To compile this:

>cd $NVOSS_CSHARP_HOME/examples
>mcs XPathExample.cs

This will create an executable XPathExample.exe in the directory.

The sample XML file summary.xml contains a list of resource types and how many there are of each. Let's suppose that we want to know the names of the resources for which there are entries, i.e. where the value of the <howmany> element is greater than zero: the XPath statement that will give us this for this file is:

//resourceType[howmany > 0]/name/text()

So we call the executable with:

>mono XPathExample.exe summary.xml "//resourceType[howmany > 0]/name/text()"
3 nodes match the query //resourceType[howmany > 0]/name/text()
Authority
Organisation
Registry

C# example code 2: Calling a web service ("ASP.NET")

Mono comes with its own code for generating client proxy code from a web service WSDL:

>wsdl -o:DistanceProxy.cs "http://voservices.net/Cosmology/ws_v1_0/Distance.asmx?WSDL"
Mono Web Services Description Language Utility
Writing file 'DistanceProxy.cs'

This creates a file called DistanceProxy.cs containing the automatically generated client proxy code. Now we use the client proxy class to build a simple client application to calculate the comoving line of sight distance (the source code can be found in $NVOSS_CSHARP_HOME/examples/DistanceClient.cs):

using System;

public class DistanceClient {
public static void Main(string[] args) {
float redshift = Convert.ToSingle(args[0]);
float hubble = Convert.ToSingle(args[1]);
float omega_m = Convert.ToSingle(args[2]);
float omega_l = Convert.ToSingle(args[3]);

Distance dist = new Distance();
Console.WriteLine("Comoving line-of-sight distance is: {0} Mpc",
dist.ComovingLineOfSight(redshift, hubble, omega_m, omega_l));
}
}

We compile this with:

>mcs -r:System.Web.Services DistanceClient.cs DistanceProxy.cs

and this produces an executable called DistanceClient.exe. Let's see how far an object at z=6.3 in the standard cosmology is:

>mono DistanceClient.exe 6.3 0.75 0.3 0.7
Comoving line-of-sight distance is: 7811.307 Mpc

C# example code 3: Making a SQL query ("ADO.NET")

Mono comes with data providers for many of the most common relational databases: MySQL, SQL Server, PostgreSQL, Oracle, Sybase, DB2, SQLite, OLE DB and ODBC. In this example, a sample query will be issued against the MySQL database containing the SPOCS sample data (the source code can be found in $NVOSS_CSHARP_HOME/examples/MySQLClient.cs):

using System;
using System.Data;

using ByteFX.Data.MySqlClient;

public class MySQLClient {
public static void Main(string[] args) {

string connectionString = string.Format("Server=localhost;Database=SPOCS;
User ID={0};Password={1};", "", "");
MySqlConnection conn = null;

try {
conn = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand("select id, name, teff, logg, metal
from SPOCS where teff between 5720 and 5820 and logg between 4.34 and 4.54
and metal between -0.1 and 0.1 order by teff", conn);
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
Console.WriteLine("Id = {0}, Name = {1}, Teff = {2}, Logg = {3}, Metal = {4}",
reader["id"], reader["name"], reader["teff"], reader["logg"], reader["metal"]);
}
reader.Close();
} catch (Exception e) {
Console.Error.WriteLine(e);
} finally {
if (conn != null && conn.State == ConnectionState.Open) {
conn.Close();
}
}
}
}

We compile this with:

>mcs -r:ByteFX.Data -r:System.Data MySQLClient.cs

and this produces an executable called MySQLClient.exe. We run this with:


>mono MySQLClient.exe
Id = 405, Name = HD75302, Teff = 5721, Logg = 4.49, Metal = 0.08
Id = 660, Name = HD138573, Teff = 5722, Logg = 4.45, Metal = -0.05
Id = 759, Name = HD159909, Teff = 5723, Logg = 4.4, Metal = 0.06
Id = 371, Name = HD68168, Teff = 5724, Logg = 4.4, Metal = 0.1
Id = 90, Name = HD10086, Teff = 5725, Logg = 4.46, Metal = 0.09
...

Optional: Serving a web service

In C#, the set of technologies which support web functionality is known as ASP.NET. ASP.NET supports two kinds of applications: web forms (known as ASPX) and web services (known as ASMX). An ASP.NET application requires a container to run in (just like Java and Apache Tomcat). Fortunately Mono provides an Apache module mod_mono which can be used with the Apache web server to provide support for ASP.NET and a standalone ASP.NET server xsp (Note that Mac OS X users will have to compile and install xsp themselves).

The listing below gives a sample ASMX file for a directory listing service:

<%@ WebService Language="C#" Class="DirectoryListing" %>
using System.IO;
using System.Web.Services;
[WebService(Namespace="http://nvo.caltech.edu/",
Description="This provides a directory listing.")]
public class DirectoryListing {
[WebMethod(Description="This lists the contents of the specified directory.")]
public string[] ListDirectory(string path) {
return Directory.GetFileSystemEntries(path);
}
}

This file DirectoryListing.asmx should be placed in the xsp root directory and the service can then be accessed at: http://localhost:8080/DirectoryListing.asmx

Useful links