Procedure for Calling C# BER Stream-Oriented Encode Methods

Once an object’s member variables have been populated, the object’s encode method can be invoked to encode the value. The general procedure to do this involves the following three steps:

  1. Create an output stream object into which the value will be encoded

  2. Invoke the encode method

  3. Close the output stream.

The first step is the creation of an output stream object. There are two forms of the constructor: a constructor with one parameter (System.IO.Stream reference) and one that allows specification of an internal buffer size. A larger internal buffer size generally provides better performance at the expense of increased memory consumption. The first constructor sets the value to a reasonable mid-range value.

The second step is the invocation of the Encode() method. The calling arguments were described earlier. As per the C# standard, this method must be invoked from within a try/catch block to catch the possible Asn1Exception and System.Exception, which may be thrown. Alternatively, the method from which the encode method is called can declare that it throws Asn1Exception and System.Exception leaving it to be dealt with at a higher level.

Finally, close the output stream.

A complete example showing how to invoke a stream-based encode method is as follows:

   // Note: personnelRecord object was previously populated with data

   Asn1BerOutputStream outs = null;

   try {
      // Step 1: Create an output stream object. This object uses the
      // default size increment for buffer expansion..

      outs = new Asn1BerOutputStream ( new System.IO.FileStream(
         filename, System.IO.FileMode.Create));

      // Step 2: Invoke the encode method. Note that it must be done
      // from within a try/catch block..

      personnelRecord.Encode (outs, true);

      if (trace) {
         System.Console.Out.WriteLine ("Encoding was successful");
         System.Console.Out.WriteLine ("Hex dump of encoded record:");
         encodeBuffer.HexDump ();
         System.Console.Out.WriteLine ("Binary dump:");
         encodeBuffer.BinDump ();
      }
   }
   catch (Exception e) {
      System.Console.Out.WriteLine (e.Message);
      Asn1Util.WriteStackTrace(e, Console.Error);
      return;
   }
   finally {

      // Step 3: Close the output stream, if opened

      try {
         if (outs != null)
             outs.Close ();
      }
      catch (Exception e) {}
   }

If you compare this example with the BER encoding example in Figure 1, you will see the encoding procedure is almost identical. This makes it very easy to switch encoding methods should the need arise. All you need to do is change Asn1BerEncodeBuffer to Asn1BerOutputStream and remove the explicit code that writes the messages into the stream. Also closing of the stream should be added.