I am working on a project in which I have to display
lots of messages to the users. Most of these messages are help text so users
will know how to navigate and how to use the website. The common approach of
displaying the messages is simply assigning the label control some text. Here is
the common approach.
if (result)
{
lblStudentWelcomeMsg.Text = "Welcome to the website";
}
As,
you can see that the above code and technique will cause a maintanence
nightware. What I proposed and implemented is saving all the messages in the XML
file. In this case we will have all the messages in one place and later when we
have to change the messages we simply edit the XML file and that's it.
Here
is part of the XML file:
<Messages>
<ClassCodeMessage>
[Please enter the code. You should have received the code
from your teacher.]
</ClassCodeMessage>
<UserCreateUserNameMessage>
[Create a User Name and Password.
Password must be 5 or more alphanumeric characters.]
</UserCreateUserNameMessage>
<ReviewInformation>
Please review the information below:
</ReviewInformation>
</Messages>
Now, after
that I also created a MessageHelper class which contains several static methods
and which return the message read from the XML file.
/* MESSAGES METHODS */
public static string GetClassCodeMessage()
{
return GetMessageByElementName("ClassCodeMessage");
}
public static string GetCreateUserNameMessage()
{
return GetMessageByElementName("UserCreateUserNameMessage");
}
public static string GetReviewInformationMessage()
{
return GetMessageByElementName("ReviewInformation");
}
And here is
the GetMessageByElementName
method:
// This method returns the message based on the Element Name
private static string GetMessageByElementName(string elementName)
{
string message = String.Empty;
string path = GetMessagesFilePath();
XmlTextReader xmlReader = new XmlTextReader(path);
try
{
while (xmlReader.Read())
{
if (xmlReader.Name == elementName)
message = xmlReader.ReadInnerXml();
}
}
catch (Exception ex)
{
string exception = ex.Message;
}
finally { xmlReader.Close(); }
if (message != null && message.Length > 0)
return message;
else return String.Empty;
}
The above
method will search the XML file whenever it requires a message. You might want
to store the contents of the message file in Cache object (Store only in
cache if your messages xml file is suitable and does not consume much of
the memory. I am pretty sure that the xml file won't be that large since it
only contains the text).
After storing
in the Cache object you can put the Cache file dependency so that whenever
the file contents are changed the Cache is refreshed.
After this you
can use the messages like this:
lblReviewInfoMsg.Text
= MessageHelper.GetReviewInformationMessage();
Hope it helps
in your projects!
powered by IMHO 1.3