Tuesday, March 13, 2012

C# parser for RDL files when using with ReportViewer control

The ASP.NET ReportViewer webcontrol is intended to be used with an RDLC file, which is a stripped down version of an RDL file. RDL files are for using with SSRS reporting services -- that is, where you keep the report on a SQL Server hosted website and can run the reports right there on the website. But if you want to embed an SSRS report into your ASP.NET application (I am doing in a few MVC applications, which is tricky too, but I never posted a blog entry about how to do it), anyway, if you want to include an SSRS report in your application, you use the ReportViewer control and when it loads you basically forcefeed it your connection and your parameters and all that. Well, that annoys me, since the RDL files already have the connection strings and parameters in them, it seems to me like you should be able to just use what's embedded in the report, so I'm working on building my own dynamic report viewer. The first step is to parse the report and get the connection string and parameters out of it. In order to efficiently transfer the parameters and the connection string as a unit, I made two classes. One holds parameter info, the other holds connection string info PLUS a collection of parameters.





//Parameter Class
public class rptParam
{
public String ParameterName { get; set; }
public String Datatype { get; set; }
public String Prompt { get; set; }
}

//Report Attributes Class
public class rptAttributes
{
public List Parameters { get; set; }
public String DataSourceName { get; set; }
public String CommandText { get; set; }
}



Then you can use this code wherever you want, it's uncommented, my apologies, but it's pretty straightforward anyway:

private rptAttributes ReadFile(string filename)
{
rptAttributes rptAtt = new rptAttributes();
List l = new List();

// Create an XmlReader
using (XmlReader reader = XmlTextReader.Create(filename))
{
reader.ReadToFollowing("DataSourceName");
rptAtt.DataSourceName = "DataSourceName: " + reader.ReadElementContentAsString();

reader.ReadToFollowing("CommandText");
rptAtt.CommandText="CommandText: " + reader.ReadElementContentAsString();

string temp = "";
reader.ReadToFollowing("ReportParameter");
reader.MoveToAttribute("Name");
temp = reader.Value;
reader.ReadToFollowing("DataType");
if (reader.NodeType != XmlNodeType.None)
{
rptParam rp = new rptParam();
rp.ParameterName = temp;
rp.Datatype = reader.ReadElementContentAsString();
reader.ReadToFollowing("Prompt");
rp.Prompt = reader.ReadElementContentAsString();
l.Add(rp);
}

rptAtt.Parameters = l;

}

return rptAtt;
}

3 comments:

fatih said...

Thank u very much.it was very helpful ...

fatih said...

hi usarian,i have a little problem.i created xmlreader object,and i can read dataset name,datasource... but i cant read reportparameter name in this way.i need help,please help me

Nathan Griffiths said...

Fantastic! Just what I was looking for, thanks!