Click here to Skip to main content
Email Password   helpLost your password?

Introduction

If you need to display a 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 RDLC file using Load method of XMLDocument class.
  2. Go through the nodes of XML document and localize the value of the property Value of static elements of the report.
  3. Load the updated RDLC document into the LocalReport object using 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 documentation 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 ToolTipLocID and LabelLocID properties for localization of 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 instruction

  1. Create 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 language). 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 value of property of ValueLocID (e.g. for 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.
res1.JPG

References

This article is partly based on the example created by Joe Jone.  
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralChart Control
Rodrigo Brandão
3:18 16 Nov '09  
What about chart control? it doesnt have LocID for Legend.

tks
Rodrigo
GeneralThank you
Member 2018497
13:27 30 Oct '09  
Good solution for WinForm application, thanx !
GeneralBest Localization Plug-in for Visual Studio.
Alexander Nesterenko
22:36 17 Dec '08  
Move strings from code to resx and translate their automatically. Try RGreatEx[^] free.

---
Best regards,
Alexander Nesterenko
Safe Develop Team
www.safedevelop.com

GeneralSubReport problem
galodoido
6:06 15 Sep '08  
Hello, do you help me ? I Have a problem.

I have a subreport in my localreport. But in the method LocalizeReport, after the command report.LoadReportDefinition
i'm call the method LoadSubreportDefinition however my subreport isn't globalized.

Each subreport have your resource.

I need globalization eache subreport of mey report contains.

thanks
AnswerRe: SubReport problem
czeshirecat
9: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
GeneralPrecompiled web
Member 4118340
0:21 11 Sep '08  
Hello when the web is precompiled the function fails, does not find the file with extension .rcp D'Oh!

Ideas? Thank you
GeneralRe: Precompiled web
Alexander Vologin
11:03 11 Sep '08  
I precomilied the web and didn't get any rcp file. What version of Visual Studio do you use?
GeneralRe: Precompiled web
Member 4118340
11:34 11 Sep '08  
Visual Studio 2005, Framework 2.0
GeneralRe: Precompiled web
Alexander Vologin
8:00 12 Sep '08  
Thanks,
I’ve made some changes in the code – I moved report’s resource files under App_LocalResources folder. Please try new version.
GeneralRe: Precompiled web
Member 4118340
5:26 15 Sep '08  
I believe that it is not a problem of the code, the problem this one in the precompiled Cry

If Precompiled your example, it continues failing. It works if I copy the original file .rcp to the capeta App_Data
GeneralRe: Precompiled web
Alexander Vologin
9:08 22 Sep '08  
Would you please send me your precompiled example?
GeneralExecution problem : System.InvalidOperationException
chabouni
4:37 8 Sep '08  
Hello, i tried to use the source code, but i had an execution exception at this line :

String localizedValue = (string)HttpContext.GetLocalResourceObject(virtReportPath, node.Attributes["rd:LocID"].Value);


"La classe de la ressource correspondant à cette page est introuvable. Vérifiez si le fichier de ressources existe et réessayez".

// System.InvalidOperationException:
// The resource class for the page was not found.




I tried in vain to resolve it so please i need your help.
Thank u.
GeneralRe: Execution problem : System.InvalidOperationException
Alexander Vologin
11:01 11 Sep '08  
Did you create a resource file for the report?
GeneralRe: Execution problem : System.InvalidOperationException
Alexander Vologin
8:00 12 Sep '08  
I’ve made some changes in the code – I moved report’s resource files under App_LocalResources folder. Please try new version.
GeneralExcellent work, I've used it on a win app project
andycted
2:07 3 May '08  
By modifying a couple of lines I've managed to use the same idea in windows applications in a ReportViewer:

- Load the report xml by doing something like this
Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream( report.ReportEmbeddedResource);
doc.Load(str);
str.Close();

- get your localized strings by ResourcesFile.ResourceManager.GetString(...

- and I don't know why but loading the report from a StringReader didn't work for me, so I did this:
File.WriteAllText(tempFile, doc.DocumentElement.OuterXml);
reportViewer1.LocalReport.ReportPath = tempFile;
and after Refreshing the reportviewer deleting the temporary file

Any idea why loading from the StringReader didn't work ?

Andrea Sabbatini
Sviluppo software - Software development
www.andreasabbatini.com
www.doctorsoffice.it

GeneralRe: Excellent work, I've used it on a win app project
Antonio David Gonzalez
23:32 13 Nov '08  
I tried your modification. In my case the StringReader didn't work because the Report's ReportEmbeddesResource had the name of the report.

Changing the line:

lr.ReportPath = String.Empty

to:

lr.ReportEmbeddedResource = String.Empty

worked for me.

Is this your case?
GeneralRe: Excellent work, I've used it on a win app project [modified]
andycted
9:21 14 Nov '08  
[EDIT][AGAIN] (sorry)

I've just found out that:
1) your method works like a charm. Thanks a lot !

2) for some reason ALL the ValueLocID, LabelLocID, etc have been lost by the project. This dodgy behaviour of visual studio has been going on for some time. Besides every time I open the project and immediately shut it down, it asks to save 'modifications' (what ?)

Ciao
Andy

Andrea Sabbatini
Sviluppo software - Software development
www.andreasabbatini.com
www.doctorsoffice.it

modified on Friday, November 14, 2008 2:43 PM

GeneralRe: Excellent work, I've used it on a win app project [modified]
Jeffrey Murdock
1:48 28 Jun '09  
wtf is the problem with ResourceManager.GetString ????

my culture info is en-GB and the ResourceManager returns a german string for the report!
btw: using of resources without ResourceManager (e.g. for Ribbon) works very good.
and yes, the Resource files are translated (means en-GB contains an english string).

has anybody this problem ????ConfusedUnsure WTF



edit: solution -> GetString(String, CultureInfo)

modified on Sunday, June 28, 2009 3:13 PM

GeneralRDLC and reporting services
0:05 23 Jan '07  
Hi,

I would like to the same think with reporting services.
When user is connecting on the portail web. I don't want to create a web application on dot.net.
Have you go a solution for me.
Thank.

Nadège BAUBANT (French)

GeneralRe: RDLC and reporting services
Alexander Vologin
7:47 23 Jan '07  
Hi Nadège,

Frankly speaking I don't work with MS SQL Report Service. I wrote this article because my friend asked me to help her to find an approach to "dynamic" report localization and I didn't find the solution in the internet.

As I know MS does not provide "dynamic" report localization (http://blogs.msdn.com/jacobcy/archive/2004/05/26/142618.aspx[^]) but I have found an article where described how to implement this: http://msdn2.microsoft.com/en-us/library/aa964130.aspx[^]. You can download an example from http://www.teamscs.com/downloads%5CReporting%20Services%20Book%20Excerpt%20-%20Brian%20Larson.zip[^]

Hope it helps.


Last Updated 12 Sep 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010