Thursday, January 28, 2010

All Your .base

I encountered some issues with a .NET service installer embedded into an .MSI package today. If you have classes dependent upon service startup in your installer and the service fails to start you will often get some unexpected and often cryptic messages. It gets even worse if your messages are relating to event log messages that wont write because of permissions or other similar issues. One gotcha I am guilty of was using EventLog instead of base.EventLog. I also failed to set the event log location when calling the static version of the method calls. By using base.EventLog the ServiceBase class creates an event log source and applies all messages to the Application log. Do this and all event log messages are not belong to us.

Tuesday, January 26, 2010

Console XML/XSD Validation Application

Could not find a decent console application to validate an XML file against multiple XSD Schema Documents so I decided to write one and share for any who may need it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Schema;

namespace XmlValidator
{
class Program
{
static void Main(string[] args)
{
int result = 0;
string documentPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, args[0]);
if (!File.Exists(documentPath)) throw new Exception(String.Format("The document '{0}' does not exist", documentPath));
List schemaPaths = new List();
foreach (string path in args.Skip(1))
{
string schemaPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, path);
if (!File.Exists(schemaPath)) throw new Exception(String.Format("The schema document '{0}' does not exist", schemaPath));
schemaPaths.Add(schemaPath);
}
using (Stream stream = File.Open(documentPath,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(
delegate(object sender, ValidationEventArgs e)
{
result = -1;
Console.Write("Line:");
Console.Write(e.Exception.LineNumber);
Console.Write(" Position:");
Console.Write(e.Exception.LinePosition);
Console.Write(" ");
Console.Write(e.Severity.ToString("G"));
Console.Write(" ");
Console.WriteLine(e.Message);

}
);
foreach (string path in schemaPaths) settings.Schemas.Add(XmlSchema.Read(XmlReader.Create(path), null));
stream.Position = 0;
XmlReader validator = XmlReader.Create(stream, settings);
while (validator.Read()) ;
validator.Close();
}
if (result == 0) Console.WriteLine("Document is valid");
#if DEBUG
Console.ReadLine();
#endif
Environment.Exit(result);
}
}
}