Getting Values from web.config file to rdlc report? - c#

How to get the values from web.config (appsettings) file to my rdlc report?
I need to show multiple values in my rdlc invoice where they are coming from web.config file? How can I get on this one?
<add key="siteName" value="desktopapplications" />
<add key="companyName" value="ProSoftware Limited" />
where can I write the code in rdlc and how to implement the above values?
I know how to get the values from web.config to .cs page
string siteName= WebConfigurationManager.AppSettings["siteName"]
How it works in rdlc? Any help thanks

In the RDLC designer in the Report Data panel, add parameters for siteName and companyName. In the code behind:
Dim myReport As New LocalReport
Dim params() As ReportParameter = New ReportParameter(1) {}
params(0) = New ReportParameter("siteName", siteName)
params(1) = New ReportParameter("companyName", companyName)
With myReport
.ReportPath = ReportPath '"MyReport.rdlc"
.DataSources.Clear()
.DataSources.Add(mydatasource)
.Refresh()
.SetParameters(params)
End With

From Lon Prosser Answer
using (var lr = new LocalReport())
{
var path = Path.Combine(HttpRuntime.AppDomainAppPath, "Report", "MyInvoice.rdlc");
lr.ReportPath = path;
var siteName = ConfigurationManager.AppSettings["siteName"];
var companyName = ConfigurationManager.AppSettings["companyName"];
var #params = new ReportParameter[2];
#params[0] = new ReportParameter("siteName", siteName);
#params[1] = new ReportParameter("companyName",companyName);
var usersinv = db.Invoices.Where(i => i.Id == invoiceid.Id);
var invoice = usersinv.SingleOrDefault();
if (invoice != null)
{
var invoiceitems = db.InvoiceItems.Where(i => i.InvoiceId == invoiceid.Id);
var rd1 = new ReportDataSource("Invoice", usersinv);
var rd2 = new ReportDataSource("InvoiceItems", invoiceitems.ToList());
lr.DataSources.Add(rd1);
lr.DataSources.Add(rd2);
lr.SetParameters(#params);
}
string encoding;
string fileNameExtention;
const string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>21cm</PageWidth>" +
" <PageHeight>29.7cm</PageHeight>" +
" <MarginTop>0.0cm</MarginTop>" +
" <MarginLeft>0.0cm</MarginLeft>" +
" <MarginRight>0.0cm</MarginRight>" +
" <MarginBottom>0.0cm</MarginBottom>" +
"</DeviceInfo>";
Microsoft.Reporting.WebForms.Warning[] warnings;
string[] streams;
renderedBytes = lr.Render("PDF",
deviceInfo,
out mimeType,
out encoding,
out fileNameExtention,
out streams,
out warnings);
}
return File(renderedBytes, mimeType);
Now, the parameters in the PDF invoice will be invoked by web.config file

Related

Change datasource using bartender dynamically using c#

I'm populating fields data from database with bartender but I'm not able to do same while changing database from code,
e.g. There is a template called TestLBL.btw and in the template we have configured database field say TestDB.Name field now I've another database say TestDB2 and that have exact same fields as TestDB now I just wanted to print label with same field with different database(TestDB2) using c# code but that doesn't works :(
below is my sample code :
btnEngine = new Engine();
btnEngine.Start();
lblDoc = btnEngine.Documents.Open(ConfigurationManager.AppSettings["BarTenderTemplate_Path"] + templateName);
var msg = new Messages();
var resolution = new Resolution(300);
string connectString = ConfigurationManager.ConnectionStrings["TestDB2"].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
lblDoc.DatabaseConnections[0].Name = builder.InitialCatalog;
lblDoc.DatabaseConnections[0].Server = builder.DataSource;
lblDoc.DatabaseConnections[0].UserID = builder.UserID;
lblDoc.DatabaseConnections[0].SetPassword(builder.Password);
lblDoc.DatabaseConnections.SetDatabaseConnection(lblDoc.DatabaseConnections[0]);
lblDoc.DatabaseConnections.QueryPrompts["pRec_Key"].Value = Rec_key.ToString();
lblDoc.DatabaseConnections.QueryPrompts["pImage_Path"].Value = Image_Path;
var fileName = templateName.Split('.')[0] + "_" + Rec_key.ToString() + ".pdf";
var fileFullPath = Path.GetDirectoryName(ConfigurationManager.AppSettings["BarTenderTemplate_Path"]) + "\\" + templateName.Split('.')[0] + "_" + Rec_key.ToString() + ".pdf";
var result = lblDoc.ExportPrintPreviewToFile(Path.GetDirectoryName(ConfigurationManager.AppSettings["BarTenderTemplate_Path"]), fileName, ImageType.PDF
, ColorDepth.ColorDepth24bit, resolution, Color.White, OverwriteOptions.Overwrite, true, true, out msg);
lblDoc.Close(SaveOptions.SaveChanges);
It throws an error in below line, without any inner exception,
var result = lblDoc.ExportPrintPreviewToFile(Path.GetDirectoryName(ConfigurationManager.AppSettings["BarTenderTemplate_Path"]), fileName, ImageType.PDF
, ColorDepth.ColorDepth24bit, resolution, Color.White, OverwriteOptions.Overwrite, true, true, out msg);
Any help would be appreciated.!
I could not comment the post so i'll ask my question here:
What is the error message in this line?
var result =
lblDoc.ExportPrintPreviewToFile(
Path.GetDirectoryName(ConfigurationManager.AppSettings["BarTenderTemplate_Path"]),
fileName,
ImageType.PDF,
ColorDepth.ColorDepth24bit,
resolution,
Color.White,
OverwriteOptions.Overwrite, true, true, out msg);
Did you set up TestDB2 in your BTW file database?
string connectString = ConfigurationManager.ConnectionStrings["TestDB2"].ConnectionString;
Did your fileName valid?
var fileName = templateName.Split('.')[0] + "_" + Rec_key.ToString() + ".pdf";

what is the solution for Crystal Report Filter option in C#

i'm using asp.net/c# with crystal report to export as PDF format, it is exporting Pdf fine. but we refereed the DB Table to Crystal Report so it is binding all data's to report not filter by parameter or select Formula model.
Here is My Code:
ReportDocument myreportdocument = new ReportDocument();
DataSet dsReport = new DataSet();
clsiCMSBLBase omenu = new clsiCMSBLBase();
string errMsg = string.Empty;
dsReport = omenu.GetListData(ref errMsg, parameters, "DBSP_PCPrintSlipRDLC");
myreportdocument = ReportFactory.GetReport(myreportdocument.GetType());
myreportdocument.Load(Server.MapPath("~/CrysReports/PCPrintSlipPUD.rpt"));
myreportdocument.SetParameterValue("UserID", Convert.ToInt32(2));
myreportdocument.SetDataSource(dsReport);
string dbUserName = ConfigurationManager.AppSettings["CrystalUserName"];
string dbPassword = ConfigurationManager.AppSettings["CrystalPassword"];
myreportdocument.SetDatabaseLogon(dbUserName, dbPassword);
cRY1.ReportSource = myreportdocument;
cRY1.SelectionFormula = " {TMP_PlotPCSlip.UserID} =" + 2;
cRY1.ReportSource = myreportdocument;
cRY1.HasCrystalLogo = false;
cRY1.DataBind();
cRY1.RefreshReport();
cRY1.BorderColor = System.Drawing.Color.Gray;
cRY1.BorderWidth = 1;
cRY1.BackColor = System.Drawing.Color.White;
cRY1.Style.Add("width", "100%");
//string filename = fact + "_" + flag + "_" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm") + ".pdf";
myreportdocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, filename);
Response.End();
this Filter Code not filtering:
myreportdocument.SetParameterValue("UserID", Convert.ToInt32(2));
even i tried TableName.UserID but there is also not filter, so please share your experience..
Myreportdocument.RecordSelectionFormula="{table.column}=2"

Affecting Specific Records Within Crystal Report

I have a Function that, when activated, iterates through the Crystal Report it is attached to, copies it to a pdf, then mails the entirety of it to a client once per identifying field.
They want to receive a pdf of records grouped by ID, for each ID in the Report, omitting some of a specific ID. I have no idea how to break the Report down into smaller Reports, though, or even where to begin if that's possible in the first place.
I am Creating Each Pdf for individual user and saving to my Google Driver also emailing using SendGrip Api.
I have used this code inside page.Aspx -> aspx.cs file.
//0. Here i am getting list users as an Object:
OpsManagementController OM = new OpsManagementController();
//1. Getting Users List:
var result = OM.UsersGetforInvoice();
//2. Creating folder for Invoices:
string folderName = #"D:\Google Drive\MonthlyInvoices";
string fileName = ("Invoices_" + DateTime.Now.ToString("yyyy-MM-dd").ToString());
string pathString = System.IO.Path.Combine(folderName, fileName);
System.IO.Directory.CreateDirectory(pathString);
string folderNameEmail = #"D:\Google Drive\MonthlyInvoices\Email";
string fileNameEmail = ("Invoices_" + DateTime.Now.ToString("yyyy-MM-dd").ToString());
string pathStringEmail = System.IO.Path.Combine(folderNameEmail, fileNameEmail);
System.IO.Directory.CreateDirectory(pathStringEmail);
//3. Generating invoices by user name:
for (int i = 0; i < result.UserDetail.Count; i++)
{
var userId = result.UserDetail[i].UserID;
var userEmail = result.UserDetail[i].Email;
var userName = result.UserDetail[i].FullName;
userName = userName.Replace(#"C\O", "CO");
userName = userName.Replace(#"C/O", "CO");
// Directories for reports:
var invoicePath = "D:/Google Drive/MonthlyInvoices/" + fileName + "/" + userId + " " + userName + ".pdf";
var invoicePath_email = "D:/Google Drive/MonthlyInvoices/Email/" + fileNameEmail + "/" + userId + " " + userName + ".pdf";
report2.SetParameterValue("UserID", result.UserDetail[i].UserID);
report2.ExportToDisk(ExportFormatType.PortableDocFormat, invoicePath);
// using sendgrip Api :
EmailUtils.SendEmail_Att(
new string[] { userEmail }, //TO : userEmail
new string[] { "email#gmail.com" }, //
invoiceSubject,
invoiceBody,
invoicePath_email
);
}

The place for the first record is empty in RDLC report

I have made a 2-column report that is like this :
Name1----------------------------Name3
Address1-------------------------Address3
Name2----------------------------Name4
Address2-------------------------Address4
But suddenly it started to give reports like this :
----------------------------Name3
-------------------------Address3
Name1----------------------------Name4
Address1-------------------------Address4
Name2
Address2
Here is my code :
public ActionResult Report()
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "Person.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<Person> cm = new List<Person>();
var viewModel = new PersonIndexData();
viewModel.People = db.Person
.Include(k => k.Groups)
.OrderBy(k => k.Name);
cm = viewModel.People.ToList();
ReportDataSource rd = new ReportDataSource("DataSet1", cm);
lr.DataSources.Add(rd);
string reportType = "pdf";
string mimeType = string.Empty;
string encoding = string.Empty;
string fileNameExtension = string.Empty;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>pdf</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>12in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.2in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
"pdf",
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
Namely the place for the first record is empty. Why do you think it happened and how I can get rid of it? I changed column spacing and margins but it didn't work. Thanks.
You cannot fetch the first column value from a table. That's the reason it cannot display the first column value.

Data retrieval failed for the subreport RDLC

I have the following code:
private void CreateExcel(string fileName)
{
var operationDate = System.DateTime.ParseExact(txtStartDate.Text, "dd/MMM/yyyy", CultureInfo.CurrentCulture);
var ds1 = new _spAvailabilityEventDailyReport1TableAdapter();
var ds2 = new _spAvailabilityEventDailyReport2TableAdapter();
var ds3 = new _spAvailabilityEventDailyReport3TableAdapter();
var ds4 = new _spAvailabilityEventTotalTableAdapter();
var ds5 = new _spAvailabilityNoteDailyReportTableAdapter();
var ds6 = new _spAvailabilityDailyReportTableAdapter();
var ds7 = new _spAvailabilityReadingTotalTableAdapter();
var ds8 = new _spAvailabilityEventSum1TableAdapter();
var ds9 = new _spAvailabilityEventSum2TableAdapter();
var ds10 = new _spAvailabilityEventSum3TableAdapter();
//default margin setting
string outputType = "Excel";
string pageHeight = "11.69in";
string pageWidth = "8.27in";
string marginTop = "0.3937in";
string marginBottom = "0.3937in";
string marginLeft = "0.3937in";
string marginRight = "0.3937in";
string reportPath = Server.MapPath("~/rdlc/dailyavailability.rdlc");
try
{
//search setting margin report & kind output export -> for parameter 2nd render RDLC
var xml = System.IO.File.ReadAllText(reportPath);
var matches = Regex.Matches(xml, #"<(?<property>PageHeight|PageWidth|TopMargin|BottomMargin|LeftMargin|RightMargin)>(?<value>[^<]+)</\k<property>>", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (!match.Success)
continue;
switch (match.Groups["property"].Value)
{
case "PageHeight":
pageHeight = match.Groups["value"].Value;
break;
case "PageWidth":
pageWidth = match.Groups["value"].Value;
break;
case "TopMargin":
marginTop = match.Groups["value"].Value;
break;
case "BottomMargin":
marginBottom = match.Groups["value"].Value;
break;
case "LeftMargin":
marginLeft = match.Groups["value"].Value;
break;
case "RightMargin":
marginRight = match.Groups["value"].Value;
break;
}
}
}
catch (System.Exception) { }
string reportType = string.IsNullOrEmpty(outputType) ? "Excel" : outputType.Trim().ToUpper();
string encoding;
string deviceInfo = string.Format(#"<DeviceInfo>
<OutputFormat>{6}</OutputFormat>
<PageWidth>{0}</PageWidth>
<PageHeight>{1}</PageHeight>
<MarginTop>{2}</MarginTop>
<MarginLeft>{3}</MarginLeft>
<MarginBottom>{4}</MarginBottom>
<MarginRight>{5}</MarginRight>
</DeviceInfo>", pageWidth, pageHeight, marginTop, marginLeft, marginBottom, marginRight, reportType);
var rds = new ReportDataSource("dsAvailabilityEventDailyReport1", (DataTable)ds1.GetData(operationDate)); //fill data report in parameter
var rds2 = new ReportDataSource("dsAvailabilityEventDailyReport2", (DataTable)ds2.GetData(operationDate)); //fill data report in parameter
var rds3 = new ReportDataSource("dsAvailabilityEventDailyReport3", (DataTable)ds3.GetData(operationDate)); //fill data report in parameter
var rds4 = new ReportDataSource("dsAvailabilityEventTotal", (DataTable)ds4.GetData(operationDate)); //fill data report in parameter
var rds5 = new ReportDataSource("dsAvailabilityNoteDailyReport", (DataTable)ds5.GetData(operationDate)); ///fill data report in parameter
var rds6 = new ReportDataSource("dsAvailabilityDailyReport", (DataTable)ds6.GetData(operationDate)); //fill data report in parameter
var rds7 = new ReportDataSource("dsAvailabilityReadingTotal", (DataTable)ds7.GetData(operationDate)); //fill data report in parameter
var rds8 = new ReportDataSource("dsAvailabilityEventSum1", (DataTable)ds8.GetData(operationDate)); //fill data report in parameter
var rds9 = new ReportDataSource("dsAvailabilityEventSum2", (DataTable)ds9.GetData(operationDate)); //fill data report in parameter
var rds10 = new ReportDataSource("dsAvailabilityEventSum3", (DataTable)ds10.GetData(operationDate)); //fill data report in parameter
// Variables
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string extension = string.Empty;
// Setup the report viewer object and get the array of bytes
var report = new LocalReport();
report.ReportPath = reportPath;
report.DataSources.Add(rds); // Add datasource here
report.DataSources.Add(rds2); // Add datasource here
report.DataSources.Add(rds3); // Add datasource here
report.DataSources.Add(rds4); // Add datasource here
report.DataSources.Add(rds5); // Add datasource here
report.DataSources.Add(rds6); // Add datasource here
report.DataSources.Add(rds7); // Add datasource here
report.DataSources.Add(rds8); // Add datasource here
report.DataSources.Add(rds9); // Add datasource here
report.DataSources.Add(rds10); // Add datasource here
//set parameter report (jika ada)
report.SetParameters(new List<ReportParameter>
{
//new ReportParameter("FacilitySubClassID", facilitySubClassId.ToString()),
new ReportParameter("OperationDate", operationDate.ToString())
});
byte[] bytes = report.Render(reportType, deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "." + extension + "\"");
Response.BinaryWrite(bytes); // create the file
Response.Flush(); // send it to the client to download
}
I have a sub-report on my rdlc report,, when i tried to export it to excel. The error message appear on excel file (sub-report section).
"Data retrieval failed for the subreport, 'srAvailabilityList', located at: C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\coco\rdlc\availabilityreading.rdlc. Please check the log files for more information."
The sub-report is using ds6 and ds7.
My questions are:
How can I retrieve the data in the sub-report?
Where I can find the log files?
Found the answer:
void MySubreportEventHandler(object sender, SubreportProcessingEventArgs e)
{
var operationDate = System.DateTime.ParseExact(txtStartDate.Text, "dd/MMM/yyyy", CultureInfo.CurrentCulture);
var ds6 = new _spAvailabilityDailyReportTableAdapter();
var ds7 = new _spAvailabilityReadingTotalTableAdapter();
var rds6 = new ReportDataSource("dsAvailabilityDailyReport", (DataTable)ds6.GetData(operationDate)); //isi data report di parameter kedua
var rds7 = new ReportDataSource("dsAvailabilityReadingTotal", (DataTable)ds7.GetData(operationDate)); //isi data report di parameter kedua
e.DataSources.Add(rds6);
e.DataSources.Add(rds7);
}
Then add this code before report.SetParameter :
report.SubreportProcessing += new SubreportProcessingEventHandler(MySubreportEventHandler);

Categories

Resources