Search This Blog

Wednesday, April 29, 2009

Bhai Log Game 5 (28/04/09)

The game yesterday had some bittersweet moments.  Although we won it was not a victory we ought to cherish nor take into our heads…there is a long long road ahead of us.

We fielded first and luckily I did not have to eat my words when I said “yes we have 8”, when actually we only had 4 players.  It was a mediocre start in the first over which I bowled conceding 11 runs, 9 of those extras although it set up Jacinth with two strikes from the last two deliveries which he executed with class getting a wicket.  Our bowling wasn’t great…it just did enough as the batsman weren’t up to par so I think there is a still a lot of work to be done in that department.  Also our fielding was a bit shaky, we have to communicate!  The pick of the bowlers I have to say was Shashank.  Great pace and always on target.

Our batting was good…well good with respect to the deliveries and fielding of the other team.  We have to start hitting the side nets and not attempt hitting the back nets every time.  Lucky for us it paid of this time around.  We were also helped by poor bowling from the other side as they conceded 25 extras (~ 75 runs).  We also saw some good clean hitting by Kasun and Jessie.

Overall a good performance by the majority of the team although the senior players had a sub-par day, maybe that’s why one of them decided to stay back and make up for it ;).

Let us carry this winning way over to next week when we play the top of the table, an unbeaten team, we’ll change that next week :).

image

imageimage

Thursday, April 23, 2009

Bhai Log Game 4 (21/04/09)

Bhai Log continues to dive further into slum.  Read more about it here.  After a disappointing two weeks of cricket, Bhai Log could not record a win in what could be defined as the easiest game so far.  After restricting the opposition for a meagre 106, Bhai Log failed to deliver with the bat.

A mediocre bowling and fielding attempt from Bhai Log was enough to restrict the opposition to 106 so imagine if Bhai Log fired every time at the right times, they would be the oppositions biggest nightmare.  This week we took a turn in the below par performances where our batting was, no other word for it, absolutely shocking.  We scored a mere 40 runs off the first two partnership with an atrocious third partnership with –4.  I seriously don’t understand what part of “hit the side nets” is so complicated to understand.  The last partnership was a consolidation attempt as in no way were we expecting them to get more than 50 runs.

Jessie was the star of the match which was his first game after he returned from a long vacation in India.  Jessie, were you training there?  Can you tell us how you do it?

Hoping we pick up our act and start getting into the winning habit which has been the essence of Bhai Log since we remember.

Here are the stats.

image

image 

image

Wednesday, April 15, 2009

Bhai Log Game 3 (14/04/09)

Following on from our below par performance from last week Bhai Log surely lived up to it.  This is a team which came from winning the last season it played to being demolished by two mediocre opponents in two consecutive weeks.  Mind you the team is not the same as last season but yet, it is not the losing that matters, it is the way the loss occurs.

This week we had a 9.35 game and only five team members showed up on time.  You would’ve thought that a late game would mean that everyone would turn up on time.  Worst part is that one team member didn’t show up at all.  Quite a disappointment but that was expected given the history.  So the game began and the only thing we have won so far is the toss.  Elected to bowl considering we have a better chance of chasing and winning as we know how our game should be depending on the score, although that didn’t help at all.

First over was a shocker and unfortunately I was to blame for that giving away 13 runs although the shambles did not stop there.  We bowled atrociously, short balls galore and the batsmen did well to utilise our underpowered field.  There was no urgency in our fielding and I think that’s what lost us the game.  The opponent posted a huge total of 178.  In indoor cricketing terms that is close to impossible to attain.

Our batting started off well with 46 and 40 coming in the first two partnerships although the third partnership didn’t go as well as hoped leaving us to get 58 in the last partnership.  This was a huge ask on its own.

To sum things up, it was yet another below average performance from Bhai Log and shabby umpiring work was partly to blame.

I hope we bounce back in the next game to record our first graded round game win.  Neil and I bowled three overs each.  Matthew Scott batted twice as we were short one player.

image

image 

image

Sunday, April 12, 2009

Reading XML Schemas

XML information is everywhere in these times.  We heavily rely on XML to send and analyse information.  After dealing with XML in every aspect of development I realised that the internet is loaded with information on how to read, write and manipulate XML in every possible language (script) there is.  And to make things worse, I myself have a post up on how to read XML documents using DOM.

This motivated me to write this document and to give XML Schemas the respect they require.  What are XML schemas?  They can be simply explained as a skeleton for a given XML file.  An XML file can have any desired structure, XML schemas are what restrict them and keep them well-formed.  So an XML schema is something like a parent which looks after it’s child (the XML document).

Let us look at an example:

<?xml version="1.0" encoding="utf-8" ?>
<blog>
<topic date="2003-08-22">My first XML document</topic>
<topic date="2006-10-18">My second XML document</topic>
</blog>

The schema for the above XML is:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Blog">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="Topic">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="Date" type="xs:date" use="required" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Now that we are familiar with XML schemas let us look at the actual reason of this post.  Given an XML schema, how do we read it?  How do we store the values within the schema, its relationships and other mandatory information required by XML data files.

The way I addressed this problem is using two passes:


  1. Reading all the information given in XML schema
    This was necessary as there can be attribute and element references throughout the file.  Therefore we first need to store all the information about the XML schema and then determine the relationships between each of the data elements.

  2. Forming relationships between elements
    After we store all the information about the XML schema, we need to traverse through it to form the relationships.  Relationships in this aspect represent the nested nature of the XML schema.

Let us look at how we start reading an XML schema.  For that we have to understand a little about the different aspects of an XML schema.  A good introduction is given by the W3C schools here.  Let me briefly go over the main types here as well just to have a reference to them:


  1. Simple types
    1. Elements
    2. Attributes
    3. Restrictions

  2. Complex types
    1. Elements
    2. Empty
    3. Elements only
    4. Text only
    5. Mixed
    6. Indicators
    7. <any>
    8. <anyAttribute>
    9. Substitution

  3. Data types

I decided that each of the above types can be represented by data structures which I can understand to make things simpler.  You don’t have to do this, you can simply rely on the .NET representation of these schema types.  Let us look at how I chose to represent each of these structures.  Let me introduce a class diagram which we will analyse a bit later.


image


The above diagram shows three interfaces which help us make things much simpler and it also abstracts us away from the .NET representation the schema:


  1. IAttribute
    Any attribute like schema object will inherit from this interface.  Note that I said “attribute type”, as I also want simple types (both implicitly and explicitly declared) to be used as attributes.

  2. IElementComplex
    Represents any complex type object within the schema.  This includes both, implicitly and explicitly declared types.

  3. IRelationship
    Merely a wrapper around the complex element type which makes us easier to form relationships between them which we will use in our second pass.

Note that the above classes were developed a while ago while working on my Part IV engineering project (in 2005), only now have I realised that there is little to no help on how to read an XML schema, therefore I decided to publish this post.  By no means is this “the only” or “the best” way.  And also I am sure there are better ways of doing this.

Let me briefly give you an example of what implicitly and explicitly declared schema elements are with the XML schema below:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="ImplicityExplicit" xmlns="http://tempuri.org/ImplicityExplicit.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mstns="http://tempuri.org/ImplicityExplicit.xsd" elementformdefault="qualified" targetnamespace="http://tempuri.org/ImplicityExplicit.xsd">
<!--Explicit complex type-->
<xs:complextype name="CTEntity" />

<!--Implicit complex type-->
<xs:element name="CTElemEntity">
<xs:complextype></xs:complextype>
</xs:element>

<!--Explicit simple type-->
<xs:simpletype name="STEntity">
<xs:restriction base="xs:string" />
</xs:simpletype>

<!--Implicit simple type-->
<xs:element name="STElemEntity">
<xs:simpletype>
<xs:restriction base="xs:string" />
</xs:simpletype>
</xs:element>

<!--Implicit shy simple type-->
<xs:element name="STElem" />

<!--An attribute-->
<xs:attribute name="attribute" />
</xs:schema>

Now that we know the basic different types of XML schema elements let us look at how we can read/extract them.  For this we rely heavily on the .NET XML classes.  Reading the XML schema is quite simple, it is done using the following code:

using System;
using System.Xml;
using System.Xml.Schema;

namespace XmlLibrary
{
public class SchemaReader
{
public String FileName { get; set; }
public XmlSchema Schema { get; set; }

private bool SchemaLoaded { get; set; }

public SchemaReader(string fileName)
{
FileName = fileName;
ReadSchema();
}

public void ExtractElements()
{
if (SchemaLoaded && Schema != null)
{
XmlSchemaObjectCollection itemsColl = Schema.Items;
foreach (XmlSchemaObject item in itemsColl)
{
// TODO: Implementation
}
}
}

private void ReadSchema()
{
if (String.IsNullOrEmpty(FileName))
{
SchemaLoaded = false;
Schema = null;
}
else
{
try
{
Schema = XmlSchema.Read(new XmlTextReader(FileName), null);
SchemaLoaded = true;
}
catch (XmlException)
{
SchemaLoaded = false;
Schema = null;
}
catch (XmlSchemaException)
{
SchemaLoaded = false;
Schema = null;
}
}
}

}
}

The important method in the above code is the “ReadSchema” call.  Note that it takes in a string as a parameter which points to the schema file on disk and then reads this in the populates the System.Xml.Schema.XmlSchema object.  From this point forward we will only be concentrating on the ExtractElements method.


Let us examine the ExtractElements method closely.  Currently it is stubbed out, although if you remember I mentioned that XML has a nested/recursive nature to it, therefore we expect to call a distinctive method recursively.  Let us examine how we do it.  After fleshing out the method a bit further we have the following:

public void ExtractElements()
{
if (SchemaLoaded && Schema != null)
{
XmlSchemaObjectCollection itemsColl = Schema.Items;
foreach (XmlSchemaObject item in itemsColl)
{
ManipulateSchemaObject(item);
}
}
}

private void ManipulateSchemaObject(XmlSchemaObject schemaObject)
{
IndentLevel++;
if (schemaObject is XmlSchemaElement || schemaObject is XmlSchemaComplexType || schemaObject is XmlSchemaSimpleType)
{
#region XmlSchemaElement
if (schemaObject is XmlSchemaElement)
{
XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
Console.WriteLine(String.Format("{0}XmlSchemElement: {1} ({2})", GetIndentationString(), schemaElement, schemaElement.Name));

ManipulateSchemaElement(schemaElement);
}
#endregion XmlSchemaElement
#region XmlSchemaComplexType
else if (schemaObject is XmlSchemaComplexType)
{
XmlSchemaComplexType explicitComplexType = schemaObject as XmlSchemaComplexType;
Console.WriteLine(String.Format("{0}XmlSchemaComplexType: {1} ({2})", GetIndentationString(), explicitComplexType, explicitComplexType.Name));
}
#endregion XmlSchemaComplexType
#region XmlSchemaSimpleType
else if (schemaObject is XmlSchemaSimpleType)
{
XmlSchemaSimpleType explicitSimpleType = schemaObject as XmlSchemaSimpleType;
Console.WriteLine(String.Format("{0}XmlSchemaSimpleType: {1} ({2})", GetIndentationString(), explicitSimpleType, explicitSimpleType.Name));
}
#endregion XmlSchemaSimpleType
}
else
{
#region AttributeGroup
if (schemaObject is XmlSchemaAttributeGroup)
{
XmlSchemaAttributeGroup schemaAttGroup = schemaObject as XmlSchemaAttributeGroup;
Console.WriteLine(String.Format("{0}XmlSchemaAttributeGroup: {1} ({2})", GetIndentationString(), schemaAttGroup, schemaAttGroup.Name));
}
#endregion AttributeGroup
#region Attribute
else if (schemaObject is XmlSchemaAttribute)
{
XmlSchemaAttribute schemaAtt = schemaObject as XmlSchemaAttribute;
Console.WriteLine(String.Format("{0}XmlSchemaAttribute: {1} ({2})", GetIndentationString(), schemaAtt, schemaAtt.Name));
}
#endregion Attribute
#region Group
else if (schemaObject is XmlSchemaGroup)
{
XmlSchemaGroup schemaGroup = schemaObject as XmlSchemaGroup;
Console.WriteLine(String.Format("{0}XmlSchemaGroup: {1} ({2})", GetIndentationString(), schemaGroup, schemaGroup.Name));
}
#endregion Group
else
{
Console.WriteLine(GetIndentationString() + schemaObject + " is not handled yet");
}
}
}

#region schema element
private void ManipulateSchemaElement(XmlSchemaElement schemaElement)
{
XmlSchemaType schemaElementSchemaType = schemaElement.SchemaType;

#region schema type defined
if (schemaElementSchemaType != null)
{
Type xmlSchemaTypeType = schemaElementSchemaType.GetType();
#region Complex type
if (schemaElementSchemaType is XmlSchemaComplexType)
{
ManipulateSchemaElementComplexType(schemaElement);
}
#endregion Complex type
#region Simple type
else if (schemaElementSchemaType is XmlSchemaSimpleType)
{
ManipulateSchemaElementSimpleType(schemaElement);
}
#endregion Simple type
}
#endregion schema type defined
#region Element with no schematype, thus simple
else
{
if (schemaElement.RefName.IsEmpty) // not a reference
{
Console.WriteLine(String.Format("{0}Implicitly implicit simple type: {1}", GetIndentationString(), schemaElement.Name));
}
}
#endregion
}
#endregion schema element

#region simple type
private void ManipulateSchemaElementSimpleType(XmlSchemaElement schemaElement)
{
XmlSchemaSimpleType simpleElement = schemaElement.SchemaType as XmlSchemaSimpleType;
Console.WriteLine(GetIndentationString() + String.Format("Simple type encountered: {0}", schemaElement.Name));
}
#endregion simple type

#region complex type
private void ManipulateSchemaElementComplexType(XmlSchemaElement schemaElement)
{
XmlSchemaComplexType complexElement = schemaElement.SchemaType as XmlSchemaComplexType;

XmlSchemaObjectCollection attColl = complexElement.Attributes;
foreach (XmlSchemaObject attCollObj in attColl)
ManipulateSchemaObject(attCollObj);

if (complexElement.Particle != null)
{
XmlSchemaParticle complexElementParicle = complexElement.Particle;
ParticleHandlingForElement(complexElementParicle);
}
else if (complexElement.ContentModel != null)
{
XmlSchemaContentModel complexElementContentModel = complexElement.ContentModel;
if (complexElementContentModel is XmlSchemaSimpleContent)
{
XmlSchemaSimpleContent contentModelSimpleType = complexElementContentModel as XmlSchemaSimpleContent;
XmlSchemaContent schemaContent = contentModelSimpleType.Content;
if (schemaContent is XmlSchemaSimpleContentExtension)
{
XmlSchemaSimpleContentExtension xmlSchemaExtension = schemaContent as XmlSchemaSimpleContentExtension;
XmlSchemaObjectCollection objColl = xmlSchemaExtension.Attributes;
foreach (XmlSchemaObject item in objColl)
{
ManipulateSchemaObject(item);
}
}
}
else
{
Console.WriteLine(GetIndentationString() + complexElementContentModel.ToString());
// Handle restrictions and extensions here (Complex or simple type)
}
}
}
#endregion complex type

#region particle handling for element
private void ParticleHandlingForElement(XmlSchemaParticle complexElementParicle)
{
Type particleType = complexElementParicle.GetType();
if (complexElementParicle is XmlSchemaSequence)
{
XmlSchemaSequence particleAsSeq = complexElementParicle as XmlSchemaSequence;
ManipulateSchemaSequence(particleAsSeq);
}
else if (particleType.Equals(typeof(XmlSchemaChoice)))
{
XmlSchemaChoice complexChoice = complexElementParicle as XmlSchemaChoice;
ManipulateSchemaChoice(complexChoice);
}
}

#region choice
private void ManipulateSchemaChoice(XmlSchemaChoice groupChoice)
{
XmlSchemaObjectCollection objColl = groupChoice.Items;
foreach (XmlSchemaObject objCollObj in objColl)
{
XmlSchemaObject schemaObj = objCollObj;
if (schemaObj.GetType().Equals(typeof(XmlSchemaSequence)))
{
XmlSchemaSequence choiceSeq = schemaObj as XmlSchemaSequence;
ManipulateSchemaSequence(choiceSeq);
}
else if (schemaObj.GetType().Equals(typeof(XmlSchemaChoice)))
{
XmlSchemaChoice choiceChoice = schemaObj as XmlSchemaChoice;
ManipulateSchemaChoice(choiceChoice);
}
else
ManipulateSchemaObject(schemaObj);
}
}
#endregion choice

#region Sequence
private void ManipulateSchemaSequence(XmlSchemaSequence choiceSeq)
{
XmlSchemaObjectCollection objColl = choiceSeq.Items;
foreach (XmlSchemaObject objCollObj in objColl)
ManipulateSchemaObject(objCollObj);
}
#endregion Sequence

There are quite a lot of methods in the above snippet, although they are quite straight forward and most of them recursively call our ExtractElements method.  Let us look at each of the methods which handle each different aspect of XML schema.

  1. ManipulateSchemaObject(XmlSchemaObject schemaObject)
    Handles various schema objects, this is the recursive method call which is centre of our XML schema reader.  This method acts like a proxy which spreads out the flow depending on the type of the XML schema element.
  2. ManipulateSchemaElement(XmlSchemaElement schemaElement)
    Handles various schema elements, Complex and Simple.
  3. ManipulateSchemaElementSimpleType(XmlSchemaElement schemaElement)
    Handles the simple type.
  4. ManipulateSchemaElementComplexType(XmlSchemaElement schemaElement)
    Handles the complex type.
  5. ParticleHandlingForElement(XmlSchemaParticle complexElementParicle)
    Handles particles, which includes sequences and choice elements.

We have looked at how to cleanly handle the XML schema and recursively traverse through its structure.  I’ll get back to this topic in a later post and show you how to I formed relationships between my custom schema based data structures using custom business objects.

Wednesday, April 8, 2009

Bhai Log Game 2 (07/04/09)

After a convincing win in Game 1 we could not have done any worse.  After a bismal fielding performance on field we continued along the downward spiral with our batting.  Some brilliant moments did occur but not enough to reward us the win.  The lost was brought upon by our own undoing.  Below are the graphs for the bowling, batting and all round performances of each team member.  Hoping to avenge our downfall in the next game.  You can also read more about the game here.

image

 image

image

Friday, April 3, 2009

StackOverflowException aka “The Uncatchable”

Ever wrote a great little application just to find that at some odd moment calling into a third party DLL throws a nice little StackOverflowException.  Then you go start digging into your code only to find that your call to this third party DLL is surrounded by not only one but two to three try/catch/finally blocks at different levels.  Hmm…weird.

The below code can quickly get this error for you and no matter if you surround it one or even 10 try/catch blocks, it will still throw the exception.

class Program
{
static void Main(string[] args)
{
try
{
Recurse();

Console.WriteLine("No exception thrown");
}
catch (StackOverflowException e)
{
Console.WriteLine("No exception caught");
}
}

private static void Recurse()
{
Recurse();
}
}

image


Does the catch block not catch StackOverflowException?

The answer is simple…only after you think about it for a little while.  No! The StackOverflowException cannot be caught by the .NET runtime because simply…according to Microsoft .NET it is bad coding practice.


Below is extracted from http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx.







Version Considerations

In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.


Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, seeICLRPolicyManager Interface and Hosting the Common Language Runtime.



I found two great articles on how to handle the StackOverflow exception:



  1. http://stackoverflow.com/questions/206820/how-do-i-prevent-and-or-handle-a-stackoverflowexception-c

  2. AppDomains.pdf

Wednesday, April 1, 2009

Bhai Log Game 1 (31/03/09)

Our first graded game was played last night.  For a change everyone turned up with Shadow aka Rainbow aka Neil making his indoor debut.  Read more about it here.  Here are the stats graphs for the game.

image

image

image

image