Thursday, December 10, 2009

Wednesday, December 9, 2009

Printing numeric values as HEX

I sometimes need to print integer numeric values as a hexadecimal string for better reading and everytime I have to search about it with google.

So here is a collection of printing values as hexadecimal string.

The simpliest way is to use the IFormattable interface:
   1:  String.Format("{0:X02}", int.MaxValue);

Other ways with support of differend radix is to user Convert.ToString().
Radix could be 2, 8, 10, or 16.
   1:  Convert.ToString(int.MaxValue, 2);

From:
MSDN: Convert.ToString()
mikrocontroller.net


Are there any other ways? So let me know!

Monday, December 7, 2009

Advanced Stringreplace

While handling string data it's often needed to replace or cut a partial string. String.Replace is such a simple method to replace values in C#.

But what about if you have to deal with patterns to replace or manipulate partial string?

Here you have to go beyond String.Replace and deal with regular expressions.
If you have't heared about Regular Expressions, I suggest to read this articles about it:
and some tools to check you patterns against data:

And now, time for some excamples.

Assume you have a string like
   1:  string data = "52/00000012340056";
and have to replace the zeros after the slash.

Your regex could be the following
   1:  Regex regex = new Regex(@"0+");

but take care about the zeros within the numbers. So you have to extend you regex like this:
   1:  Regex regex = new Regex(@"^\d+/0+");

If you run this expression over the sample data, the result looks like this:
   1:  string result = regex.Replace(data, String.Empty);
   2:  // result == "12340056";

Missing the prefix?

Extend the expressions with some named groups and use the matching values:
   1:  Regex regex = new Regex(@"^(?<prefix>\d+/)(0+)");
   2:  string result = regex.Replace(data, "${prefix}"); 
   3:  // result == "52/12340056";


That's it!

Thursday, November 19, 2009

WANTED - Dead or Alive

What devolpers hunting for:

Thursday, November 5, 2009

MetalScroll

Just got a hint from rschu@twitter / blogpost @ kodierer.blogspot.com about a MetalScroll extension for Visual Studio.

Here some features:
  • scrollbar extension (shows file structure with highlighted position of booksmarks and breakpoints)
  • split editor into two panes
  • highlighting all occurrences of a word within a file

Check it out:
MetalScroll @ code.google.com
MetalScroll in der Visual Studio Gallery

XML Validation

Next post in the line of XML processing hints with C#. This time we want to validate a xml file.

Assume a sample:
You've got an XML-File books.xml as follows:

   1:  <books xmlns="urn:books">
   2:   <book>
   3:    <author>It's just me</author>
   4:    <publisheddate>2009-09-25T09:06</publisheddate>
   5:   </book>
   6:  </books>

And a xml schmema (books.xsd) like this:

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <xs:schema targetNamespace="urn:books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
   3:   <xs:element name="books">
   4:    <xs:complexType>
   5:     <xs:sequence>
   6:      <xs:element name="book">
   7:       <xs:complexType>
   8:        <xs:sequence>
   9:         <xs:element name="author" type="xs:string" />
  10:         <xs:element name="publisheddate" type="xs:dateTime" />
  11:        </xs:sequence>
  12:       </xs:complexType>
  13:      </xs:element>
  14:     </xs:sequence>
  15:    </xs:complexType>
  16:   </xs:element> 
  17:  </xs:schema>

Now there is more than one way to validate the xml file.

The first way I want to show is to load the whole xml file into a XmlDocument instance like.

   1:  // load xml
   2:  XmlDocument xmlDoc = new XmlDocument();
   3:  xmlDoc.Load("books.xml");

Now we need the schema to validate against ...

   1:  // load schema XmlSchema schema; using(XmlReader schemaReader = XmlReader.Create("books.xsd")) schema = XmlSchema.Read(schemaReader, (p, q) => if(q.Exception != null) throw q.Exception); 

Add this to the schemas of the XmlDocument to provide it for validation. Be carefull, that the schema is added for the namespace of the document nodes.

   1:  // add schema xmlDoc.Schemas.Add(xmlDoc.DocumentElement.NamespaceUri, schema);

Now the document could be validated. (Just providing a lamda expression as ValidationEventHandler.)

   1:  // validate document
   2:  xmlDoc.Validate((p, q) => if(q.Exception != null) throw q.Exception);

There is only one handycap: Validation Warnings are not passed to the ValidationEventHandler.

The other way to validate a xml file is to use a XmlReader (or just one of it's derived classes). This is the favored way for large xml files.

First let us initialize such an reader. To use validation functionality of the reader we must pass in some XmlReaderSettings to configure that reader.

   1:  // loading schema
   2:  XmlSchemaSet schemaSet = new XmlSchemaSet();
   3:  schemaSet.Add("urn:books", "books.xsd");
   4:  XmlReaderSettings settings = new XmlReaderSettings();
   5:  settings.ValidationType = ValidationType.Schema;
   6:  settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
   7:  settings.Schemas = schemaSet;
   8:  settings.ValidationEventHandler += (p, q) =>
   9:  {
  10:     if (args.Severity==XmlSeverityType.Warning)
  11:        Console.WriteLine("Warning: Matching schema not found. No validation occurred." + args.Message);
  12:     else if(q.Exception != null)
  13:        throw q.Exception;
  14:     else
  15:        Console.WriteLine("\tValidation error: " + args.Message);
  16:  };
  17:  // create reader
  18:  using(XmlReader reader = XmlReader.Create("books.xml", settings))
  19:  {
  20:     // validate
  21:     while(reader.Read());
  22:  }

This is it, now you receive validation errors and warnings.

Monday, September 28, 2009

Just a prefix issue

Everybody who has to deal with XML and XPath in .NET just Run into an issue of accessing elements without having any prefix for the default namespace.

Assume a sample:
You've got an XML-File books.xml as follows:
<books xmlns="urn:books">
 <book>
  <author>It's just me</author>
  <publisheddate>2009-09-25T09:06</publisheddate>
 </book>
</books>

And now? How to access a node?

First attempt:
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
 
// just build xPath for testing
StringBuilder xPath = new StringBuilder();
XmlNode someNode = doc.DocumentElement.FirstChild.FirstChild;
 
do
{
   xPath.Insert(0, someNode.LocalName);
   xPath.Insert(0, "/");
   someNode = someNode.ParentNode;
}
while (someNode != null && someNode.NodeType != XmlNodeType.Document);
 
// xPath == "/books/book/author"
XmlNode author = doc.DocumentElement.SelectSingleNode(xPath.ToString());

What is the value of author? Right, it's null, hu.

Next attempt, try using XmlNamespaceManager.
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
// try to access with XmlNamespaceManager
XmlNode author = doc.DocumentElement.SelectSingleNode(xPath.ToString(), manager);

What is the value of author? Right, it's still null, hu.

And now?

Try to explain: The Namespace and the Prefix of the used namespace is not defined so xpath could not be resolved.

So try this:
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
// try to access with XmlNamespaceManager
XmlNode author = doc.DocumentElement.SelectSingleNode(xPath.ToString(), manager);

So try this:
string prefix = "mySample";
if (String.IsNullOrEmpty(manager.LookupPrefix(doc.DocumentElement.NamespaceURI)))
{
   // namespace not added
   manager.AddNamespace(prefix, doc.DocumentElement.NamespaceURI);
}
 
// injecting the namespace
xPath.Replace("/", String.Format("/{0}:", prefix));
 
// xPath is now  "/{mySample}:books/{mySample}:book/{mySample}:author"
author = doc.DocumentElement.SelectSingleNode(xPath.ToString(), manager);

And now, author sould be the selected node.

Thursday, September 10, 2009

Keep clean with temporary files

Every developer runs into a situation where temporary files are needed. In cause of an error, many developers forget to clean up this garbage within the temporary files directory. And I HATE that.

So therefore here is an hint for C# developers:
Just use the
FileOptions.DeleteOnClose
value as parameter of the
FileStream
constructor, this will keep you handles clean.

Heres comes an excample:
using (FileStream fStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.DeleteOnClose)))
{
// do work
}

Good luck.

Exchange variables for experts - or these who want to be

To show how cool you could code, you can use the following snippet to impress your girlfriend 8)

estimating x and y are integers
x = x ^ y;
y = y ^ x;
x = x ^ y;

shorter
x ^= y;
y ^= x;
x ^= y;

and a one liner if you like sunglasses
x ^=  y; y ^=  x; x ^=  y;

Cool as ice ...