Mental Jetsam

By Peter Finch

Archive for June, 2007

C# Generics Enumerator Example

Posted by pcfinch on June 29, 2007

In order to implement a generics Enumerator, so that you can use a foreach on a class, in C# there is a bit of trick. If you are getting compilation error messages similar to the following then you have this problem.


'System.Collections.IEnumerable.GetEnumerator()'.
'Results.GetEnumerator()' is either static, not public, or
has the wrong return type.

Using the generic type 'System.Collections.Generic.IEnumerator<T>'
requires '1' type arguments

In order to implement an Enumerator correctly you need a IEnumerable.GetEnumerator() member and your need to include System.Collections. although this seems to go against logic, I believe this is because the new generics Enumerator system uses the “old” Enumerator in some way.


using System.Collections.Generic;
using System.Collections;

public class Results : IEnumerable<SearchResult>
{
  private LinkedList<SearchResult> m_results;

  public IEnumerator<SearchResult> GetEnumerator() {
    foreach (SearchResult item in m_results)
      yield return item;
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
  }
}

This will allow you to do the following.


Results results ;
foreach (SearchResult result in results)
  System.Console.WriteLine(result.Title);

Posted in C#.NET | Leave a Comment »

Reading number fields form Oracle in C#

Posted by pcfinch on June 19, 2007

If you are using C# and are trying to read a field from an Oracle table defined as NUMBER then when you try to access the field from a C# OleDbDataReader using the GetInt32() member, you may get the a “Specified cast is not valid” exception. I found that reading a number from Oracle tables using the GetDecimal() works without an exception.

OleDbCommand cmd = db.createCommand(
  "Select TOPID_ID from TOPICS");
using(OleDbDataReader dr = cmd.ExecuteReader()) {
  while (dr.Read())
  {
    int nTopicId = Decimal.ToInt32(dr.GetDecimal(0));
    Console.WriteLine(nTopicId) ;
  }
}

Posted in C#.NET | 1 Comment »

How to Process a HTTP XML Post in C#

Posted by pcfinch on June 15, 2007

This is a quick bit of code that can be used to read and decode XML data submitted to a C# HTTP web service (usually derived from a IHttpHandler) using the POST method. This is better that a GET as more data can be submitted and the data can be structured. In this example the incoming XML on the POST is…

<Request>
<Header>
<UserId>fuzzy</UserId>
</Header>
<Body>
<AddPart>Screwdriver</AddPart>
<AddPart>Drill</AddPart>
</Body>
</Request>

Reading the XML data is really easy using the System.Xml API.

StreamReader reader = new StreamReader(
    context.Request.InputStream, System.Text.Encoding.UTF8);
String sXMLRequest = reader.ReadToEnd();
XmlDocument xmlRequest = new XmlDocument();
xmlRequest.LoadXml(sXMLRequest);

Once the XML has been loaded to a DOM, elements, attributes and text from the DOM can easily be extracted using the SelectSingleNode() and SelectNodes() members functions available on each node. Both functions take an XPath expression as input. This makes these two functions very powerful when processing the DOM.

XmlNode xmlUserId = xmlRequest.SelectSingleNode(
    "/Request/Header/UserId");
String sUserId = (xmlUserId != null) ?
    xmlUserId.InnerText : "undefined" ;
context.Response.ContentType = "text/html";
context.Response.Write("<br>UserId = " +
    sUserId);

XmlNodeList xmlParts = xmlRequest.SelectNodes(
    "/Request/Body/AddPart");
if (xmlParts != null) {
    foreach (XmlNode node in xmlParts) {
        context.Response.Write("<br>Add part to catalog : " +
            node.InnerText);
    }
}

Posted in C#.NET | Leave a Comment »

Using Unicode characters in python

Posted by pcfinch on June 7, 2007

It’s really easy to work with strings in Python, but when it comes to handling Unicode there are a few issues that you may have to deal with. The main problem you will have is using Unicode characters with devices (consoles) or in database that do not support Unicode. If you have tried printing a Unicode string and got the following message then you will have experienced the issue.

>>> string = u'\\u7279\\u6b8a Unicode'
>>> print string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'latin-1' codec can't encode characters 
in position 0-1: ordinal not in range(256)

The issue is that Python is unable to convert the Unicode string into the encoding of the current terminal. A similar problem can also happen when trying to put Unicode data into a database that does not accept [has not been configured] to use unicode characters or send it via E-Mail. A couple of simple tricks using the very powerful “encode()” function can help a lot have make your code more resilient.

To convert a Uncode string so it can be displayed on an ASCII screen.

>>> print string.encode('ascii','replace')
?? Unicode
>>> print string.encode('ascii','ignore')
Unicode

A more useful approach is to escape the characters into another encoding. My favorite is to use XML character entities. The string can then be safely put into a the database field, sent out in E-Mails or placed in a HTML page.

>>> string.encode('ascii', 'xmlcharrefreplace')
'& #29305;& #27530; Unicode'

References.

Posted in Python | Leave a Comment »