Friday, September 25, 2009

Storing Application Message Staticly - ASP.NET - C#

Having a list of messages is always required within application, there are many ways to implement a message list. First of all you should categorized the messages such as Info ,Warnings , Errors , ... . may be you think the best way is saving messages in database but what if the database is down ,so we couldnt access to our messages, or saving all messages in XML file, what if the XML file is deleted , so you see we should prepare a general solution to satisfy all of the situations, here I'm going to implement a list of messages in the application staticly to store a critical messages ,in this case we could sure the list is always available. later I will implement a general solution which consists Database/XML Message list and types and Static message list in the application.

First of all we should prepare SystemMessage Class which contains messages, then we you should prepare the EntityBase class which inherits from Web.UI.page class and has a private SystemMessage member, then all of the other classes and pages should be inherited from BaseEntityClass. Here is the sample Class Diagram and Code :

Class Diagram for Message Listpublic class BaseEntity: System.Web.UI.Page
{
private SystemMessage sm;
protected BaseEntity()
{
sm = new SystemMessage();
}
///


/// Define Message by index
///
public string Message(int MessageIndex)
{
return sm[MessageIndex];
}
}

//--------------------------------------------------

public class SystemMessage
{
private static System.Collections.Generic.Dictionary _MessageList=null;
public SystemMessage()
{
_MessageList = new System.Collections.Generic.Dictionary();
_MessageList.Add(1, "Error #16576");
_MessageList.Add(2, "Add record to database");
_MessageList.Add(3, "Warning , this field already exist in database");
_MessageList.Add(4, "Try later!");
}

//Define Readonly indexer for this class
public string this[int index]
{
get
{
if (_MessageList.ContainsKey(index) == true)
return _MessageList[index];
return index.ToString() + " does not exist in the message list";
}
}
}

//-----------------------------------------------
//Now we are in Default.aspx.cs class can access our message list by typing just Message( MessageIndex )

public partial class _Default : BaseEntity
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Message(2));
}
}

Then you should see "Add record to database" text in your page.

In the EntityBase class you could add other methods which are required in the application such as check user access or Logging methods.

No comments:

Post a Comment

Thank you for sharing your knowledge and experiences with this weblog.