public void GenerateInvoiceReport(double Sum, List <tblcustomer> customer, List <tblproduct> reportModelList, HttpResponseBase response, HttpServerUtilityBase server) { if (reportModelList.Count() > 0) { string TodaysDate = DateTime.Now.ToString("dd MMM yyyy"); LocalReport localReport = new LocalReport(); localReport.ReportPath = server.MapPath("~/Reports/" + "invoice_report.rdlc"); //Passing Parameters localReport.SetParameters(new ReportParameter("TodaysDate", TodaysDate)); localReport.SetParameters(new ReportParameter("Sum", Sum.ToString())); ReportDataSource CustomerDataSource = new ReportDataSource("Cutomer", customer); localReport.DataSources.Add(CustomerDataSource); localReport.Refresh(); ReportDataSource reportDataSource = new ReportDataSource("DataSet1", reportModelList); localReport.DataSources.Add(reportDataSource); localReport.Refresh(); string extensionString = "Pdf"; string outputType = "Pdf"; ReportExportHelper(localReport, outputType, "Invoice", true, extensionString, response); } }
//select path to print private void PrintBtn_Click(object sender, EventArgs e) { //throw new NotImplementedException(); LocalReport report = new LocalReport(); report.ReportPath = @"..\..\rpt_receiptSingle.rdlc"; //add report params List <ReportParameter> rpParams = new List <ReportParameter>() { new ReportParameter("crtDate", crtDate.Value.ToString(lConfigMng.GetDateFormat())), new ReportParameter("bookNo", bookNumTxt.Text), new ReportParameter("pcNo", pcNoTxt.Text), new ReportParameter("name", nameTxt.Text), new ReportParameter("addr", addrTxt.Text), new ReportParameter("reason", reasonTxt.Text), new ReportParameter("note", noteTxt.Text), new ReportParameter("amount", amountTxt.Text) }; report.SetParameters(rpParams); report.Refresh(); fileExporter exprt = new fileExporter(); exprt.export(report); }
private LocalReport LoadReport() { LocalReport report = new LocalReport(); report.ReportPath = this.ReportLocation; foreach (string ds in this.Context.DataSources.Keys) { report.DataSources.Add(new ReportDataSource(ds, this.Context.DataSources[ds])); } report.Refresh(); if (this.Context.Parameters.Count > 0) { ReportParameter[] parameters = new ReportParameter[Context.Parameters.Count]; int i = 0; foreach (string pm in this.Context.Parameters.Keys) { ReportParameter param = new ReportParameter(pm); param.Values.Add(this.Context.Parameters[pm]); parameters[i] = param; i++; } report.SetParameters(parameters); } return(report); }
public void Export(LocalReport report, Dictionary <string, double> size = null) { string deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.25in</MarginTop>" + " <MarginLeft>0.25in</MarginLeft>" + " <MarginRight>0.25in</MarginRight>" + " <MarginBottom>0.25in</MarginBottom>" + "</DeviceInfo>"; if ((size != null)) { Console.WriteLine("Resizing Paper...."); string paperWidth_in = size["width"].ToString("0.00"); string paperHeight_in = size["height"].ToString("0.00"); deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>" + paperWidth_in + "in</PageWidth>" + " <PageHeight>" + paperHeight_in + "in</PageHeight>" + " <MarginTop>0.25in</MarginTop>" + " <MarginLeft>0.25in</MarginLeft>" + " <MarginRight>0.25in</MarginRight>" + " <MarginBottom>0.25in</MarginBottom>" + "</DeviceInfo>"; } Console.WriteLine("Device Info:"); Console.WriteLine(deviceInfo); Warning[] warnings = null; m_streams = new List <Stream>(); report.Refresh(); report.Render("Image", deviceInfo, CreateStream, out warnings); Console.WriteLine(report.GetDefaultPageSettings().PaperSize); Console.WriteLine(report.GetDefaultPageSettings().Margins); Stream stream = null; foreach (Stream stream_loopVariable in m_streams) { stream = stream_loopVariable; stream.Position = 0; } }
public HttpResponseMessage RelFinanceiro(DateTime datainicio, DateTime datatermino, string tipo, string situacao, int idpessoa) { try { if (datainicio > datatermino) { throw new Exception("Periodo inválido"); } var lista = _serviceRelatorio.RelFinanceiro(datainicio, datatermino, tipo, situacao, idpessoa, base.GetUsuarioLogado().IdClinica); //vinculando dataset ao objeto relat var ds = new ReportDataSource(); ds.Name = "dsdados"; ds.Value = lista; var report = new LocalReport() { ReportPath = AppDomain.CurrentDomain.BaseDirectory + "Report/RelatorioFinanceiro.rdlc" }; report.DataSources.Add(ds); report.Refresh(); ReportParameter[] parametros = new ReportParameter[] { new ReportParameter("usuario", base.GetUsuarioLogado().Nome), new ReportParameter("tipo", tipo), new ReportParameter("datainicio", datainicio.ToString("dd/MM/yyyy")), new ReportParameter("datatermino", datatermino.ToString("dd/MM/yyyy")) }; report.SetParameters(parametros); //configurações da página ex: margin, top, left ... string deviceInfo = "<DeviceInfo>" + "<OutputFormat>PDF</OutputFormat>" + "<PageWidth>29.7cm</PageWidth>" + "<PageHeight>21cm</PageHeight>" + "<MarginTop>0.5cm</MarginTop>" + "<MarginLeft>0.5cm</MarginLeft>" + "<MarginRight>0.5cm</MarginRight>" + "<MarginBottom>0.5cm</MarginBottom>" + "</DeviceInfo>"; string mimeType = ""; string encoding = ""; string filenameExtension = ""; string[] streams = null; Microsoft.Reporting.WebForms.Warning[] warnings = null; byte[] bytes = report.Render("PDF", deviceInfo, out mimeType, out encoding, out filenameExtension, out streams, out warnings); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(bytes); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mimeType); return(result); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
private void BuildReport() { List <ReportParameter> paramarr = new List <ReportParameter>(); string addpath; bool isArabic = ReportCls.checkLang(); if (isArabic) { addpath = @"\Reports\Store\Ar\ArInventory.rdlc";//////////?????????? } else { addpath = @"\Reports\Store\En\Inventory.rdlc";/////////??????????? } string reppath = reportclass.PathUp(Directory.GetCurrentDirectory(), 2, addpath); ReportCls.checkLang(); clsReports.inventoryReport(invItemsLocations, rep, reppath, paramarr);////////////????? clsReports.setReportLanguage(paramarr); clsReports.Header(paramarr); rep.SetParameters(paramarr); rep.Refresh(); }
private void BuildReport() { List <ReportParameter> paramarr = new List <ReportParameter>(); string addpath; string firstTitle = "accountProfits"; string secondTitle = ""; string subTitle = ""; string Title = ""; bool isArabic = ReportCls.checkLang(); if (isArabic) { if (selectedTab == 0) { addpath = @"\Reports\StatisticReport\Accounts\Profit\Ar\Profit.rdlc"; secondTitle = "invoice"; } else { addpath = @"\Reports\StatisticReport\Accounts\Profit\Ar\ProfitItem.rdlc"; secondTitle = "items"; } //Reports\StatisticReport\Sale\Daily\Ar } else { if (selectedTab == 0) { addpath = @"\Reports\StatisticReport\Accounts\Profit\En\Profit.rdlc"; secondTitle = "invoice"; } else { addpath = @"\Reports\StatisticReport\Accounts\Profit\En\ProfitItem.rdlc"; secondTitle = "items"; } } string reppath = reportclass.PathUp(Directory.GetCurrentDirectory(), 2, addpath); ReportCls.checkLang(); subTitle = clsReports.ReportTabTitle(firstTitle, secondTitle); Title = MainWindow.resourcemanagerreport.GetString("trAccounting") + " / " + subTitle; paramarr.Add(new ReportParameter("trTitle", Title)); // IEnumerable<ItemUnitInvoiceProfit> clsReports.ProfitReport(profitsQuery, rep, reppath, paramarr); paramarr.Add(new ReportParameter("totalBalance", tb_total.Text)); clsReports.setReportLanguage(paramarr); clsReports.Header(paramarr); rep.SetParameters(paramarr); rep.Refresh(); }
private void PrintLeave(int studentID) { try { clsManager manager = new clsManager(); ReportViewer1.Visible = true; ReportDataSource rds = new ReportDataSource(); ReportViewer1.Reset(); ReportViewer1.ProcessingMode = ProcessingMode.Local; LocalReport rep = ReportViewer1.LocalReport; rep.Refresh(); rds.Name = "Student"; rep.ReportPath = "Reports/rptStudentInfo.rdlc"; rds.Value = manager.RetrunDataset("select *from tblStudent where StudentId =" + studentID + " ").Tables[0]; ReportParameter[] p = { new ReportParameter("Company", "Square") }; rep.SetParameters(p); //This name must be in "<datasetname>_<datatablename>" format. This name can also be seen in dataset's datasource view. rep.DataSources.Add(rds); } catch { } }
/// <summary> /// Al seleccionar un elemento del reporte /// navega por el mismo /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void reportViewer1_Drillthrough(object sender, Microsoft.Reporting.WinForms.DrillthroughEventArgs e) { AppHelper.Try( delegate { // Obtenemos los parámetros ReportParameterInfoCollection parameters = e.Report.GetParameters(); // Obtenemos ticket_id int conductor_id = Convert.ToInt32(parameters["Conductor_ID"].Values[0]); int cuenta_id = Convert.ToInt32(parameters["Cuenta_ID"].Values[0]); // Obtenemos los DataSources // Obtenemos los registros de cuentaCajas List <Entities.Vista_CuentaConductores> cuentaconductores = Entities.Vista_CuentaConductores.Get(conductor_id, cuenta_id); // Obtenemos el local report LocalReport localReport = (LocalReport)e.Report; // Le asignamos las datasources localReport.DataSources.Clear(); localReport.DataSources.Add( new ReportDataSource( "ReporteCuentaConductores_DataSet", cuentaconductores ) ); // Refrescamos el reporte localReport.Refresh(); } // End delegate ); // End method }
public LocalReport getRptEvFinal(string reportPath) { LocalReport rptEvAcumulativa = new LocalReport(); try { dtstEvaluacion_ImprimirActas dtaEvFinal = this.getReporteActasExPrincipal(); ReportDataSource rds = new ReportDataSource(); rds.Value = dtaEvFinal.Acta; rds.Name = "dtsExamenPrincipal"; rptEvAcumulativa.DataSources.Clear(); rptEvAcumulativa.DataSources.Add(rds); rptEvAcumulativa.ReportPath = reportPath; rptEvAcumulativa.SetParameters(this._getParametrosGeneralesReporte()); rptEvAcumulativa.Refresh(); } catch (Exception ex) { Errores err = new Errores(); err.SetError(ex, "getReporteHorarios"); } return(rptEvAcumulativa); }
public void BuildReport() { //string firstTitle = "paymentsReport"; ////string secondTitle = ""; ////string subTitle = ""; //string Title = ""; List <ReportParameter> paramarr = new List <ReportParameter>(); string addpath; bool isArabic = ReportCls.checkLang(); if (isArabic) { addpath = @"\Reports\SectionData\En\EnAgents.rdlc"; } else { addpath = @"\Reports\SectionData\En\EnAgents.rdlc"; } //D:\myproj\posproject3\AdministratorApp\AdministratorApp\Reports\statisticReports\En\EnBook.rdlc string reppath = reportclass.PathUp(Directory.GetCurrentDirectory(), 2, addpath); // subTitle = clsReports.ReportTabTitle(firstTitle, secondTitle); // Title = MainWindow.resourcemanagerreport.GetString("trAccountantReport"); clsReports.agentReport(usersQuery, rep, reppath, paramarr); clsReports.setReportLanguage(paramarr); clsReports.Header(paramarr); rep.SetParameters(paramarr); rep.Refresh(); }
public FileResult TEstimatedUtilized(string Task, string Product, string Client, DateTime FromDate, DateTime ToDate) { string sQuery = "EXEC [sp_TaskDetailsUtlEst] '%" + Task + "%', '%" + Product + "%', '%" + Client + "%', '" + FromDate.Date + "', '" + ToDate.Date + "'"; glb_dt_Tasks.Clear(); glb_dt_Tasks.tbl_TasksUtlEst.Merge(cls_HelpMethods.ExecQuery(sQuery).Tables[0]); LocalReport lr = new LocalReport(); lr.ReportPath = Server.MapPath("~/Reports/rptTaskEstimatedUtilizedHours.rdlc"); lr.DataSources.Clear(); lr.DataSources.Add(new ReportDataSource("DataSet", glb_dt_Tasks.tbl_TasksUtlEst.ToList())); //.Tables[0] ReportParameterCollection reportParameters = new ReportParameterCollection(); reportParameters.Add(new ReportParameter("ReportName", "Task Estimated Vs Utilized Hours Report")); reportParameters.Add(new ReportParameter("CompanyName", "Digiteq Solution (Pvt) Ltd")); lr.SetParameters(reportParameters); lr.Refresh(); byte[] streamBytes = null; string mimeType = ""; string encoding = ""; string filenameExtension = ""; string[] streamids = null; Warning[] warnings = null; streamBytes = lr.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); return(File(streamBytes, mimeType)); //, "TimeSheetReport" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".pdf" }
public FileResult TUtilizedHours(string Task, string Status, DateTime FromDate, DateTime ToDate) { string sQuery = "EXEC [sp_TaskUtilizedHours] '%" + Task + "%', '%" + Status + "%', '" + FromDate.Date + "', '" + ToDate.Date + "'"; glb_dt_Tasks.Clear(); glb_dt_Tasks.tbl_Tasks.Merge(cls_HelpMethods.ExecQuery(sQuery).Tables[0]); LocalReport lr = new LocalReport(); lr.ReportPath = Server.MapPath("~/Reports/rptTaskUtilizedHours.rdlc"); lr.DataSources.Clear(); lr.DataSources.Add(new ReportDataSource("DataSet", glb_dt_Tasks.tbl_Tasks.ToList())); //.Tables[0] ReportParameterCollection reportParameters = new ReportParameterCollection(); reportParameters.Add(new ReportParameter("ReportName", "Task Wise Utilized Hours Detail Report")); reportParameters.Add(new ReportParameter("CompanyName", "Digiteq Solution (Pvt) Ltd")); lr.SetParameters(reportParameters); lr.Refresh(); byte[] streamBytes = null; string mimeType = ""; string encoding = ""; string filenameExtension = ""; string[] streamids = null; Warning[] warnings = null; streamBytes = lr.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); return(File(streamBytes, mimeType)); }
public static MemoryStream GetExportedMemoryStreamReport(ExportType expType, DataSet reportSource, String reportPath, List <RDLParameter> rdlParameters, List <RDLReportDocument> subReportList, String savePath) { try { SubReportList = subReportList; MimeType = String.Empty; LocalReport localReport = new LocalReport(); localReport.ReportPath = reportPath; localReport.DisplayName = "Exported Report"; localReport.EnableExternalImages = true; localReport.SubreportProcessing += localReport_SubreportProcessing; ReportDataSource rdSource = null; foreach (DataTable dtTable in reportSource.Tables) { rdSource = new ReportDataSource(); rdSource.Name = dtTable.TableName; rdSource.Value = dtTable.DefaultView; localReport.DataSources.Add(rdSource); } SetParameter(localReport, rdlParameters); localReport.Refresh(); return(ExportReportMemoryStreamToPDFOnly(localReport, savePath)); } catch (Exception ex) { throw (ex); } }
public void Imprimir(string fecha_proforma, int id_proforma) { LocalReport report = new LocalReport(); report.ReportPath = @"RepCaracteristicasProforma.rdlc"; List <ReportParameter> reportParams = new List <ReportParameter>(); reportParams.Add(new ReportParameter("Fecha", fecha_proforma)); report.SetParameters(reportParams); Consultas con = new Consultas(); string cs = AppVentas.Properties.Settings.Default.dbsisventasConnString; SqlConnection cn = new SqlConnection(cs); string query = "select p.codigo, p.nombre_producto, p.marca, p.imagen, p.descripcion, p.valor_venta, dp.id from detalle_proforma dp " + "inner join producto p " + "on dp.id_producto = p.id " + "where dp.id_proforma = " + id_proforma; SqlDataAdapter da = new SqlDataAdapter(query, cn); da.Fill(con, con.Tables[7].TableName); ReportDataSource rds = new ReportDataSource("DetalleCaracteristicasProforma", con.Tables[7]); report.DataSources.Clear(); report.DataSources.Add(rds); report.Refresh(); Export(report); Print(); }
public HttpResponseMessage Print(string periode, string posisi, string jumlah) { try { ReportParameter[] Params = new ReportParameter[5]; string Nomor = String.Format("{0}/JPS-HR/SK/VI{1}/{2}", DateTime.Now.ToString("FFF"), DateTime.Now.Month.ToString("00"), DateTime.Now.Year); Params[0] = new ReportParameter("NomorSurat", Nomor); Params[1] = new ReportParameter("WeekDay", TodayName()); Params[2] = new ReportParameter("Today", MonthName()); Params[3] = new ReportParameter("Periode", periode); Params[4] = new ReportParameter("Posisi", ctx.Set <Lowongan>().Find(posisi).Nama); ReportDataSource reportDs = new ReportDataSource("DataSet1", genRepo.FindRankingPosisi(periode, posisi, jumlah)); using (LocalReport localReport = new LocalReport()) { string rdlc = "print"; localReport.DataSources.Add(reportDs); localReport.ReportPath = GetReportPath(rdlc); localReport.SetParameters(Params); localReport.Refresh(); return(ShowPdfReport(localReport, "hasil_akhir", "0.2", "8.27", "11.69", "0.30", "0.40", "0.20")); } } catch (ReportViewerException ex) { throw new Exception(ex.InnerException.Message); } }
public void GenerateCustomerReport(HttpResponseBase response, HttpServerUtilityBase server) { using (var db = new InvoiceEntities1()) { var reportModelList = db.tblcustomers.ToList(); if (reportModelList.Count() > 0) { LocalReport localReport = new LocalReport(); localReport.ReportPath = server.MapPath("~/Reports/" + "Customer.rdlc"); //Passing Parameters ReportDataSource reportDataSource = new ReportDataSource("customerds", reportModelList); localReport.DataSources.Clear(); localReport.DataSources.Add(reportDataSource); localReport.Refresh(); string extensionString = "Pdf"; string outputType = "Pdf"; ReportExportHelper(localReport, outputType, "Invoice", true, extensionString, response); } } }
private void BuildReport() { List <ReportParameter> paramarr = new List <ReportParameter>(); string addpath; bool isArabic = ReportCls.checkLang(); if (isArabic) { addpath = @"\Reports\Catalog\Ar\ArStorageCostReport.rdlc"; } else { addpath = addpath = @"\Reports\Catalog\En\StorageCostReport.rdlc"; } string reppath = reportclass.PathUp(Directory.GetCurrentDirectory(), 2, addpath); ReportCls.checkLang(); clsReports.storageCostReport(storageCostQuery, rep, reppath, paramarr); clsReports.setReportLanguage(paramarr); clsReports.Header(paramarr); rep.SetParameters(paramarr); rep.Refresh(); }
public LocalReport getRptEvRecuperacion(string reportPath) { LocalReport rptEvRecuperacion = new LocalReport(); try { dtstEvaluacion_ImprimirActas dtaEvRecuperacion = this._getDtaImpresionEvRecuperacion(); ReportDataSource rds = new ReportDataSource(); rds.Value = dtaEvRecuperacion.Acta; rds.Name = "dtsExamenPrincipal"; rptEvRecuperacion.DataSources.Clear(); rptEvRecuperacion.DataSources.Add(rds); rptEvRecuperacion.ReportPath = reportPath; rptEvRecuperacion.SetParameters(this._getParametrosGeneralesReporte()); rptEvRecuperacion.Refresh(); }catch (Exception ex) { Errores err = new Errores(); err.SetError(ex, "getRptEvRecuperacion"); } return(rptEvRecuperacion); }
protected override bool RenderInternal(ref MemoryStream chunk, out string mime) { mime = null; try { var rpt = new LocalReport { ReportEmbeddedResource = ReportDesignerResourcename, EnableExternalImages = false }; rpt.SetParameters(new[] { new ReportParameter("Title", "Titel"), new ReportParameter("SomeText", "Text") //TODO!!! }); rpt.Refresh(); RenderAsMsdbrpt(ResultFileBasename, ref chunk, ref mime, rpt); return(true); } catch (Exception ex) { OnBuiltinReportError(ex.Message, ex); return(false); } }
private void PrintReport() { try { LocalReport RptCasesheet = new LocalReport(); RptCasesheet.DataSources.Clear(); // Set a DataSource to the report // First Parameter - Report DataSet Name // Second Parameter - DataSource Object i.e DataTable RptCasesheet.DataSources.Add(new ReportDataSource("DataSet1", ObjIns.RptCaseSheetBAL(Session["RegNo"].ToString(), Session["VisitDate"].ToString(), ConnKey))); // OR Set Report Path RptCasesheet.ReportPath = HttpContext.Current.Server.MapPath("~/RDLCReports/Casesheet.rdlc"); // Refresh and Display Report RptCasesheet.Refresh(); Export(RptCasesheet); Print(); } catch (Exception ex) { ExceptionLogging.SendExcepToDB(ex, Session["UsrName"].ToString(), Request.ServerVariables["REMOTE_ADDR"].ToString()); Response.Redirect("~/Error.aspx"); } }
protected void ShowReport(string rptPath_RDLC, string dispName, DataSet rptDatasrc, string reportType) { try { //ShowReport(Me, "Report_Kaveri\RptPaySlip_New.rdlc", DisplayName, New ReportDataSource("DSReports_DT_SALARYSLIP", DS.Tables(0)), "PDF") LocalReport lr = new LocalReport(); lr.EnableExternalImages = true; lr.ReportPath = rptPath_RDLC; lr.DisplayName = dispName; List <ReportParameter> rptpara = new List <ReportParameter>();//("Path", Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath.ToString(), "") + @"UpLoadedFiles/photo/1077.jpeg"); //rptpara.Add(new ReportParameter("Path", Server.MapPath(@"UpLoadedFiles/photo"))); //rptpara.Add(new ReportParameter("Path", Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, "") + @"/UpLoadedFiles/photo")); //lr.SetParameters(rptpara); //lr.ReportPath = Server.MapPath(rptPath_RDLC); //lr.DisplayName = dispName; //lr.DataSources.Add(CType(rptDatasrc, ReportDataSource)) for (Int16 I = 0; I <= rptDatasrc.Tables.Count - 1; I++) { lr.DataSources.Add(new ReportDataSource(rptDatasrc.Tables[I].TableName, rptDatasrc.Tables[I])); } lr.Refresh(); //Dim reportType As String = "Excel" // reportType = "Excel" // reportType = "PDF" // reportType = "HTML" string mimeType = null; string encoding = null; string fileNameExtension = null; //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>0.25in</MarginLeft>" + " <MarginRight>0.25in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; //string deviceInfo = null; // = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11.5in</PageHeight>" + " <MarginTop>0.50cm</MarginTop>" + " <MarginLeft>1.25cm</MarginLeft>" + " <MarginRight>0.25cm</MarginRight>" + " <MarginBottom>0.50cm</MarginBottom>" + "</DeviceInfo>" Microsoft.Reporting.WebForms.Warning[] warnings = null; string[] streams = null; byte[] renderedBytes = null; //Render the report renderedBytes = lr.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); //Clear the response stream and write the bytes to the outputstream //Set content-disposition to "attachment" so that user is prompted to take an action //on the file (open or save) Response.Clear(); Response.ContentType = mimeType; //sender.Response.AddHeader("content-disposition", "attachment; filename=" & lr.DisplayName & "." & fileNameExtension) Response.AddHeader("content-disposition", "attachment;open; filename=" + lr.DisplayName + ".pdf"); Response.BinaryWrite(renderedBytes); Response.End(); } catch (System.Exception ex) { //Login.Profile.ErrorHandling(ex, ParentPage, "UCToolbar", "ShowReport"); Response.Write(ex); } finally { } }
private void PrintAllReports(string ReportName) { try { LocalReport Report = new LocalReport(); Report.DataSources.Clear(); if (ReportName == "GenarateStikker") { dt = new DataTable(); objBE.SampleID = Session["sampleid"].ToString(); objBE.Action = "STICKER"; // objBE.qrcode =byte.Parse( Session["qrcode"].ToString()); dt = Objrdl.GenerateSticker(objBE, Session["con"].ToString()); Report.ReportPath = HttpContext.Current.Server.MapPath("~/RdlcReports/StikerDI.rdlc"); Report.DataSources.Add(new ReportDataSource("DataSet1", dt)); Report.Refresh(); } Export(Report); Print(ReportName); } catch (Exception ex) { //ExceptionLogging.SendExcepToDB(ex, Session["UsrName"].ToString(), Request.ServerVariables["REMOTE_ADDR"].ToString()); } }
public byte[] ExportCollaborators(string exportType, String path) { LocalReport localreport = new LocalReport(); localreport.ReportPath = path; localreport.SubreportProcessing += new SubreportProcessingEventHandler( delegate(object sender, SubreportProcessingEventArgs e) { ReportDataSource reportSource = new ReportDataSource(); reportSource.Name = "ColaborateurDataSet"; reportSource.Value = colab.getCollaborators().ToList(); e.DataSources.Add(reportSource); } ); localreport.Refresh(); ReportDataSource reportDataSource = new ReportDataSource(); reportDataSource.Name = "DeplacementDataSet"; reportDataSource.Value = dep.getDisplacements().ToList(); localreport.DataSources.Add(reportDataSource); string fileNameExtension = this.FileExtension(exportType); string reportType = exportType; string mimeType; string encoding; string[] streams; Warning[] warning; byte[] renderedByte; renderedByte = localreport.Render(reportType, "", out mimeType, out encoding, out fileNameExtension, out streams, out warning); return(renderedByte); }
public byte[] RunReport(string[] DSet, string[] SQL, string RptName, string ExportType, HttpContext oContext, bool bDownloadAttachment = false) { LocalReport viewer = new LocalReport(); viewer.ReportEmbeddedResource = RptName; //string ext = "xlsx"; //EXCELOPENXML //if (ExportType == "pdf") { ext = "pdf"; } else if(ExportType == "WORDOPENXML") { ext = "docx"; } for (int i = 0; i < DSet.Length; i++) { DataTable dt = new DataTable(); dt = FillDSet(SQL[i]).Tables[0]; if ((RptName == "FRDP.LRP_Profile.rdlc") && (i == 0)) { string path = HttpContext.Current.Server.MapPath("~/images/distt/" + dt.Rows[0]["Distt"].ToString() + ".png"); dt.Rows[0]["DisttMap"] = File.ReadAllBytes(path); } ReportDataSource datasource = new ReportDataSource(DSet[i], dt); viewer.DataSources.Add(datasource); } viewer.Refresh(); byte[] Contents = viewer.Render(ExportType); return(Contents); //oContext.Response.Clear(); //oContext.Response.ContentType = "application/" + ExportType; //if (bDownloadAttachment == true) //{ // oContext.Response.AddHeader("Content-disposition", "attachment; filename=Report." + ext); //} //oContext.Response.BinaryWrite(pdfContent); //oContext.Response.End(); }
public LocalReport getReporteHorariosExamenes(string reportPath) { LocalReport rptHorarioExEst = new LocalReport(); try { WSGestorDeReportesEvaluacion.dtstHorarioExamenes dsHorariosExamenes = this._getHorarioExamenes(); ReportDataSource rds = new ReportDataSource(); rds.Name = "dsHorarioExamenes"; rds.Value = dsHorariosExamenes.Materias; rptHorarioExEst.DataSources.Clear(); rptHorarioExEst.DataSources.Add(rds); rptHorarioExEst.ReportPath = reportPath; rptHorarioExEst.SetParameters(this._getParametrosGeneralesReporte()); rptHorarioExEst.Refresh(); } catch (Exception ex) { Errores err = new Errores(); err.SetError(ex, "getReporteHorariosExamenes"); } return(rptHorarioExEst); }
public LocalReport getRptEvAcumulativa(string reportPath) { LocalReport rptEvAcumulativa = new LocalReport(); try{ WSGestorEvaluacion.dtstEvaluacion_ImprimirAcumulados dtaEvAcumulativa = this._getDtaImpresionEvAcumulativa(); ReportDataSource rds = new ReportDataSource(); rds.Value = dtaEvAcumulativa.Acta; rds.Name = "dtsActasAcumuladas"; rptEvAcumulativa.DataSources.Clear(); rptEvAcumulativa.DataSources.Add(rds); rptEvAcumulativa.ReportPath = reportPath; rptEvAcumulativa.SetParameters(this._getParametrosGeneralesReporte()); rptEvAcumulativa.Refresh(); } catch (Exception ex) { Errores err = new Errores(); err.SetError(ex, "getReporteHorarios"); } return(rptEvAcumulativa); }
public LocalReport getReporteHorarios(string reportPath) { LocalReport rptHorarioAcademico = new LocalReport(); try { WSGestorDeReportesMatriculacion.dtstHorario he = (_strCodNivel == "-2") ? _horarioEstudiante() : _horarioCursoParalelo(_strCodNivel, _strCodParalelo); ReportDataSource rds = new ReportDataSource(); rds.Name = "dsHorarioAcademico"; rds.Value = he.Horario; rptHorarioAcademico.DataSources.Clear(); rptHorarioAcademico.DataSources.Add(rds); rptHorarioAcademico.ReportPath = reportPath; rptHorarioAcademico.SetParameters(_getParametrosGeneralesReporte()); rptHorarioAcademico.Refresh(); } catch (Exception ex) { Errores err = new Errores(); err.SetError(ex, "getReporteHorarios"); } return(rptHorarioAcademico); }
/// <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(); }
public void Save(string fileName) { Warning[] warnings; string[] streamids; string mimeType; string encoding; string filenameExtension; string deviceInf = ""; //byte[] bytes; //string extension; string directoryPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); string exe = Process.GetCurrentProcess().MainModule.FileName; string path = Path.GetDirectoryName(exe); reportViewerMain.ProcessingMode = ProcessingMode.Local; LocalReport localReport = reportViewerMain.LocalReport; localReport.ReportPath = string.Format("{0}\\{1}", path, "Reports\\AutoLogStatsReport.rdlc"); localReport.Refresh(); localReport.DataSources[0].Value = _rs; byte[] pdfReport = localReport.Render("pdf", deviceInf, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(pdfReport, 0, pdfReport.Length); } }
public HttpResponseMessage PostRaceInvoice(int raceId) { var party = context.RaceEntries.Where(x => x.RaceId == raceId); var data = party.Select(x=>new{RaceName=x.Race.RaceName, CyclistFirstName = x.Person.FirstName, CyclistSurname = x.Person.Surname, CyclistIdNumber = x.Person.IdNumber, CyclistDistance = x.Race.RaceDistance, CyclistRaceCost = x}).ToList(); var report = new LocalReport { ReportPath = @".\RaceInvoice.rdlc" }; report.DataSources.Add( new ReportDataSource("RaceInvoice", data)); report.Refresh(); return Export(report, "PDF"); }
private void DoPrinting(DepartmentStockOut deptStockOut) { streamList = new List<Stream>(); // push data to local report DeptStockOutInvoice = new LocalReport(); DeptStockOutInvoice.ReportEmbeddedResource = "AppFrameClient.Report.DepartmentStockOutInvoice.rdlc"; ReportDataSource DeptStockOutRDS = new ReportDataSource("AppFrameClient_ViewModel_DepartmentStockOutView"); BindingSource bdsHeader = new BindingSource(); DepartmentStockOutView deptSOView = new DepartmentStockOutViewMapper().Convert(deptStockOut); deptSOView.EmployeeName = txtCustomerName.Text.Trim(); if(rdoWholesale.Checked) { deptSOView.StockOutKind = "BÁN SỈ"; } else { deptSOView.StockOutKind = "BÁN LẺ"; } bdsHeader.DataSource = deptSOView; DeptStockOutRDS.Value = bdsHeader; DeptStockOutInvoice.DataSources.Add(DeptStockOutRDS); ReportDataSource DeptStockOutDetailRDS = new ReportDataSource("AppFrameClient_ViewModel_DepartmentStockOutDetailView"); BindingSource bdsDetails = new BindingSource(); DepartmentStockOutViewDetailMapper detailMapper = new DepartmentStockOutViewDetailMapper(); IList<DepartmentStockOutDetailView> viewList = new List<DepartmentStockOutDetailView>(); foreach (DepartmentStockOutDetail outDetail in deptStockOut.DepartmentStockOutDetails) { DepartmentStockOutDetailView detailView = detailMapper.Convert(outDetail); if(rdoWholesale.Checked) { detailView.Price = outDetail.DepartmentPrice.WholeSalePrice; } else { detailView.Price = outDetail.DepartmentPrice.Price; } viewList.Add(detailView); } // remove duplicate int count = viewList.Count; for (int i = 0; i < count; i++ ) { DepartmentStockOutDetailView detailView = viewList[i]; int last = count - 1; while(last >i) { DepartmentStockOutDetailView otherView = viewList[last]; if(otherView.ProductName.Equals(detailView.ProductName)) //&& otherView.ColorName.Equals(detailView.ColorName) ) { detailView.Quantity += otherView.Quantity; detailView.GoodCount += otherView.GoodCount; viewList.RemoveAt(last); count -= 1; } last -= 1; } } bdsDetails.DataSource = viewList; DeptStockOutDetailRDS.Value = bdsDetails; DeptStockOutInvoice.DataSources.Add(DeptStockOutDetailRDS); // do printing streamList.Clear(); //const string printerName = "Epson TM-T88IV"; string printerName = ClientSetting.PrinterName; PrintDocument printDoc = new PrintDocument(); printDoc.PrinterSettings.PrinterName = printerName; if (!printDoc.PrinterSettings.IsValid) { MessageBox.Show(String.Format("Can't find printer \"{0}\".", printerName)); return; } PageSettings pageSettings = printDoc.PrinterSettings.DefaultPageSettings; pageSettings.PrinterResolution.X = 180; pageSettings.PrinterResolution.Y = 180; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>8.2in</PageWidth>" + " <PageHeight>5.5in</PageHeight>" + " <DpiX>180</DpiX>" + " <DpiY>180</DpiY>" + " <MarginTop>0.0in</MarginTop>" + " <MarginLeft>0.0in</MarginLeft>" + " <MarginRight>0.0in</MarginRight>" + " <MarginBottom>0.0in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; if (DeptStockOutInvoice == null) { return; } DeptStockOutInvoice.Refresh(); DeptStockOutInvoice.Render("Image", deviceInfo, CreateStream, out warnings); if (streamList.Count > 0) { foreach (Stream stream in streamList) { stream.Position = 0; } } printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage); printDoc.EndPrint += new PrintEventHandler(printDoc_EndPrint); printDoc.Print(); }
/// <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(); }
public void CreateReport() { LocalReport report = new LocalReport(); byte[] file; string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; ReportDataSource rds = new ReportDataSource(); rds.Name = "MostreFabrica"; List<MostreFabrica> mostre = MostreFabrica.GetMostreFabrica(DropDownList1.SelectedValue, TextBox1.Text, TextBox2.Text); string datatestare = TextBox1.Text; string datatestare2 = TextBox2.Text; rds.Value = mostre; report.DataSources.Clear(); report.DataSources.Add(rds); report.ReportPath = "ReportFabricaIntre4.rdlc"; report.Refresh(); string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>29.7cm</PageWidth>" + " <PageHeight>21cm</PageHeight>" + " <MarginTop>0.0cm</MarginTop>" + " <MarginLeft>0.1cm</MarginLeft>" + " <MarginRight>0.1cm</MarginRight>" + " <MarginBottom>0.5cm</MarginBottom>" + "</DeviceInfo>"; string deviceInfoXls = "<DeviceInfo>" + " <OutputFormat>XLS</OutputFormat>" + " <PageWidth>29.7cm</PageWidth>" + " <PageHeight>21cm</PageHeight>" + " <MarginTop>0.0cm</MarginTop>" + " <MarginLeft>0.0cm</MarginLeft>" + " <MarginRight>0.1cm</MarginRight>" + " <MarginBottom>0.1cm</MarginBottom>" + "</DeviceInfo>"; 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(); //set report parameters string laborator = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString(); string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString(); string combi = mostre[0].Combi; ReportParameter pDatatestare = new ReportParameter("datatestare", datatestare); ReportParameter pDatatestare2 = new ReportParameter("datatestare2", datatestare2); ReportParameter pCombi = new ReportParameter("combi", combi); 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); ReportParameter pVersiune = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportFabricaIntre4")); ReportParameter[] p = { pDatatestare, pDatatestare2, pCombi, pFabricanume, pFabricastrada, pFabricanumar, pFabricaoras, pFabricajudet, pLaborator, pResponsabil, pVersiune }; report.SetParameters(p); file = report.Render("PDF", deviceInfo, out mimeType, out encoding, out fileExtension, out streams, out warnings); string httppath = StaticDataHelper.SettingsManager.CaleRapoarteHttp; string filepath = StaticDataHelper.SettingsManager.CaleRapoarte; fabricaname = replace_special_car_null(fabricaname); string raport_name = "RaportFabrica" + datatestare.Replace("/", "_") + "_" + datatestare2.Replace("/", "_") + "_" + fabricaid + "-" + fabricaname + ".pdf"; string raport_excel = "RaportFabrica" + datatestare.Replace("/", "_") + "_" + datatestare2.Replace("/", "_") + "_" + fabricaid + "-" + fabricaname + ".xls"; string path_raport_http = "http://" + Request.ServerVariables.Get("HTTP_HOST") + "/" + httppath; string pdf_link = path_raport_http + @"Fabrici/" + raport_name; string pdf_file = filepath + @"Fabrici/" + raport_name; // writefile string excel_link = path_raport_http + @"Fabrici/" + raport_excel; string excel_file = filepath + @"Fabrici/" + raport_excel; report.SetParameters(new ReportParameter("BkImage", "")); File.WriteAllBytes(pdf_file, file); byte[] file_xls = report.Render("EXCEL", deviceInfoXls, 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; }
private void RenderWorkOrderEquipExcelReport() { string strReportType = "Excel"; LocalReport objLocalReport; ReportDataSource WorkOrderDataSource; string mimeType; string encoding; string fileNameExtension; string deviceInfo = ""; Warning[] warnings; string[] streams; objLocalReport = new LocalReport { ReportPath = Server.MapPath(Settings.ReportDirectory + "WorkOrderEquipment.rdlc") }; objLocalReport.SubreportProcessing += new SubreportProcessingEventHandler(MySubreportEventHandler); //Give the reportdatasource a name so that we can reference it in our report designer WorkOrderDataSource = new ReportDataSource("WorkOrders", WorkOrderCollection); objLocalReport.DataSources.Add(WorkOrderDataSource); objLocalReport.Refresh(); //The DeviceInfo settings should be changed based on the reportType //http://msdn2.microsoft.com/en-us/library/ms155397.aspx deviceInfo = string.Format( "<DeviceInfo>" + "<OmitDocumentMap>True</OmitDocumentMap>" + "<OmitFormulas>True</OmitFormulas>" + "<SimplePageHeaders>True</SimplePageHeaders>" + "</DeviceInfo>", strReportType); //Render the report var renderedBytes = objLocalReport.Render( strReportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); //Clear the response stream and write the bytes to the outputstream //Set content-disposition to "attachment" so that user is prompted to take an action //on the file (open or save) Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.ContentType = mimeType; Response.AddHeader("content-disposition", "attachment; filename=WorkOrderEquip" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + "." + fileNameExtension); Response.BinaryWrite(renderedBytes); Response.End(); }
public void CreateReportExt(int year) { LocalReport report = new LocalReport(); string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; Session["year"] = year; report.SubreportProcessing += new SubreportProcessingEventHandler(ItemsSubreportProcessingEventHandler); int fermaid = 0; try { fermaid = Convert.ToInt32(FermaId.Text); } catch { fermaid = 0; } string username = Username.Text; UserInfos userinfos = UserInfos.getUserInfos(username); 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"; logger.Info(string.Format("CreateReportExt|getting samples")); List<SampleAnalizeExt> samplesext = SampleAnalize.GetSampleAnalizeExt(fermaid, year); logger.Info(string.Format("CreateReportExt|got {0} samples", samplesext.Count)); 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 = FermaName.Text + " - " + "Cod exploatatie " + FermaCod.Text; ReportParameter pCod = new ReportParameter("CodExpl", FermaCod.Text); 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 fermaname = replace_special_car_null(FermaName.Text); string raport_excel = FermaCod.Text + "_" + fermaname + ".xls"; string excel_file = filepath + raport_excel; string excel_link = path_raport_http + raport_excel; // infomess.Text = infomess.Text + ";" + excel_file; byte[] xls_content = report.Render("EXCEL", StaticData.DEVICE_INFO_XLS, out mimeType, out encoding, out fileExtension, out streams, out warnings); File.WriteAllBytes(excel_file, xls_content); logger.Info(string.Format("CreateReportExt|wrote excel file {0}", excel_file)); //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); } } } }
public void CreateReport() { Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = "."; logger.Info(string.Format("GetMostreFerma|CreateReport")); LocalReport report = new LocalReport(); byte[] file; string mimeType, encoding, fileExtension; string[] streams; Warning[] warnings; long reportNumber; ReportManager rManager = new ReportManager(ctx); Report dalReport = rManager.GetOrCreateReport(FCCLReportType.Crotalii, ObjectId , 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.GetMostreFerma(DropDownList1.SelectedValue, DateTime.Parse(TextBox1.Text)); logger.Info(string.Format("GetMostreFerma|mostre cnt:{0}", mostre.Count)); rds.Value = mostre; DateTime datatestare = DateTime.Parse(TextBox1.Text); DateTime datatmin = datatestare; DateTime datatmax = datatestare; string datatesttitlu = datatestare.ToShortDateString(); DateTime datapmin = DateTime.MaxValue; DateTime datapmax = DateTime.MinValue; string dataprimtitlu; string nrcomanda = ""; string combi = mostre[0].Combi; foreach (MostreFabrica mf in mostre) { DateTime datamin = mf.DataTestare; DateTime datamax = mf.DataTestareFinala; if (mf.NrComanda.Trim() != "") nrcomanda = mf.NrComanda.Trim(); if (DateTime.Compare(datamin, datatmin) < 0) datatmin = datamin; if (DateTime.Compare(datamax, datatmax) > 0) datatmax = datamax; if (DateTime.Compare(mf.DataPrimirii, datapmin) < 0) datapmin = mf.DataPrimirii; if (DateTime.Compare(mf.DataPrimirii, datapmax) > 0) datapmax = mf.DataPrimirii; } if (datatmin != datatmax) datatesttitlu = datatmin.ToShortDateString() + " - " + datatmax.ToShortDateString(); if (datapmin != datapmax) dataprimtitlu = datapmin.ToShortDateString() + " si " + datapmax.ToShortDateString(); else dataprimtitlu = datapmin.ToShortDateString(); rds.Value = mostre; report.DataSources.Clear(); report.DataSources.Add(rds); report.ReportPath = "ReportCrotalii.rdlc"; report.Refresh(); string fermaid = DropDownList1.SelectedValue; string fermaname = 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 Ferme_CCL.Cod,Ferme_CCL.Strada,Ferme_CCL.Numar,Ferme_CCL.Oras,Judete.Denloc " + "FROM Ferme_CCL,Judete WHERE Ferme_CCL.ID=" + fermaid + " AND Ferme_CCL.Judet=Judete.ID"; cnn.Open(); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); string fermastrada = Convert.ToString(reader["Strada"]); string fermanumar = Convert.ToString(reader["Numar"]); string fermaoras = Convert.ToString(reader["Oras"]); string fermajudet = Convert.ToString(reader["Denloc"]); string fermacod = Convert.ToString(reader["Cod"]); reader.Close(); cnn.Close(); cmd.CommandText = "SELECT Fabrici.Nume, Ferme_CCL.FabricaID from Ferme_CCL, Fabrici " + " WHERE Ferme_CCL.ID =" + fermaid + " AND Ferme_CCL.FabricaID = Fabrici.ID"; cnn.Open(); reader = cmd.ExecuteReader(); reader.Read(); string asocid = Convert.ToString(reader["FabricaID"]); string asocnume = Convert.ToString(reader["Nume"]); reader.Close(); cnn.Close(); FermaName.Text = fermaname; FermaCod.Text = fermacod; FermaId.Text = "" + fermaid; string datab = TextBox2.Text; string nrb = dalReport.ReportNumber.ToString(); //set report parameters string laborator = ddlLaborator.Items[ddlLaborator.SelectedIndex].ToString(); string responsabil = ddlResponsabil.Items[ddlResponsabil.SelectedIndex].ToString(); ReportParameter pAsocnume = new ReportParameter("asocnume", asocnume); ReportParameter pNrcomanda = new ReportParameter("nrcomanda", nrcomanda); 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 pFermanume = new ReportParameter("fabricanume", fermaname); ReportParameter pFermastrada = new ReportParameter("fabricastrada", fermastrada); ReportParameter pFermanumar = new ReportParameter("fabricanumar", fermanumar); ReportParameter pFermaoras = new ReportParameter("fabricaoras", fermaoras); ReportParameter pFermajudet = new ReportParameter("fabricajudet", fermajudet); ReportParameter pLaborator = new ReportParameter("laborator", laborator); ReportParameter pResponsabil = new ReportParameter("responsabil", responsabil); ReportParameter pVersiune = new ReportParameter("Versiune", new SettingManager(StaticDataHelper.FCCLDbContext).GetValueByName("ReportCrotalii")); ReportParameter[] p ={ pDatatestare, pDataprimirii,pCombi, pNrcomanda, pDatab, pNrb, pFermanume, pFermastrada, pFermanumar, pFermaoras, pFermajudet, pAsocnume, 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; fermaname = replace_special_car_null(fermaname); string nrcom = nrcomanda.Replace("/", "_"); nrcom = nrcom.Replace(".", ""); string raport_name = "Raport" + nrcom + "-" + fermaname + "_" + fermacod + "-" + datatestare.ToShortDateString().Replace("/", "") + ".pdf"; string raport_excel = "Raport" + nrcom + "-" + fermaname + "_" + fermacod + "-" + datatestare.ToShortDateString().Replace("/", "") + ".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; // writefile string excel_link = path_raport_http + @"Ferme/" + raport_excel; string excel_file = filepath + @"Ferme/" + raport_excel; // Trace.Write(pdf_file); File.WriteAllBytes(pdf_file, file); logger.Info(string.Format("GetMostreFerma|pdf done")); dalReport.SampleCount = mostre.Count; dalReport.PageCount = PDFHelper.GetNumberOfPdfPages(pdf_file); rManager.Save(dalReport); ctx.SaveChanges(); logger.Info(string.Format("GetMostreFerma|saved report")); // raport excel LocalReport rapexcel = new LocalReport(); ReportDataSource rdse = new ReportDataSource(); rdse.Name = "MostreFabrica"; rdse.Value = mostre; rapexcel.DataSources.Clear(); rapexcel.DataSources.Add(rdse); rapexcel.ReportPath = "ReportCrotalii.rdlc"; rapexcel.SetParameters(p); rapexcel.Refresh(); rapexcel.SetParameters(new ReportParameter("BkImage", "")); byte[] file_xls = rapexcel.Render("EXCEL", StaticData.DEVICE_INFO_XLS, out mimeType, out encoding, out fileExtension, out streams, out warnings); // end raport excel File.WriteAllBytes(excel_file, file_xls); logger.Info(string.Format("GetMostreFerma|excel done")); int firstyear; if (int.TryParse(ConfigurationManager.AppSettings["firstyear"], out firstyear)) { // test rep. portal SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString); SqlCommand cmda = new SqlCommand("Select aspnet_Users.UserName from aspnet_users join usersinformation on aspnet_Users.userid = usersinformation.userid where usersinformation.asocid=" + asocid, connection); connection.Open(); string username = ""; using (SqlDataReader rdr = cmda.ExecuteReader()) { if (rdr.Read()) { username = rdr["UserName"].ToString(); } rdr.Close(); } connection.Close(); if (username.Length > 0) { try { MembershipUser User = Membership.Providers["PortalProvider"].GetUser(username, false); Username.Text = User.UserName; //Start generating from test date for (int year = firstyear; year <= DateTime.Now.Year; year++) { logger.Info(string.Format("GetMostreFerma|ext call year:{0}", year)); CreateReportExt(year); } } catch { } } } string raport_csv = "CSV_Registru_" + datatestare.ToShortDateString().Replace("/", "") + "_" + fermaid + "_" + fermaname + ".csv"; string csv_link = path_raport_http + @"Registru/" + raport_csv; string csv_file = filepath + @"Registru/" + raport_csv; logger.Info(string.Format("CreateReportExt|write csv file {0}", csv_file)); CreateExcelFile(mostre, csv_file); logger.Info(string.Format("GetMostreFerma|processing done")); pdflink.Visible = true; pdflink.NavigateUrl = pdf_link; pdflink.Text = raport_name; xlslink.Visible = true; xlslink.NavigateUrl = excel_link; xlslink.Text = raport_excel; csvlink.Visible = true; csvlink.NavigateUrl = csv_link; csvlink.Text = raport_csv; }
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(); }
/// <summary> /// Handles drilldown report events /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void reportViewer1_Drillthrough(object sender, DrillthroughEventArgs e) { _localReport = (LocalReport)e.Report; OnReportDrilledThrough(e); byte[] rdlBytes = Encoding.UTF8.GetBytes(_reportInfo.ReportDefinition); System.IO.MemoryStream stream = new System.IO.MemoryStream(rdlBytes); _localReport.LoadReportDefinition(stream); RunReport(); if (!_bDisplayedError) _localReport.Refresh(); }
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 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); }
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; }
public Byte[] ObtenerPropuestaRPT(int id) { /* Carga de lista de datos */ var propuesta = modelEntity.SP_SAF_PROPUESTA_RPT(id).ToList(); equipoAuditoriaRpt = modelEntity.SP_SAF_EQUIPOAUDITORIA_RPT(id).ToList(); /* Creación de reporte */ const string reportPath = "~/Reports/rptPropuesta.rdlc"; var localReport = new LocalReport { ReportPath = Server.MapPath(reportPath) }; /* Seteando el datasource */ var dtPropuesta = new ReportDataSource("dtPropuesta") { Value = propuesta }; var dtEquipoAuditoria = new ReportDataSource("dtEquipoAuditoria") { Value = equipoAuditoriaRpt }; localReport.DataSources.Add(dtPropuesta); localReport.DataSources.Add(dtEquipoAuditoria); //localReport.SubreportProcessing += ReportePropuestaSubreportProcessingEventHandler; localReport.Refresh(); //Configuración del reporte string deviceInfoA4 = "<DeviceInfo>" + " <OutputFormat>A4</OutputFormat>" + " <PageWidth>21cm</PageWidth>" + " <PageHeight>29.7cm</PageHeight>" + " <MarginTop>1cm</MarginTop>" + " <MarginLeft>1cm</MarginLeft>" + " <MarginRight>1cm</MarginRight>" + " <MarginBottom>1cm</MarginBottom>" + "</DeviceInfo>"; string mimeType; string encoding; string fileNameExtension; Warning[] warnings; string[] streams; var file = localReport.Render("pdf", deviceInfoA4, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); return file; }
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; }
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; }
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; } }
private static LocalReport CreateLocalReport(string reportFileName, DataTable dataSource, string reportDataSourceName) { LocalReport localReport = new LocalReport(); localReport.ReportPath = reportFileName; localReport.DataSources.Clear(); localReport.DataSources.Add(new ReportDataSource(reportDataSourceName, dataSource)); localReport.Refresh(); return localReport; }