Some time back I wrote an article about how to store and retrieve the user interface messages. When I say user interface messages I meant the messages we display on the screen to notify the user of some operation. These messages can be "Account has been created!", "Details have been updated" and so on. You can view the article here.
One problem with the above approach was the weak typing. This means that if I had to display a login successful message I had to send the string "LoginSuccessfull" to the GetMessages(string elementName) method. This introduces bugs and becomes harder to maintain. There is another way to accomplish the same task with the benefit of strong typing.
This method involves saving all the messages into the XML file and then using the schema of the XML file to generate a .CS or VB file. Let's start with an XML file.
<MeanWormMessages>
<LoginMessage message ="Thanks for loggin in!">
</LoginMessage>
</MeanWormMessages>
Open the XML file in VS editor and then generate the schema using the "Create Schema" option under XML menu. Now, you can convert the XSD schema file to CS or VB file using the tool XSD.exe.
At the command prompt of VS 200X type the following command to generate the file.
xsd.exe MeanWormMessages.xsd /classes
This will generate a C# file (C# is default) named MeanWormMessages.cs. Include this file to your project. Before you start using the MeanWormMesssages class you need to deserialize the XML file to the object. This will populate the object with the contents from the XML file. This is accomplished using the following code.
public static MeanWormMessages GetDeserializedMeanWormMessages()
{
XmlSerializer xSer = new XmlSerializer(typeof(MeanWormMessages));
using(XmlReader reader = XmlReader.Create(messageFilePath))
{
messages = (MeanWormMessages) xSer.Deserialize(reader);
}
return messages;
}
Now, you can use the strongly typed messages as shown below:
