Click here to Skip to main content
Click here to Skip to main content

Working with Resource Files in ASP.NET Programatically

, 12 Nov 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
This article will represent how to work with Resource Files dynamically

Introduction

It is seen sometimes that you need to develop a multilingual website. And for that, you need to maintain resource files (.resx) in ASP.NET. You need to make resource files for each language your website is going to support. But suppose your client wants to make some changes in the text entered in resource files, then what will you do?

Background

I am not going to explain anything about globalization. There are so many articles already well explained on CodeProject which you can refer to.

Using the Code

Here, I am using a BasePage class in which there is a method to return current path of the Resource file which I am using.

protected string CurrentRes
 {
   get
    {
     if (null != Session["SelectResource"])
      {
       if(System.IO.File.Exists(Session["SelectResource"].ToString()))
         {
           return Session["SelectResource"].ToString();
        }
      }
    return Server.MapPath("App_GlobalResources\\Resource.resx");
   }
}

Now inheriting BasePage.cs class to my aspx page will return to me the file path & name. On the page load, I am binding Gridview with resource file as dataset to show user the contents of file.

When user clicks on Insert button, then method insertElement is called which has two parameters Name & Value. Here, a new object of xmldocument is created & xmlnodes are defined. Make sure you inherited System.Xml & System.Resources. Then, I had created a rootnode after loading the XML document.

Following are the steps to be followed:

  1. Create a parent node 'data' with node type as element.
  2. Create an XML attribute 'name'.
  3. Append xmlnode with attributes.
  4. Repeat the same steps if there are child nodes.
  5. Finally, call the saveDoc() method to save your changes in Resource file.
 public void insertElement(string name, string value)
    {
        XmlDocument doc = new XmlDocument();
        XmlNode child = null;
        XmlNode xname = null;
        XmlNode rootnode = null;
        doc.Load(FileName);
        rootnode = doc.SelectSingleNode("root");
        xname = doc.CreateNode(XmlNodeType.Element,"data",null);
        XmlAttribute xa =  doc.CreateAttribute("name");
        xa.Value = name;
        XmlAttribute xa1 = doc.CreateAttribute("xml","space",null);
        xa1.Value = "preserve";
        xname.Attributes.Append(xa);
        xname.Attributes.Append(xa1);
        child = doc.CreateNode(XmlNodeType.Element, "value", null);
        child.InnerText = value;
        xname.AppendChild(child);
        rootnode.AppendChild(xname);
       saveDoc(doc, FileName);
    }

SaveDoc method saves the Insertion/ updation operations to the Resource.resx file. SaveDoc takes two arguments document name & path, writes the XML Text to doc file and saves it.

private void saveDoc(XmlDocument doc, string docPath)
{
try
{
   XmlTextWriter writer = new XmlTextWriter(docPath, null);
   writer.Formatting = Formatting.Indented;
   doc.WriteTo(writer);
   writer.Flush();
   writer.Close();
  return;
}
catch{
throw;
  }
} 

In the same way, you can Update the Resource file. Select a record from the Grid. As the Name parameter is always unique, so the resource Value field will get updated. Following is the code snippet for update.

public void updateElement(string name, string value)
{
XmlDocument doc = new XmlDocument();
XmlNode rootnode = null;
doc.Load(FileName);
rootnode = doc.SelectSingleNode("//root");
XmlNode xnode = rootnode.SelectSingleNode("//data[@name='" + name + "']/value");
xnode.InnerText = value;
saveDoc(doc, FileName);
DataBinder();
}

Biding the Grid with Resource File

The following code shows how we can bind the grid with resource file. This solution fits for MVS-2008 or above. Note that in the below code snippet, I am binding only the "data" table from the dataset. The dataset consists of multiple tables like "metadata", "resource", but we only need "data" table. In this way, we can bind the grid with resource file.

 private void bindgrid()
    {
      DataSet dsgrid = new DataSet();  
      DataTable dt = new DataTable();
      try
        {
            dsgrid.ReadXml(CurrentRes);
            dt.Merge(dsgrid.Tables["data"]);
            dt.AcceptChanges();
            this.grdResource.DataSource = dt;
            this.grdResource.DataBind();
            
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
        finally
        {
            if (dsgrid != null)
            {
                dsgrid.Dispose();
                dsgrid = null;
            }
        }
    }

If you are working in MVS-2005 or lower, you just need to bind grid with dataset.

Points To Be Taken Care Of

Make sure that you don't enter space while making a new entry in the name field as it's a unique field & cannot have a space within. Also be sure that you enter unique Names. Values can be variable or same.

Conclusion

In this article, we have seen how we can manage resource files dynamically to provide user friendly interface to the end users which makes things more clear and easy to handle. Resource files act like the back bone while working with multilingual sites. This opens up numerous possibilities for dynamic and robust systems.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

sameer_s
Software Developer (Senior) CMMi-3
India India
Working in .NET Technologies from the last +5 years and Exploring myself in .NET by learning, implementing and sharing my ideas of latest topics.
For further queries, shoot me a mail at sameersayani@gmail.com

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberjitu10jan23-Feb-13 2:33 
GeneralMy vote of 5 Pinmemberpinkeshpatel95-Mar-11 2:43 
GeneralYour New Stuff Works Well in MVS 2010! Pinmemberpdg7811-Nov-10 9:03 
GeneralRe: Your New Stuff Works Well in MVS 2010! Pinmembersameer_s12-Nov-10 10:24 
GeneralGetting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pinmemberpdg789-Nov-10 8:27 
GeneralRe: Getting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pinmembersameer_s9-Nov-10 22:18 
GeneralRe: Getting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pinmemberpdg7811-Nov-10 8:34 
GeneralYour gridview only binds with your xml resource file Pinmemberpdg788-Nov-10 9:22 
GeneralRe: Your gridview only binds with your xml resource file Pinmembersameer_s8-Nov-10 9:42 
GeneralRe: Your gridview only binds with your xml resource file Pinmemberpdg788-Nov-10 13:59 
GeneralRe: Your gridview only binds with your xml resource file Pinmembersameer_s8-Nov-10 19:24 
GeneralRe: Your gridview only binds with your xml resource file Pinmemberpdg789-Nov-10 4:56 
GeneralRe: Your gridview only binds with your xml resource file Pinmembersameer_s9-Nov-10 22:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 12 Nov 2010
Article Copyright 2010 by sameer_s
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid