Mental Jetsam

By Peter Finch

Archive for the ‘C#.NET’ Category

Binary HTTP GET in C#

Posted by pcfinch on January 13, 2011

The following code returns binary data (an array of bytes) from a HTTP GET request, and returns the mime type as a output parameter of the function.

public byte[] httpGetBytes(String url, out String mimeType)
  byte[] response = null;
  byte[] buffer = new byte[4096];
  int read;

  HttpWebRequest fetchReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  fetchReq.Method = "GET";
  HttpWebResponse fetchResp = (HttpWebResponse)fetchReq.GetResponse();
  Stream responseStr = fetchResp.GetResponseStream();
  mimeType = fetchResp.ContentType;

  MemoryStream ms = new MemoryStream();
  while((read = responseStr.Read(buffer, 0, buffer.Length)) > 0)
    ms.Write(buffer, 0, read) ;
  response = ms.ToArray();

  return (response);

Posted in C#.NET | Leave a Comment »

C# SQL Server result in XML

Posted by pcfinch on April 5, 2009

Formatting the output of a SQL query in XML using SQL Server is really simple and
very powerful if you want to deal with XML in the applications instead of normal
Record sets. The following is a simple SQL Query to
produce the results in XML. The XML essentially comes back to the application
as if it were one column of a result set with one row.

SELECT username AS '@username', password AS 'password' 
FROM [dbo].users 
WHERE username = @USERNAME
FOR XML PATH('User'), ROOT('Users'), TYPE ;

The PATH(‘User’) option creates an XML ‘User’ element for each row in the
result set and the ROOT(‘Users’) option wraps all the results in the ‘Users’ element.
For each of the columns in the result set simple specify the element name you want
the data to appear in (e.g. ‘password’) or put a ‘@’ at the start of the name
to place the contents of the column in an attribute of the row element
(e.g. ‘@username’). The output of the query is as follows.

 <User username="fmcske">

If your using C#, the following example code can be used to read the
results of the query and create a DOM object.

using (SqlConnection connection = new SqlConnection(sConnectString)) 
    using (SqlCommand command = connection.CreateCommand())
        DateTime startTime = DateTime.Now;
        command.CommandText = sSqlQuery ;
        command.Parameters.Add("@USERNAME", SqlDbType.VarChar, 32) ;
        command.Parameters["@USERNAME"].Value = sUsername ;
        using (XmlReader reader = command.ExecuteXmlReader())
            XmlDocument dom = new XmlDocument();
            /* ... */

Posted in C#.NET | 3 Comments »

Sorting an array in C#

Posted by pcfinch on January 14, 2009

The following code is a simple and quick way to sort and arbitrary array of objects in C#. I like using a delegate in this way as you can pick any attribute or member of the object to sort on at the time you need to perform the sort in the code.

class Customer {
	internal String sName ;
	internal String sAddress ;
} ;

Customer[] customers = new Customer[20] ;
/* Load array ...*/

Array.Sort<Customer>(customers, new Comparison<Customer>(delegate(Customer l, Customer r)
	return (l.sName.CompareTo(r.sName));
})) ;

Make sure the array is full, i.e. no null entries, otherwise you will have to check for null values in l and r.

Posted in C#.NET | Leave a Comment »

Dynamically creating C# class instances using reflection.

Posted by pcfinch on November 27, 2008

Reflection, the ability for a program to dynamically inspect itself, is possibly one of the most powerful features of modern programming languages like C# and Java. The following is a simple example of how to interrogate the current C# assembly, locate all the classes that are derived from a base class, and then dynamically created and executed an instance of the class.

I wrote this code for a set of tests I wanted to implement. The idea was to make it simple to add new tests to the project by just adding new class derived from the base “Test” class. The program would then automatically find all the tests and run them.

  1. First, create the “Test” base class.

    abstract class Test {
      protected String m_sName ;
      public String name { get { return (m_sName) ; } }
      protected Test(String sName) { m_sName = sName; }
      abstract public void run() ;

  2. Derive the actual tests from the “Test” base class.

    class UsersTest : Test {
      public UsersTest() : base("Test user names and passwords") { }
      override public void run() {
        // Test code does here

  3. To run the tests, first get the current Assembly, and find all the Types that are “Classes” and are derived from the class “Test”. Once you have the type you need to Dynamically create and instance of it. This method looks for the default constructor (the one with no parameters) and uses that, however, the code could look for any constructor if required. It then calls the contractor to
    create an instance of the class, and finally executes the classes run() method.

    Assembly asm = Assembly.GetExecutingAssembly();
    foreach (Type type in asm.GetTypes()) {
      if (type.IsSubclassOf(typeof(Test)) && type.IsClass) {
        ConstructorInfo ci = type.GetConstructor(new Type[] { });
        Test t = (Test)ci.Invoke(new Object[] { }) ;
        Console.Out.WriteLine ("Running Test - " +;;

This is a very simple example, and there are other ways to runs tests, but it is easy to see how this design could be extended and used in all sorts of situations.

Posted in C#.NET, Programming | 3 Comments »