Click here to Skip to main content
Licence CPOL
First Posted 19 Dec 2006
Views 75,921
Downloads 1,014
Bookmarked 24 times

Localization (Globalization) of RDLC reports in ASP.NET applications

By Alexander Vologin | 12 Sep 2008
Localization of the RDLC reports in the ASP.NET applications

1
1 vote, 7.7%
2

3
5 votes, 38.5%
4
7 votes, 53.8%
5
4.48/5 - 13 votes
1 removed
μ 4.19, σa 1.55 [?]

Introduction

If you need to display an RDLC report in one of several different languages, you need to create a localized version of the report for each language because RDLC reports do not support localization at the moment. However, that is complex and time-consuming, so it would be useful to localize the RDC reports similar to the way .NET handles localization normally.

Solution

The reports that you create for ReportViewer controls (.RDLC files) are XML files containing the definition of the report, so the procedure of localization doesn't look too difficult:

  1. Load the RDLC file using the Load method of the XMLDocument class.
  2. Go through the nodes of the XML document and localize the value of the Value property of the static elements of the report.
  3. Load the updated RDLC document into the LocalReport object using the LoadReportDefinition method.

To specify a resource key used for localization of the text of static elements, we can use a property named ValueLocID - the localization identifier associated with the Value property. I have not found any information about this property in any of the MSDN documentations or the RDL specification, and looks that this property is not used by the ReportViewer control in any way, so I hope that it is safe enough to use this property to specify a resource key for the localized text. Similarly, we can use the ToolTipLocID and LabelLocID properties for the localization of the ToolTip and Label properties.

Code

private void LocalizeReport(LocalReport report)
{
    // Load RDLC file. 
    XmlDocument doc = new XmlDocument();
    try
    {
        doc.Load(Server.MapPath(ResolveUrl(report.ReportPath)));
    }
    catch (XmlException)
    {
        // TIP: If your web site was published with the updatable option switched off
        // you must copy your reports to the target location manually
        return;
    }
    // Create an XmlNamespaceManager to resolve the default namespace.
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("nm", "http://schemas.microsoft.com/" + 
                       "sqlserver/reporting/2005/01/reportdefinition");
    nsmgr.AddNamespace("rd", "http://schemas.microsoft.com/" + 
                       "SQLServer/reporting/reportdesigner");
    //path to the local resource object
    string resourcePath = Path.Combine(ResolveUrl("."), 
                          Path.GetFileName(report.ReportPath));
    //Go through the nodes of XML document and localize
    //the text of nodes Value, ToolTip, Label. 
    foreach (string nodeName in new String[] { "Value", 
             "ToolTip", "Label" })
    {
        foreach (XmlNode node in doc.DocumentElement.SelectNodes(
                 String.Format("//nm:{0}[@rd:LocID]", nodeName), nsmgr))
        {
            String nodeValue = node.InnerText;
            if (String.IsNullOrEmpty(nodeValue) || !nodeValue.StartsWith("="))
            {
                try
                {
                    String localizedValue = (string)HttpContext.GetLocalResourceObject(
                      resourcePath, node.Attributes["rd:LocID"].Value);
                    if (!String.IsNullOrEmpty(localizedValue))
                    {
                        node.InnerText = localizedValue;
                    }
                }
                catch (InvalidCastException)
                {
                    // if the specified resource is not a String
                }
            }
        }
    }
    report.ReportPath = String.Empty;
    //Load the updated RDLC document into LocalReport object.
    using (StringReader rdlcOutputStream = new StringReader(doc.DocumentElement.OuterXml))
    {
        report.LoadReportDefinition(rdlcOutputStream);
        // TIP: If the loaded report definition contains any
        // subreports, you must call LoadSubreportDefinition
    }
}

An example of using of LocalizeReport function is shown below:

protected void Page_Load(object sender, EventArgs e)
{
    //...
    ReportViewer reportViewer = new ReportViewer();
    reportViewer.LocalReport.ReportPath = "App_Data/Reports/Report.rdlc";
    // you must run the LocalizeReport function before
    // setting parameters or data sources to the report
    LocalizeReport(reportViewer.LocalReport);
    // set parameters
    reportViewer.LocalReport.SetParameters(...);
    // set datasources
    reportViewer.LocalReport.DataSources.Add(...)
    //...
    form1.Controls.Add(reportViewer);
}

Step-by-Step Instructions

res1.JPG

  1. Create the App_LocalResources folder.
  2. Create a resx file named after your report for each language you want to support (e.g., for a report file named Report.rdlc, you would create a Report.rdlc.resx for the default language, and Report.rdlc.es.resx for Spanish). Always have a default language resx file.
  3. Add whatever strings you need to the resx file.
  4. In your RDLC, enter the string names from the resx file as the value of the property of ValueLocID (e.g., for the resource string Hello, set the value of property ValueLocID of textboxHello to Hello).
  5. Call the LocalizeReport function. Note that you must run the LocalizeReport function before setting parameters or data sources to the report; otherwise, it will not work.

References

This article is partly based on the example created by Joe Jone.

License

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

About the Author

Alexander Vologin



United States United States

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 4 Pinmembersamiatcodeproject5:44 22 Nov '11  
GeneralExport to PDF Pinmembersgamage0621:13 25 Apr '11  
GeneralRe: Export to PDF PinmemberAlexander Vologin6:47 3 May '11  
GeneralRe: Export to PDF Pinmembersgamage0621:54 5 May '11  
GeneralError in RDLC report creating! Pinmembersomeonesays1:19 4 Aug '10  
GeneralChart Control PinmemberRodrigo Brandão3:18 16 Nov '09  
GeneralThank you PinmemberMember 201849713:27 30 Oct '09  
GeneralBest Localization Plug-in for Visual Studio. PinmemberAlexander Nesterenko22:36 17 Dec '08  
GeneralSubReport problem Pinmembergalodoido6:06 15 Sep '08  
AnswerRe: SubReport problem Pinmemberczeshirecat9:24 27 May '09  
The following is what I'm using. I'm very new at coding for xml, so it was a struggle working out how to navigate. So I'm sure someone will know how better to search for the node.
I also wasn't able to work out what to do if a sub report had its own subreports (if that's possible).
 
private void ProcessReport(LocalReport report)
{
   // I use an event to process the xml as I might want to
   // change the processing depending on the report
   // and this is a generic report processor.
   if (OnProcessXmlEvent != null)
   {
 
      string nameSpace = GetNamespace(report.ReportEmbeddedResource);
      const string rdlc = ".rdlc";
      string reportName = report.ReportEmbeddedResource;
 
      XmlNamespaceManager manager;
      XmlDocument document = GetDocument(out manager, reportName);
 
      if (document.DocumentElement != null)
      {
         // Call event to process xml
         OnProcessXmlEvent(reportName, document, manager);
 
         report.ReportEmbeddedResource = string.Empty;
         using (StringReader outputStream = new StringReader(document.DocumentElement.OuterXml))
         {
            report.LoadReportDefinition(outputStream);
         }
 
         // Read in each subreport name
         foreach (XmlNode node in
            document.DocumentElement.SelectNodes("/nm:Report/nm:Body/nm:ReportItems/nm:Subreport/nm:ReportName", manager))
         {
            // Process each subreport
            string fullPath = nameSpace + node.InnerText + rdlc;
            XmlNamespaceManager subReportManager;
            XmlDocument subReportDocument = GetDocument(out subReportManager, fullPath);
            if (subReportDocument.DocumentElement != null)
            {
               // Callback to process whatever's needed in the subreport
               OnProcessXmlEvent(fullPath, subReportDocument, subReportManager);
               using (StringReader outputStream = new StringReader(subReportDocument.DocumentElement.OuterXml))
               {
                  report.LoadSubreportDefinition(node.InnerText, outputStream);
               }
            }
         }
 
      } //if (document.DocumentElement != null)
   }
 
}// function
 
// Returns an XLM document for the report
private XmlDocument GetDocument(out XmlNamespaceManager manager, string reportName)
{
   XmlDocument result = new XmlDocument();
   using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(reportName))
   {
      if (stream != null)
      {
         result.Load(stream);
         manager = new XmlNamespaceManager(result.NameTable);
         manager.AddNamespace("nm", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
         manager.AddNamespace("rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
         return result;
      }
      throw new Exception("Stream = null");
   }
}// function
 
// The following is example event handler I use to process one of my reports
private static void OnProcessXml(string reportName, XmlDocument document, XmlNamespaceManager manager)
{
   if (reportName.ToUpper() == C_REPORT_DAILY_SUBREPORT.ToUpper())
   {
      if (document.DocumentElement != null)
      {
         // Make legend invisible in this report
         foreach (XmlNode node in document.DocumentElement.SelectNodes(
            "/nm:Report/nm:Body/nm:ReportItems/nm:List/nm:ReportItems/nm:Chart/nm:Legend/nm:Visible", manager))
         {
            node.InnerText = C_FALSE.ToLower();
         }
         // do localization as in original author's article
         LocaliseDocument(document);
      }
   }
}// function
GeneralRe: SubReport problem Pinmemberandrea_scurci1:47 22 Mar '10  
GeneralPrecompiled web PinmemberMember 41183400:21 11 Sep '08  
GeneralRe: Precompiled web PinmemberAlexander Vologin11:03 11 Sep '08  
GeneralRe: Precompiled web PinmemberMember 411834011:34 11 Sep '08  
GeneralRe: Precompiled web PinmemberAlexander Vologin8:00 12 Sep '08  
GeneralRe: Precompiled web PinmemberMember 41183405:26 15 Sep '08  
GeneralRe: Precompiled web PinmemberAlexander Vologin9:08 22 Sep '08  
GeneralExecution problem : System.InvalidOperationException Pinmemberchabouni4:37 8 Sep '08  
GeneralRe: Execution problem : System.InvalidOperationException PinmemberAlexander Vologin11:01 11 Sep '08  
GeneralRe: Execution problem : System.InvalidOperationException PinmemberAlexander Vologin8:00 12 Sep '08  
GeneralExcellent work, I've used it on a win app project Pinmemberandycted2:07 3 May '08  
GeneralRe: Excellent work, I've used it on a win app project PinmemberAntonio David Gonzalez23:32 13 Nov '08  
GeneralRe: Excellent work, I've used it on a win app project [modified] Pinmemberandycted9:21 14 Nov '08  
GeneralRe: Excellent work, I've used it on a win app project [modified] PinmemberJeffrey Murdock1:48 28 Jun '09  
GeneralRDLC and reporting services PinmemberMember #34838910:05 23 Jan '07  

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.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 12 Sep 2008
Article Copyright 2006 by Alexander Vologin
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid