Generate and Design Rdlc file programmatically - c#

I'm doing mvc reporting and i'm very new at it. I'm trying to create a report, and i have done it using rdlc. Everything works well, it can be exported to various format. My problem, when using rdlc is that we need to design and bind it first. How can i create an empty rdlc template, design and bind it with dataset programmatically.
My work so far (using empty rdlc template - just created the file without any table),
Controller File,
public ActionResult Report(string id)
{
DB.Open();
LocalReport lr1 = new LocalReport();
string path1 = Path.Combine(Server.MapPath("~/Report"), "TestEmptyReport.rdlc");
lr1.ReportPath = path1;
DataTable pc2a = new DataTable();
pc2a = DB.getDataSet().Tables[0];
pc2a.Columns.Add("Product Name");
pc2a.Columns.Add("Price");
pc2a.Columns.Add("Quantity");
ReportDataSource rdc = new ReportDataSource("DataSet1", pc2a);
lr1.DataSources.Add(rdc);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
"<OutputFormat>" + id + "</OutputFormat>" +
"<PageWidth>8.5in</PageWidth>" +
"<PageHeight>11in</PageHeight>" +
"<MarginTop>0.5in</MarginTop>" +
"<MarginLeft>1in</MarginLeft>" +
"<MarginRight>1in</MarginRight>" +
"<MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr1.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
Model File,
public DataSet getDataSet()
{
string query = "SELECT * FROM tblproduct";
if (con.State.ToString() == "Open")
{
SqlDataAdapter ad = new SqlDataAdapter(query, con);
DataSet ds = new DataSet("tblproduct");
ad.Fill(ds);
return ds;
}
else
{
return null;
}
}
View File,
<div style="padding: 10px; border: 1px solid black">
<div>Get PDF Report</div>
<div>Get Excel Report</div>
<div>Get Word Report</div>
<div>Get Image Report</div>
The data is there, but i just dont know how to connect it with rdlc. Means creating column based on the data and fill it with the data called from sql server.
TQVM in advanced. Explanation and example or any other method will be helpful.

If I understand your question correctly you wanted to create a report from a blank RDLC. You have to tell a RDLC file about the data in the design time. You can customize the report in the design time by adding columns or columns from another table or make a join.
Whereas Dynamic RDLC Generator through C# would be there to generate the report dynamically from RDLC. Since the complete ReportingEngine has been custom made but very generic. Copy paste might be going to help generating the report.

Your question implies that you need to generate RDLC report on runtime mode. Things you should remember to:
RDLC report viewer uses Microsoft.ReportViewer.WebForms and Microsoft.Reporting.WebForms namespaces, which utilizing WebForms logic code to bind and render the report. You can use a partial view which acts as container for ASPX page (either using single page or page with code behind) to render the report in MVC view pages.
NB: You can use ReportViewer instance in controller action method to render RDLC as PDF file and returning FileContentResult (see here).
RDLC contains XML tags which can be generated from various XML builder classes (see MSDN Report Definition for details).
Hence, you may create ReportViewer instance first, e.g.:
using Microsoft.Reporting.WebForms;
protected void Form_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report.rdlc");
// add your DataSet here
var data = new DataTable(); // example data source
var dataSource = new ReportDataSource(DataSetName, data);
ReportViewer1.LocalReport.DataSources.Add(dataSource);
// put rendering stuff here
}
}
Then, use steps from Generating RDLC Dynamically for the Report Viewer Local Report example (WebForms is similar to WinForms in terms of event handling usage, thus may be applicable in ASPX page) to create corresponding XML tags which generates report structure, summarized as below.
Create and add DataSet for usage in DataSources element.
Create report body and report items element.
Create Tablix and TablixCorner elements according to table structure inside DataSet.
Create TablixColumn, TablixRow and TablixCell elements which includes Textbox control depending to each column data types. The Value element inside Textbox control should contain expression =Fields!(ColumnName).Value for database-bound columns.
Create report property elements (dataset query, fields, etc.)
Add LoadReportDefinition into ASPX page after all report elements generated properly.
Alternatively, if you already know entire RDLC element structure, the similar solution using XmlWriter class can generate required elements for building the report from scratch, then rename generated XML to RDLC extension and bind it for ReportViewer control (seems takes some time to build each RDLC elements).
Additional references:
Rendering an RDLC report in HTML in ASP.NET MVC
Dynamic Reports with Reporting Services

Related

How to display images in Crystal Report that are retrieved as blob's from mysql?

Currently we are saving images in our database as blob's they have been resized to be much smaller to not take up all to much space. We need to display a image on the Crystal Report Viewer (Crystal Report Viewer 13) and I retrieve this from the MYSQL database and convert it to a byte[] and my dataset has a column System.Byte[], but the Crystal Report Viewer still shows nothing. I haven't found a solution yet.
I've tried using OLE objects but with no success, and tried linking a picture to the dataset column but no success.
The results I keep getting is blank fields. Also tried to see if it shows up when I export it to PDF but shows up blank there as well. The result should be the image that is stored in the database
This is how i retrieve the blob from the MYSQL database
clsDataAccess getData = new clsDataAccess(System.Configuration.ConfigurationManager.ConnectionStrings["PAW.Data"].ConnectionString);
getData.SQLCommand.CommandText = "SELECT * from userimages where UserName = ?";
getData.SQLCommand.Parameters.Add("", OdbcType.VarChar).Value = UserName;
System.Data.DataTable tblData = getData.PopulateDataTableWithParameters();
if (tblData.Rows.Count > 0)
{
foreach (System.Data.DataRow item in tblData.Rows)
{
userImage.Name = item["Name"].ToString();
userImage.ContentType = item["Content"].ToString();
object LogoTest = item["Data"];
userImage.Data = (byte[])item["Data"];
}
}
When I inspect the image I get this in the console
http://localhost:31720/Areas/Administration/ReportsASPX/CrystalImageHandler.aspx?dynamicimage=cr_tmp_image_14fda631-5f94-4fa2-8419-f95f447fe08b.png
I'm not aware of any way of access blob storage from inside mysql. I do however has a possible work around.
Why not store an id for the image in the database. Ensure the blob container has read public access. Inside of the report you could then have a link like "https://myblob.blob.azure.net/container/{id}", then just replace the {id} with the id retrieved from the database?

c# how to filter stimulsoft report programatically?

I am working on a c# project. I used stimulsoft to create and show report in my project.
I design my report in stimulsoft software and save my report file in ...\bin\debug\reports path.
this is my report design :
enter image description here
this report shows system users.
Now, i want to filter my report in c#. how can i send formul to filter my report result?
this is my code to show report:
StiReport report = new StiReport();
report.Load(System.AppDomain.CurrentDomain.BaseDirectory + "\\reports\\userinfo.mrt");
report.Show();
This example is partially taken from their file Stimulsoft_NET_FAQ.pdf
First you create a parameter in the query used to extract data from the datasource
SELECT * from Users WHERE userID = #userID
then you pass this parameter before calling Show
StiReport report = new StiReport();
report.Load(.... your file....));
report.Dictionary.Databases.Clear();
StiSqlDatabase db = new StiSqlDatabase("the_name_of_datasource", "the connection string");
report.Dictionary.Databases.Add(db);
report.CacheAllData = true;
report.Dictionary.Synchronize();
report.Compile();
// Finally set the parameter
report["#userID"] = 1; // <= value to search for....
report.Show(true);
This example is for an Sql Server Database backend. If you have a different database engine then please use one of the various StiXXXXXXDatabase classes available

Chinese character cannot be read export to pdf from crystal report (parameter)

I am using crystal report viewer to print and export the report to pdf file. I realized when printing chinese character, it will show a box instead of the word it self.
The code is how I assign the data to the parameter in crystal report.
ReportDocument reportData = new ReportDocument();
string reportPath = Server.MapPath("IncidentReport.rpt");
reportData.Load(reportPath);
//get data from database
string sqlcommand = "SELECT TICKETNO, TO_CHAR(REPORTDATE,'dd-mm-yyyy HH:MM') AS REPORTDATE, STATUS, SEVERITY,CATEGORY,ASSIGNEE,INCIDENTDESC,INCIDENTDETAIL,INCIDENTTYPE,ANALYSIS,SOLUTION,ATTACHMENT,TO_CHAR(CREATEDATE,'dd-mm-yyyy') AS CREATEDATE,CREATEUSERID,TO_CHAR(UPDATEDATE,'dd-mm-yyyy') AS UPDATEDATE, UPDATEUSERID FROM TICKET WHERE TICKETNO = '" + Session["ticketNoR"] + "' ";
DataSet ds = new DataSet();
readdata.selectdata(ds, sqlcommand);
//set parameter
reportData.SetParameterValue("ticketNo", (String)Session["ticketNoR"]);
reportData.SetParameterValue("reportedDate", ds.Tables[0].Rows[0]["REPORTDATE"].ToString());
reportData.SetParameterValue("Status", ds.Tables[0].Rows[0]["STATUS"].ToString());
reportData.SetParameterValue("severity", ds.Tables[0].Rows[0]["SEVERITY"].ToString());
reportData.SetParameterValue("category", ds.Tables[0].Rows[0]["CATEGORY"].ToString());
reportData.SetParameterValue("assignee", ds.Tables[0].Rows[0]["ASSIGNEE"].ToString());
reportData.SetParameterValue("attachment", ds.Tables[0].Rows[0]["ATTACHMENT"].ToString());
reportData.SetParameterValue("type", ds.Tables[0].Rows[0]["INCIDENTTYPE"].ToString());
reportData.SetParameterValue("incidentDesc", ds.Tables[0].Rows[0]["INCIDENTDESC"].ToString());
reportData.SetParameterValue("incidentDetail", ds.Tables[0].Rows[0]["INCIDENTDETAILS"].ToString());
reportData.SetParameterValue("Analysis", ds.Tables[0].Rows[0]["ANALYSIS"].ToString());
reportData.SetParameterValue("Solution", ds.Tables[0].Rows[0]["SOLUTION"].ToString());
I am using oracle 11g as database and asp.net C# for coding.
Everything looks good in browser but when export to pdf file then it become none-readable character already. ( only parameter that i use C# to pass the value to it cannot show chinese. text object are shown pretty good.
English characters are well display but for chinese character is not working.
Anyone have any idea on this?
Your comment and suggestion is much appreciated!

Make A4 reports with background image in C# (like Jasper Reports and iReport)

I just want to put some values from my database on an A4 page (I have a JPG template)
and create a PDF book/report with an insert per page.
I have easily done it with NetBeans Java Jasper Reports using iReport editor.
It seems so much more difficult in Visual Studio C# Crystal Reports.
I've really searched for tutorials for Crystal Reports and none of them
is using an A4 image as a template. Please help me if you know any such tutorials.
I prefer a solution which works programmatically and not through a wizard.
I already manage my database with my program. I just need the report and some
documentation of how to give input values to the report. I don't even
need for the report to access the database. I can get all the values in my
program. The best solution for me is a template with my JPG file as background
and boxes (like textboxes) where I give text from my program through parameters
of a function. Like Jasper Reports / iReport.
OK, I spend some time to find an easy solution and I got the following:
First of all I didn't use Crystal Reports, but Windows Reports (rdlc files).
Windows Reports are more simple and easy and it is possible to add an image as a background
and above this image some TextBoxes that refer to String parameters (exactly what I needed). They are in Visual Studio by default and you design your report in Visual Studio (right click in Solution Explorer --> Add Report)
Then I found a code sample which converts the report to PDF files and I used it to write the following Class:
public class XReport
{
private ReportViewer reportViewer = new ReportViewer();
public XReport()
{
}
public XReport(String reportFilePath)
{
setReportFile(reportFilePath);
}
// set rdlc file
public void setReportFile(String reportFilePath)
{
reportViewer.Reset();
reportViewer.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local;
reportViewer.LocalReport.ReportPath = reportFilePath;
}
public void setParameters(List<ReportParameter> parameters)
{
reportViewer.LocalReport.SetParameters(parameters.ToArray());
reportViewer.LocalReport.Refresh();
}
public void setParameters(Dictionary<String, String> parameters)
{
XList<ReportParameter> parameterList = new List<ReportParameter>();
XList<String> parameterKeys = parameters.getKeys();
foreach (String parameterKey in parameterKeys) {
parameterList.Add(new ReportParameter(parameterKey, parameters.get(parameterKey))); }
setParameters(parameterList);
}
public void exportToPDF(String pdfFilePath)
{
Warning[] warnings;
string[] streamids;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
byte[] bytes = null;
// render PDF file
try { bytes = reportViewer.LocalReport.Render( "PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings); }
catch (Exception ex) { System.Console.Write(ex.Message); }
// write PDF file
using (FileStream fs = new FileStream(pdfFilePath, FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); fs.Close(); }
// release reportViewer resources to avoid errors
reportViewer.LocalReport.ReleaseSandboxAppDomain();
}
}
It works. Try it. Be careful with 2 things:
Use correct paths for reportFilePath and pdfFilePath. (pdfFilePath worked only with non-relative path for me)
Make sure that you have added all parameters with their correct names in your rdlc report. You can add them at View --> Report Data --> Add New Parameter (right click at Parameters). Also see this: Create a parameter in rdlc report
Hope I helped. It worked for me great.
You can set the paper size of the report using the below mentioned option in Crystal itself.
Open the report first and then go to
File -> Page Setup

Excel Report Setting page setup options in C#

I am using the following approach to create a dynamic Excel Report from HTML in my ASP.NET Application.
While creating the excel report, I want to set the Page Setup options such that the report fits into one page.
This is the approach I'm using to create the excel report...
Please tell me how to fit this report to one page or to zoom in the report?
string sContentType = "application/vnd.excel";
string sFileName = "Detail Qutation.xls";
Hashtable oData = new Hashtable();
oData.Add("Content-Disposition", "attachment;filename=" + sFileName);
oData.Add("Charset", "");
oData.Add("ContentType", sContentType);
oData.Add("Content", sTable.ToString());
oData.Add("IsBinaryContent", false);
this.StoreObject("Document", oData);
You might need to render using htmltextwriter as explained in
http://forums.asp.net/p/1063850/1538066.aspx#1538066
and take the concept to get a solution.

Categories

Resources