public FileContentResult CreateReport(SqlReportType type, string reportName, string area, string datasetName, IEnumerable dataList, List<ReportParameter> myparams) { string mimeType; var report = new LocalReport(); report.LoadReportDefinition(AssetResolver.GetEmbeddedResourceStream(reportName, area)); report.SetParameters(myparams); var reportDataSource = new ReportDataSource(datasetName, dataList); report.DataSources.Add(reportDataSource); byte[] reportBytes = GenerateReport(type, report, out mimeType); return new FileContentResult(reportBytes, mimeType); }
public void SetParam ( ref LocalReport localReport , string strParam , string strValue ) { ReportParameter Param = new ReportParameter (); Param.Name = strParam; Param.Values.Add ( strValue ); localReport.SetParameters ( new ReportParameter [] { Param } ); }
protected void executeReport_click(object sender, EventArgs e) { if (reportSelector.SelectedIndex == 9) executeReportInAppDomain_click(sender, e); else { LocalReport rpt = new LocalReport(); rpt.EnableExternalImages = true; rpt.ReportPath = String.Concat(Path.GetDirectoryName(Request.PhysicalPath), "\\Reports\\", reportSelector.SelectedValue); string orientation = (rpt.GetDefaultPageSettings().IsLandscape) ? "landscape" : "portrait"; StringReader formattedReport = Business.reportHelper.FormatReportForTerritory(rpt.ReportPath, orientation, cultureSelector.SelectedValue); rpt.LoadReportDefinition(formattedReport); // Add Data Source rpt.DataSources.Add(new ReportDataSource("InvoiceDataTable", dt)); // Internationlisation: Add uiCulture and Translation Labels if (reportSelector.SelectedIndex >= 3) { Dictionary<string, string> reportLabels = Reports.reportTranslation.translateInvoice(cultureSelector.SelectedValue); ReportParameterCollection reportParams = new ReportParameterCollection(); reportParams.Add(new ReportParameter("uiCulture", cultureSelector.SelectedValue)); foreach (string key in reportLabels.Keys) reportParams.Add(new ReportParameter(key, reportLabels[key])); rpt.SetParameters(reportParams); } // Render To Browser renderPDFToBrowser(rpt.Render("PDF", Business.reportHelper.GetDeviceInfoFromReport(rpt, cultureSelector.SelectedValue, "PDF"))); } }
public void Render(string reportDesign, ReportDataSource[] dataSources, string destFile, IEnumerable<ReportParameter> parameters = null) { var localReport = new LocalReport(); using (var reportDesignStream = System.IO.File.OpenRead(reportDesign)) { localReport.LoadReportDefinition(reportDesignStream); } localReport.EnableExternalImages = true; localReport.EnableHyperlinks = true; if (parameters != null) { localReport.SetParameters(parameters); } foreach (var reportDataSource in dataSources) { localReport.DataSources.Add(reportDataSource); } //Export to PDF string mimeType; string encoding; string fileNameExtension; string[] streams; Warning[] warnings; var content = localReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); System.IO.File.WriteAllBytes(destFile, content); }
// Create a local report for Report.rdlc, load the data, // export the report to an .emf file, and print it. public void PrintDataSource(DataTable dt, IEnumerable<ReportParameter> param, System.Drawing.Printing.PrinterSettings ps, ref System.IO.MemoryStream ReportDefinition) { LocalReport report = new LocalReport(); this.ps = ps; //report.ReportPath = @"Examine.rdlc"; ReportDefinition.Seek(0, SeekOrigin.Begin); report.LoadReportDefinition(ReportDefinition); report.DataSources.Add(new ReportDataSource("BossCom_RecordPatient", dt)); report.SetParameters(param); Export(report); m_currentPageIndex = 0; Print(); }
public ReportPrintClass(string _DataSourceName, DataTable _DataSourceValue, string _ReportPath, ReportParameter[] arrParams,double pagewidth,double pageheight, double leftmargin, double rightmargin, double topmargin, double bottommargin) { this.pageWidth = pagewidth; this.pageHeight = pageheight; this.leftMargin = leftmargin; this.rightMargin = rightmargin; this.topMargin = topmargin; this.bottomMargin = bottommargin; LocalReport report = new LocalReport(); report.ReportPath = _ReportPath; report.DataSources.Add(new ReportDataSource(_DataSourceName, _DataSourceValue)); report.SetParameters(arrParams); Export(report); m_currentPageIndex = 0; }
public byte[] Render(ReportName reportName, IDictionary<string, object[]> dataSources, params ReportParameter[] parameters) { var localReport = new LocalReport(); localReport.ReportEmbeddedResource = new ReportResourceResolver().ResolveResource(reportName); foreach (var dataSource in dataSources) { var reportDataSource = new ReportDataSource(dataSource.Key, dataSource.Value); localReport.DataSources.Add(reportDataSource); } if (parameters != null && parameters.Length > 0) localReport.SetParameters(parameters); var reportType = "PDF"; var settings = localReport.GetDefaultPageSettings(); var width = settings.IsLandscape ? settings.PaperSize.Height : settings.PaperSize.Width; var height = settings.IsLandscape ? settings.PaperSize.Width : settings.PaperSize.Height; var deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>" + width / 100.0m + "in</PageWidth>" + " <PageHeight>" + height / 100.0m + "in</PageHeight>" + " <MarginTop>" + settings.Margins.Top / 100.0m + "in</MarginTop>" + " <MarginLeft>" + settings.Margins.Left / 100.0m + "in</MarginLeft>" + " <MarginRight>" + settings.Margins.Right / 100.0m + "in</MarginRight>" + " <MarginBottom>" + settings.Margins.Bottom / 100.0m + "in</MarginBottom>" + "</DeviceInfo>"; string mimeType; string encoding; string fileNameExtension; Warning[] warnings; string[] streams; return localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _client = this.dgdClientVendor.ClientNumber; string _div = this.dgdClientVendor.ClientDivsionNumber; string _clientName = this.dgdClientVendor.ClientName; string _pickupIDs = "", _vendor = "", _pudate = "", _punum = "", _pickups = ""; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = REPORT_NAME; report.EnableExternalImages = true; EnterpriseGateway enterprise = new EnterpriseGateway(); DataSet ds = new DataSet(REPORT_DS); foreach (GridViewRow row in SelectedRows) { DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex]; _pickupIDs += (_pickupIDs.Length > 0 ? "," : "") + dataKey["PickupID"].ToString(); _vendor = dataKey["VendorNumber"].ToString(); _pudate = DateTime.Parse(dataKey["PUDate"].ToString()).ToString("MM/dd"); _punum = dataKey["PUNumber"].ToString(); _pickups += (_pickups.Length > 0 ? ", " : "") + _vendor + "-" + _pudate + "-" + _punum; //_pickupIDs += (_pickupIDs.Length > 0 ? "," : "") + dataKey["PickupID"].ToString(); OnExportReport() } DataSet _ds = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _pickupIDs }); ds.Merge(_ds); if (ds.Tables[TBL_REPORT].Rows.Count >= 0) { switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); //Set the report parameters for the report ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter div = new ReportParameter("ClientDivision", _div); ReportParameter clientName = new ReportParameter("ClientName", _clientName); ReportParameter pickups = new ReportParameter("Pickups", _pickups); report.SetParameters(new ReportParameter[] { client, div, clientName, pickups }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, REPORT_DS, "RGXSQLR.TSORT")); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=MultiPickupSortInfo.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[TBL_REPORT]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } else { Master.Status = "There were no records found."; } }
public JsonResult GenerateReportForSearchResult(int supplierId, DateTime fromDate, DateTime toDate) { try { List <DAL.ViewModel.VM_Product> productList = unitOfWork.CustomRepository.sp_ProductEntryHistoryFromSupplierToMainStore(fromDate, toDate, supplierId); decimal totalAmount = 0; var newProductList = new List <VM_Product>(); foreach (var product in productList) { VM_Product newProduct = new VM_Product(); newProduct.ProductName = product.ProductName; newProduct.UnitPrice = product.UnitPrice; newProduct.Quantity = product.Quantity; newProduct.TotalPrice = product.TotalPrice; newProductList.Add(newProduct); } totalAmount = productList.Select(s => s.TotalPrice).Sum(); string supplierName = unitOfWork.SuppliersInformationRepository.GetByID(supplierId).SupplierName; int restaurantId = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString());; string restaurantName = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name; string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/ProductEntryHistoryFromSupplierToMainStoreReport.rdlc"); localReport.SetParameters(new ReportParameter("FromDate", fromDate.ToString())); localReport.SetParameters(new ReportParameter("ToDate", toDate.ToString())); localReport.SetParameters(new ReportParameter("SupplierName", supplierName)); localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName)); localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress)); ReportDataSource reportDataSource = new ReportDataSource("ProductEntryHistoryFromSupplierToMainStoreDataSet", newProductList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Product Report generated.", result = productList, TotalAmount = totalAmount }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// Loads Overusage summary report. /// </summary> /// <param name="reportName">Name of overusage summary report.</param> /// <param name="localReport"> /// Instance or <see cref="LocalReport"/> class. /// This instance serves as a container for report being loaded. /// </param> protected void BindOverusageSummaryReport(string reportName, LocalReport localReport) { // 1. Localize report localReport.DisplayName = reportName; localReport.LoadReportDefinition( ReportingServicesUtils.LoadReportFromFile( GetReportFullPath(reportName) , reportName , this ) ); // 2. Update parameters List<ReportParameter> parameters = new List<ReportParameter>(); parameters.Add( new ReportParameter( ParameterBandwidthStartDate , startDateCalendar.SelectedDate.ToString() ) ); parameters.Add( new ReportParameter( ParameterBandwidthEndDate , endDateCalendar.SelectedDate.ToString() ) ); localReport.SetParameters(parameters); // 3. Update DataSet DataSet report = ES.Services.Packages .GetOverusageSummaryReport( PanelSecurity.SelectedUserId , PanelSecurity.PackageId , startDateCalendar.SelectedDate , endDateCalendar.SelectedDate ); localReport.DataSources.Clear(); TranslateStatusField(report.Tables["HostingSpace"]); // If you open reports DataSet file in XML and file <DataSets> node // you will see the same names as applied to ReportDataSource(name, value) instances below LoadDiskspaceOverusageData(report.Tables["HostingSpace"], report.Tables["DiskspaceOverusage"]); LoadBandwidthOverusageData(report.Tables["HostingSpace"], report.Tables["BandwidthOverusage"]); // BindDataTableToReport(localReport, "OverusageReport_HostingSpace", report.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_DiskspaceOverusage", report.Tables["DiskspaceOverusage"]); BindDataTableToReport(localReport, "OverusageReport_BandwidthOverusage", report.Tables["BandwidthOverusage"]); BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", report.Tables["OverusageDetails"]); localReport.Refresh(); }
private static LocalReport ProccessLocalReport(ReportTypeEnum reportTypeEnum, string reportPath, IEnumerable<ReportDataSource> reportDataSources, List<ReportParameter> reportParameters, out string reportType, out string deviceInfo) { LocalReport lr = new LocalReport(); if (!File.Exists(reportPath)) throw new Exception("Report não encontrado!"); lr.ReportPath = reportPath; foreach (var reportDataSource in reportDataSources) lr.DataSources.Add(reportDataSource); if (reportParameters.Any()) lr.SetParameters(reportParameters); switch (reportTypeEnum) { case ReportTypeEnum.Pdf: reportType = "PDF"; break; case ReportTypeEnum.Excel: reportType = "Excel"; break; case ReportTypeEnum.Word: reportType = "Word"; break; case ReportTypeEnum.Image: reportType = "Image"; break; default: throw new ArgumentOutOfRangeException("reportTypeEnum"); } deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + reportType + "</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>1in</MarginLeft>" + " <MarginRight>1in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; return lr; }
private byte[] GenerateReportForMaterial(List<FiwpmaterialDTO> fiwpmaterials, rptProjectCwaIwpDTO rptInfo) { byte[] bytes = null; Microsoft.Reporting.WebForms.Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; string DeviceInfo = "<DeviceInfo>" + " <OutputFormat>JPEG</OutputFormat>" + " <EndPage>1</EndPage>" + " <PageWidth>17in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0in</MarginBottom>" + "</DeviceInfo>"; List<ReportParameter> paramList = new List<ReportParameter>(); //Default Parameter paramList = GetReportParams(rptInfo); if (fiwpmaterials == null || fiwpmaterials.Count <= 0) fiwpmaterials = new List<FiwpmaterialDTO>(); LocalReport report = new LocalReport(); report.ReportPath = @".\Prev\Resource\rdl\RPTCreateFIWPP3.rdl"; report.EnableExternalImages = true; report.SetParameters(paramList); report.DataSources.Clear(); //Material DataSource report.DataSources.Add(new ReportDataSource("rptMaterial", fiwpmaterials)); bytes = report.Render("Image", DeviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings); return bytes; }
public FileContentResult ExportPDF() { var tn_ExamUser = (TN_ExamUser)Session[SessionKey.ExamUserObject]; if (tn_ExamUser == null) return null; var tnExamUser = db.TN_ExamUser.FirstOrDefault(m => m.ID == tn_ExamUser.ID); if (tnExamUser != null) { var user = tnExamUser.TN_User; string fileType = "pdf"; string fileExtendsion = "pdf"; var listTN_ExamUserAnswer = tnExamUser != null ? tnExamUser.TN_ExamUserAnswer : null; int count = 0; string[] getAnswer = { "A", "B", "C", "D", "E", "F", "G", "H" }; if (listTN_ExamUserAnswer != null && listTN_ExamUserAnswer.Count > 0) { DataTable dt = new DataSet1().KetQua; for (int i = 0; i < listTN_ExamUserAnswer.Count; i++) { var quest = listTN_ExamUserAnswer.ElementAt(i).TN_Question; var answerTrue = quest != null && quest.TN_Answer != null && quest.TN_Answer.Count > 0 ? quest.TN_Answer : null; if (answerTrue != null && answerTrue.Count > 0) { string traloi = "", dapan = ""; for (int j = 0; j < answerTrue.Count; j++) { if (answerTrue.ElementAt(j).ID == listTN_ExamUserAnswer.ElementAt(i).AnswerID) { traloi = getAnswer[j]; } if (answerTrue.ElementAt(j).IsCorrect) { dapan = getAnswer[j]; if (answerTrue.ElementAt(j).ID == listTN_ExamUserAnswer.ElementAt(i).AnswerID) { count++; } } } DataRow dr = dt.NewRow(); dr["CauHoi"] = "Câu " + (i + 1); dr["TraLoi"] = traloi; dr["DapAn"] = dapan; dt.Rows.Add(dr); } } LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Views/Home/KetQua.rdlc"); string title = tnExamUser.TN_Exam != null ? tnExamUser.TN_Exam.Content : ""; ReportParameter param0 = new ReportParameter("Title", title); ReportParameter param1 = new ReportParameter("Name", user.FullName); ReportParameter param2 = new ReportParameter("SBD", user.SBD); ReportParameter param3 = new ReportParameter("Mark", count + " / " + listTN_ExamUserAnswer.Count); ReportDataSource reportDataSource = new ReportDataSource(); localReport.SetParameters(new ReportParameter[] { param0, param1, param2, param3 }); reportDataSource.Name = "DataSet1"; reportDataSource.Value = dt; localReport.DataSources.Add(reportDataSource); Byte[] mybytes = localReport.Render(fileType); Response.AppendHeader("Content-Disposition", "inline; Ket-qua_" + user.SBD + "." + fileExtendsion); return File(mybytes, "application/pdf"); } } return null; }
public ActionResult Comprobante(int?id) { try { if (id == null) { TempData["typemessage"] = "2"; TempData["message"] = "Verifique sus datos"; return(View("Index")); } Reporte_Datos R = new Reporte_Datos(); List <ComprobantePagosModels> ListaComprobantePagosDetalles = new List <ComprobantePagosModels>(); _Comprobante_Datos oDatosComprobante = new _Comprobante_Datos(); ComprobanteCabeceraModels Cabecera = new ComprobanteCabeceraModels(); Cabecera = oDatosComprobante.Comprobante_spCSLDB_get_Cabecera(1, id.Value.ToString(), conexion); ListaComprobantePagosDetalles = oDatosComprobante.Comprobante_spCIDDB_get_detallesPagos(1, id.Value.ToString(), conexion); LocalReport Rtp = new LocalReport(); Rtp.EnableExternalImages = true; Rtp.DataSources.Clear(); string path = Path.Combine(Server.MapPath("~/Formatos"), "ComprobantePesajeGanado.rdlc"); if (System.IO.File.Exists(path)) { Rtp.ReportPath = path; } else { return(RedirectToAction("Index")); } ReportParameter[] Parametros = new ReportParameter[13]; Parametros[0] = new ReportParameter("urlLogo", Cabecera.LogoEmpresa); Parametros[1] = new ReportParameter("nombreEmpresa", Cabecera.NombreEmpresa); Parametros[2] = new ReportParameter("rubroEmpresa", Cabecera.RubroEmpresa); Parametros[3] = new ReportParameter("direccionEmpresa", Cabecera.DireccionEmpresa); Parametros[4] = new ReportParameter("folio", Cabecera.Folio); Parametros[5] = new ReportParameter("nombreCliente", Cabecera.NombreCliente); Parametros[6] = new ReportParameter("telefonoCliente", Cabecera.TelefonoCliente); Parametros[7] = new ReportParameter("rfcCliente", Cabecera.RFCCliente); Parametros[8] = new ReportParameter("diaImpresion", Cabecera.DiaImpresion); Parametros[9] = new ReportParameter("mesImpresion", Cabecera.MesImpresion); Parametros[10] = new ReportParameter("annoImpresion", Cabecera.AnnoImpresion); Parametros[11] = new ReportParameter("kilos", Cabecera.KilosPesajeGanado.ToString()); Parametros[12] = new ReportParameter("costoPesaje", Cabecera.CostoPesajeGanado.ToString()); Rtp.SetParameters(Parametros); Rtp.DataSources.Add(new ReportDataSource("ListaDetallesPagos", ListaComprobantePagosDetalles)); string reportType = "PDF"; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>Comprobante</OutputFormat>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; renderedBytes = Rtp.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); return(File(renderedBytes, mimeType)); } catch (Exception ex) { string Mensaje = ex.Message.Replace("\r\n", "").Replace("\r", "").Replace("\n", ""); TempData["typemessage"] = "2"; TempData["message"] = "No se puede cargar la vista, error: " + Mensaje; return(View("Index")); } }
//categorise report public ActionResult categoriseReport(string id, string category) { LocalReport lr = new LocalReport(); string path = Path.Combine(Server.MapPath("~/Reports"), "Brands.rdlc"); //lr.SetParameters(p1); //lr.Refresh(); if (System.IO.File.Exists(path)) { lr.ReportPath = path; } else { //return View("Index"); } List <vechicle> vlst = new List <vechicle>(); using (portableDBEntities dbmodel = new portableDBEntities()) { //vlst = dbmodel.vechicles.ToList(); vlst = dbmodel.vechicles.Where(x => x.vbrand == category).ToList(); } ReportDataSource rd = new ReportDataSource("DataSet2", vlst); lr.DataSources.Add(rd); ReportParameter p1 = new ReportParameter("brand", category); lr.SetParameters(new ReportParameter[] { p1 }); 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>" + "<MarginBottom>0.5in</MarginBottom>" + "<MarginRight>1in</MarginRight>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); return(File(renderedBytes, mimeType)); }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _client = Master.ClientNumber; string _division = Master.Division; string _agentnumber = Master.AgentNumber; string _subagentnumber = Master.SubAgentNumber; string _region = Master.Region; string _district = Master.District; string _store = Master.StoreNumber; string _start = Master.StartDate; string _end = Master.EndDate; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = TITLE; report.EnableExternalImages = true; EnterpriseRGateway enterprise = new EnterpriseRGateway(); DataSet ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _client, _division, _agentnumber, _subagentnumber, _region, _district, _store, _start, _end }); if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(SOURCE); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); DataSet _ds = enterprise.FillDataset("uspRptClientRead", mTBLName, new object[] { _client }); report.DataSources.Add(new ReportDataSource("DataSet1", _ds.Tables[mTBLName])); //Set the report parameters for the report ReportParameter clientName = new ReportParameter("ClientName", Master.ClientName); ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter division = new ReportParameter("Division", _division); ReportParameter agentnumber = new ReportParameter("AgentParentNumber", _agentnumber); ReportParameter subagentnumber = new ReportParameter("AgentNumber", _subagentnumber); ReportParameter region = new ReportParameter("Region"); if (_region != null) { region.Values.Add(_region); } ReportParameter district = new ReportParameter("District"); if (_district != null) { district.Values.Add(_district); } ReportParameter store = new ReportParameter("StoreNumber"); if (_store != null) { store.Values.Add(_store); } ReportParameter start = new ReportParameter("StartDate", _start); ReportParameter end = new ReportParameter("EndDate", _end); report.SetParameters(new ReportParameter[] { client, division, agentnumber, subagentnumber, region, district, store, start, end, clientName }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName)); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=ScanningSummaryByAgent.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex); } }
protected void OnViewerDrillthrough(object sender, DrillthroughEventArgs e) { //Event handler for drill through if (!e.Report.IsDrillthroughReport) { return; } //Determine which drillthrough report is requested LocalReport report = (LocalReport)e.Report; report.DisplayName = e.ReportPath; report.EnableExternalImages = true; switch (e.ReportPath) { case "Scanning Summary By Client": { //Get drillthrough parameters string _agent = "", _start = "", _end = ""; for (int i = 0; i < report.OriginalParametersToDrillthrough.Count; i++) { switch (report.OriginalParametersToDrillthrough[i].Name) { case "StartDate": _start = report.OriginalParametersToDrillthrough[i].Values[0]; break; case "EndDate": _end = report.OriginalParametersToDrillthrough[i].Values[0]; break; case "AgentNumber": _agent = report.OriginalParametersToDrillthrough[i].Values[0]; break; } } //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition("/Executive/" + e.ReportPath); report.LoadReportDefinition(stream); EnterpriseRGateway enterprise = new EnterpriseRGateway(); DataSet ds = enterprise.FillDataset("uspRptScanningSummaryByClient", "NewTable", new object[] { null, _agent, _start, _end }); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource("ScanningSummaryByClientDS", ds.Tables["NewTable"])); DataSet _ds = enterprise.FillDataset("uspRptAgentRead", mTBLName, new object[] { _agent }); report.DataSources.Add(new ReportDataSource("DataSet1", _ds.Tables["NewTable"])); ReportParameter client = new ReportParameter("ClientNumber"); ReportParameter agent = new ReportParameter("AgentNumber", _agent); ReportParameter start = new ReportParameter("StartDate", _start); ReportParameter end = new ReportParameter("EndDate", _end); report.SetParameters(new ReportParameter[] { client, agent, start, end }); report.Refresh(); } break; case "Scanning Summary By Agent": { //Get drillthrough parameters string _client = "", _start = "", _end = ""; for (int i = 0; i < report.OriginalParametersToDrillthrough.Count; i++) { switch (report.OriginalParametersToDrillthrough[i].Name) { case "StartDate": _start = report.OriginalParametersToDrillthrough[i].Values[0]; break; case "EndDate": _end = report.OriginalParametersToDrillthrough[i].Values[0]; break; case "ClientNumber": _client = report.OriginalParametersToDrillthrough[i].Values[0]; break; } } //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition("/Executive/" + e.ReportPath); report.LoadReportDefinition(stream); EnterpriseRGateway enterprise = new EnterpriseRGateway(); DataSet ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _client, null, null, null, null, null, null, _start, _end }); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); DataSet _ds = enterprise.FillDataset("uspRptClientRead", mTBLName, new object[] { _client }); report.DataSources.Add(new ReportDataSource("DataSet1", _ds.Tables[mTBLName])); ReportParameter clientName = new ReportParameter("ClientName"); ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter division = new ReportParameter("Division"); ReportParameter agentnumber = new ReportParameter("AgentParentNumber"); ReportParameter subagentnumber = new ReportParameter("AgentNumber"); ReportParameter region = new ReportParameter("Region"); ReportParameter district = new ReportParameter("District"); ReportParameter store = new ReportParameter("StoreNumber"); ReportParameter start = new ReportParameter("StartDate", _start); ReportParameter end = new ReportParameter("EndDate", _end); report.SetParameters(new ReportParameter[] { client, division, agentnumber, subagentnumber, region, district, store, start, end, clientName }); report.Refresh(); } break; } }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _clientName = this.dgdClientVendor.ClientName; string _pickupID = "", _termCode = ""; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = this.mTitle; report.EnableExternalImages = true; EnterpriseGateway enterprise = new EnterpriseGateway(); DataSet ds = new DataSet(this.mDSName); foreach (GridViewRow row in SelectedRows) { DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex]; _pickupID += (_pickupID.Length > 0 ? ", " : "") + dataKey["PickupID"].ToString(); _termCode = dataKey["TerminalCode"].ToString(); DataSet _ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { dataKey["TerminalCode"].ToString(), dataKey["PickupID"].ToString() }); ds.Merge(_ds); } if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(this.mSource); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); //Set the report parameters for the report ReportParameter clientName = new ReportParameter("ClientName", _clientName); ReportParameter puID = new ReportParameter("PickupID", _pickupID); ReportParameter termCode = new ReportParameter("TerminalCode", _termCode); ReportParameter store = new ReportParameter("StoreNumber", this.txtStore.Text.Trim().Length > 0 ? this.txtStore.Text.Trim() : null); ReportParameter zone = new ReportParameter("ZoneCode", this.txtZone.Text.Trim().Length > 0 ? this.txtZone.Text.Trim().PadRight(2) : null); report.SetParameters(new ReportParameter[] { termCode, puID, clientName, store, zone }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName)); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=ASNTracking.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex); } }
private void PrintReciept() { try { if (_postTransactionID > 0) { using (var uow = new UnitOfWork(new DataContext())) { var posProductTransactions = uow.PosTransactionProducts.GetAllBy(_postTransactionID); var posTransaction = uow.PosTransaction.GetPosTransaction(_postTransactionID); dsReports ds = new dsReports(); DataTable t = ds.Tables["dsReciept"]; DataRow r; int count = 0; foreach (var item in posProductTransactions) { count++; r = t.NewRow(); r["ID"] = count.ToString(); r["Quantity"] = item.Quantity.ToString(); r["Item"] = item.Product.Description; r["Price"] = item.Product.Price; r["Total"] = item.Quantity * item.Product.Price; t.Rows.Add(r); } LocalReport report = new LocalReport(); string path = Path.GetDirectoryName(Application.ExecutablePath); //string fullPath = path.Remove(path.Length - 10) + @"\Reports\Reciept.rdlc"; string fullPath = path + @"\Reports\Reciept.rdlc"; report.ReportPath = fullPath; report.DataSources.Add(new ReportDataSource("dsReciept", t)); var paramDate = new ReportParameter("date", DateTime.Now.ToShortDateString()); var p_time = new ReportParameter("time", DateTime.Now.ToShortTimeString()); var paramTotal = new ReportParameter("totalAmount", txtTotal.Text); var paramCash = new ReportParameter("cash", posTransaction.AmountTender.Value.ToString()); var paramChange = new ReportParameter("change", txtChange.Text); var p_cashier = new ReportParameter("cashier", CurrentUser.Name); var p_transcCode = new ReportParameter("transCode", posTransaction.TransactionCode); report.SetParameters(new ReportParameter[] { paramDate, p_time, paramTotal, paramCash, paramChange, p_cashier, p_transcCode }); PrintToPrinter(report); // rptViewer.LocalReport.DataSources.Clear(); // ReportDataSource rds = new ReportDataSource("PrevPrenatalRecord", t); // ReportDataSource rds2 = new ReportDataSource("PresPrenatalRecord", t2); // ReportParameter p_age = new ReportParameter("Age", txtAge.Text); // ReportParameter p_weight = new ReportParameter("Weight", txtWeight.Text); // ReportParameter p_height = new ReportParameter("Height", txtHeight.Text); // ReportParameter p_bmi = new ReportParameter("BMI", txtBMI.Text); // ReportParameter p_lastMensDate = new ReportParameter("LastMensDate", txtLastMens.Text); // ReportParameter p_expDeliveryDate = new ReportParameter("ExpDeliveryDate", txtExpectedDelivery.Text); // ReportParameter p_prenatalMonthCount = new ReportParameter("PrenatalMonthCount", txtMonthCount.Text); // ReportParameter p_prenatalCount = new ReportParameter("PrenatalCount", txtPregnancyCount.Text); // this.rptViewer.LocalReport.SetParameters(new ReportParameter[] //{ p_age, //p_weight, //p_height, //p_bmi, //p_lastMensDate, //p_expDeliveryDate, //p_prenatalMonthCount, //p_prenatalCount //}); // var currentRec = uow.PrenatalRecords.Get(prenatalRecID); // rptViewer.LocalReport.DataSources.Add(rds); // rptViewer.LocalReport.DataSources.Add(rds2); // rptViewer.SetDisplayMode(DisplayMode.PrintLayout); // rptViewer.ZoomMode = ZoomMode.PageWidth; // rptViewer.LocalReport.DisplayName = currentRec.FullName; // this.rptViewer.RefreshReport(); } } else { MetroMessageBox.Show(this, "No Transaction Reciept to print!", "Print Reciept", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { LocalUtils.ShowErrorMessage(this, ex.ToString()); } }
//为打印报表准备数据 public void StartPrint(string ReportName) { m_streams = new List<Stream>(); LocalReport report = new LocalReport(); //foreach (string ReportName in dataSourceList) //{ switch (ReportName) { case "Report1.rdlc": { var resultSet = FacilityBLL.getOrderDetail(2); report.ReportEmbeddedResource = "Annon.Report.Report1.rdlc"; var ordersInfo = FacilityBLL.getOrderInfo(1); ReportParameter rp = new ReportParameter("Latitute", "200m"); ReportParameter rpTag = new ReportParameter("CustomerName", "ordersInfo.Customer"); ReportParameter rpProjectName = new ReportParameter("ProjectName", ordersInfo.JobName); ReportParameter rpProjectNo = new ReportParameter("ProjectNo", ordersInfo.JobNum); ReportParameter rpSeller = new ReportParameter("AnnonContact", "ordersInfo.AAonCon"); ReportParameter rpOrderDate = new ReportParameter("DealDate", ordersInfo.Activity); report.SetParameters(new ReportParameter[] { rp, rpTag, rpProjectName, rpProjectNo, rpSeller, rpOrderDate }); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", resultSet)); } break; case "Report2.rdlc": { var resultSet2 = FacilityBLL.getOrderDetail(2); report.ReportEmbeddedResource = "Annon.Report.Report2.rdlc"; var ordersInfo = FacilityBLL.getOrderInfo(1); ReportParameter rp = new ReportParameter("Latitute", "200m"); ReportParameter rpTag = new ReportParameter("CustomerName", "ordersInfo.Customer"); ReportParameter rpProjectName = new ReportParameter("ProjectName", ordersInfo.JobName); ReportParameter rpProjectNo = new ReportParameter("ProjectNo", ordersInfo.JobNum); ReportParameter rpSeller = new ReportParameter("AnnonContact", "ordersInfo.AAonCon"); ReportParameter rpOrderDate = new ReportParameter("DealDate", ordersInfo.Activity); report.SetParameters(new ReportParameter[] { rp, rpTag, rpProjectName, rpProjectNo, rpSeller, rpOrderDate }); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", resultSet2)); } break; case "Report3.rdlc": { var resultSet = FacilityBLL.getFacility(1, 1, "model"); var resultSet1 = FacilityBLL.getFacility(1, 1, "feature"); var productDescription = FacilityBLL.getDescription(1); var ordersInfo = FacilityBLL.getOrderInfo(1); report.ReportEmbeddedResource = "Annon.Report.Report3.rdlc"; ReportParameter rp = new ReportParameter("ProductDescription", "6ERM-" + productDescription); ReportParameter rpTag = new ReportParameter("AnnonContact", "Annon.contact"); ReportParameter rpProjectName = new ReportParameter("ProjectName", ordersInfo.JobName); ReportParameter rpProjectNo = new ReportParameter("ProjectNo", ordersInfo.JobNum); ReportParameter rpOrderDate = new ReportParameter("OrderDate", ordersInfo.Activity); report.SetParameters(new ReportParameter[] { rp, rpTag, rpProjectName, rpProjectNo, rpOrderDate }); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", resultSet)); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet2", resultSet1)); } break; case "Report4.rdlc": { var resultSet = FacilityBLL.getFacility(1, 1, "model"); var resultSet1 = FacilityBLL.getFacility(1, 1, "feature"); var productDescription = FacilityBLL.getDescription(1); var ordersInfo = FacilityBLL.getOrderInfo(1); report.ReportEmbeddedResource = "Annon.Report.Report4.rdlc"; ReportParameter rp = new ReportParameter("ProductDescription", "6ERM-" + productDescription); ReportParameter rpTag = new ReportParameter("Tag", "6ERM"); ReportParameter rpProjectName = new ReportParameter("ProjectName", ordersInfo.JobName); ReportParameter rpProjectNo = new ReportParameter("ProjectNo", ordersInfo.JobNum); ReportParameter rpSeller = new ReportParameter("Seller", "ordersInfo.AAonCon"); ReportParameter rpOrderDate = new ReportParameter("OrderDate", ordersInfo.Activity); report.SetParameters(new ReportParameter[] { rp, rpTag, rpProjectName, rpProjectNo, rpSeller, rpOrderDate }); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", resultSet)); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet2", resultSet1)); } break; case "Report5.rdlc": { var resultSet = FacilityBLL.getOrderDetail(1); report.ReportEmbeddedResource = "Annon.Report.Report5.rdlc"; report.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing); report.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", resultSet)); } break; } //将报表原始数据输出,并进行转换 Export(report); //} m_currentPageIndex = 0; Print(); }
private void PrintBills() { LocalReport report = new LocalReport(); string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string rptPath = Path.Combine(appPath, "RptBill.rdlc"); report.ReportPath = rptPath; report.SetParameters(new ReportParameter("Cardno", ProcessResult.Cardno)); report.SetParameters(new ReportParameter("Mkt", MKT)); report.SetParameters(new ReportParameter("PayValue", ProcessResult.Payvalue)); report.SetParameters(new ReportParameter("Banlance", ProcessResult.Balance)); report.SetParameters(new ReportParameter("Order", GetOrder())); report.SetParameters(new ReportParameter("Oper", OPER)); report.SetParameters(new ReportParameter("OperName", OPERNAME)); report.SetParameters(new ReportParameter("CardType", ProcessResult.Cardno)); ExportBillsReport(report); PrintReport(); }
private void btnFinalizar_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBoxValorRecebido.Text) && !string.IsNullOrEmpty(textBoxValorTotal.Text)) { DialogResult janela = MessageBox.Show("Você deseja finalizar o pedido?", "Finalizar pedido?", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (janela.ToString().ToUpper() == "OK") { resultado = new Resultado(); //Tb_ProdutoPedido produtoPedido = new Tb_ProdutoPedido(); pedido = new Tb_Pedido() { DataPedido = DateTime.Now, ValorPedido = decimal.Parse(textBoxValorAPagar.Text) != 0 ? decimal.Parse(textBoxValorAPagar.Text): decimal.Parse(textBoxValorTotal.Text) }; resultado = new PedidoBusiness().InserirPedido(pedido); pedido.Id = resultado.RetornoId; if (resultado.Sucesso) { foreach (var item in listaProd) { resultado = new PedidoBusiness().InserirItemPedido(this.pedido.Id, item.Id, item.Quantidade, item.ValorVenda); resultado = substrairEstoque(item.Id, item.Quantidade); } if (resultado.Sucesso) { using (LocalReport relatorio = new LocalReport()) { relatorio.ReportPath = "RelatorioVenda.rdlc"; var listParameter = new List <ReportParameter>(); relatorio.DataSources.Add(new ReportDataSource("ListaVendas", listParameter)); foreach (var item in listaProd) { string desc = item.Descricao; string value = item.Quantidade.ToString(); string qtd = item.ValorVenda.ToString(); relatorio.SetParameters(new ReportParameter("Descricao", desc)); relatorio.SetParameters(new ReportParameter("Quantidade", value)); relatorio.SetParameters(new ReportParameter("ValorVenda", qtd)); } relatorio.DataSources.Add(new ReportDataSource("ListaVendas", listParameter)); //relatorio.ReportEmbeddedResource = "RelatorioVenda.rdlc"; //foreach (var item in listParameter) //{ // relatorio.SetParameters(new ReportParameter("Descricao", item.Values)); // relatorio.SetParameters(new ReportParameter("Quantidade", item.Quantidade.ToString())); // relatorio.SetParameters(new ReportParameter("ValorVenda", item.ValorVenda.ToString())); //} relatorio.Refresh(); using (var rpd = new ReportViewerPrint()) { rpd.PrinterSettings.PrinterName = "POS-76C"; rpd.Export(relatorio); rpd.Imprimir(rpd.PrinterSettings.PrinterName); } } MessageBox.Show("Venda finalizada", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); //Limpar campos #region [Reiniciar tela de vendas] dataGridItemPedido.Rows.Clear(); textBoxCodBarra.Clear(); textBoxCodProduto.Clear(); textBoxTroco.Clear(); textBoxValorTotal.Clear(); textBoxValorRecebido.Clear(); textBoxDesconto.Text = "0"; textBoxValorAPagar.Text = "0"; ActiveControl = textBoxCodBarra; #endregion } } } } else { MessageBox.Show("Valor total e valor recebido não pode ser vazio", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
protected override bool RenderInternal(ref MemoryStream chunk, out string mime) { mime = null; try { /* 1. instantiate the report */ var rdlcname = "sherm.rpt.msdbrpt.ReportHardcopyWra002brief.rdlc"; var rpt = new LocalReport() { ReportEmbeddedResource = rdlcname, EnableExternalImages = true }; /* 2. populate it */ rpt.DataSources.Clear(); var dr = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_WRA_BRIEF].Rows[0]; /* 2.I static literals */ rpt.SetParameters(new ReportParameter[] { new ReportParameter("PagenumberFormatstring", m(2410)), /* Strana {0} z {1} */ new ReportParameter("lPrint", m(5194)), /* Print */ new ReportParameter("lTitle", m(5195)), /* Bezpečnostní instrukce */ new ReportParameter("lActivityDescription", m(5196)), /* Popis činnosti */ new ReportParameter("lDocuments", m(415)), /* Souvisejicí vnitřni předpisy */ new ReportParameter("lName", m(5197)), /* Název */ new ReportParameter("lNumber", m(5198)), /* Číslo/Značka */ new ReportParameter("lSubstances", m(5200)), /* Chemical substances and mixtures */ new ReportParameter("lPictograms", m(5199).Replace(" ", "<br>")), /* Nebezpečné vlastnosti */ new ReportParameter("lSpill", m(5201)), /* Co dělat v pripadě nouze */ new ReportParameter("lHazards", m(5202)), /* Nebezpečí a jejich výsledná mira rizika */ new ReportParameter("lHazard", m(234)), /* Nebezpečí */ new ReportParameter("lHazDescription", m(5203)), /* Upřesnění */ new ReportParameter("lRiskScore", m(5204)), /* Míra rizika */ new ReportParameter("lRiskLevel", m(5041)), /* Kategorie */ new ReportParameter("lMeaTech", m(5205)), /* Řídící opatření - technická */ new ReportParameter("lMeaOrg", m(5206)), /* Řídící opatření - organizační */ new ReportParameter("lMeaOrgCaption", m(42)), /* Opatření */ new ReportParameter("lMeaOrgResponsible", m(5207)), /* Realizace kým */ new ReportParameter("lMeaOrgDate", m(5208)), /* Realizace kdy */ new ReportParameter("lPPE", m(5210)), /* Řídící opatření - ochranné prostředky */ new ReportParameter("lPPEPicto", m(5142)), /* Symbol */ new ReportParameter("lPPESpec", m(5211)), /* Specifikace */ new ReportParameter("lPPEConditions", m(5144)), /* Conditions */ new ReportParameter("lMeaTra", m(5209)), /* Řídící opatření - školení a výcvik */ new ReportParameter("lMeaTraCaption", m(42)), /* Opatření */ new ReportParameter("lMeaTraResponsible", m(5207)), /* Realizace kým */ new ReportParameter("lMeaTraDate", m(5208)), /* Realizace kdy */ new ReportParameter("lDos", m(5081)), /* Specifické pokyny */ new ReportParameter("lDonts", m(5084)), /* Seznam specifických zákazú */ new ReportParameter("lOriginator", m(5212)) /* Vytvořil(a) / Zpracoval(a) */ }); /* 2.II toplevel values */ rpt.SetParameters(new ReportParameter[] { new ReportParameter("lCompanyname", dr["fCompanyInfo"].ToString()), new ReportParameter("lWorkplaceNumber", dr["fWorkplaceNumber"].ToString()), new ReportParameter("lVersion", dr["fVersion"].ToString()), new ReportParameter("lOrgUnit", dr["fOrgunit"].ToString()), new ReportParameter("ActivityDescription", dr["mProcess"].ToString()), new ReportParameter("MeaTech", dr["fMeaTech"].ToString()), new ReportParameter("Dos", dr["mDos"].ToString()), new ReportParameter("Donts", dr["mDonts"].ToString()), new ReportParameter("Originator", dr["fOriginator"].ToString()) }); /* 2.III sublists; * 2.III.1 docs */ var docs = new List <ReportHardcopyWRABriefDoc>(); foreach (DataRow drdoc in Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_WRABRIEF_DOCS].Rows) { docs.Add(new ReportHardcopyWRABriefDoc() { Number = drdoc["Number"].ToString(), Name = drdoc["fName"].ToString() }); } var dsDocs = "dsDocs"; var dynDS_Docs = new ReportDataSource(dsDocs, docs); rpt.DataSources.Add(dynDS_Docs); /* 2.III.2 ppe */ var ppes = new List <ReportHardcopyWRABriefPPE>(); foreach (DataRow drppe in Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_WRABRIEF_PPE].Rows) { ppes.Add(new ReportHardcopyWRABriefPPE() { PictoURL = MediaURLAbsolute(sherm.core.formatting.mime.BINGET_NAMEDRESOURCE_CLPPICTOGRAMS, drppe["fPictoURL"].ToString(), null, 75, new FileType[] { FileType.ft_png }), PPESpec = drppe["mDescription"].ToString(), PPEConditions = drppe["mApproach"].ToString() }); } var dsPPE = "dsPPE"; var dynDS_PPE = new ReportDataSource(dsPPE, ppes); rpt.DataSources.Add(dynDS_PPE); /* 2.III.3 haz */ var hazs = new List <ReportHardcopyWRABriefHaz>(); foreach (DataRow drhaz in Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_WRABRIEF_HAZS].Rows) { hazs.Add(new ReportHardcopyWRABriefHaz() { Caption = drhaz["Caption"].ToString(), Description = drhaz["mDescription"].ToString(), RiskScore = drhaz["RiskScore"].ToString(), RiskLevel = drhaz["RiskLevel"].ToString() }); } var dsHaz = "dsHaz"; var dynDS_HAZ = new ReportDataSource(dsHaz, hazs); rpt.DataSources.Add(dynDS_HAZ); /* 2.III.4 mea-org-tra */ var meaorgs = new List <ReportHardcopyWRABriefMea>(); var meatras = new List <ReportHardcopyWRABriefMea>(); foreach (DataRow drmea in Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_WRABRIEF_MEAS].Rows) { if (drmea["OT"].Equals(DBNull.Value) == false) { var meax = new ReportHardcopyWRABriefMea() { Caption = drmea["Caption"].ToString(), Responsible = drmea["ResponsibleName"].ToString(), Date = drmea["fDate"].ToString() }; if (Convert.ToInt32(drmea["OT"]) == (int)ObjectType.ot_Training) { meatras.Add(meax); } else { meaorgs.Add(meax); } } } var dsMeaOrg = "dsMeaOrg"; var dsMeaTra = "dsMeaTra"; var dynDS_MEAORG = new ReportDataSource(dsMeaOrg, meaorgs); var dynDS_MEATRA = new ReportDataSource(dsMeaTra, meatras); rpt.DataSources.Add(dynDS_MEAORG); rpt.DataSources.Add(dynDS_MEATRA); /* 2.III.6 substances */ var substs = new List <ReportHardcopyWRABriefSubst>(); foreach (DataRow drsubst in Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_WRABRIEF_SUBSTS].Rows) { substs.Add(new ReportHardcopyWRABriefSubst() { Name = drsubst["Name"].ToString(), PictoURL = MediaURLAbsolute(sherm.core.formatting.mime.BINGET_NAMEDRESOURCE_CLPPICTOGRAMS, drsubst["fPictoURL"].ToString(), null, 75, new FileType[] { FileType.ft_png }), Spill = drsubst["fSpill"].ToString() }); } var dsSubstances = "dsSubstances"; var dynDS_SUBSTANCES = new ReportDataSource(dsSubstances, substs); rpt.DataSources.Add(dynDS_SUBSTANCES); /* 3. render the report into the desired format */ rpt.Refresh(); RenderAsMsdbrpt(ResultFileBasename, ref chunk, ref mime, rpt); /* succeeded */ return(true); } catch (Exception ex) { /* some error */ OnBuiltinReportError(ex.Message, ex); return(false); } }
public ActionResult ViewPdfReportForSearchResult(string registrationNo, string fromDate, string toDate) { try { List <DAL.ViewModel.VM_CostForBusRegistrationNo> totalCostInfoList = unitOfWork.CustomRepository.sp_totalCostHistoryFromDateToDateForBusRegistrationNoFullFinal(registrationNo, Convert.ToDateTime(fromDate), Convert.ToDateTime(toDate)); var newTotalCostInfoList = new List <DAL.ViewModel.VM_CostForBusRegistrationNo>(); foreach (var totalCostInfo in totalCostInfoList) { DAL.ViewModel.VM_CostForBusRegistrationNo newtotalCostInfo = new DAL.ViewModel.VM_CostForBusRegistrationNo(); newtotalCostInfo.CompanyName = totalCostInfo.CompanyName; newtotalCostInfo.PartsName = totalCostInfo.PartsName; newtotalCostInfo.Other = totalCostInfo.Other; newtotalCostInfo.Quantity = totalCostInfo.Quantity; newtotalCostInfo.UnitPrice = totalCostInfo.UnitPrice; newtotalCostInfo.Price = totalCostInfo.Price; newtotalCostInfo.StoreName = totalCostInfo.StoreName; newTotalCostInfoList.Add(totalCostInfo); } int workShopId = Int32.Parse(SessionManger.WorkShopOfLoggedInUser(Session).ToString()); string workShopName = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Name; string workShopAddress = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/TotalCostHistoryFromDateToDateForABusRegistrationNoReport.rdlc"); localReport.SetParameters(new ReportParameter("RegistrationNo", registrationNo)); localReport.SetParameters(new ReportParameter("FromDate", fromDate.ToString())); localReport.SetParameters(new ReportParameter("ToDate", toDate.ToString())); localReport.SetParameters(new ReportParameter("WorkShopName", workShopName)); localReport.SetParameters(new ReportParameter("WorkShopAddress", workShopAddress)); ReportDataSource reportDataSource = new ReportDataSource("TotalCostHistoryFromDateToDateForABusRegistrationNoDataSet", newTotalCostInfoList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); return(File(renderedBytes, mimeType)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
private byte[] GenerateReportForCover(string imageUrl, rptProjectCwaIwpDTO rptInfo) { byte[] bytes = null; Microsoft.Reporting.WebForms.Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; string DeviceInfo = "<DeviceInfo>" + " <OutputFormat>JPEG</OutputFormat>" + " <EndPage>1</EndPage>" + " <PageWidth>17in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0in</MarginBottom>" + "</DeviceInfo>"; List<ReportParameter> paramList = new List<ReportParameter>(); //Default Parameter paramList = GetReportParams(rptInfo); //Cover Image Parameter if (!string.IsNullOrEmpty(imageUrl)) { var imageBytes = (new TrueTask.Common()).FileToByteArray(imageUrl); //System.IO.File.ReadAllBytes(imageUrl); if (imageBytes != null) imageUrl = Convert.ToBase64String(imageBytes); } paramList.Add(new ReportParameter("par_imageurl", imageUrl)); LocalReport report = new LocalReport(); report.ReportPath = @".\Prev\Resource\rdl\RPTCreateFIWPP1.rdl"; report.EnableExternalImages = true; report.SetParameters(paramList); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource("CostCode", new List<CostcodeDTO>())); bytes = report.Render("Image", DeviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings); return bytes; }
public JsonResult GenerateReportForSearchResult(string registrationNo, string fromDate, string toDate) { try { List <DAL.ViewModel.VM_CostForBusRegistrationNo> totalCostInfoList = unitOfWork.CustomRepository.sp_totalCostHistoryFromDateToDateForBusRegistrationNoFullFinal(registrationNo, Convert.ToDateTime(fromDate), Convert.ToDateTime(toDate)); double totalAmount = 0; var newTotalCostInfoList = new List <DAL.ViewModel.VM_CostForBusRegistrationNo>(); foreach (var totalCostInfo in totalCostInfoList) { DAL.ViewModel.VM_CostForBusRegistrationNo newtotalCostInfo = new DAL.ViewModel.VM_CostForBusRegistrationNo(); newtotalCostInfo.CompanyName = totalCostInfo.CompanyName; newtotalCostInfo.PartsName = totalCostInfo.PartsName; newtotalCostInfo.Other = totalCostInfo.Other; newtotalCostInfo.Quantity = totalCostInfo.Quantity; newtotalCostInfo.UnitPrice = totalCostInfo.UnitPrice; newtotalCostInfo.Price = totalCostInfo.Price; newtotalCostInfo.StoreName = totalCostInfo.StoreName; newTotalCostInfoList.Add(totalCostInfo); } totalAmount = totalCostInfoList.Select(s => s.Price).Sum(); int workShopId = Int32.Parse(SessionManger.WorkShopOfLoggedInUser(Session).ToString()); string workShopName = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Name; string workShopAddress = unitOfWork.WorkShopInformationRepository.GetByID(workShopId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/TotalCostHistoryFromDateToDateForABusRegistrationNoReport.rdlc"); localReport.SetParameters(new ReportParameter("RegistrationNo", registrationNo)); localReport.SetParameters(new ReportParameter("FromDate", fromDate.ToString())); localReport.SetParameters(new ReportParameter("ToDate", toDate.ToString())); localReport.SetParameters(new ReportParameter("WorkShopName", workShopName)); localReport.SetParameters(new ReportParameter("WorkShopAddress", workShopAddress)); ReportDataSource reportDataSource = new ReportDataSource("TotalCostHistoryFromDateToDateForABusRegistrationNoDataSet", newTotalCostInfoList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport")); var saveAs = string.Format("{0}.pdf", Path.Combine(path, "myfilename")); var idx = 0; while (System.IO.File.Exists(saveAs)) { idx++; saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, "myfilename"), idx); } Session["report"] = saveAs; using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write)) { stream.Write(renderedBytes, 0, renderedBytes.Length); stream.Close(); } localReport.Dispose(); return(Json(new { success = true, successMessage = "Report generated successfully.", result = totalCostInfoList, TotalAmount = totalAmount }, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
public ActionResult Report(string id, Int32? idventa) { LocalReport lr = new LocalReport(); Int32 idVenta; string path = Path.Combine(Server.MapPath("~/Reportes"), "ComprobantePago.rdlc"); if (System.IO.File.Exists(path)) { if (idventa != null) { idVenta = Int32.Parse(idventa.ToString()); } else { return View("ListarReservas"); } lr.ReportPath = path; } else { return View("ListarReservas"); } string reportType = id; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + id + "</OutputFormat>" + " <PageWidth>16cm</PageWidth>" + " <PageHeight>12cm</PageHeight>" + " <MarginTop>0.5cm</MarginTop>" + " <MarginLeft>0.5cm</MarginLeft>" + " <MarginRight>0.5cm</MarginRight>" + " <MarginBottom>0.5cm</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; List<DatosReportVentaComprobante> cm = new List<DatosReportVentaComprobante>(); Venta pru = ventaService.ObtenerVentaPorId(idVenta); foreach (var item in pru.Reseras) { var datos = new DatosReportVentaComprobante { DniRuc = item.Cliente.DniRuc, Apellidos = item.Cliente.Nombre + " " + item.Cliente.Apellidos, OrigenId = item.Horario.EstacionOrigen.Provincia, DestinoId = item.Horario.EstacionDestino.Provincia, Hora = item.Horario.HoraText, Asiento = item.Asiento.ToString(), Pago = item.Pago }; cm.Add(datos); } ReportDataSource rd = new ReportDataSource("ComprobantePago", cm); lr.DataSources.Add(rd); ReportParameter[] parametros = new ReportParameter[7]; parametros[0] = new ReportParameter("NroVenta", pru.NroVenta + ""); parametros[1] = new ReportParameter("Nombre", pru.Cliente.Nombre + " " + pru.Cliente.Apellidos); parametros[2] = new ReportParameter("Fecha", pru.Fecha + ""); parametros[3] = new ReportParameter("DniRuc", pru.Cliente.DniRuc + ""); parametros[4] = new ReportParameter("Direccion", pru.Cliente.Direccion + ""); parametros[5] = new ReportParameter("Telefono", pru.Cliente.Telefono + ""); parametros[6] = new ReportParameter("Tipo", "Reserva"); lr.SetParameters(parametros); renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); switch (id) { case "PDF": return File(renderedBytes, mimeType); case "Excel": return File(renderedBytes, mimeType, pru.NroVenta + ".xls"); case "Word": return File(renderedBytes, mimeType, pru.NroVenta + ".doc"); case "Image": return File(renderedBytes, mimeType, pru.NroVenta + ".png"); default: break; } var ven = ventaService.ObtenerVentaPorId(idVenta); RegUsuarios movimiento = new RegUsuarios { Usuario = User.Identity.Name, Modulo = "Reserva", Cambio = "Reporte Reserva", IdModulo = ven.NroVenta + "", Fecha = DateTime.Now }; movCuentaService.GuardarMovimiento(movimiento); return File(renderedBytes, mimeType); }
public static byte[] RenderReport(ReportTypeEnum type, Dictionary <string, object> dataSources, string reportePathCompleto, string[] columnasMostrar, IDictionary <string, string> parametros, IDictionary <string, string> imagenes, decimal?pageWidth, decimal?pageHeight, decimal?marginTop, decimal?marginLeft, decimal?marginRight, decimal?marginBottom, out string mimeType) { var localReport = new LocalReport(); ReporteLoadReportDefinition(localReport, reportePathCompleto, imagenes); localReport.DataSources.Clear(); foreach (var dataSourcesName in dataSources.Keys) { var reporteDataSource = new ReportDataSource(dataSourcesName, dataSources[dataSourcesName]); localReport.DataSources.Add(reporteDataSource); } //Imagenes externas localReport.EnableExternalImages = true; if (columnasMostrar.Any()) { var sb = new StringBuilder(); foreach (string columna in columnasMostrar) { sb.AppendFormat("#{0}#", columna.Trim()); } parametros.Add("Columnas", sb.ToString()); } foreach (var clave in parametros.Keys) { var param = new ReportParameter(); param.Name = clave; param.Values.Add(parametros[clave]); localReport.SetParameters(param); } string outputFormat = OutputFormat(type); string reporteType = ReportType(type); string encoding; string fileNameExtension; StringBuilder deviceInfo = new StringBuilder(); deviceInfo.AppendFormat("<DeviceInfo>"); deviceInfo.AppendFormat("<OutputFormat>{0}</OutputFormat>", outputFormat); if (pageWidth.HasValue) { deviceInfo.AppendFormat(" <PageWidth>{0}cm</PageWidth>", pageWidth); } if (pageHeight.HasValue) { deviceInfo.AppendFormat(" <PageHeight>{0}cm</PageHeight>", pageHeight); } if (marginTop.HasValue) { deviceInfo.AppendFormat(" <MarginTop>{0}cm</MarginTop>", marginTop); } if (marginLeft.HasValue) { deviceInfo.AppendFormat(" <MarginLeft>{0}cm</MarginLeft>", marginLeft); } if (marginRight.HasValue) { deviceInfo.AppendFormat(" <MarginRight>{0}cm</MarginRight>", marginRight); } if (marginBottom.HasValue) { deviceInfo.AppendFormat(" <MarginBottom>{0}cm</MarginBottom>", marginBottom); } deviceInfo.AppendLine("<Encoding>UTF-8</Encoding>"); deviceInfo.AppendFormat("</DeviceInfo>"); Warning[] warnings; string[] streams; localReport.Refresh(); //Render the report return(localReport.Render( reporteType, deviceInfo.ToString(), out mimeType, out encoding, out fileNameExtension, out streams, out warnings)); }
protected void BindHostingSpaceBandwidthOverusageDetailsReport(string reportName, LocalReport localReport) { // 1. Localize report localReport.DisplayName = reportName; localReport.LoadReportDefinition( ReportingServicesUtils.LoadReportFromFile( GetReportFullPath(reportName) , reportName , this ) ); // 2. Update parameters // Note: here we are always in Drill-through mode. localReport.SetParameters(localReport.OriginalParametersToDrillthrough); string hostingSpaceId = localReport.GetParameters()["HostingSpaceId"].Values[0]; List<ReportParameter> parameters = new List<ReportParameter>(); parameters.Add( new ReportParameter( ParameterBandwidthStartDate , startDateCalendar.SelectedDate.ToString() ) ); parameters.Add( new ReportParameter( ParameterBandwidthEndDate , endDateCalendar.SelectedDate.ToString() ) ); localReport.SetParameters(parameters); //3. Update data DataSet ds = ES.Services.Packages .GetBandwidthOverusageDetailsReport( PanelSecurity.SelectedUserId , int.Parse(hostingSpaceId) , startDateCalendar.SelectedDate , endDateCalendar.SelectedDate ); localReport.DataSources.Clear(); TranslateStatusField(ds.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_HostingSpace", ds.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_BandwidthOverusage", ds.Tables["BandwidthOverusage"]); BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", ds.Tables["OverusageDetails"]); localReport.Refresh(); }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _client = this.dgdClientVendor.ClientNumber; string _div = this.dgdClientVendor.ClientDivsionNumber; string _clientName = this.dgdClientVendor.ClientName; string _vendor = "", _pudate = "", _punum = ""; string filter = this.cboFilter.SelectedValue; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = TITLE; report.EnableExternalImages = true; EnterpriseRGateway enterprise = new EnterpriseRGateway(); DataSet ds = new DataSet(this.mDSName); foreach (GridViewRow row in SelectedRows) { DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex]; _vendor = dataKey["VendorNumber"].ToString(); _pudate = DateTime.Parse(dataKey["PUDate"].ToString()).ToString("yyyy-MM-dd"); _punum = dataKey["PUNumber"].ToString(); DataSet _ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _client, _div, _vendor, _pudate, _punum }); DataSet __ds = new DataSet(); if (filter.Length == 0) { __ds.Merge(_ds); } else if (filter == "OS") { __ds.Merge(_ds.Tables[mTBLName].Select("Status='O' OR Status='S'")); } else { __ds.Merge(_ds.Tables[mTBLName].Select("Status='" + filter + "'")); } ds.Merge(__ds); } if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(SOURCE); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); //Set the report parameters for the report ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter div = new ReportParameter("ClientDivision", _div); ReportParameter vendor = new ReportParameter("VendorNumber", ""); ReportParameter pudate = new ReportParameter("PUDate", ""); ReportParameter punum = new ReportParameter("PuNumber", "0"); ReportParameter vendorName = new ReportParameter("VendorName", ""); ReportParameter clientName = new ReportParameter("ClientName", _clientName); report.SetParameters(new ReportParameter[] { client, div, vendor, pudate, punum, vendorName, clientName }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName)); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=CartonNumberDiscrepancy.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex); } }
public ActionResult ViewPdfReportForSearchResult(int supplierId, string fromDate, string toDate) { try { List <DAL.ViewModel.VM_Product> productList = unitOfWork.CustomRepository.sp_ProductEntryHistoryFromSupplierToMainStore(Convert.ToDateTime(fromDate), Convert.ToDateTime(toDate), supplierId); var newProductList = new List <DAL.ViewModel.VM_Product>(); foreach (var product in productList) { DAL.ViewModel.VM_Product newProduct = new DAL.ViewModel.VM_Product(); newProduct.ProductName = product.ProductName; newProduct.UnitPrice = product.UnitPrice; newProduct.Quantity = product.Quantity; newProduct.TotalPrice = product.TotalPrice; newProductList.Add(newProduct); } string supplierName = unitOfWork.SuppliersInformationRepository.GetByID(supplierId).SupplierName; int restaurantId = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString());; string restaurantName = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name; string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/ProductEntryHistoryFromSupplierToMainStoreReport.rdlc"); localReport.SetParameters(new ReportParameter("FromDate", fromDate.ToString())); localReport.SetParameters(new ReportParameter("ToDate", toDate.ToString())); localReport.SetParameters(new ReportParameter("SupplierName", supplierName)); localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName)); localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress)); ReportDataSource reportDataSource = new ReportDataSource("ProductEntryHistoryFromSupplierToMainStoreDataSet", newProductList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); return(File(renderedBytes, mimeType)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
public byte[] GetExportFileFromEmbeddedReport(string reportName, DataSet reportData, string formatNm, IEnumerable <ReportParameter> reportParams, Dictionary <string, string> dataSrcDataTableMapping, List <string> subReportNames, bool includeDeviceInfo, out string fileExtension, out string mimeNType) { Warning[] warnings; string[] streamids; string mimeType; string encoding; string filenameExtension; //Set deviceInfo parameter string deviceInfo = null; if (includeDeviceInfo) { if (formatNm == "PDF") { deviceInfo = pdfDeviceInfo; } } Microsoft.Reporting.WebForms.LocalReport locReport = new LocalReport(); locReport.LoadReportDefinition(GetResourceStream(reportName.Trim())); if (dataSrcDataTableMapping != null && dataSrcDataTableMapping.Count > 0) { foreach (var dataSrcMapping in dataSrcDataTableMapping) { if (reportData.Tables.Contains(dataSrcMapping.Value)) { locReport.DataSources.Add(new ReportDataSource(dataSrcMapping.Key, reportData.Tables[dataSrcMapping.Value])); } } } else { foreach (DataTable dtbl in reportData.Tables) { //locReport.DataSources.Add(new ReportDataSource(string.Format("{0}_{1}", reportData.DataSetName, dtbl.TableName), dtbl)); locReport.DataSources.Add(new ReportDataSource(string.Format("{0}", reportData.DataSetName), dtbl)); } } if (subReportNames != null && subReportNames.Count > 0) { foreach (string subReport in subReportNames) { locReport.LoadSubreportDefinition(subReport, GetResourceStream(subReport)); } locReport.SubreportProcessing += new SubreportProcessingEventHandler(locReport_SubreportProcessing); } if (formatNm.ToUpper() == "EXCEL") { RenderingExtension[] renderExts = locReport.ListRenderingExtensions(); foreach (RenderingExtension renExt in renderExts) { if (renExt.Name.ToUpper() == "EXCELOPENXML") { formatNm = renExt.Name; break; } } } if (reportParams != null) { locReport.SetParameters(reportParams); } byte[] pdfBytes = locReport.Render(formatNm, deviceInfo, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); fileExtension = filenameExtension; mimeNType = mimeType; return(pdfBytes); }
private void SyncParameters(LocalReport localReport) { //设置参数值 foreach (var kv in this._parameters) { localReport.SetParameters(new ReportParameter(kv.Key, kv.Value)); } }
private void btnOK_Click(object sender, EventArgs e) { // valida os campos if (!this.ValidarCampos()) { return; } this.Cursor = Cursors.WaitCursor; try { //repositório var incidenciaDoencaEmUnidadeSaude = new DoencaEmUnidadeSaudeRepositorio(); //repositorio var incidenciaDoencaPorAno = new DoencaRepositorio(); //recupera informações para o relatório var listaIncidenciaDoencaEmUnidadeSaude = incidenciaDoencaEmUnidadeSaude.ListarDoencasERegionais((int)this.cmbDoenca.SelectedValue, this.dtDe.Value.Year, this.dtAte.Value.Year); var listaDeIncidenciaDoencaEmUnidadeSaude = listaIncidenciaDoencaEmUnidadeSaude.OrderBy(y => y.DescricaoDoenca).ToList(); //recupera lista de incidencia da doenca por ano var listaIncidenciaPorAno = incidenciaDoencaPorAno.ListarIncidenciaDoencaPorAno((int)this.cmbDoenca.SelectedValue, this.dtDe.Value.Year, this.dtAte.Value.Year); //ordena a lista por ano var listaDeIncidenciaPorAno = listaIncidenciaPorAno.OrderBy(w => w.Ano).ToList(); var incidencia = listaIncidenciaPorAno.OrderBy(x => x.Incidencia).ToList(); //define os datasources do relatório var localReport = new LocalReport(); localReport.ReportEmbeddedResource = "GestaoSMSAddin.DataAccess.Reports.DoencaEmUnidadesSaudeRpt.rdlc"; localReport.DataSources.Clear(); localReport.DataSources.Add(new ReportDataSource("DoencaEmUnidadesSaude", listaDeIncidenciaDoencaEmUnidadeSaude)); localReport.DataSources.Add(new ReportDataSource("Doenca", listaDeIncidenciaPorAno)); localReport.Refresh(); // parâmetros do relatório string descricaoDoenca = this.cmbDoenca.Text; string ano = DateTime.Now.Year.ToString(); string soma = listaIncidenciaDoencaEmUnidadeSaude.Sum(w => w.Incidencia).ToString(); var rptParameter1 = new ReportParameter("descricaoDoenca", descricaoDoenca); var rptParameter2 = new ReportParameter("ano", ano); var rptParameter3 = new ReportParameter("somaIncidencia", soma); localReport.SetParameters( new ReportParameter[] { rptParameter1, rptParameter2, rptParameter3 }); if (this.dtDe.Value.Year == this.dtAte.Value.Year) { string anoIncidencia = this.dtAte.Value.Year.ToString(); var rptParameter4 = new ReportParameter("anoIncidencia", anoIncidencia); localReport.SetParameters( new ReportParameter[] { rptParameter4 }); } else { string anoIncidencia = this.dtDe.Value.Year.ToString() + " - " + this.dtAte.Value.Year.ToString(); var rptParameter4 = new ReportParameter("anoIncidencia", anoIncidencia); localReport.SetParameters( new ReportParameter[] { rptParameter4 }); } //nome do relatório string nomePdfRelatorio = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + ".pdf"); //criação de arquivo do relatório byte[] pdfBytes = localReport.Render("PDF"); var binaryWriter = new BinaryWriter(new FileStream(nomePdfRelatorio, FileMode.CreateNew, FileAccess.Write)); binaryWriter.Write(pdfBytes, 0, pdfBytes.Length); binaryWriter.Close(); //mostra o arquivo de relatório ao usuário Process.Start(nomePdfRelatorio); } catch (Exception ex) { this.MostrarErro(ex); } finally { this.Cursor = Cursors.Default; } }
public ActionResult totaltongji(string action, string type = "PDF") { if (action == "查询全部档案统计信息") { LocalReport localReport = new LocalReport(); string dateS = Request.Form["startdata"]; string dateE = Request.Form["enddata"]; DateTime DataFrom = DateTime.Parse(Request.Form["startdata"]); DateTime DataTo = DateTime.Parse(Request.Form["enddata"]); //竣工档案 var jungong = db.vw_projectList.Where(ad => ad.dateReceived >= DataFrom).Where(ad => ad.dateReceived <= DataTo); int jungongProCnt = jungong.Count(); //竣工总工程数 List <vw_projectList> list1 = jungong.ToList(); long?jungongArchCnt = 0; for (int i = 0; i < list1.Count(); i++) { if (list1[i].archivesCount == null || list1[i].archivesCount == "") { list1[i].archivesCount = "0"; }//竣工案卷数 string n = list1[i].archivesCount.Trim(); long cnt = long.Parse(n); jungongArchCnt += cnt; } var jungongarea = db.vw_projectList.Where(ad => ad.dateReceived >= DataFrom).Where(ad => ad.dateReceived <= DataTo); List <vw_projectList> list2 = jungongarea.ToList(); double?jungongArea = 0; for (int i = 0; i < list2.Count(); i++) { if (list2[i].buildingArea == null) { list2[i].buildingArea = 0; } jungongArea += list2[i].buildingArea; //竣工工程面积 } //馆内 var jungongchargeNei = db.Charger.Where(ad => ad.chargeTime >= DataFrom).Where(ad => ad.chargeTime <= DataTo).Where(a => a.chargeClassify == 8); int jungongChargeN = jungongchargeNei.Count(); //馆内整理工程数 List <Charger> list3 = jungongchargeNei.ToList(); decimal? jungongtotalCharge = 0; decimal? jungongtheoryCharge = 0; for (int i = 0; i < list3.Count(); i++) { if (list3[i].totalExpense == null) { list3[i].totalExpense = 0; } if (list3[i].theoryExpense == null) { list3[i].theoryExpense = 0; } jungongtotalCharge += list3[i].totalExpense; //馆内整理收费 jungongtheoryCharge += list3[i].theoryExpense; //馆内理论整理收费 } //馆外 var jungongchargeWai = db.Charger.Where(ad => ad.chargeTime >= DataFrom).Where(ad => ad.chargeTime <= DataTo).Where(a => a.chargeClassify == 9); int jungongChargeW = jungongchargeWai.Count(); //馆外整理工程数 List <Charger> list4 = jungongchargeWai.ToList(); decimal? jungongtotalChargeW = 0; decimal? jungongtheoryChargeW = 0; for (int i = 0; i < list4.Count(); i++) { if (list4[i].totalExpense == null) { list4[i].totalExpense = 0; } if (list4[i].theoryExpense == null) { list4[i].theoryExpense = 0; } jungongtotalChargeW += list4[i].totalExpense; //馆外整理收费 jungongtheoryChargeW += list4[i].theoryExpense; //馆外理论整理收费 } //声像档案 var shengxiang = bb.VideoArchives.Where(ad => ad.dateReceived >= DataFrom).Where(ad => ad.dateReceived <= DataTo);; int shengxiangProCnt = shengxiang.Count(); //声像总工程数 List <VideoArchives> list5 = shengxiang.ToList(); int? videoArchCnt = 0; int? photoArchCnt = 0; double?videoarea = 0; for (int i = 0; i < list5.Count(); i++) { videoArchCnt += int.Parse(list5[i].videoCassetteBoxCount); //视频案卷数 photoArchCnt += int.Parse(list5[i].photoBoxCount); //照片案卷数 videoarea += list3[i].buildingArea; //声像工程面积 } var videocharge = db.Charger.Where(ad => ad.chargeTime >= DataFrom).Where(ad => ad.chargeTime <= DataTo).Where(a => a.chargeClassify == 3); List <Charger> list6 = videocharge.ToList(); decimal? videototalCharge = 0; decimal? videotheoryCharge = 0; for (int i = 0; i < list6.Count(); i++) { if (list6[i].totalExpense == null) { list6[i].totalExpense = 0; } if (list6[i].theoryExpense == null) { list6[i].theoryExpense = 0; } videototalCharge += list6[i].totalExpense; //声像档案盒资料费 videotheoryCharge += list6[i].theoryExpense; //声像理论档案盒资料费 } var videogongben = db.Charger.Where(ad => ad.chargeTime >= DataFrom).Where(ad => ad.chargeTime <= DataTo).Where(a => a.chargeClassify == 7); List <Charger> list7 = videogongben.ToList(); decimal? videototalgongben = 0; decimal? videotheorygongben = 0; for (int i = 0; i < list7.Count(); i++) { if (list7[i].totalExpense == null) { list7[i].totalExpense = 0; } if (list7[i].theoryExpense == null) { list7[i].theoryExpense = 0; } videototalgongben += list7[i].totalExpense; //声像录制工本费 videotheorygongben += list7[i].theoryExpense; //声像理论录制工本费 } //档案借阅收费汇总,包括查卷费和证明费 var jieyuecharge = db.Charger.Where(ad => ad.chargeTime >= DataFrom).Where(ad => ad.chargeTime <= DataTo).Where(a => (a.chargeClassify == 5) || (a.chargeClassify == 6) || (a.chargeClassify == 9)); List <Charger> list8 = jieyuecharge.ToList(); decimal? jieyuefei = 0; for (int i = 0; i < list8.Count(); i++) { if (list8[i].totalExpense == null) { list8[i].totalExpense = 0; } jieyuefei += list8[i].totalExpense; //借阅费汇总 } //档案复印收费汇总 var fuyincharge = db.Charger.Where(ad => ad.chargeTime >= DataFrom).Where(ad => ad.chargeTime <= DataTo).Where(a => (a.chargeClassify == 4)); List <Charger> list9 = fuyincharge.ToList(); decimal? fuyinfei = 0; for (int i = 0; i < list9.Count(); i++) { if (list9[i].totalExpense == null) { list9[i].totalExpense = 0; } fuyinfei += list9[i].totalExpense; //fuyin费汇总 } //收费合计 decimal?totalFee = jungongtotalCharge + jungongtotalChargeW + videototalCharge + videototalgongben + jieyuefei + fuyinfei; //规划档案 var guihua = eb.PlanProject.Where(ad => ad.dateReceived >= DataFrom).Where(ad => ad.dateReceived <= DataTo); int guihuaProCnt = guihua.Count(); //规划总工程数 int?NoS = guihua.Min(d => d.seqNo); int?NoE = guihua.Max(d => d.seqNo); var guihuabox = eb.PlanArchiveBox.Where(ad => ad.ID >= NoS).Where(ad => ad.ID <= NoE); int guihuaArchCnt = guihuabox.Count(); //规划案卷数 localReport.ReportPath = Server.MapPath("~/Report/guanzhang/totaltongji.rdlc"); ReportDataSource reportDataSource1 = new ReportDataSource("total", guihua); localReport.DataSources.Add(reportDataSource1); List <ReportParameter> parameterList = new List <ReportParameter>(); parameterList.Add(new ReportParameter("DataFrom", DataFrom.ToString().Trim())); parameterList.Add(new ReportParameter("DataTo", DataTo.ToString().Trim())); parameterList.Add(new ReportParameter("jungongProCnt", jungongProCnt.ToString().Trim())); parameterList.Add(new ReportParameter("jungongArchCnt", jungongArchCnt.ToString().Trim())); parameterList.Add(new ReportParameter("jungongArea", jungongArea.ToString().Trim())); parameterList.Add(new ReportParameter("jungongChargeN", jungongChargeN.ToString().Trim())); parameterList.Add(new ReportParameter("jungongtotalCharge", jungongtotalCharge.ToString().Trim())); parameterList.Add(new ReportParameter("jungongtheoryCharge", jungongtheoryCharge.ToString().Trim())); parameterList.Add(new ReportParameter("jungongChargeW", jungongChargeW.ToString().Trim())); parameterList.Add(new ReportParameter("jungongtotalChargeW", jungongtotalChargeW.ToString().Trim())); parameterList.Add(new ReportParameter("jungongtheoryChargeW", jungongtheoryChargeW.ToString().Trim())); parameterList.Add(new ReportParameter("shengxiangProCnt", shengxiangProCnt.ToString().Trim())); parameterList.Add(new ReportParameter("videoArchCnt", videoArchCnt.ToString().Trim())); parameterList.Add(new ReportParameter("photoArchCnt", photoArchCnt.ToString().Trim())); parameterList.Add(new ReportParameter("videoarea", videoarea.ToString().Trim())); parameterList.Add(new ReportParameter("videototalCharge", videototalCharge.ToString().Trim())); parameterList.Add(new ReportParameter("videotheoryCharge", videotheoryCharge.ToString().Trim())); parameterList.Add(new ReportParameter("videototalgongben", videototalgongben.ToString().Trim())); parameterList.Add(new ReportParameter("videotheorygongben", videotheorygongben.ToString().Trim())); parameterList.Add(new ReportParameter("jieyuefei", jieyuefei.ToString().Trim())); parameterList.Add(new ReportParameter("fuyinfei", fuyinfei.ToString().Trim())); parameterList.Add(new ReportParameter("totalFee", totalFee.ToString().Trim())); parameterList.Add(new ReportParameter("guihuaArchCnt", guihuaArchCnt.ToString().Trim())); parameterList.Add(new ReportParameter("guihuaProCnt", guihuaProCnt.ToString().Trim())); localReport.SetParameters(parameterList); string reportType = type; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + "<OutPutFormat>" + type + "</OutPutFormat>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings ); return(File(renderedBytes, mimeType)); } return(View()); }
// Create a local report for Report.rdlc, load the data, // export the report to an .emf file, and print it. private void RunPrint() { LocalReport report = new LocalReport(); report.ReportPath = "Laporan/PenerimaanDetail.rdlc"; PenerimaanDomain peDomain = GeneratePenerimaan(TbIDNoPengajuan.Text); ReportParameter[] parameters = new ReportParameter[6]; parameters[0] = new ReportParameter("No", peDomain.No); parameters[1] = new ReportParameter("TglPenerimaan", peDomain.TglPenerimaan); parameters[2] = new ReportParameter("Hal", peDomain.Hal); parameters[3] = new ReportParameter("Keterangan", peDomain.Keterangan); if (peDomain.Tipe.Equals("1")) { parameters[4] = new ReportParameter("Tipe", "Dengan Pengajuan Barang"); } else if (peDomain.Tipe.Equals("2")) { parameters[4] = new ReportParameter("Tipe", "Dengan Pengajuan Service"); } else { parameters[5] = new ReportParameter("Tipe", "Tanpa Pengajuan"); } SqlConnection conn = Common.getConnection(); string query = ""; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.Text; if (peDomain.Tipe.Equals("1")) { query = "select no_pengajuan from t_pengajuan_inventaris where id = " + peDomain.id + ""; } else if (peDomain.Tipe.Equals("2")) { query = "select no_pengajuan from t_service_inventaris where id = " + peDomain.id + ""; } cmd.CommandText = query; conn.Open(); try { SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); string pengajuan = reader["no_pengajuan"].ToString().Trim(); parameters[5] = new ReportParameter("RefPengajuan", pengajuan); } catch { } conn.Close(); report.SetParameters(parameters); DataTable dt = GetData(peDomain); report.DataSources.Add(new ReportDataSource("DataSet1", dt)); Export(report); Print(); }
public Task<HttpResponseMessage> PDF(int id, [FromUri]string empresa, string cliente, string inmueble, string local) { log.DebugFormat("Empresa: {0}, Cliente: {1}, Inmueble: {2}, Local: {3}", empresa, cliente, inmueble, local); if (id == 1) { string jsonSerial = serializer.Serialize(Queryable.AsQueryable<spPANGEAEdoCta_Result>(db.spPANGEAEdoCta(empresa, cliente, inmueble, local)).ToList()); using (Stream s = GenerateStreamFromString(jsonSerial)) { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(s) }; response.Content = new ByteArrayContent(((MemoryStream)s).ToArray()); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); return Task.FromResult(response); } } else { string pangeaWebApiCookie = null; CookieHeaderValue cookie = Request.Headers.GetCookies(supraterraCookie).FirstOrDefault(); var response = new HttpResponseMessage(HttpStatusCode.Forbidden); if (cookie != null) { pangeaWebApiCookie = cookie[supraterraCookie].Value; } else { return Task.FromResult(response); } var encoding = Encoding.GetEncoding("iso-8859-1"); var credentials = encoding.GetString(Convert.FromBase64String(pangeaWebApiCookie)); log.DebugFormat("Credenciales: {0}", credentials); int separator = credentials.IndexOf(':'); string name = credentials.Substring(0, separator); string password = credentials.Substring(separator + 1); if (CheckPassword(name, password)) { LocalReport report = new LocalReport(); //var assembly = Assembly.LoadFrom("PangeaWebApi.dll"); //var stream = assembly.GetManifestResourceStream("PangeaWebApi.Reportes.EdoCta.rdlc"); string reportPath = HttpContext.Current.Server.MapPath("~/Reportes/EdoCta.rdlc"); log.Debug(reportPath); //report.LoadReportDefinition(str) report.ReportPath = reportPath; ReportDataSource rds = new ReportDataSource(); rds.Name = "EdoCtaDataSet";//This refers to the dataset name in the RDLC file spPANGEAEdoCtaTableAdapter da = new spPANGEAEdoCtaTableAdapter(); rds.Value = da.GetData(empresa, cliente, inmueble, local); report.DataSources.Add(rds); ReportParameter[] parametros = new ReportParameter[1]; parametros[0] = new ReportParameter("Empresa", empresa); report.SetParameters(parametros); //Byte[] mybytes = report.Render("WORD"); Byte[] mybytes = report.Render("PDF");// for exporting to PDF //using (FileStream fs = File.Create(@"D:\SalSlip.doc")) //{ // fs.Write(mybytes, 0, mybytes.Length); //} Stream s = new MemoryStream(); //pdf.Save(s, false); response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new ByteArrayContent(mybytes); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = "Estado de Cuenta " + cliente + "-" + local + ".pdf"; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); } return Task.FromResult(response); } }
public void CreateReportAll() { LocalReport report = new LocalReport(); string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; int year = Int32.Parse(Session["year"].ToString()); ReportDataSource rds = new ReportDataSource(); rds.Name = "SampleAnalize"; string username = User.Identity.Name; UserInfos userinfos = UserInfos.getUserInfos(username); int fermaid = GetFermaId(userinfos.UserCod); if (fermaid != 0) { List<SampleAnalize> samples = SampleAnalize.GetSampleAnalize(fermaid,"",year); if (samples.Count > 0) { string[] parIds = { "g", "p", "c", "l", "s", "h", "u", "n", "z" }; string[] chartLabelsName = { "Grasime (g/100g)", "Proteine (g/100g)", "Cazeina (g/100g)", "Lactoza (g/100g)", "SUN (g/100g)", "pH", "Uree (mg/dl)", "NCSx1000", "Cantitate lapte (l)" }; string[] chartTitles = { "Grasime", "Proteine", "Cazeina", "Lactoza", "SUN", "Ph", "Uree", "NCS","Cantitate lapte"}; string[] um = { "g/100g", "g/100g", "g/100g", "g/100g", "g/100g", "pH", "mg/dl", "NCSx1000", "l" }; ContentPlaceHolder holder = (ContentPlaceHolder)Master.FindControl("MainContent"); for (int i = 0; i < 1 ; i++) {//parIds.Length string endChar = parIds[i].ToUpper(); CheckBox chk = (CheckBox)holder.FindControl("chk" + endChar); if (chk.Checked) { //set current param foreach (SampleAnalize sample in samples) { switch (i) { case 0: sample.Val = sample.Grasime; break; case 1: sample.Val = sample.Proteine; break; case 2: sample.Val = sample.Caseina; break; case 3: sample.Val = sample.Lactoza; break; case 4: sample.Val = sample.Solide; break; case 5: sample.Val = sample.Ph; break; case 6: sample.Val = sample.Urea; break; case 7: sample.Val = sample.Ncs; break; case 8: sample.Val = sample.Cantitate; break; default: break; } sample.Val = Math.Round(sample.Val, 2); } // create samplescontrol from samples // set reports datasource rds.Value = samples; report.DataSources.Clear(); report.DataSources.Add(rds); // ReportDataSource rdsc = new ReportDataSource(); rdsc.Name = "SampleAnalizeControl"; List<SampleAnalizeControl> samplescontrol = SampleAnalize.getSampleAnalizeControl(samples,year); rdsc.Value = samplescontrol; report.DataSources.Add(rdsc); // detaliu ReportDataSource rdscrot = new ReportDataSource(); rdscrot.Name = "SampleAnalizeCrotalia"; List<SampleAnalizeCrotalia> samplescrot = SampleAnalize.getSampleAnalizeCrotalia(fermaid, i,year); rdscrot.Value = samplescrot; report.DataSources.Add(rdscrot); //controale ReportDataSource rdsm = new ReportDataSource(); rdsm.Name = "SampleAnalizeExt"; List<SampleAnalizeExt> samplesext = SampleAnalize.GetSampleAnalizeExt(fermaid,year); rdsm.Value = samplesext; report.DataSources.Add(rdsm); report.ReportPath = "ControlsSummaryAll.rdlc"; string datatestare = "Data: " + DateTime.Now.ToString("dd/MM/yyyy"); // set reports parameters string title = userinfos.NumeFerma + " - " + "Cod exploatatie " + userinfos.UserCod; ReportParameter pCod = new ReportParameter("CodExpl", userinfos.UserCod); ReportParameter pData = new ReportParameter("DataExec", datatestare); ReportParameter pChartTitle = new ReportParameter("ChartTitle", chartTitles[i]); ReportParameter pChartLabelsName = new ReportParameter("ChartLabelsName", chartLabelsName[i]); ReportParameter pUm = new ReportParameter("Um", um[i]); ReportParameter pTitle = new ReportParameter("Title", title); ReportParameter pUsername = new ReportParameter("UserName", username); string baseurl = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + ConfigurationManager.AppSettings["baseurl"]; ReportParameter pBaseurl = new ReportParameter("BaseUrl", baseurl); ReportParameter[] p = { pCod, pData, pChartTitle, pChartLabelsName, pUm,pTitle,pUsername,pBaseurl }; report.SetParameters(p); report.Refresh(); // write xls string httppath = ConfigurationManager.AppSettings["httppath"]; //"/Downloads/"; string filepath = ConfigurationManager.AppSettings["filepath"]; //"D:\\portal\\Downloads\\"; string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string fileid = chartTitles[i]; if (i == 8) fileid = fileid.Substring(0, 4); string raport_excel = "Grafic" + fileid + "_" + userinfos.UserCod + "_" + (DateTime.Now).ToString("ddMMyyyy") + ".xls"; string excel_file = filepath + raport_excel; string excel_link = path_raport_http + raport_excel; byte[] xls_content = report.Render("EXCEL", deviceInfoXls, out mimeType, out encoding, out fileExtension, out streams, out warnings); File.WriteAllBytes(excel_file, xls_content); //rename sheets using (StreamReader input = new StreamReader(excel_file)) { HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(input.BaseStream)); if (workbook != null) { workbook.SetSheetName(0, chartTitles[i]); // workbook.SetSheetName(1, "Detaliu date"); WriteExcel(excel_file, workbook); } } // HyperLink hyper = (HyperLink)holder.FindControl("xlslink" + parIds[i]); hyper.Visible = true; hyper.NavigateUrl = excel_link; hyper.Text = raport_excel; ErrorMessage.Text = ""; } //checked }//for }//samplecount >0 }//fermaid >0 else { // ErrorMessage.Text = "Nu exista date pentru codul "+ userinfos.UserCod; } }
public void CreateReport() { ReportManager rManager = new ReportManager(ctx); DateTime testDate; int farmId; DateTime.TryParse(TextBox1.Text, out testDate); Int32.TryParse(DropDownList1.SelectedValue, out farmId); Report b = rManager.GetByDateAndId(testDate, farmId); string nrb = b.ReportNumber.ToString(); string datab = b.TestDate.ToShortDateString(); int pos = 0; LocalReport report = new LocalReport(); byte[] file; string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; string fabricaid = DropDownList1.SelectedValue; string fabricaname = DropDownList1.Items[DropDownList1.SelectedIndex].ToString(); // read fabrica SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["fccl2ConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.Connection = cnn; cmd.CommandText = "SELECT Fabrici.Strada,Fabrici.Numar,Fabrici.Oras,Judete.Denloc " + "FROM Fabrici,Judete WHERE Fabrici.ID=" + fabricaid + " AND Fabrici.Judet=Judete.ID"; cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); string fabricastrada = Convert.ToString(reader["Strada"]); string fabricanumar = Convert.ToString(reader["Numar"]); string fabricaoras = Convert.ToString(reader["Oras"]); string fabricajudet = Convert.ToString(reader["Denloc"]); reader.Close(); cnn.Close(); string datatestare = TextBox1.Text; // date fabrica //deviceinfo string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>29.7cm</PageWidth>" + " <PageHeight>21cm</PageHeight>" + " <MarginTop>0.0cm</MarginTop>" + " <MarginLeft>0.5cm</MarginLeft>" + " <MarginRight>0.5cm</MarginRight>" + " <MarginBottom>0.5cm</MarginBottom>" + "</DeviceInfo>"; string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp; string filepath = StaticDataHelper.SettingsManager.CaleRapoarte; cmd.CommandTimeout = 300; cmd.CommandText = "SELECT DISTINCT Ferme_CCL.Nume,Ferme_CCL.ID, MostreTancuri.FermaID, Ferme_CCL.Cod, " + "Ferme_CCL.Strada,Ferme_CCL.Numar, Ferme_CCL.Oras, Ferme_CCL.Judet,Ferme_CCL.PersonaDeContact,Ferme_CCL.TelPersoanaContact,Ferme_CCL.Ferme_CCL,Ferme_CCL.FermierID,Judete.Denloc " + " FROM MostreTancuri, Ferme_CCL INNER JOIN JUDETE ON Convert(int,Ferme_CCL.Judet,2)=Judete.ID WHERE" + " CONVERT(datetime, MostreTancuri.DataTestareFinala, 103) = CONVERT(datetime, '" + datatestare + "', 103) " + " AND MostreTancuri.CodFerma = Ferme_CCL.Cod " + " AND Ferme_CCL.FabricaID = " + fabricaid + " AND MostreTancuri.Validat = 1 ORDER BY Ferme_CCL.Nume"; cnn.Open(); SqlDataReader drferme = cmd.ExecuteReader(); //prepare report parameters string laborator = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString(); string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString(); string semnlab = ddlLaborator.SelectedValue; string semnresp = ddlResponsabil.SelectedValue; semnresp = semnresp.Substring(0, semnresp.LastIndexOf(".")); semnlab = semnlab.Substring(0, semnlab.LastIndexOf(".")); semnresp = semnresp.ToLower(); semnlab = semnlab.ToLower(); ReportParameter pDatatestare = new ReportParameter("datatestare", datatestare); ReportParameter pDatab = new ReportParameter("datab", datab); ReportParameter pNrb = new ReportParameter("nrb", nrb); ReportParameter pFabricanume = new ReportParameter("fabricanume", fabricaname); ReportParameter pFabricastrada = new ReportParameter("fabricastrada", fabricastrada); ReportParameter pFabricanumar = new ReportParameter("fabricanumar", fabricanumar); ReportParameter pFabricaoras = new ReportParameter("fabricaoras", fabricaoras); ReportParameter pFabricajudet = new ReportParameter("fabricajudet", fabricajudet); ReportParameter pLaborator = new ReportParameter("laborator", laborator); ReportParameter pResponsabil = new ReportParameter("responsabil", responsabil); List<FileLinks> list = new List<FileLinks>(); while (drferme.Read()) { FileLinks filelink = new FileLinks(); string fermacod = Convert.ToString(drferme["Cod"]); string fermanume = Convert.ToString(drferme["Nume"]); string fermastrada = Convert.ToString(drferme["Strada"]); string fermanumar = Convert.ToString(drferme["Numar"]); string fermaoras = Convert.ToString(drferme["Oras"]); string judet = Convert.ToString(drferme["Denloc"]); string codferma = Convert.ToString(drferme["Cod"]); string fermaadresa = "Str. " + fermastrada + " nr. " + fermanumar + ", " + fermaoras; string fermatelcontact = Convert.ToString(drferme["TelPersoanaContact"]); string fermaperscontact = Convert.ToString(drferme["PersonaDeContact"]); ReportDataSource rds = new ReportDataSource(); rds.Name = "MostreFabrica"; List<MostreFabrica> mostre = MostreFabrica.GetMostreFerma(fabricaid, fermacod, datatestare); rds.Value = mostre; // build dates interval string datatmin = datatestare; string datatmax = datatestare; string datatesttitlu = datatestare; string dataprimirii = ""; string datapmin = dataprimirii; string datapmax = dataprimirii; string dataprimtitlu = dataprimirii; string combi = mostre[0].Combi; foreach (MostreFabrica mf in mostre) { string datamin = mf.DataTestare; string datamax = mf.DataTestareFinala; dataprimirii = mf.DataPrimirii; if (datapmin == "") datapmin = dataprimirii; if (datapmax == "") datapmax = dataprimirii; if (datamin != datatmin) { DateTime dt1 = new DateTime(Int32.Parse(datamin.Substring(6, 4)), Int32.Parse(datamin.Substring(3, 2)), Int32.Parse(datamin.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datatmin.Substring(6, 4)), Int32.Parse(datatmin.Substring(3, 2)), Int32.Parse(datatmin.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) < 0) datatmin = datamin; } if (datamax != datatmax) { DateTime dt1 = new DateTime(Int32.Parse(datamax.Substring(6, 4)), Int32.Parse(datamax.Substring(3, 2)), Int32.Parse(datamax.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datatmax.Substring(6, 4)), Int32.Parse(datatmax.Substring(3, 2)), Int32.Parse(datatmax.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) > 0) datatmax = datamax; } // data primirii if (dataprimirii != datapmin) { DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datapmin.Substring(6, 4)), Int32.Parse(datapmin.Substring(3, 2)), Int32.Parse(datapmin.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) < 0) datapmin = dataprimirii; } if (dataprimirii != datapmax) { DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datapmax.Substring(6, 4)), Int32.Parse(datapmax.Substring(3, 2)), Int32.Parse(datapmax.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) > 0) datapmax = dataprimirii; } } if (datatmin != datatmax) datatesttitlu = datatmin + " - " + datatmax; if (datapmin != datapmax) dataprimtitlu = datapmin + " si " + datapmax; else dataprimtitlu = datapmin; // end dates interval report.DataSources.Clear(); report.DataSources.Add(rds); pos++; report.ReportPath = "ReportFerme4.rdlc"; report.Refresh(); ReportParameter pDatatitlu = new ReportParameter("datatestare", datatesttitlu); ReportParameter pDataprimirii = new ReportParameter("dataprimirii", dataprimtitlu); ReportParameter pCombi = new ReportParameter("combi", combi); ReportParameter pPos = new ReportParameter("pos", pos.ToString()); ReportParameter pCodferma = new ReportParameter("codferma", codferma); ReportParameter pFermanume = new ReportParameter("fermanume", fermanume); ReportParameter pFermaadresa = new ReportParameter("fermaadresa", fermaadresa); ReportParameter pFermajudet = new ReportParameter("fermajudet", judet); ReportParameter pFermaperscontact = new ReportParameter("fermaperscontact", fermaperscontact); ReportParameter pFermatelcontact = new ReportParameter("fermatelcontact", fermatelcontact); ReportParameter versiuneRaport = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportFerme4")); ReportParameter[] p ={ pDatatitlu,pDataprimirii,pCombi,pDatab,pNrb,pFabricanume,pFabricastrada,pFabricanumar,pFabricaoras,pFabricajudet,pLaborator,pResponsabil, pPos,pFermanume,pFermaadresa,pFermajudet,pCodferma,pFermaperscontact,pFermatelcontact, versiuneRaport}; report.SetParameters(p); file = report.Render("PDF", deviceInfo, out mimeType, out encoding, out fileExtension, out streams, out warnings); // read from date fixe!!! fermanume = replace_special_car_null(fermanume); string raport_name = "RaportFerma" + datatestare.Replace("/", "_") + "_" + fermacod + "-" + fermanume + ".pdf"; string raport_excel = "RaportFerma" + datatestare.Replace("/", "_") + "_" + fermacod + "-" + fermanume + ".xls"; string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string pdf_link = path_raport_http + @"Ferme/" + raport_name; string pdf_file = filepath + @"Ferme/" + raport_name; File.WriteAllBytes(pdf_file, file); filelink.Url = pdf_link; filelink.Des = raport_name; list.Add(filelink); } drferme.Close(); cnn.Close(); //raport cumulat LocalReport report_cum = new LocalReport(); ReportDataSource rdsc = new ReportDataSource(); rdsc.Name = "MostreFabrica1"; rdsc.Value = MostreFabrica.GetMostreFabrica(fabricaid, datatestare); report_cum.DataSources.Clear(); report_cum.DataSources.Add(rdsc); report_cum.ReportPath = "ReportCumulat4.rdlc"; report_cum.Refresh(); ReportParameter pSemnlab = new ReportParameter("semnlab", semnlab); ReportParameter pSemnresp = new ReportParameter("semnresp", semnresp); ReportParameter pVersiuneRaport = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportCumulat4")); ReportParameter[] rp = { pDatatestare, pDatab, pNrb, pFabricanume, pFabricastrada, pFabricanumar, pFabricaoras, pFabricajudet, pLaborator, pResponsabil, pSemnlab, pSemnresp, pVersiuneRaport }; report_cum.SetParameters(rp); byte[] file_cum = report_cum.Render("PDF", deviceInfo, out mimeType, out encoding, out fileExtension, out streams, out warnings); string fabricanume = replace_special_car_null(fabricaname); string raport_name_cum = "RaportCumulat" + datatestare.Replace("/", "_") + "_" + fabricaid + "-" + fabricanume + ".pdf"; string path_raport_http_cum = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string pdf_link_cum = path_raport_http_cum + @"Ferme/" + raport_name_cum; string pdf_file_cum = filepath + @"Ferme/" + raport_name_cum; // writefile File.WriteAllBytes(pdf_file_cum, file_cum); linkall.Visible = true; linkall.NavigateUrl = pdf_link_cum; linkall.Text = raport_name_cum; // Repeater1.DataSource = list; Repeater1.DataBind(); Repeater1.Visible = true; }
private HttpResponseMessage PostScheduledTrainingReport(string exportFormat, string orderByField, string groupByField) { try { var data = reportObject.PostScheduledTrainingReport(); var report = new LocalReport { ReportPath = @".\Reports\ScheduledTraining.rdlc" }; report.DataSources.Add( new ReportDataSource("DataSet1", data)); var rp = new ReportParameter("OrderByField", orderByField); var gf = new ReportParameter("GroupByField", groupByField); report.SetParameters(rp); report.SetParameters(gf); return Export(report, exportFormat); } catch (Exception e) { Logger.Error(e); throw new Exception(e.Message); } }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _client = Master.ClientNumber; string _agent = Master.AgentNumber; string _start = Master.StartDate; string _end = Master.EndDate; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = REPORT_NAME; report.EnableExternalImages = true; EnterpriseGateway enterprise = new EnterpriseGateway(); DataSet ds = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _client, _agent, _start, _end }); if (ds.Tables[TBL_REPORT].Rows.Count >= 0) { switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); //Set the report parameters for the report ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter agent = new ReportParameter("AgentNumber", _agent); ReportParameter start = new ReportParameter("StartDate", _start); ReportParameter end = new ReportParameter("EndDate", _end); report.SetParameters(new ReportParameter[] { client, agent, start, end }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, REPORT_DS, "RGXSQLR.TSORT")); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=ScanningSummaryByClient.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[TBL_REPORT]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } else { Master.Status = "There were no records found."; } }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query DateTime _from = Master.FromDate; DateTime _to = Master.ToDate; string _client = Master.ClientNumber; string _clientName = Master.ClientName; string _div = Master.DivisionNumber; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = this.mTitle; report.EnableExternalImages = true; EnterpriseGateway enterprise = new EnterpriseGateway(); DataSet ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _client, _div, _from.ToString("yyyy-MM-dd"), _to.ToString("yyyy-MM-dd") }); if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(this.mSource); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); //Set the report parameters for the report ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter div = new ReportParameter("ClientDivision", _div); ReportParameter from = new ReportParameter("StartPUDate", _from.ToString("yyyy-MM-dd")); ReportParameter to = new ReportParameter("EndPUDate", _to.ToString("yyyy-MM-dd")); ReportParameter clientName = new ReportParameter("ClientName", _clientName); report.SetParameters(new ReportParameter[] { client, div, from, to, clientName }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName)); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=OnTimeByDayAndWindow.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex); } }
public void CreateReportExt() { LocalReport report = new LocalReport(); string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; int year = Int32.Parse(Session["year"].ToString()); report.SubreportProcessing += new SubreportProcessingEventHandler(ItemsSubreportProcessingEventHandler); string username = User.Identity.Name; UserInfos userinfos = UserInfos.getUserInfos(username); int fermaid = GetFermaId(userinfos.UserCod); if (fermaid != 0) { string[] parIds = { "g", "p", "c", "l", "s", "h", "u", "n", "z" }; string[] chartLabelsName = { "Grasime (g/100g)", "Proteine (g/100g)", "Cazeina (g/100g)", "Lactoza (g/100g)", "SUN (g/100g)", "pH", "Uree (mg/dl)", "NCSx1000", "Cantitate lapte (l)" }; string[] chartTitles = { "Grasime", "Proteine", "Cazeina", "Lactoza", "SUN", "Ph", "Uree", "NCS","Cantitate lapte"}; string[] um = { "g/100g", "g/100g", "g/100g", "g/100g", "g/100g", "pH", "mg/dl", "NCSx1000", "l" }; //controale ReportDataSource rdsm = new ReportDataSource(); rdsm.Name = "SampleAnalizeExt"; List<SampleAnalizeExt> samplesext = SampleAnalize.GetSampleAnalizeExt(fermaid,year); rdsm.Value = samplesext; report.DataSources.Clear(); report.DataSources.Add(rdsm); report.ReportPath = "ControlsSummaryExt.rdlc"; string datatestare = "Data: " + DateTime.Now.ToString("dd/MM/yyyy"); // set reports parameters string title = userinfos.NumeFerma + " - " + "Cod exploatatie " + userinfos.UserCod; ReportParameter pCod = new ReportParameter("CodExpl", userinfos.UserCod); ReportParameter pData = new ReportParameter("DataExec", datatestare); // ReportParameter pChartTitle = new ReportParameter("ChartTitle", chartTitles[i]); // ReportParameter pChartLabelsName = new ReportParameter("ChartLabelsName", chartLabelsName[i]); // ReportParameter pUm = new ReportParameter("Um", um[i]); ReportParameter pTitle = new ReportParameter("Title", title); ReportParameter pUsername = new ReportParameter("UserName", username); string baseurl = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + ConfigurationManager.AppSettings["baseurl"]; ReportParameter pBaseurl = new ReportParameter("BaseUrl", baseurl); ReportParameter[] p = { pCod, pData,pTitle,pBaseurl,pUsername }; report.SetParameters(p); report.Refresh(); // write xls string httppath = ConfigurationManager.AppSettings["httppath"]+userinfos.AsocId+"/" + year +"/"; //"/Downloads/"; string filepath = ConfigurationManager.AppSettings["filepath"]+userinfos.AsocId+"\\" + year +"\\"; if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } //"D:\\portal\\Downloads\\"; string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string fileid = chartTitles[0]; string fermaname = replace_special_car_null(userinfos.NumeFerma); string raport_excel = userinfos.UserCod + "_" + fermaname +".xls"; string excel_file = filepath + raport_excel; string excel_link = path_raport_http + raport_excel; byte[] xls_content = report.Render("EXCEL", deviceInfoXls, out mimeType, out encoding, out fileExtension, out streams, out warnings); File.WriteAllBytes(excel_file, xls_content); //rename sheets List<SampleAnalize> samples = SampleAnalize.GetSampleAnalize(fermaid, "",year); using (StreamReader input = new StreamReader(excel_file)) { HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(input.BaseStream)); if (workbook != null && samples.Count >0) { for (int count=0; count < samples.Count; count++) workbook.SetSheetName(count, samples[count].Nrcontrol); for (int count = 0; count < chartTitles.Length; count++) { string sheetname = chartTitles[count].Replace(" ", ""); workbook.SetSheetName(count + samples.Count, "Grafic" + sheetname); } // workbook.SetSheetName(1, "Detaliu date"); WriteExcel(excel_file, workbook); } } // ContentPlaceHolder holder = (ContentPlaceHolder)Master.FindControl("MainContent"); HyperLink hyper = (HyperLink)holder.FindControl("xlslink" + parIds[0]); hyper.Visible = true; hyper.NavigateUrl = excel_link; hyper.Text = raport_excel; ErrorMessage.Text = ""; }//fermaid >0 else { // ErrorMessage.Text = "Nu exista date pentru codul "+ userinfos.UserCod; } }
public ActionResult ViewPdfReportForVoucher(int?VoucherID) { try { var VoucherDetailsList = unitOfWork.AccVoucherDetailsRepository.Get().Where(a => a.VoucherID == VoucherID).Select(s => new VM_AccVoucher() { VoucherDetailID = s.VoucherDetailID.ToString(), VoucherID = s.VoucherID, LedgerID = s.LedgerID.ToString(), LedgerName = s.acc_Ledger.LedgerName, Debit = (double)s.Debit, Credit = (double)s.Credit, ChequeNumber = s.ChequeNumber, TransactionDate = s.TransactionDate.ToString(), VTypeID = (int)s.VTypeID, OCode = (int)s.OCode, RestaurantId = (int)s.RestaurantId, CreatedBy = s.CreatedBy, CreatedDateTime = s.CreatedDateTime.ToString(), EditedBy = s.EditedBy, EditedDateTime = s.EditedDateTime.ToString() }).ToList(); string VNumber = unitOfWork.AccVoucherEntryRepository.GetByID(VoucherID).VNumber; string VoucherName = unitOfWork.AccVoucherEntryRepository.GetByID(VoucherID).VoucherName; string transactionDate = unitOfWork.AccVoucherEntryRepository.GetByID(VoucherID).TransactionDate.ToString(); int restaurantId = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString());; string restaurantName = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name; string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address; LocalReport localReport = new LocalReport(); localReport.ReportPath = Server.MapPath("~/Reports/VoucherReport.rdlc"); localReport.SetParameters(new ReportParameter("VNumber", VNumber)); localReport.SetParameters(new ReportParameter("VoucherName", VoucherName)); localReport.SetParameters(new ReportParameter("TransactionDate", transactionDate)); localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName)); localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress)); ReportDataSource reportDataSource = new ReportDataSource("VoucherDataSet", VoucherDetailsList); localReport.DataSources.Add(reportDataSource); string reportType = "pdf"; string mimeType; string encoding; string fileNameExtension; //The DeviceInfo settings should be changed based on the reportType //http://msdn.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</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; //Render the report renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); return(File(renderedBytes, mimeType)); } catch (Exception ex) { return(Json(new { success = false, errorMessage = ex.Message }, JsonRequestBehavior.AllowGet)); } }
public ActionResult ReportEmpleados(string id, Int32 idempleado, DateTime fechaIni, DateTime fechaFin) { LocalReport lr = new LocalReport(); var pru = empleadoService.ObtenerEmpleadoPorCriterios(idempleado, fechaIni, fechaFin); string path = Path.Combine(Server.MapPath("~/Reportes"), "ReporteEmpleados.rdlc"); if (System.IO.File.Exists(path)) { lr.ReportPath = path; } else { return View("ReporteEmpleado"); } string reportType = id; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + id + "</OutputFormat>" + " <PageWidth>21cm</PageWidth>" + " <PageHeight>29.7cm</PageHeight>" + " <MarginTop>1.54cm</MarginTop>" + " <MarginLeft>1.54cm</MarginLeft>" + " <MarginRight>1.54cm</MarginRight>" + " <MarginBottom>1.54cm</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; ReportDataSource rd = new ReportDataSource("VistaEmpleados", pru); lr.DataSources.Add(rd); var empleado = empleadoService.ObtenerEmpleadoPorId(idempleado); ReportParameter[] parametros = new ReportParameter[6]; parametros[0] = new ReportParameter("Nombre", empleado.Nombre); parametros[1] = new ReportParameter("Apellidos", empleado.Apellidos); parametros[2] = new ReportParameter("Telefono", empleado.Telefono); parametros[3] = new ReportParameter("FechaIni", fechaIni.Date.Day + "/" + fechaIni.Date.Month + "/" + fechaIni.Date.Year + ""); parametros[4] = new ReportParameter("FechaFin", fechaFin.Date.Day + "/" + fechaFin.Date.Month + "/" + fechaFin.Date.Year + ""); parametros[5] = new ReportParameter("TotalHoras", pru.Count() + ""); lr.SetParameters(parametros); renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); switch (id) { case "PDF": return File(renderedBytes, mimeType); case "Excel": return File(renderedBytes, mimeType, "Empleado " + empleado.Nombre + DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Date.Year + ".xls"); case "Word": return File(renderedBytes, mimeType, "Empleado " + empleado.Nombre + DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Date.Year + ".doc"); case "Image": return File(renderedBytes, mimeType, "Empleado " + empleado.Nombre + DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Date.Year + ".png"); default: break; } var emp = empleadoService.ObtenerEmpleadoPorId(idempleado); RegUsuarios movimiento = new RegUsuarios { Usuario = User.Identity.Name, Modulo = "Empleado", Cambio = "Reporte", IdModulo = emp.NombreMostrar, Fecha = DateTime.Today }; movCuentaService.GuardarMovimiento(movimiento); return File(renderedBytes, mimeType); }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for view button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _from = DateTime.Parse(this.txtFrom.Text).ToString("yyyy-MM-dd"); string _to = DateTime.Parse(this.txtTo.Text).ToString("yyyy-MM-dd"); string _client = this.cboClient.SelectedValue; string _terminal = this.cboTerminal.SelectedValue == "" ? null : this.cboTerminal.SelectedValue; string _vendor = this.cboVendor.SelectedValue == "" ? null : this.cboVendor.SelectedValue; string _zone = this.cboZone.SelectedValue == "" ? null : this.cboZone.SelectedValue; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = TITLE; report.EnableExternalImages = true; EnterpriseRGateway enterprise = new EnterpriseRGateway(); DataSet ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _client, _terminal, _vendor, _zone, _from, _to }); if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(SOURCE); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); //Set the report parameters for the report ReportParameter client = new ReportParameter("ClientNumber", _client); ReportParameter terminal = new ReportParameter("TerminalCode", _terminal); ReportParameter vendor = new ReportParameter("VendorNumber", _vendor); ReportParameter zone = new ReportParameter("ZoneCode", _zone); ReportParameter from = new ReportParameter("StartSortDate", _from.ToString()); ReportParameter to = new ReportParameter("EndSortDate", _to.ToString()); report.SetParameters(new ReportParameter[] { client, terminal, vendor, zone, from, to }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName)); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=ClientCube.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex); } }
public void CreateReport() { ReportManager rManager = new ReportManager(ctx); LocalReport report = new LocalReport(); byte[] file; string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; long reportNumber; Report dalReport = rManager.GetOrCreateReport(FCCLReportType.FCB, -1 , DropDownList1.SelectedItem.Text, TestDate, PrintDate, long.TryParse(TextBox3.Text, out reportNumber) ? (long?)reportNumber : null); TextBox3.Text = dalReport.ReportNumber.ToString(); ReportDataSource rds = new ReportDataSource(); rds.Name = "MostreFabrica"; List<MostreFabrica> mostre = MostreFabrica.GetMostreFCB(DropDownList1.SelectedValue, TextBox1.Text); rds.Value = mostre; string datatestare = TextBox1.Text; string datatmin = datatestare; string datatmax = datatestare; string datatesttitlu = datatestare; string dataprimirii = ""; string datapmin = dataprimirii; string datapmax = dataprimirii; string dataprimtitlu = dataprimirii; string combi = mostre[0].Combi; foreach (MostreFabrica mf in mostre) { string datamin = mf.DataTestare; string datamax = mf.DataTestareFinala; dataprimirii = mf.DataPrimirii; if (datapmin == "") datapmin = dataprimirii; if (datapmax == "") datapmax = dataprimirii; if (datamin != datatmin) { DateTime dt1 = new DateTime(Int32.Parse(datamin.Substring(6, 4)), Int32.Parse(datamin.Substring(3, 2)), Int32.Parse(datamin.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datatmin.Substring(6, 4)), Int32.Parse(datatmin.Substring(3, 2)), Int32.Parse(datatmin.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) < 0) datatmin = datamin; } if (datamax != datatmax) { DateTime dt1 = new DateTime(Int32.Parse(datamax.Substring(6, 4)), Int32.Parse(datamax.Substring(3, 2)), Int32.Parse(datamax.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datatmax.Substring(6, 4)), Int32.Parse(datatmax.Substring(3, 2)), Int32.Parse(datatmax.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) > 0) datatmax = datamax; } // data primirii if (dataprimirii != datapmin) { DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datapmin.Substring(6, 4)), Int32.Parse(datapmin.Substring(3, 2)), Int32.Parse(datapmin.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) < 0) datapmin = dataprimirii; } if (dataprimirii != datapmax) { DateTime dt1 = new DateTime(Int32.Parse(dataprimirii.Substring(6, 4)), Int32.Parse(dataprimirii.Substring(3, 2)), Int32.Parse(dataprimirii.Substring(0, 2))); DateTime dt2 = new DateTime(Int32.Parse(datapmax.Substring(6, 4)), Int32.Parse(datapmax.Substring(3, 2)), Int32.Parse(datapmax.Substring(0, 2))); if (DateTime.Compare(dt1, dt2) > 0) datapmax = dataprimirii; } } if (datatmin != datatmax) datatesttitlu = datatmin + " - " + datatmax; if (datapmin != datapmax) dataprimtitlu = datapmin + " si " + datapmax; else dataprimtitlu = datapmin; rds.Value = mostre; report.DataSources.Clear(); report.DataSources.Add(rds); report.ReportPath = "ReportFCB4.rdlc"; report.Refresh(); string client = DropDownList1.SelectedValue; // read fabrica SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["fccl2ConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.Connection = cnn; cmd.CommandText = "SELECT MostreTancuri.AdresaClient,MostreTancuri.NumeClient,MostreTancuri.Localitate,MostreTancuri.Judet,MostreTancuri.NrComanda " + "FROM MostreTancuri WHERE MostreTancuri.NumeClient='" + client + "'"; cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); string fabricastrada = mostre[0].FabriciStrada; string fabricaoras = mostre[0].FabriciOras; string fabricajudet = mostre[0].FabriciJudet; string nrcomanda = mostre[0].NrComanda; reader.Close(); cnn.Close(); string nrb = dalReport.ReportNumber.ToString(); ; //set report parameters string laborator = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString(); string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString(); ReportParameter pDatatestare = new ReportParameter("datatestare", datatesttitlu); ReportParameter pDataprimirii = new ReportParameter("dataprimirii", dataprimtitlu); ReportParameter pCombi = new ReportParameter("combi", combi); ReportParameter pDatab = new ReportParameter("datab", TextBox2.Text); ReportParameter pNrb = new ReportParameter("nrb", nrb); ReportParameter pFabricanume = new ReportParameter("fabricanume", client); ReportParameter pFabricastrada = new ReportParameter("fabricastrada", fabricastrada); ReportParameter pComanda = new ReportParameter("nrcomanda", nrcomanda); ReportParameter pFabricaoras = new ReportParameter("fabricaoras", fabricaoras); ReportParameter pFabricajudet = new ReportParameter("fabricajudet", fabricajudet); ReportParameter pLaborator = new ReportParameter("laborator", laborator); ReportParameter pResponsabil = new ReportParameter("responsabil", responsabil); ReportParameter pVersiune = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportFCB4")); ReportParameter[] p = { pDatatestare, pDataprimirii, pCombi, pDatab, pNrb, pFabricanume, pFabricastrada, pComanda, pFabricaoras, pFabricajudet, pLaborator, pResponsabil, pVersiune }; report.SetParameters(p); file = report.Render("PDF", StaticData.DEVICE_INFO_PDF, out mimeType, out encoding, out fileExtension, out streams, out warnings); string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp; string filepath = StaticDataHelper.SettingsManager.CaleRapoarte; string parse_client = replace_special_car(client); string raport_name = "RaportFCB" + datatestare.Replace("/", "_") + "_" + nrb + "_" + parse_client + ".pdf"; string raport_excel = "RaportFCB" + datatestare.Replace("/", "_") + "_" + nrb + "_" + parse_client + ".xls"; string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string pdf_link = path_raport_http + @"FCB/" + raport_name; string pdf_file = filepath + @"FCB/" + raport_name; // writefile string excel_link = path_raport_http + @"FCB/" + raport_excel; string excel_file = filepath + @"FCB/" + raport_excel; report.SetParameters(new ReportParameter("BkImage", "")); File.WriteAllBytes(pdf_file, file); dalReport.SampleCount = mostre.Count; dalReport.PageCount = PDFHelper.GetNumberOfPdfPages(pdf_file); rManager.Save(dalReport); ctx.SaveChanges(); byte[] file_xls = report.Render("EXCEL", StaticData.DEVICE_INFO_XLS, out mimeType, out encoding, out fileExtension, out streams, out warnings); File.WriteAllBytes(excel_file, file_xls); pdflink.Visible = true; pdflink.NavigateUrl = pdf_link; pdflink.Text = raport_name; xlslink.Visible = true; xlslink.NavigateUrl = excel_link; xlslink.Text = raport_excel; }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked try { //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _start = DateTime.Parse(this.txtFrom.Text).ToString("yyyy-MM-dd"); string _end = DateTime.Parse(this.txtTo.Text).ToString("yyyy-MM-dd"); string _flag = this.cboFilter.SelectedValue; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = TITLE; report.EnableExternalImages = true; EnterpriseRGateway enterprise = new EnterpriseRGateway(); DataSet ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _start, _end, _flag }); if (ds.Tables[mTBLName] == null) { ds.Tables.Add(mTBLName); } switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(SOURCE); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); //Set the report parameters for the report ReportParameter start = new ReportParameter("FromDate", _start); ReportParameter end = new ReportParameter("ToDate", _end); report.SetParameters(new ReportParameter[] { start, end }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName)); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=LOccitaneDelivery.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[mTBLName]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } catch (Exception ex) { Master.ReportError(ex); } }
private byte[] GenerateReportForCombo(List<ComboBoxDTO> combos, rptProjectCwaIwpDTO rptInfo, string listTitle) { byte[] bytes = null; Microsoft.Reporting.WebForms.Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; string DeviceInfo = "<DeviceInfo>" + " <OutputFormat>JPEG</OutputFormat>" + " <EndPage>1</EndPage>" + " <PageWidth>8in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0in</MarginTop>" + " <MarginLeft>0in</MarginLeft>" + " <MarginRight>0in</MarginRight>" + " <MarginBottom>0in</MarginBottom>" + "</DeviceInfo>"; List<ReportParameter> paramList = new List<ReportParameter>(); //Default Parameter paramList = GetReportParams(rptInfo); //Defined Parameter For Combo paramList.Add(new ReportParameter("par_title", string.IsNullOrEmpty(listTitle) ? "" : listTitle)); //List Title if (combos == null || combos.Count <= 0) combos = new List<ComboBoxDTO>(); LocalReport report = new LocalReport(); report.ReportPath = @".\Prev\Resource\rdl\RPTAssembleList.rdl"; report.EnableExternalImages = true; report.SetParameters(paramList); report.DataSources.Clear(); //Material DataSource report.DataSources.Add(new ReportDataSource("rptCombobox", combos)); bytes = report.Render("Image", DeviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings); return bytes; }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _cartonID = this.txtSearchNo.Text; string _client = this.grdClients.SelectedRow.Cells[1].Text; string _div = this.grdClients.SelectedRow.Cells[2].Text; string _clientName = this.grdClients.SelectedRow.Cells[3].Text; string _terminal = this.grdClients.SelectedRow.Cells[4].Text; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = REPORT_NAME; report.EnableExternalImages = true; EnterpriseGateway enterprise = new EnterpriseGateway(); DataSet ds = enterprise.FillDataset(((this.cboSearchBy.SelectedValue == "ByCarton") ? USP_REPORT_BYCARTONNUMBER : USP_REPORT_BYLABELSEQNUMBER), TBL_REPORT, new object[] { _cartonID, _terminal, _client }); if (ds.Tables[TBL_REPORT].Rows.Count >= 0) { switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); //Set the report parameters for the report ReportParameter cartonID = new ReportParameter("SearchNumber", _cartonID); ReportParameter terminal = new ReportParameter("TerminalCode", _terminal); ReportParameter client = new ReportParameter("Client", _client); report.SetParameters(new ReportParameter[] { cartonID, terminal, client }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, REPORT_DS, "RGXSQLR.TSORT")); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=CartonSearch.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[TBL_REPORT]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } else { Master.Status = "There were no records found."; } }
public static byte[] RenderReport(ReportTypeEnum type, Dictionary<string, object> dataSources, string reportePathCompleto, string[] columnasMostrar, IDictionary<string, string> parametros, IDictionary<string, string> imagenes, decimal? pageWidth, decimal? pageHeight, decimal? marginTop, decimal? marginLeft, decimal? marginRight, decimal? marginBottom, out string mimeType) { var localReport = new LocalReport(); ReporteLoadReportDefinition(localReport, reportePathCompleto, imagenes); localReport.DataSources.Clear(); foreach (var dataSourcesName in dataSources.Keys) { var reporteDataSource = new ReportDataSource(dataSourcesName, dataSources[dataSourcesName]); localReport.DataSources.Add(reporteDataSource); } //Imagenes externas localReport.EnableExternalImages = true; if (columnasMostrar.Any()) { var sb = new StringBuilder(); foreach (string columna in columnasMostrar) { sb.AppendFormat("#{0}#", columna.Trim()); } parametros.Add("Columnas", sb.ToString()); } foreach (var clave in parametros.Keys) { var param = new ReportParameter(); param.Name = clave; param.Values.Add(parametros[clave]); localReport.SetParameters(param); } string outputFormat = OutputFormat(type); string reporteType = ReportType(type); string encoding; string fileNameExtension; StringBuilder deviceInfo = new StringBuilder(); deviceInfo.AppendFormat("<DeviceInfo>"); deviceInfo.AppendFormat("<OutputFormat>{0}</OutputFormat>", outputFormat); if (pageWidth.HasValue) { deviceInfo.AppendFormat(" <PageWidth>{0}cm</PageWidth>", pageWidth); } if (pageHeight.HasValue) { deviceInfo.AppendFormat(" <PageHeight>{0}cm</PageHeight>", pageHeight); } if (marginTop.HasValue) { deviceInfo.AppendFormat(" <MarginTop>{0}cm</MarginTop>", marginTop); } if (marginLeft.HasValue) { deviceInfo.AppendFormat(" <MarginLeft>{0}cm</MarginLeft>", marginLeft); } if (marginRight.HasValue) { deviceInfo.AppendFormat(" <MarginRight>{0}cm</MarginRight>", marginRight); } if (marginBottom.HasValue) { deviceInfo.AppendFormat(" <MarginBottom>{0}cm</MarginBottom>", marginBottom); } deviceInfo.AppendLine("<Encoding>UTF-8</Encoding>"); deviceInfo.AppendFormat("</DeviceInfo>"); Warning[] warnings; string[] streams; localReport.Refresh(); //Render the report return localReport.Render( reporteType, deviceInfo.ToString(), out mimeType, out encoding, out fileNameExtension, out streams, out warnings); }
/// <summary> /// used to print report /// </summary> /// <param name="Batch"></param> /// <param name="ListToPrint"></param> private void PrintReport(string Batch, List <Barcode> ListToPrint) { //sb copy LocalReport packingReportSB = new LocalReport(); packingReportSB.ReportPath = AppDomain.CurrentDomain.BaseDirectory + @"Reports\WATSONSXPackingList.rdlc"; packingReportSB.DataSources.Add(new ReportDataSource("DataSet", ListToPrint)); List <ReportParameter> packingListParametersSB = new List <ReportParameter>(); packingListParametersSB.Add(new ReportParameter("Title", "PACKING LIST - SB COPY")); packingListParametersSB.Add(new ReportParameter("Batch", Batch)); packingReportSB.SetParameters(packingListParametersSB); //customer copy LocalReport packingReportCustomer = new LocalReport(); packingReportCustomer.ReportPath = AppDomain.CurrentDomain.BaseDirectory + @"Reports\WATSONSXPackingList.rdlc"; packingReportCustomer.DataSources.Add(new ReportDataSource("DataSet", ListToPrint)); List <ReportParameter> packingListParametersCustomer = new List <ReportParameter>(); packingListParametersCustomer.Add(new ReportParameter("Title", "PACKING LIST - Customer Copy")); packingListParametersCustomer.Add(new ReportParameter("Batch", Batch)); packingReportCustomer.SetParameters(packingListParametersCustomer); //finance copy LocalReport packingReportFinance = new LocalReport(); packingReportFinance.ReportPath = AppDomain.CurrentDomain.BaseDirectory + @"Reports\WATSONSXPackingList.rdlc"; packingReportFinance.DataSources.Add(new ReportDataSource("DataSet", ListToPrint)); List <ReportParameter> packingListParametersFinance = new List <ReportParameter>(); packingListParametersFinance.Add(new ReportParameter("Title", "PACKING LIST - Finance Copy")); packingListParametersFinance.Add(new ReportParameter("Batch", Batch)); packingReportFinance.SetParameters(packingListParametersFinance); string deviceInfo = @"<DeviceInfo> <OutputFormat>EMF</OutputFormat> <PageWidth>8.27in</PageWidth> <PageHeight>11.69in</PageHeight> <MarginTop>0.0in</MarginTop> <MarginLeft>0.0in</MarginLeft> <MarginRight>0.0in</MarginRight> <MarginBottom>0.0in</MarginBottom> </DeviceInfo>"; DynamicPrinting packingListPrinting = new DynamicPrinting(); //sb copy packingListPrinting.Export(packingReportSB, deviceInfo); packingListPrinting.Print(); //customer copy packingListPrinting.Export(packingReportCustomer, deviceInfo); packingListPrinting.Print(); //finance copy packingListPrinting.Export(packingReportFinance, deviceInfo); packingListPrinting.Print(); }
// Parameters public static void SetSingleParameter(LocalReport rpt, string paramName, string paramValue) { var rptParam = new ReportParameter(paramName, paramValue); rpt.SetParameters(new ReportParameter[] { rptParam }); }
protected void Page_Load(object sender, EventArgs e) { LocalReport report = new LocalReport(); List <ReportParameter> lstParam = new List <ReportParameter>(); lstParam.Add(new ReportParameter("Logotipo", Logotipo.GetReportLogo())); report.EnableExternalImages = true; uint?idCliente = UserInfo.GetUserInfo.IdCliente; // Se não for um cliente que estiver logado, não imprime relatório if (idCliente == null || idCliente == 0) { return; } if (Request["rel"] == "Danfe") { Response.Redirect("~/Handlers/Danfe.ashx?idNf=" + Request["idNf"] + "&previsualizar=" + Request["previsualizar"]); return; } uint idFunc = UserInfo.GetUserInfo.CodUser; // Verifica qual relatório será chamado switch (Request["rel"]) { case "Debitos": report.ReportPath = "Relatorios/rptDebitosCliente.rdlc"; var debitos = ContasReceberDAO.Instance.GetDebitosList(idCliente.Value, Glass.Conversoes.StrParaUint(Request["idPedido"]), Glass.Conversoes.StrParaUint(Request["idLiberarPedido"]), null, 0, 0, null, null, null, 0, 100000); report.DataSources.Add(new ReportDataSource("ContasReceber", debitos)); lstParam.Add(new ReportParameter("TextoRodape", Geral.TextoRodapeRelatorio(FuncionarioDAO.Instance.GetNome(idFunc)))); lstParam.Add(new ReportParameter("CorRodape", "DimGray")); lstParam.Add(new ReportParameter("LiberarPedido", PedidoConfig.LiberarPedido.ToString())); break; default: throw new Exception("Nenhum relatório especificado."); } report.SetParameters(lstParam); Warning[] Warnings = null; string[] StreamIds = null; string MimeType = null; string Encoding = null; string Extension = null; byte[] bytes = null; bytes = report.Render("PDF", null, out MimeType, out Encoding, out Extension, out StreamIds, out Warnings); try { // Utilizado para exibir na tela Response.Clear(); Response.ContentType = MimeType; Response.AddHeader("Content-disposition", "inline"); Response.BinaryWrite(bytes); Response.End(); } catch (Exception ex) { ex.Data["warnings"] = Warnings; ex.Data["streamids"] = StreamIds; ex.Data["mimetype"] = MimeType; ex.Data["encoding"] = Encoding; ex.Data["extension"] = Extension; throw ex; } }
public ActionResult ReportReportesReserva(string id, string criterio, DateTime fechaini, DateTime fechafin, int EstacionOringen = 0) { LocalReport lr = new LocalReport(); var estmos = ""; var pru = ventaService.ObtenerReservas(criterio, fechaini, fechafin, EstacionOringen); if (String.IsNullOrEmpty(criterio)) { criterio = ""; } if (EstacionOringen == 0) { estmos = ""; } else { var est = estacionService.ObtenerEstacionPorId(EstacionOringen); estmos = est.EstacionesT; } string path = Path.Combine(Server.MapPath("~/Reportes"), "ReporteVentaPasajes.rdlc"); if (System.IO.File.Exists(path)) { lr.ReportPath = path; } else { return View("ListarVentas"); } string reportType = id; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + id + "</OutputFormat>" + " <PageWidth>21cm</PageWidth>" + " <PageHeight>29.7cm</PageHeight>" + " <MarginTop>1.54cm</MarginTop>" + " <MarginLeft>1.54cm</MarginLeft>" + " <MarginRight>1.54cm</MarginRight>" + " <MarginBottom>1.54cm</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; List<DatosReportVentaPasaje> cm = new List<DatosReportVentaPasaje>(); foreach (var item in pru) { foreach (var item2 in item.Reseras) { var datos = new DatosReportVentaPasaje { NroVenta = item.NroVenta + "", Fecha = item.Fecha.Day + "/" + item.Fecha.Month + "/" + item.Fecha.Year, Id = item.TotalVenta + "", TotalVenta = item.EstadoMostrar, DniRuc = item2.Cliente.DniRuc, Nombre = item2.Cliente.Nombre, OrigenId = item2.Horario.EstacionOrigen.Provincia, DestinoId = item2.Horario.EstacionDestino.Provincia, Hora = item2.Horario.HoraText, Pago = item2.Pago }; cm.Add(datos); } } ReportDataSource rd = new ReportDataSource("DataSet1", cm); lr.DataSources.Add(rd); ReportParameter[] parametros = new ReportParameter[5]; parametros[0] = new ReportParameter("Cliente", criterio); parametros[1] = new ReportParameter("EstOrigen", estmos); parametros[2] = new ReportParameter("FechaInicio", fechaini.Date.Day + "/" + fechaini.Date.Month + "/" + fechaini.Date.Year + ""); parametros[3] = new ReportParameter("FechaFin", fechafin.Date.Day + "/" + fechafin.Date.Month + "/" + fechafin.Date.Year + ""); parametros[4] = new ReportParameter("Tipo", "Reserva - Pasajes"); lr.SetParameters(parametros); renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); switch (id) { case "PDF": return File(renderedBytes, mimeType); case "Excel": return File(renderedBytes, mimeType, "Reserva " + DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Date.Year + ".xls"); case "Word": return File(renderedBytes, mimeType, "Reserva " + DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Date.Year + ".doc"); case "Image": return File(renderedBytes, mimeType, "Reserva " + DateTime.Now.Date.Day + "-" + DateTime.Now.Date.Month + "-" + DateTime.Now.Date.Year + ".png"); default: break; } RegUsuarios movimiento = new RegUsuarios { Usuario = User.Identity.Name, Modulo = "Reserva", Cambio = "Reportes Reserva", IdModulo = "", Fecha = DateTime.Now }; movCuentaService.GuardarMovimiento(movimiento); return File(renderedBytes, mimeType); }
protected virtual void AssignCommonParameters(LocalReport rpt, DataRow dt, string Logo, StringBuilder spers) { rpt.SetParameters(new ReportParameter[] { /* header section */ new ReportParameter("lClassification", m(2550)), /* Classification */ new ReportParameter("LogoURL", Logo), new ReportParameter("lNumber", m(27)), /* Number */ new ReportParameter("lOriginator", m(45)), /* Originator */ new ReportParameter("lEventDatetime", m(2302)), /* Incident date */ new ReportParameter("lArea", m(739)), /* Incident location */ new ReportParameter("lWorkplace", m(1036)), /* Details Unfallort */ new ReportParameter("lPersInvolved", m(407)), /* Persons involved */ new ReportParameter("lCourseOfEvents", m(550)), /* Circumstances */ new ReportParameter("Status", dt["fStatus"].ToString()), new ReportParameter("NrComposite", dt["NrComposite"].ToString()), new ReportParameter("OriginatorName", dt["OriginatorName"].ToString()), new ReportParameter("EventDatetime", dt["fTime"].ToString()), new ReportParameter("Area", dt["OrgCap"].ToString()), new ReportParameter("Workplace", dt["Workplace"].ToString()), new ReportParameter("hPersInvolved", spers.ToString()), new ReportParameter("CourseOfEvents", dt["fCourseOfEvents"].ToString()), new ReportParameter("lcreawhen", m(2301)), /* Created on */ new ReportParameter("crea_when", dt["fcrea_when"].ToString()), new ReportParameter("llm_when", m(3255)), /* Last modified */ new ReportParameter("lm_when", dt["flm_when_who"].ToString()), new ReportParameter("lActivity", m(565)), /* Activity performed */ new ReportParameter("Activity", dt["ActivityCaption"].ToString()), new ReportParameter("lRisk", m(7080)), /* Risk estimation */ new ReportParameter("Risk", dt["sRisk"].ToString()), new ReportParameter("RiskScore", dt["RiskEstimation"].ToString()), new ReportParameter("lLegendTitle", m(2985).ToUpper() + ": " + m(7080)), /* Legend / Risk estimation */ new ReportParameter("lLowRiskValue", "1-2 = " + m(6496) + ";"), /* Low */ new ReportParameter("lMiddleRiskValue", "3-4 = " + m(218) + ";"), /* Middle */ new ReportParameter("lHighRiskValue", "5-7 = " + m(220) + ";"), /* High */ new ReportParameter("lLowRiskDescription", m(7089) + ";"), /* No risk mitigating actions required */ new ReportParameter("lMiddleRiskDescription", m(7090) + ";"), /* Risk mitigating actions required */ new ReportParameter("lHighRiskDescription", m(7091) + ";"), /* Corrective actions with significant risk reduction urgently needed */ new ReportParameter("lPageNofM", m(2410)), /* Page {0} of {1} */ new ReportParameter("lTabBasic", m(156)), /* General information */ new ReportParameter("lImmediateCauses", m(551)), /* Immediate causes */ new ReportParameter("ImmediateCauses", dt["fCauses"].ToString()), new ReportParameter("lImmediateMeasures", m(3842)), /* Immediate actions */ new ReportParameter("ImmediateMeasures", dt["fImmediateMeasures"].ToString()), /* sections below the header */ new ReportParameter("lTabMedia", m(56)), /* Attached files */ new ReportParameter("lDocuments", m(3607)), /* Documents */ new ReportParameter("Documents", dt["fDocuments"].ToString()), new ReportParameter("lTabFinMea", m(3844)), /* Causes, findings, measures */ new ReportParameter("lFinMeaStatusNumber", m(249)), /* Status */ new ReportParameter("lFinMeaCategory", m(3845)), /* Cat. */ new ReportParameter("lFinMeaArea", m(251)), /* Area */ new ReportParameter("lFinMeaText", m(289)), /* Text */ new ReportParameter("lFinMeaResponsible", m(290)), /* Responsible */ new ReportParameter("lFinMeaPicture", m(3166)), /* Pictures */ new ReportParameter("lTabAcf", m(4271)), /* Action forces */ new ReportParameter("lAFEventtimeFrom", m(1320)), /* Date/time */ new ReportParameter("lAFCat", m(4284)), /* Event */ new ReportParameter("lAFDept", m(4286)), /* Department */ new ReportParameter("lAFEventtimeTo", m(4285)), /* Date/time to */ new ReportParameter("lAFRemarks", m(3202)), /* Notes */ new ReportParameter("lTabRca", m(418)), /* Root Cause Analysis */ new ReportParameter("lRcaNr", m(3042)), /* Nr. */ new ReportParameter("lRcaSection", dt["fRcaSectionCap"].ToString()), new ReportParameter("lRcaCause", m(576)), /* Cause */ new ReportParameter("lRcaVerified", m(577)), /* Verified */ new ReportParameter("lRcaMeasures", m(240)), /* Measures */ new ReportParameter("lConfidentialityNote", ConfidentialityNote), new ReportParameter("FooterInfoline", dt["fFooterInfoline"].ToString()) }); }
/// <summary> /// Load a detailed diskspace report. /// </summary> /// <param name="reportName">Name of detailed diskspace report.</param> /// <param name="localReport"> /// Instance or <see cref="LocalReport"/> class. /// This instance serves as a container for report being loaded. /// </param> protected void BindHostingSpaceDiskspaceOverusageDetailsReport(string reportName, LocalReport localReport) { // 1. Localize report localReport.DisplayName = reportName; localReport.LoadReportDefinition( ReportingServicesUtils.LoadReportFromFile( GetReportFullPath(reportName) , reportName , this ) ); // 2. Update parameters // Note: here we are always in Drill-through mode. localReport.SetParameters(localReport.OriginalParametersToDrillthrough); string hostingSpaceId = localReport.GetParameters()["HostingSpaceId"].Values[0]; // 3. Update DataSet DataSet report = ES.Services.Packages .GetDiskspaceOverusageDetailsReport( PanelSecurity.SelectedUserId , int.Parse(hostingSpaceId) ); localReport.DataSources.Clear(); TranslateStatusField(report.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_HostingSpace", report.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_DiskspaceOverusage", report.Tables["DiskspaceOverusage"]); BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", report.Tables["OverusageDetails"]); localReport.Refresh(); }
protected override bool RenderInternal(ref MemoryStream chunk, out string mime) { mime = null; try { /* 1. instantiate the report */ var rpt = new LocalReport() { ReportEmbeddedResource = ReportDesignerResourcename, EnableExternalImages = true }; /* 1a. persons involved */ var invo = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_SHARED_PERS]; var spers = new StringBuilder(); foreach (DataRow dr in invo.Rows) { var sheading = dr["Heading"].ToString(); var sname = dr["Name"].ToString(); if (String.IsNullOrWhiteSpace(sheading)) { spers.AppendFormat(", {0}", sname); } else { spers.AppendFormat("{0}<strong>{1}</strong> {2}", spers.Length > 0 ? "<br />" : String.Empty, sheading, sname); } } /* 2. populate the report */ rpt.DataSources.Clear(); var Logo = MediaURLAbsolute(sherm.core.formatting.mime.BINGET_NAMEDRESOURCE_CORPORATELOGO, new FileType[] { FileType.ft_png }); var dt = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_INCIDENTVERBOSE].Rows[0]; /* 2a. set the parameters which are common to all subclasses of incidents */ AssignCommonParameters(rpt, dt, Logo, spers); /* 2b. assign the parameters which are different from subclass to subclass */ AssignSpecificParameters(rpt, dt); /* shovel the other lists; * a) the action forces table */ var acfs = new List <builtin.msdbrpt_datasources.ReportHardcopyIncidentActionforce>(); var acfstable = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_INCIDENT_AFS]; rpt.SetParameters(new ReportParameter("bACFHidden", acfstable.Rows.Count > 0 ? String.Empty : "hide")); foreach (DataRow dr in acfstable.Rows) { acfs.Add(new builtin.msdbrpt_datasources.ReportHardcopyIncidentActionforce() { EventtimeFrom = dr["fEventtimeFrom"].ToString(), CatCap = dr["CatCaption"].ToString(), Department = dr["Department"].ToString(), EventtimeTo = dr["fEventtimeTo"].ToString(), Remarks = dr["fRemark"].ToString() }); } /* b) the rca table */ var rcas = new List <builtin.msdbrpt_datasources.ReportHardcopyIncidentRca>(); var rcastable = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_INCIDENT_RCA]; /* [pkosec 20141211] MEA-2014-00492.2: let's show only one rca tablix */ try { rpt.SetParameters(new ReportParameter("bRCAHidden", CfgVariant2_COMMON ? String.Empty : "hide")); /* VDM flavor without the verified column */ rpt.SetParameters(new ReportParameter("bRCAVerifiedHidden", CfgVariant2_COMMON ? "hide" : String.Empty)); /* the others have the verified column */ } catch { /* [dlatikay 20150129] quick and dirty fix for failure in EIN and FIR/EFR, which are * derived from this but do not have these params */ } foreach (DataRow dr in rcastable.Rows) { rcas.Add(new builtin.msdbrpt_datasources.ReportHardcopyIncidentRca() { Number = dr["fNumber"].ToString(), Section = dr["fSection"].ToString(), Cause = dr["fCauseHTML"].ToString(), Verified = dr["fVerified"].ToString(), Measures = dr["fMeasurecount"].ToString() }); } /* c) the item overview */ var ovvw = new List <builtin.msdbrpt_datasources.ReportHardcopyIncidentFinMea>(); var itemstable = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_MEASURES_OVW]; foreach (DataRow dr in itemstable.Rows) { ovvw.Add(new builtin.msdbrpt_datasources.ReportHardcopyIncidentFinMea() { Area = dr["fAreaHTML"].ToString(), Category = dr["fCategory"].ToString(), HTML = dr["fHTML"].ToString(), Number = dr["fNumber"].ToString(), PicUrl = (dr["HasAttachment"].Equals(DBNull.Value) || Convert.ToBoolean(dr["HasAttachment"]) == false) ? FileURLAbsolute("images/spacer.png") : (Convert.ToBoolean(dr["AttachmentIsPicture"]) ? MediaURLAbsolute(Convert.ToInt32(dr["AttachmentBinID"]), sherm.core.formatting.mime.HARDCOPY_FINMEAPIC_MAXWIDTH, sherm.core.formatting.mime.HARDCOPY_FINMEAPIC_MAXHEIGHT, new FileType[] { FileType.ft_png }) /* need not coerce to png, gallery thumbnails are always png anyway; [dlatikay 20131205] do need to - we're now no longer using the thumbnail for higher resolution requirement */ : FileURLAbsolute("images/attch.gif") /* [pkosec,dlatikay 20131206] MEA-2013-00783 */ ), Responsible = dr["fResponsibleHTML"].ToString(), StatusPicFin = FileURLAbsolute("images/" + dr["fStatusPicFin"].ToString() + ".png"), StatusPicMea = FileURLAbsolute("images/" + dr["fStatusPicMea"].ToString() + ".png") }); } /* d) the pictures */ var incpics = new List <builtin.msdbrpt_datasources.ReportHardcopyIncidentPicsTwoColumn>(); int ipic = 0; var picstable = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_SHARED_PICS]; builtin.msdbrpt_datasources.ReportHardcopyIncidentPicsTwoColumn running = null; foreach (DataRow dr in picstable.Rows) { var binid = Convert.ToInt32(dr["BinID"]); if (ipic % 2 == 0) { running = new builtin.msdbrpt_datasources.ReportHardcopyIncidentPicsTwoColumn() { UrlLeft = MediaURLAbsolute(binid, 320, 320, new FileType[] { FileType.ft_jpg, FileType.ft_png }), UrlRight = FileURLAbsolute("images/spacer.png") }; incpics.Add(running); } else { running.UrlRight = MediaURLAbsolute(binid, 320, 320, new FileType[] { FileType.ft_jpg, FileType.ft_png }); } /* advance */ ++ipic; } /* equip the report with the rest of the data sources */ var dsBasic = "Basic"; var dsPics = "Pics"; var dsAcf = "AcfTable"; var dsRca = "RcaTable"; var dsFinMea = "FinMeaTable"; var dynDS_Basic = new ReportDataSource(dsBasic, new List <builtin.msdbrpt_datasources.ReportHardcopyIncidentBasic>() { new builtin.msdbrpt_datasources.ReportHardcopyIncidentBasic() }); /* this is but an empty record to satisfy the tablix, actual content comes with parameters */ var dynDS_Pics = new ReportDataSource(dsPics, incpics); var dynDS_Acf = new ReportDataSource(dsAcf, acfs); var dynDS_Rca = new ReportDataSource(dsRca, rcas); var dynDS_FinMea = new ReportDataSource(dsFinMea, ovvw); rpt.DataSources.Clear(); rpt.DataSources.Add(dynDS_Basic); rpt.DataSources.Add(dynDS_Pics); rpt.DataSources.Add(dynDS_Acf); rpt.DataSources.Add(dynDS_Rca); rpt.DataSources.Add(dynDS_FinMea); /* 3. render the report into the desired format */ rpt.Refresh(); RenderAsMsdbrpt(ResultFileBasename, ref chunk, ref mime, rpt); /* succeeded */ return(true); } catch (Exception ex) { /* some error */ OnBuiltinReportError(ex.Message, ex); return(false); } }
public string CreateReport(string username, string crot, string nrpar) { string url = ""; try { int i = Convert.ToInt32(nrpar); string[] parIds = {"g", "p", "c", "l", "s", "h", "u", "n", "z", "gp"}; string[] chartLabelsName = { "Grasime (g/100g)", "Proteine (g/100g)", "Cazeina (g/100g)", "Lactoza (g/100g)", "SUN (g/100g)", "pH", "Uree (mg/dl)", "NCSx1000", "Cantitate lapte (l)", "Grasime/Proteine (%)" }; string[] chartTitles = { "Grasime", "Proteine", "Cazeina", "Lactoza", "SUN", "Ph", "Uree", "NCS", "Cantitate lapte", "Raport Grasime/Proteine" }; string[] um = {"g/100g", "g/100g", "g/100g", "g/100g", "g/100g", "pH", "mg/dl", "NCSx1000", "l", "%"}; // string username = Page.User.Identity.Name; UserInfos userinfos = UserInfos.getUserInfos(username); int fermaid = GetFermaId(userinfos.UserCod); int year = Int32.Parse(Session["year"].ToString()); string baseurl = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + ConfigurationManager.AppSettings["httppath"]; string filepath = ConfigurationManager.AppSettings["filepath"]; string fileid = chartTitles[i]; fileid = fileid.Replace("/", ""); fileid = fileid.Replace("/", ""); if (i == 8) fileid = fileid.Substring(0, 4); string raport_excel = "Grafic" + fileid + "_" + userinfos.UserCod + "_" + crot + "_" + year + ".xls"; LocalReport report = new LocalReport(); report.EnableHyperlinks = true; string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; if (fermaid != 0) { List<SampleAnalize> samples = SampleAnalize.GetSampleAnalize(fermaid, crot, year); if (samples.Count > 0) { //set current param foreach (SampleAnalize sample in samples) { switch (i) { case 0: sample.Val = sample.Grasime; break; case 1: sample.Val = sample.Proteine; break; case 2: sample.Val = sample.Caseina; break; case 3: sample.Val = sample.Lactoza; break; case 4: sample.Val = sample.Solide; break; case 5: sample.Val = sample.Ph; break; case 6: sample.Val = sample.Urea; break; case 7: sample.Val = sample.Ncs; break; case 8: sample.Val = sample.Cantitate; break; case 9: sample.Val = 0; if (sample.Proteine > 0) sample.Val = sample.Grasime/sample.Proteine; break; default: break; } sample.Val = Math.Round(sample.Val, 2); } //datasources ReportDataSource rds = new ReportDataSource(); rds.Name = "SampleAnalize"; rds.Value = samples; report.DataSources.Clear(); report.DataSources.Add(rds); // ReportDataSource rdsc = new ReportDataSource(); rdsc.Name = "SampleAnalizeControl"; List<SampleAnalizeControl> samplescontrol = SampleAnalize.getSampleAnalizeControl(samples, year); rdsc.Value = samplescontrol; report.DataSources.Add(rdsc); //parameters report.ReportPath = "GraficCrotalie.rdlc"; string datatestare = "Data: " + DateTime.Now.ToString("dd/MM/yyyy"); // set reports parameters string title = userinfos.NumeFerma + " - " + "Cod exploatatie " + userinfos.UserCod; ReportParameter pCod = new ReportParameter("CodExpl", title); ReportParameter pData = new ReportParameter("DataExec", datatestare); ReportParameter pChartTitle = new ReportParameter("ChartTitle", chartTitles[i] + " - Nr. matricol: " + crot); ReportParameter pChartLabelsName = new ReportParameter("ChartLabelsName", chartLabelsName[i]); ReportParameter pUm = new ReportParameter("Um", um[i]); ReportParameter[] p = {pCod, pData, pChartTitle, pChartLabelsName, pUm}; report.SetParameters(p); report.Refresh(); string excel_file = filepath + raport_excel; byte[] xls_content = report.Render("EXCEL", deviceInfoXls, out mimeType, out encoding, out fileExtension, out streams, out warnings); File.WriteAllBytes(excel_file, xls_content); url = baseurl + raport_excel; } } else { FailureText.Text = "Nu exista date pentru codul " + userinfos.UserCod + " si numarul matricol " + crot; } } catch (Exception ex) { string err = ex.Message; string trace = ex.StackTrace; Logger.Error(trace + "|" + err); } return url; }
protected void OnButtonCommand(object sender, CommandEventArgs e) { //Event handler for command button clicked //Change view to Viewer and reset to clear existing data Master.Viewer.Reset(); //Get parameters for the query string _clientName = this.dgdClientVendor.ClientName; string _pickupID = "", _termCode = ""; //Initialize control values LocalReport report = Master.Viewer.LocalReport; report.DisplayName = REPORT_NAME; report.EnableExternalImages = true; EnterpriseService enterprise = new EnterpriseService(); DataSet ds = new DataSet(REPORT_DS); foreach (GridViewRow row in SelectedRows) { DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex]; _pickupID = dataKey["PickupID"].ToString(); _termCode = dataKey["TerminalCode"].ToString(); DataSet _ds = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _termCode, _pickupID }); ds.Merge(_ds); } if (ds.Tables[TBL_REPORT].Rows.Count >= 0) { switch (e.CommandName) { case "Run": //Set local report and data source System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC); report.LoadReportDefinition(stream); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); //Set the report parameters for the report ReportParameter puID = new ReportParameter("PickupID", "0"); ReportParameter clientName = new ReportParameter("ClientName", _clientName); ReportParameter termCode = new ReportParameter("TerminalCode", "0"); report.SetParameters(new ReportParameter[] { puID, clientName, termCode }); //Update report rendering with new data report.Refresh(); if (!Master.Viewer.Enabled) { Master.Viewer.CurrentPage = 1; } break; case "Data": //Set local export report and data source report.LoadReportDefinition(Master.CreateExportRdl(ds, REPORT_DS, "RGXSQLR.TSORT")); report.DataSources.Clear(); report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT])); report.Refresh(); break; case "Excel": //Create Excel mime-type page Response.ClearHeaders(); Response.Clear(); Response.Charset = ""; Response.AddHeader("Content-Disposition", "inline; filename=DeliveryInfoByPickup.xls"); Response.ContentType = "application/vnd.ms-excel"; //application/octet-stream"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); DataGrid dg = new DataGrid(); dg.DataSource = ds.Tables[TBL_REPORT]; dg.DataBind(); dg.RenderControl(hw); Response.Write(sw.ToString()); Response.End(); break; } } else { Master.Status = "There were no records found."; } }