Click here to Skip to main content
11,577,429 members (57,886 online)
Click here to Skip to main content

Working with Resource Files in ASP.NET Programatically

, 12 Nov 2010 CPOL 27.9K 1K 14
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

You may also be interested in...

Comments and Discussions

 
QuestionGetting problem while update resource file. Pin
sunilgoyani17-Apr-15 1:41
membersunilgoyani17-Apr-15 1:41 
AnswerRe: Getting problem while update resource file. Pin
sameer_s2-Jul-15 17:50
membersameer_s2-Jul-15 17:50 
GeneralMy vote of 5 Pin
jitu10jan23-Feb-13 1:33
memberjitu10jan23-Feb-13 1:33 
GeneralMy vote of 5 Pin
pinkeshpatel95-Mar-11 1:43
memberpinkeshpatel95-Mar-11 1:43 
GeneralYour New Stuff Works Well in MVS 2010! Pin
pdg7811-Nov-10 8:03
memberpdg7811-Nov-10 8:03 
GeneralRe: Your New Stuff Works Well in MVS 2010! Pin
sameer_s12-Nov-10 9:24
membersameer_s12-Nov-10 9:24 
GeneralGetting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pin
pdg789-Nov-10 7:27
memberpdg789-Nov-10 7:27 
GeneralRe: Getting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pin
sameer_s9-Nov-10 21:18
membersameer_s9-Nov-10 21:18 
GeneralRe: Getting this to work with asp.net 2.0, MVS 2010, and reader/writer 4.0.0.0 Pin
pdg7811-Nov-10 7:34
memberpdg7811-Nov-10 7:34 
GeneralYour gridview only binds with your xml resource file Pin
pdg788-Nov-10 8:22
memberpdg788-Nov-10 8:22 
GeneralRe: Your gridview only binds with your xml resource file Pin
sameer_s8-Nov-10 8:42
membersameer_s8-Nov-10 8:42 
GeneralRe: Your gridview only binds with your xml resource file Pin
pdg788-Nov-10 12:59
memberpdg788-Nov-10 12:59 
GeneralRe: Your gridview only binds with your xml resource file Pin
sameer_s8-Nov-10 18:24
membersameer_s8-Nov-10 18:24 
GeneralRe: Your gridview only binds with your xml resource file Pin
pdg789-Nov-10 3:56
memberpdg789-Nov-10 3:56 
GeneralRe: Your gridview only binds with your xml resource file Pin
sameer_s9-Nov-10 21:18
membersameer_s9-Nov-10 21: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.150603.1 | Last Updated 12 Nov 2010
Article Copyright 2010 by sameer_s
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid