When you’re using the Ama­zon S3 client, have you come across the occa­sional excep­tion that says some­thing like one of these excep­tion messages:

“The request was aborted: The con­nec­tion was closed unexpectedly”

“Unable to read data from the trans­port con­nec­tion: A block­ing oper­a­tion was inter­rupted by a call to WSACancelBlockingCall”

“Unable to read data from the trans­port con­nec­tion: An estab­lished con­nec­tion was aborted by the soft­ware in your host machine “

If you do, then you’re prob­a­bly attempt­ing to return the response stream directly back to the rest of your appli­ca­tion with some­thing like this:

   1: var response = _s3Client.GetObject(request);

   2: return response.ResponseStream;

How­ever, because the stream is com­ing from the Ama­zon S3 ser­vice and is fed to your code in chunks, your code needs to ensure that the con­nec­tion to S3 stays open until all the data has been received. So as men­tioned in the S3 doc­u­men­ta­tion (which inci­den­tally, most of us don’t read in great details…) here, you should be wrap­ping the response you get from the GetO­b­ject method in a using clause.

Depends on what it is you want to do with the stream, you might have to han­dle it dif­fer­ently. For instance, if you just want to read the string con­tent of a text file, you might want to do this:

   1: using (var response = _s3Client.GetObject(request))

   2: {

   3:     using (var reader = new StreamReader(response.ResponseStream))

   4:     {

   5:         return reader.ReadToEnd();

   6:     }

   7: }

Alter­na­tively, if you want to return the response stream itself, you’ll need to first load the stream in its entirety and return the loaded stream. Unfor­tu­nately, at the time of this writ­ing, the AWSSDK library still hasn’t been migrated to .Net 4 and there­fore doesn’t have the uber use­ful CopyTo method added in .Net 4, so you will most likely have to do the heavy lift­ing your­self and read the data out man­u­ally into a mem­ory stream:

   1: using (var response = _s3Client.GetObject(request))

   2: {

   3:     var binaryData = ReadFully(response.ResponseStream);

   4:     return new MemoryStream(binaryData);

   5: }

   6:

   7: /// <summary>

   8: /// See Jon Skeet's article on reading binary data:

   9: /// http://www.yoda.arachsys.com/csharp/readbinary.html

  10: /// </summary>

  11: public static byte[] ReadFully (Stream stream, int initialLength = -1)

  12: {

  13:     // If we've been passed an unhelpful initial length, just

  14:     // use 32K.

  15:     if (initialLength < 1)

  16:     {

  17:         initialLength = 32768;

  18:     }

  19:

  20:     byte[] buffer = new byte[initialLength];

  21:     int read=0;

  22:

  23:     int chunk;

  24:     while ( (chunk = stream.Read(buffer, read, buffer.Length-read)) > 0)

  25:     {

  26:         read += chunk;

  27:

  28:         // If we've reached the end of our buffer, check to see if there's

  29:         // any more information

  30:         if (read == buffer.Length)

  31:         {

  32:             int nextByte = stream.ReadByte();

  33:

  34:             // End of stream? If so, we're done

  35:             if (nextByte==-1)

  36:             {

  37:                 return buffer;

  38:             }

  39:

  40:             // Nope. Resize the buffer, put in the byte we've just

  41:             // read, and continue

  42:             byte[] newBuffer = new byte[buffer.Length*2];

  43:             Array.Copy(buffer, newBuffer, buffer.Length);

  44:             newBuffer[read]=(byte)nextByte;

  45:             buffer = newBuffer;

  46:             read++;

  47:         }

  48:     }

  49:     // Buffer is now too big. Shrink it.

  50:     byte[] ret = new byte[read];

  51:     Array.Copy(buffer, ret, read);

  52:     return ret;

  53: }

Share

When you are devel­op­ing an appli­ca­tion to run as a ser­vice it’s nice to be able to also run it as a con­sole app so you can eas­ily debug, etc. On the rare occa­sion you might even want to find out if your app is run­ning in a con­sole win­dow at run­time so you can set the title of the con­sole win­dow to dis­play some use­ful debug­ging infor­ma­tion, for example.

After some quick dig­ging around, I found a rel­e­vant ques­tion on Stack­Over­flow and the answer here, all you need is a sim­ple method like this:

   1: public bool IsService()

   2: {

   3:     var entryAssembly = Assembly.GetEntryAssembly();

   4:     var entryPoint = entryAssembly.EntryPoint;

   5:

   6:     // add a little error handling to make sure there is a BaseType

   7:     return

   8:         entryPoint.ReflectedType.BaseType != null &&

   9:         entryPoint.ReflectedType.BaseType.FullName == "System.ServiceProcess.ServiceBase";

  10: }

Share

It’s been a while since I had to cre­ate a con­fig sec­tion han­dler and my god did I for­get how cum­ber­some a process it is!

Instead of doing all these work to make a bespoke con­fig sec­tion han­dler every time you want to parse some data out of the app.config file, wouldn’t it be nice to have a more generic, reusable com­po­nent to do all the work for you? Well, turns out it wasn’t all that hard to make one either!

Broadly speak­ing, you usu­ally want to parse either an object, or a col­lec­tion of objects out of the con­fig file, and they required slightly dif­fer­ent han­dling so I ended up writ­ing one for each.

Sin­gle Object

The sin­gle object case is fairly easy, all you need is an XmlSe­ri­al­izer for dese­ri­al­iz­ing the XML node:

   1: public sealed class GenericConfigSectionHandler<T> : IConfigurationSectionHandler

   2: {

   3:     public object Create(object parent, object configContext, XmlNode section)

   4:     {

   5:         var xmlSerializer = new XmlSerializer(typeof(T));

   6:         var xmlNodeReader = new XmlNodeReader(section);

   7:         return xmlSerializer.Deserialize(xmlNodeReader);

   8:     }

   9: }

Assum­ing you have a sim­ple class like this:

   1: [XmlRoot("MyClass")]

   2: public class MyClass

   3: {

   4:     public string Name { get; set; }

   5:  

   6:     public int Age { get; set; }

   7: }

To parse it out of your app.config file, you need some­thing like this in the con­fig file:

   1: <configuration>

   2:   <configSections>

   3:     <section name="MyClass" 

   4:              type="ConsoleApplication.GenericConfigSectionHandler`1[[ConsoleApplication.MyClass, ConsoleApplication]], ConsoleApplication"/>    

   5:   </configSections>

   6:  

   7:   <MyClass>

   8:     <Name>Yan</Name>

   9:     <Age>29</Age>

  10:   </MyClass>  

  11: <configuration>

And your code will be the same as before:

   1: var myObj = (MyClass)ConfigurationManager.GetSection("MyClass");

Col­lec­tions

Col­lec­tions usu­ally rep­re­sent a whole new level of pain because to get an array of objects out of the con­fig file you have to first cre­ate a wrap­per object to hold the array. You then need to set up your con­fig sec­tion to parse the wrap­per object instead of the array itself, just an addi­tional hoop you have to jump through to get some­thing sim­ple done…

Well, with this Gener­ic­Col­lec­tion­Con­fig­Sec­tion­Han­dler class hope­fully you won’t ever have to do that again!

   1: public sealed class GenericCollectionConfigSectionHandler<T> : IConfigurationSectionHandler

   2: {    

   3:     static GenericCollectionConfigSectionHandler()

   4:     {

   5:         // get the XmlRootAttribute element on the type

   6:         var type = typeof(T);

   7:         var xmlRootAttributes =

   8:             type.GetCustomAttributes(typeof(XmlRootAttribute), false)

   9:                 .OfType<XmlRootAttribute>();

  10:  

  11:         // if an XmlRootAttribute is found then use its ElementName property as the

  12:         // root element name for the type T, otherwise, use the name of the type T

  13:         // as the default root element name

  14:         RootElementName = 

  15:             !xmlRootAttributes.Any() 

  16:                 ? type.Name 

  17:                 : xmlRootAttributes.First().ElementName;

  18:     }

  19:  

  20:     private static string RootElementName { get; set; }

  21:     

  22:     public object Create(object parent, object configContext, XmlNode section)

  23:     {

  24:         var xmlSerializer = new XmlSerializer(typeof(T));

  25:         var xmlNodeReader = new XmlNodeReader(section);

  26:         var xdoc = XDocument.Load(xmlNodeReader);

  27:         var items =

  28:             xdoc.Descendants(RootElementName)

  29:                 .Select(e => (T)xmlSerializer.Deserialize(e.CreateReader()));

  30:         return items.ToArray();

  31:     }

  32: }

As you can see, this class is pretty sim­ple, to use it your con­fig file ought to look a lit­tle like this:

   1: <configuration>

   2:   <configSections>

   3:     <section name="MyClasses" 

   4:              type="ConsoleApplication.GenericCollectionConfigSectionHandler`1[[ConsoleApplication.MyClass, ConsoleApplication]], ConsoleApplication"/>    

   5:   </configSections>

   6:  

   7:   <MyClasses>

   8:     <MyClass>

   9:       <Name>Yan</Name>

  10:       <Age>29</Age>

  11:     </MyClass>

  12:     <MyClass>

  13:       <Name>Yinan</Name>

  14:       <Age>29</Age>

  15:     </MyClass>

  16:   </MyClasses>

  17: </configuration>

So you see, no wrap­per class required and you get an array of MyClass instances back:

   1: var myObjs = (MyClass[])ConfigurationManager.GetSection("MyClasses");

Share

Sup­pose you have an array of num­bers, say, [1, 3, 5, 7, 9, …], and you want to pair each ele­ment up with its neigh­bour in the array, e.g. [[1, 3], [3, 5], [5, 7], [7, 9], …].

Sure, you can iter­ate through the indices of the ele­ments and recur­sively grab the ele­ment at an index and its neighbour:

   1: // an array of odd numbers

   2: var arr = new[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };

   3:  

   4: // standard imperative way, iterate through the indices and grab

   5: // the elements from the arrays

   6: var arrPairs = new List<int[]>();

   7: for (var i = 0; i < arr.Length - 1; i++)

   8: {

   9:     arrPairs.Add(new[] { arr[i], arr[i+1] });

  10: }

OR, you can use LINQ and the Zip method added in .Net 4 and do this instead:

   1: var arrPairsLinq = arr.Skip(1).Zip(arr, (second, first) => new[] { first, second }).ToArray();

A much more ele­gant solu­tion, no? ;-)

Share

Admit it, we’ve all done it before, writ­ing those nasty nested loops just so we can iter­ate through mul­ti­ple lists to get some combination/permutation of the lists, e.g.:

   1: for (int i = 0; i < 10; i++)

   2: {

   3:     for (int j = 0; j < 10; j++)

   4:     {

   5:         for (int k = 0; k < 10; k++)

   6:         {

   7:             // do something

   8:         }

   9:     }

  10: }

This code obvi­ously works and well under­stood amongst devel­op­ers, but it’s not very read­able and try­ing to ter­mi­nate the outer loops from the inner loops is a pain and requires you to use one or more boolean flags which you need to track on every iter­a­tion at poten­tially every level of your loop…

A bet­ter way to solve this com­mon prob­lem is to use LINQ to ‘flat­ten’ the nested loops into a sin­gle loop:

   1: var triplets = from I in Enumerable.Range(0, 10)

   2:                from J in Enumerable.Range(0, 10)

   3:                from K in Enumerable.Range(0, 10)

   4:                select new { I, J, K };

   5:  

   6: foreach (var triplet in triplets)

   7: {

   8:     // do something

   9: }

Sweet, right? :-)

Share