Example #1
0
        private void LoadReport(string reportPath)
        {
            Stream stream = _assembly.GetManifestResourceStream(reportPath + ".rdlc");

            using (MemoryStream memoryStream = new MemoryStream()) {
                stream.CopyTo(memoryStream);
                _localReport          = new LocalReport();
                memoryStream.Position = 0;
                _localReport.LoadReportDefinition(memoryStream);
                _dataSetSources = new Dictionary <string, MethodInfo>();

                var reportNamespace = reportPath.Substring(0, reportPath.LastIndexOf('.'));
                FillSubReports(stream, reportNamespace);

                if (_subReports != null)
                {
                    foreach (var subReport in _subReports)
                    {
                        _localReport.LoadSubreportDefinition(subReport.Key, subReport.Value);
                        FillDataSources(subReport.Value);
                    }
                }

                _localReport.EnableHyperlinks = true;

                FillDataSources(memoryStream);
            }
        }
Example #2
0
        /// <summary>
        /// Carga la definicion del reporte cambiando namesapces y secciones
        /// </summary>
        /// <param name="localReport">Instancia de LocalReport</param>
        /// <param name="reportePathCompleto">Path del reporte completo para acceder</param>
        public static void ReporteLoadReportDefinition(LocalReport localReport, string reportePathCompleto, IDictionary <string, string> imagenes)
        {
            string strReport = System.IO.File.ReadAllText(reportePathCompleto, System.Text.Encoding.Default);

            if (strReport.Contains("http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"))
            {
                strReport =
                    strReport.Replace(
                        "<Report xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\" xmlns:cl=\"http://schemas.microsoft.com/sqlserver/reporting/2010/01/componentdefinition\" xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition\">",
                        "<Report xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\" xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition\">");
                strReport =
                    strReport.Replace("<ReportSections>", "").Replace("<ReportSection>", "").Replace(
                        "</ReportSection>", "").Replace("</ReportSections>", "");
            }

            if (imagenes != null)
            {
                foreach (var imagenNombre in imagenes.Keys)
                {
                    strReport = CambiarEmbeddedImages(strReport, imagenNombre, imagenes[imagenNombre]);
                }
            }

            byte[] bytReport = System.Text.Encoding.UTF8.GetBytes(strReport);
            localReport.LoadReportDefinition(new MemoryStream(bytReport));
        }
Example #3
0
        private LocalReport GetReporteRecibiConforme(int idPedido)
        {
            var localReport = new LocalReport();

            var pedido  = _dbContext.Pedidos.Find(idPedido);
            var polizas = pedido.Polizas.Where(a => a.DetallePolizas.Any()).ToList();

            var datosPedido = new List <RecibiConformeDto>
            {
                new RecibiConformeDto {
                    NombreCompleto = pedido.Cliente.NombreCompleto,
                    Contenedor     = string.IsNullOrEmpty(pedido.Contenedores) ? "" : pedido.Contenedores,
                    Descripcion    = pedido.Descripcion,
                    Direccion      = string.IsNullOrEmpty(pedido.Direccion) ? "" : pedido.Direccion,
                    Telefono       = pedido.Cliente.Telefono,
                    LugarFecha     = $"Santa Cruz - {DateTime.Now.Day} de {DateTime.Now.ToString("MMMM")} del {DateTime.Now.Year}",
                    Poliza         = string.Join(" - ", polizas.Select(a => a.Codigo))
                }
            };

            var memory = pedido.EmpresaId == (int)EmpresaEnum.MaxiTrader
                ? new MemoryStream(ReportesResources.RecibiConformeMaxT)
                : new MemoryStream(ReportesResources.RecibiConforme);

            localReport.LoadReportDefinition(memory);
            localReport.DataSources.Clear();
            ////Agregar nuevo ReportDataSource con el nombre y lista correspondiente.
            localReport.DataSources.Add(new ReportDataSource("DatosPedido", datosPedido));
            return(localReport);
        }
Example #4
0
        /// <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();
        }
Example #5
0
        protected void cargar()
        {
            LocalReport Reporte = new LocalReport();

            byte[] reporte;

            reporte = Desktop.Reportes.Analisis;

            Stream archivoReporte = new MemoryStream(reporte);

            Reporte.LoadReportDefinition(archivoReporte);

            Parametros = new Dictionary <string, object>();
            Parametros.Add("idRutina", idRutina);

            DataSet          dataSet      = obtenerDataSet("Rutina");
            DataSet          dataSet2     = obtenerDataSet("MuestrasRutina");
            ReportDataSource origenDatos  = new ReportDataSource("Rutina", dataSet.Tables[0]);
            ReportDataSource origenDatos2 = new ReportDataSource("MuestrasRutina", dataSet2.Tables[0]);

            List <ReportParameter> paramsReporte = new List <ReportParameter>();

            paramsReporte.Add(new ReportParameter("idRutina", idRutina.ToString()));
            Reporte.DataSources.Add(origenDatos);
            Reporte.DataSources.Add(origenDatos2);
            Reporte.SetParameters(paramsReporte);

            this.setLocalReport(rpvGeneral, Reporte);

            rpvGeneral.RefreshReport();
        }
Example #6
0
 private void GenerateReport(LocalReport lr, ReportParemeter Paras)
 {
     lr.LoadReportDefinition(GetReportStream(Paras.MainReport.ReportName));
     //lr.DataSources.Add(new ReportDataSource("dsTemplateNomal", ReportHeader));
     //--
     ReportSourceParameter = Paras;
 }
        protected void executeReport_click(object sender, EventArgs e)
        {
            if (reportSelector.SelectedIndex == 9)
                executeReportInAppDomain_click(sender, e);
            else
            {
                LocalReport rpt = new LocalReport();
                rpt.EnableExternalImages = true;
                rpt.ReportPath = String.Concat(Path.GetDirectoryName(Request.PhysicalPath), "\\Reports\\", reportSelector.SelectedValue);
                string orientation = (rpt.GetDefaultPageSettings().IsLandscape) ? "landscape" : "portrait";
                StringReader formattedReport = Business.reportHelper.FormatReportForTerritory(rpt.ReportPath, orientation, cultureSelector.SelectedValue);
                rpt.LoadReportDefinition(formattedReport);

                // Add Data Source
                rpt.DataSources.Add(new ReportDataSource("InvoiceDataTable", dt));

                // Internationlisation: Add uiCulture and Translation Labels
                if (reportSelector.SelectedIndex >= 3)
                {
                    Dictionary<string, string> reportLabels = Reports.reportTranslation.translateInvoice(cultureSelector.SelectedValue);
                    ReportParameterCollection reportParams = new ReportParameterCollection();

                    reportParams.Add(new ReportParameter("uiCulture", cultureSelector.SelectedValue));
                    foreach (string key in reportLabels.Keys)
                        reportParams.Add(new ReportParameter(key, reportLabels[key]));

                    rpt.SetParameters(reportParams);
                }

                // Render To Browser
                renderPDFToBrowser(rpt.Render("PDF", Business.reportHelper.GetDeviceInfoFromReport(rpt, cultureSelector.SelectedValue, "PDF")));
            }
        }
Example #8
0
        protected void cargar()
        {
            //Comienzo carga de reporte
            LocalReport Reporte = new LocalReport();

            byte[] reporte;

            reporte = Desktop.Reportes.LotesCerrados;

            Stream archivoReporte = new MemoryStream(reporte);

            Reporte.LoadReportDefinition(archivoReporte);

            Parametros = new Dictionary <string, object>();
            Parametros.Add("idTipoArticulo", idTipoArticulo);
            Parametros.Add("nroLote", nroLote);

            DataSet          dataSet     = obtenerDataSet("LotesCerrados");
            ReportDataSource origenDatos = new ReportDataSource("DataSet1", dataSet.Tables[0]);

            List <ReportParameter> paramsReporte = new List <ReportParameter>();

            paramsReporte.Add(new ReportParameter("idTipoArticulo", idTipoArticulo.ToString()));
            paramsReporte.Add(new ReportParameter("nroLote", nroLote));

            Reporte.DataSources.Add(origenDatos);
            Reporte.SetParameters(paramsReporte);

            this.setLocalReport(rpvGeneral, Reporte);

            rpvGeneral.RefreshReport();
        }
Example #9
0
        public static void GenerateReportByLanguageCode(LocalReport report, string[] subReportPath)
        {
            var doc = new XmlDocument();

            doc.Load(Assembly.GetExecutingAssembly()
                     .GetManifestResourceStream("SureMedPlusRdlc.Rdlc.SureMedReport2ColsView.rdlc"));

            PrepareXmlDocument(doc);

            report.ReportPath = string.Empty;

            using (var rdlcOutputStream = new StringReader(doc.DocumentElement.OuterXml))
            {
                report.LoadReportDefinition(rdlcOutputStream);
            }

            foreach (var sub in subReportPath)
            {
                if (sub != "")
                {
                    var docSubReport = new XmlDocument();
                    var subPath      = "SureMedPlusRdlc.Rdlc." + sub + ".rdlc";
                    docSubReport.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(subPath));

                    PrepareXmlDocument(docSubReport);

                    using (var rdlcSubReportOutputStream = new StringReader(docSubReport.DocumentElement.OuterXml))
                    {
                        report.LoadSubreportDefinition(sub, rdlcSubReportOutputStream);
                    }
                }
            }
        }
        public void Render(string reportDesign, ReportDataSource[] dataSources, string destFile, IEnumerable<ReportParameter> parameters = null)
        {
            var localReport = new LocalReport();

            using (var reportDesignStream = System.IO.File.OpenRead(reportDesign))
            {
                localReport.LoadReportDefinition(reportDesignStream);
            }
            localReport.EnableExternalImages = true;
            localReport.EnableHyperlinks = true;

            if (parameters != null)
            {
                localReport.SetParameters(parameters);
            }
            foreach (var reportDataSource in dataSources)
            {
                localReport.DataSources.Add(reportDataSource);
            }

            //Export to PDF
            string mimeType;
            string encoding;
            string fileNameExtension;
            string[] streams;
            Warning[] warnings;
            var content = localReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);

            System.IO.File.WriteAllBytes(destFile, content);
        }
Example #11
0
    protected void OnButtonCommand(object sender, CommandEventArgs e)
    {
        //Event handler for command button clicked
        try {
            //Change view to Viewer and reset to clear existing data
            Master.Viewer.Reset();

            //Get parameters for the query
            string _clientName = this.ddlClient.SelectedItem.Text;
            string _pickupID = "", _termCode = "";

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = REPORT_NAME;
            report.EnableExternalImages = true;
            EnterpriseService enterprise = new EnterpriseService();
            DataSet           ds         = new DataSet(REPORT_DS);
            foreach (GridViewRow row in SelectedRows)
            {
                DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex];
                _pickupID = dataKey["PickupID"].ToString();
                _termCode = dataKey["TerminalCode"].ToString();
                DataSet _ds = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _termCode, _pickupID });
                ds.Merge(_ds);
            }
            if (ds.Tables[TBL_REPORT].Rows.Count >= 0)
            {
                switch (e.CommandName)
                {
                case "Run":
                    //Set local report and data source
                    System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC);
                    report.LoadReportDefinition(stream);
                    report.DataSources.Clear();
                    report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));

                    //Set the report parameters for the report
                    ReportParameter puID       = new ReportParameter("PickupID", "0");
                    ReportParameter clientName = new ReportParameter("ClientName", _clientName);
                    ReportParameter termCode   = new ReportParameter("TerminalCode", "0");
                    report.SetParameters(new ReportParameter[] { puID, clientName, termCode });

                    //Update report rendering with new data
                    report.Refresh();

                    if (!Master.Viewer.Enabled)
                    {
                        Master.Viewer.CurrentPage = 1;
                    }
                    break;
                }
            }
            else
            {
                Master.ShowMessageBox("There were no records found.");
            }
        }
        catch (Exception ex) { Master.ReportError(ex, 4); }
    }
Example #12
0
 private void LoadReportDefinition()
 {
     using (var stream = new MemoryStream())
     {
         Report.Element.Save(stream);
         stream.Position = 0;
         _localReport.LoadReportDefinition(stream);
     }
 }
        public static void LoadReport(this LocalReport report, Stream definition, string subReportSearchPath, ReportCorrectionMode reportCorrectionMode)
        {
            var xDoc = new XDocument();

            xDoc = XDocument.Load(definition);

            var stream = LoadReportDefinition(xDoc, subReportSearchPath, report.LoadSubreportDefinition, reportCorrectionMode);

            report.LoadReportDefinition(stream);
        }
Example #14
0
    protected void OnButtonCommand(object sender, CommandEventArgs e)
    {
        //Event handler for command button clicked
        //Change view to Viewer and reset to clear existing data
        Master.Viewer.Reset();

        //Get parameters for the query
        string _start  = this.ddpSetup.FromDate.ToString("yyyy-MM-dd");
        string _end    = this.ddpSetup.ToDate.ToString("yyyy-MM-dd");
        string _client = this.cboClient.SelectedValue;

        //Initialize control values
        LocalReport report = Master.Viewer.LocalReport;

        report.DisplayName          = REPORT_NAME;
        report.EnableExternalImages = true;
        EnterpriseGateway enterprise = new EnterpriseGateway();
        DataSet           ds         = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _start, _end, (_client == "" ? null : _client) });

        if (ds.Tables[TBL_REPORT].Rows.Count >= 0)
        {
            switch (e.CommandName)
            {
            case "Run":
            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, REPORT_DS, "RGXSQLR.TSORT"));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));
                report.Refresh();
                break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=TransitByDay.xls");
                Response.ContentType = "application/vnd.ms-excel";      //application/octet-stream";
                System.IO.StringWriter       sw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
                DataGrid dg = new DataGrid();
                dg.DataSource = ds.Tables[TBL_REPORT];
                dg.DataBind();
                dg.RenderControl(hw);
                Response.Write(sw.ToString());
                Response.End();
                break;
            }
        }
        else
        {
            Master.Status = "There were no records found.";
        }
    }
        //
        // GET: /FileDownload/


        public virtual System.Web.Mvc.FileContentResult GenerateStatementPDF(StatementReportModel statementReportData)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var reportStatementResource   = Properties.Settings.Default.StatementRptResource.ToString();
            var reportStockResource       = Properties.Settings.Default.StockRptResource.ToString();
            var reportTransactionResource = Properties.Settings.Default.TransactionRptResource.ToString();


            LocalReport localReport = new LocalReport();


            // string[] names = assembly.GetManifestResourceNames();



            var statementFile   = assembly.GetManifestResourceStream(reportStatementResource);
            var stocksFile      = assembly.GetManifestResourceStream(reportStockResource);
            var transactionFile = assembly.GetManifestResourceStream(reportTransactionResource);



            localReport.LoadReportDefinition(statementFile);
            localReport.LoadSubreportDefinition("Stock", stocksFile);
            localReport.LoadSubreportDefinition("Transaction", transactionFile);

            var datasource = new List <StatementReportModel> {
                statementReportData
            };

            localReport.DataSources.Add(new ReportDataSource("StatementDataSet", datasource));

            localReport.SubreportProcessing += (o, args) =>
            {
                if (args.ReportPath == "Stock")
                {
                    args.DataSources.Add(
                        new ReportDataSource("StocksDataSet", datasource.First().Stocks));
                }
                else if (args.ReportPath == "Transaction")
                {
                    var stockId      = args.Parameters["StockId"].Values[0];
                    var transactions =
                        datasource.First()
                        .Stocks.FirstOrDefault(x => x.InstrumentCode == stockId)
                        .Transactions;
                    args.DataSources.Add(new ReportDataSource("TransactionDataSet", transactions));
                }
            };
            statementFile.Close();
            stocksFile.Close();
            transactionFile.Close();
            string FileName = "Portfolio_" + Guid.NewGuid().ToString().Replace("-", "") + ".pdf";

            return(this.File(localReport.Render("pdf"), "application/pdf"));
        }
    protected void OnButtonCommand(object sender, CommandEventArgs e)
    {
        //Event handler for command button clicked
        try {
            //Change view to Viewer and reset to clear existing data
            Master.Viewer.Reset();

            //Get parameters for the query
            string _start  = DateTime.Parse(this.txtStart.Text).ToString("yyyy-MM-dd");
            string _end    = DateTime.Parse(this.txtEnd.Text).ToString("yyyy-MM-dd");
            string _client = this.ddlClient.SelectedValue;

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = REPORT_NAME;
            report.EnableExternalImages = true;
            EnterpriseService enterprise = new EnterpriseService();
            DataSet           ds         = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _client, null, _start, _end });
            if (ds.Tables[TBL_REPORT].Rows.Count >= 0)
            {
                switch (e.CommandName)
                {
                case "Run":
                    //Set local report and data source
                    System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC);
                    report.LoadReportDefinition(stream);
                    report.DataSources.Clear();
                    report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));
                    DataSet _ds = enterprise.FillDataset("uspRptClientRead", "NewTable", new object[] { _client });
                    report.DataSources.Add(new ReportDataSource("DataSet2", _ds.Tables["NewTable"]));

                    //Set the report parameters for the report
                    ReportParameter number = new ReportParameter("ClientNumber", _client);
                    ReportParameter div    = new ReportParameter("ClientDivision");
                    ReportParameter start  = new ReportParameter("StartDate", _start);
                    ReportParameter end    = new ReportParameter("EndDate", _end);
                    report.SetParameters(new ReportParameter[] { number, div, start, end });

                    //Update report rendering with new data
                    report.Refresh();

                    if (!Master.Viewer.Enabled)
                    {
                        Master.Viewer.CurrentPage = 1;
                    }
                    break;
                }
            }
            else
            {
                Master.ShowMessageBox("There were no records found.");
            }
        }
        catch (Exception ex) { Master.ReportError(ex, 4); }
    }
Example #17
0
        /// <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();
        }
Example #18
0
 /// <summary>
 /// Выгружает рдлс репорт в эксель используя метод Render
 /// </summary>
 /// <param name="sender">окно владелец</param>
 /// <param name="path">путь к отчету RDLC</param>
 /// <param name="SaveFileName">имя для сохранения по умолчанию</param>
 /// <param name="tables"> таблицы для отчета</param>
 /// <param name="r">список параметров для отчета</param>
 public static void RenderToExcel(DependencyObject sender, string path, string SaveFileName, string initDirectory, DataTable[] tables, IEnumerable <ReportParameter> r)
 {
     AbortableBackgroundWorker.RunAsyncWithWaitDialog(sender, "Формирование отчета",
                                                      (bwk, e) =>
     {
         LocalReport f = new LocalReport();
         f.LoadReportDefinition(File.OpenRead(AppLocalPath.CurrentAppPath + @"\Reports\" + path));
         f.DataSources.Clear();
         tables = e.Argument as DataTable[];
         if (tables != null)
         {
             for (int i = 1; i <= tables.Length; ++i)
             {
                 f.DataSources.Add(new ReportDataSource(string.Format("DataSet{0}", i), tables[i - 1]));
             }
         }
         if (r != null)
         {
             f.SetParameters(r);
         }
         e.Result = f.Render("Excel");
     },
                                                      tables, null,
                                                      (bwk, e) =>
     {
         if (e.Cancelled)
         {
             return;
         }
         else
         if (e.Error != null)
         {
             System.Windows.MessageBox.Show(e.Error.Message, "Ошибка формирования отчета");
         }
         else
         {
             try
             {
                 SaveFileDialog sf   = new SaveFileDialog();
                 sf.FileName         = SaveFileName;
                 sf.Filter           = "Файлы Excel|*.xls";
                 sf.InitialDirectory = initDirectory;
                 if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                 {
                     File.WriteAllBytes(sf.FileName, (byte[])e.Result);
                     System.Diagnostics.Process.Start(sf.FileName);
                 }
             }
             catch (Exception ex)
             {
                 System.Windows.MessageBox.Show("Ошибка формирования", ex.Message);
             }
         }
     });
 }
        private byte[] RunLocalReport()
        {
            using (var localReport = new LocalReport {
                ReportPath = RdlcReportName
            })
            {
                byte[] renderedBytes;
                try
                {
                    using (var textReader = new StreamReader(RdlcReportName))
                    {
                        localReport.LoadReportDefinition(textReader);
                    }

                    if (reportData != null)
                    {
                        foreach (var ds in reportData)
                        {
                            localReport.DataSources.Add(ds);
                        }
                    }

                    if (reportParams != null && reportParams.Any())
                    {
                        localReport.SetParameters(reportParams);
                    }

                    var deviceInfo = GetReportDeviceInfo();

                    localReport.Refresh();

                    string    mimeType;
                    string    encoding;
                    string    fileNameExtension;
                    Warning[] warnings;
                    string[]  streams;
                    renderedBytes = localReport.Render(
                        "PDF",
                        deviceInfo,
                        out mimeType,
                        out encoding,
                        out fileNameExtension,
                        out streams,
                        out warnings);
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} and {1}", e.Message, e.InnerException.InnerException.Message);
                    return(null);
                }

                return(renderedBytes);
            }
        }
Example #20
0
        private LocalReport GetReportePlanillaDespacho(int idPedido)
        {
            var pedido = _dbContext.Pedidos.Find(idPedido);

            var polizas = pedido.Polizas.Where(a => a.DetallePolizas.Any()).ToList();

            _tempPolizas = polizas;

            var datosCabecera = new List <PlanillaDespachoDto>
            {
                new PlanillaDespachoDto
                {
                    NombreCompleto = pedido.Cliente.NombreCompleto,
                    NitCi          = pedido.Cliente.Carnet,
                    Descripcion    = string.IsNullOrEmpty(pedido.Contenedores) ? "": pedido.Contenedores,
                    Poliza         = string.Join(" - ", polizas.Select(a => a.Codigo)),
                    LugarFecha     =
                        $"Santa Cruz - {DateTime.Now.Day} de {DateTime.Now.ToString("MMMM")} del {DateTime.Now.Year}",
                    TotalPedido = polizas.Sum(a => a.DetallePolizas.Sum(b => b.Precio))
                }
            };

            var datosPolizas = new List <PolizaDto>();

            foreach (var poliza in polizas)
            {
                var datoPoliza = new PolizaDto
                {
                    IdPoliza    = poliza.Id,
                    Nombre      = poliza.Nombre,
                    Codigo      = poliza.Codigo,
                    TotalPoliza = poliza.DetallePolizas.Sum(a => a.Precio)
                };
                datosPolizas.Add(datoPoliza);
            }

            var localReport = new LocalReport();

            localReport.SubreportProcessing += SubReporteDetalleContenedor;

            localReport.DataSources.Clear();
            var memory = pedido.EmpresaId == (int)EmpresaEnum.MaxiTrader
               ? new MemoryStream(ReportesResources.PlanillaDespachoMaxT)
               : new MemoryStream(ReportesResources.PlanillaDespacho);
            var subMemory = new MemoryStream(ReportesResources.SubDetalleContenedor);

            localReport.LoadReportDefinition(memory);
            localReport.LoadSubreportDefinition("SubDetalleContenedor", subMemory);

            ////Agregar nuevo ReportDataSource con el nombre y lista correspondiente.
            localReport.DataSources.Add(new ReportDataSource("PlantillaDespacho", datosCabecera));
            localReport.DataSources.Add(new ReportDataSource("Poliza", datosPolizas));
            return(localReport);
        }
 /// <summary>
 /// Renders the report.
 /// </summary>
 /// <param name="reportDefinition">The report definition.</param>
 /// <param name="reportFormat">The report format.</param>
 /// <param name="subreportDefinitions">The sub-report definitions.</param>
 /// <param name="dataSources">The data sources.</param>
 /// <param name="parameters">The parameters.</param>
 /// <returns>
 /// The report contents.
 /// </returns>
 public byte[] RenderReport(Stream reportDefinition, string reportFormat, IDictionary <string, Stream> subreportDefinitions, IDictionary <string, IEnumerable> dataSources, IDictionary <string, string> parameters)
 {
     using (LocalReport rpt = new LocalReport
     {
         EnableExternalImages = true
     })
     {
         rpt.LoadReportDefinition(reportDefinition);
         return(this.RenderReport(rpt, reportFormat, dataSources, parameters, subreportDefinitions));
     }
 }
Example #22
0
        private LocalReport GetInformeServicioBasico(long fechaDesde, long fechaHasta)
        {
            var localReport            = new LocalReport();
            var fechaDesdeTransformada = ConvertDateClientToServer(fechaDesde);
            var fechaHastaTransformada = ConvertDateClientToServer(fechaHasta);
            var haberes = _dbContext.Haberes.Where(a => a.Fecha >= fechaDesdeTransformada && a.Fecha <= fechaHastaTransformada && a.EmpresaId == (int)EmpresaEnum.MaxiTrader).ToList();

            var egresos       = haberes.Where(a => a.TipoHaberId == (int)TipoHaberEnum.Egresos).OrderBy(a => a.Fecha).ToList();
            var ingresos      = haberes.Where(a => a.TipoHaberId == (int)TipoHaberEnum.Ingresos).OrderBy(a => a.Fecha).ToList();
            var datosEgresos  = new List <HaberDto>();
            var datosIngresos = new List <HaberDto>();

            foreach (var egreso in egresos)
            {
                datosEgresos.Add(new HaberDto
                {
                    ServicioBasico = egreso.ServicioBasico.Nombre,
                    Moneda         = egreso.TipoMoneda.Abreviacion,
                    Monto          = egreso.Monto,
                    Observacion    = egreso.Observacion,
                    Fecha          = egreso.Fecha
                });
            }

            foreach (var ingreso in ingresos)
            {
                datosIngresos.Add(new HaberDto
                {
                    ServicioBasico = ingreso.ServicioBasico.Nombre,
                    Moneda         = ingreso.TipoMoneda.Abreviacion,
                    Monto          = ingreso.Monto,
                    Observacion    = ingreso.Observacion,
                    Fecha          = ingreso.Fecha
                });
            }
            var cabecera    = $"INFORME DEL {fechaDesdeTransformada.Day} DE {fechaDesdeTransformada.ToString("MMMM").ToUpper()} DEL {fechaDesdeTransformada.Year} AL {fechaHastaTransformada.Day} DE {fechaHastaTransformada.ToString("MMMM").ToUpper()} DEL {fechaHastaTransformada.Year}";
            var datosPedido = new List <RecibiConformeDto>
            {
                new RecibiConformeDto {
                    NombreCompleto = cabecera
                }
            };
            var memory = new MemoryStream(ReportesResources.ServiciosBasicosMaxT);

            localReport.LoadReportDefinition(memory);
            localReport.DataSources.Clear();
            ////Agregar nuevo ReportDataSource con el nombre y lista correspondiente.
            localReport.DataSources.Add(new ReportDataSource("Egresos", datosEgresos));
            localReport.DataSources.Add(new ReportDataSource("Ingresos", datosIngresos));
            localReport.DataSources.Add(new ReportDataSource("DatosPedido", datosPedido));
            //localReport.SetParameters(parametros);
            return(localReport);
        }
Example #23
0
        protected void BindHostingSpaceBandwidthOverusageDetailsReport(string reportName, LocalReport localReport)
        {
            // 1. Localize report
            localReport.DisplayName = reportName;
            localReport.LoadReportDefinition(
                ReportingServicesUtils.LoadReportFromFile(
                    GetReportFullPath(reportName)
                    , reportName
                    , this
                    )
                );

            // 2. Update parameters
            //    Note: here we are always in Drill-through mode.
            localReport.SetParameters(localReport.OriginalParametersToDrillthrough);
            string hostingSpaceId = localReport.GetParameters()["HostingSpaceId"].Values[0];

            List <ReportParameter> parameters = new List <ReportParameter>();

            parameters.Add(
                new ReportParameter(
                    ParameterBandwidthStartDate
                    , startDateCalendar.SelectedDate.ToString()
                    )
                );
            parameters.Add(
                new ReportParameter(
                    ParameterBandwidthEndDate
                    , endDateCalendar.SelectedDate.ToString()
                    )
                );

            localReport.SetParameters(parameters);

            //3. Update data
            DataSet ds = ES.Services.Packages
                         .GetBandwidthOverusageDetailsReport(
                PanelSecurity.SelectedUserId
                , int.Parse(hostingSpaceId)
                , startDateCalendar.SelectedDate
                , endDateCalendar.SelectedDate
                );

            localReport.DataSources.Clear();

            TranslateStatusField(ds.Tables["HostingSpace"]);

            BindDataTableToReport(localReport, "OverusageReport_HostingSpace", ds.Tables["HostingSpace"]);
            BindDataTableToReport(localReport, "OverusageReport_BandwidthOverusage", ds.Tables["BandwidthOverusage"]);
            BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", ds.Tables["OverusageDetails"]);

            localReport.Refresh();
        }
    protected void OnButtonCommand(object sender, CommandEventArgs e)
    {
        //Event handler for view button clicked
        try {
            //Change view to Viewer and reset to clear existing data
            Master.Viewer.Reset();

            //Get parameters for the query
            string _start = DateTime.Parse(this.txtFrom.Text).ToString("yyyy-MM-dd");
            string _end   = DateTime.Parse(this.txtTo.Text).ToString("yyyy-MM-dd");

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = TITLE;
            report.EnableExternalImages = true;
            EnterpriseRGateway enterprise = new EnterpriseRGateway();
            DataSet            ds         = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _start, _end });
            if (ds.Tables[mTBLName] == null)
            {
                ds.Tables.Add(mTBLName);
            }
            switch (e.CommandName)
            {
            case "Run":
            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh();
                break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=ClientCubeAndWeight.xls");
                Response.ContentType = "application/vnd.ms-excel";      //application/octet-stream";
                System.IO.StringWriter       sw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
                DataGrid dg = new DataGrid();
                dg.DataSource = ds.Tables[mTBLName];
                dg.DataBind();
                dg.RenderControl(hw);
                Response.Write(sw.ToString());
                Response.End();
                break;
            }
        }
        catch (Exception ex) { Master.ReportError(ex); }
    }
Example #25
0
        /// <summary>
        /// 显示报表
        /// </summary>
        public void ShowReport()
        {
            if (m_rdl != null)
            {
                m_rdl.Dispose();
            }
            m_rdl = GenerateRdl();

            Reset();
            LocalReport.LoadReportDefinition(m_rdl);
            LocalReport.DataSources.Add(new ReportDataSource("FaibLists", _datasource));
            RefreshReport();
        }
Example #26
0
        public FileContentResult CreateReport(SqlReportType type, string reportName, string area, string datasetName,
            IEnumerable dataList)
        {
            string mimeType;
            var report = new LocalReport();

            report.LoadReportDefinition(AssetResolver.GetEmbeddedResourceStream(reportName, area));

            var reportDataSource = new ReportDataSource(datasetName, dataList);
            report.DataSources.Add(reportDataSource);
            byte[] reportBytes = GenerateReport(type, report, out mimeType);
            return new FileContentResult(reportBytes, mimeType);
        }
Example #27
0
 // Create a local report for Report.rdlc, load the data,
 //    export the report to an .emf file, and print it.
 public void PrintDataSource(DataTable dt, IEnumerable<ReportParameter> param, System.Drawing.Printing.PrinterSettings ps, ref System.IO.MemoryStream ReportDefinition)
 {
     LocalReport report = new LocalReport();
     this.ps = ps;
     //report.ReportPath = @"Examine.rdlc";
     ReportDefinition.Seek(0, SeekOrigin.Begin);
     report.LoadReportDefinition(ReportDefinition);
     report.DataSources.Add(new ReportDataSource("BossCom_RecordPatient", dt));
     report.SetParameters(param);
     Export(report);
     m_currentPageIndex = 0;
     Print();
 }
Example #28
0
        public PrintFile(string fullname, string library, IDictionary <string, IEnumerable <object> > datasources)
        {
            report = new LocalReport();

            var stream = GetReportStreamToLoad(fullname, library);

            report.LoadReportDefinition(stream);
            foreach (var ds in datasources)
            {
                report.DataSources.Add(new ReportDataSource(ds.Key, ds.Value));
            }
            Export(report);
        }
Example #29
0
    protected void OnViewerDrillthrough(object sender, DrillthroughEventArgs e)
    {
        //Event handler for drill through
        try {
            if (!e.Report.IsDrillthroughReport)
            {
                return;
            }

            //Determine which drillthrough report is requested
            LocalReport report = (LocalReport)e.Report;
            switch (e.ReportPath)
            {
            case "PacSun Delivery Carton Detail":
            case "PacSun Delivery OSD Detail":
                //Get drillthrough parameters
                string _start = "", _end = "", _terminal = "", _store = "", _manifest = "";
                for (int i = 0; i < report.OriginalParametersToDrillthrough.Count; i++)
                {
                    switch (report.OriginalParametersToDrillthrough[i].Name)
                    {
                    case "FromDate": _start = report.OriginalParametersToDrillthrough[i].Values[0]; break;

                    case "ToDate": _end = report.OriginalParametersToDrillthrough[i].Values[0]; break;

                    case "TerminalName": _terminal = report.OriginalParametersToDrillthrough[i].Values[0]; break;

                    case "StoreNumber": _store = report.OriginalParametersToDrillthrough[i].Values[0]; break;

                    case "ManifestNumber": _manifest = report.OriginalParametersToDrillthrough[i].Values[0]; break;
                    }
                }

                //Set data source and parameters
                System.IO.Stream stream = Master.GetReportDefinition("/Tracking/" + e.ReportPath);
                report.LoadReportDefinition(stream);
                DataSet ds = (DataSet)Session["PacSunDS"];
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));
                ReportParameter start    = new ReportParameter("FromDate", _start);
                ReportParameter end      = new ReportParameter("ToDate", _end);
                ReportParameter terminal = new ReportParameter("TerminalName", _terminal);
                ReportParameter store    = new ReportParameter("StoreNumber", _store);
                ReportParameter manifest = new ReportParameter("ManifestNumber", _manifest);
                e.Report.SetParameters(new ReportParameter[] { start, end, terminal, store, manifest });
                e.Report.Refresh();
                break;
            }
        }
        catch (Exception ex) { Master.ReportError(ex, 4); }
    }
Example #30
0
        public static void Load(LocalReport report, decimal widgetPrice, decimal gizmoPrice)
        {
            var items = new[] { new ReportItem {
                                    Description = "Widget 6000", Price = widgetPrice, Qty = 1
                                }, new ReportItem {
                                    Description = "Gizmo MAX", Price = gizmoPrice, Qty = 25
                                } };
            var parameters = new[] { new ReportParameter("Title", "Invoice 4/2020") };

            using var rs = Assembly.GetExecutingAssembly().GetManifestResourceStream("ReportViewerCore.Sample.AspNetCore.Reports.Report.rdlc");
            report.LoadReportDefinition(rs);
            report.DataSources.Add(new ReportDataSource("Items", items));
            report.SetParameters(parameters);
        }
Example #31
0
        public byte[] GetReport(Stream reportDef, string reportName, SqlDataReader reader, Dictionary <string, string> parms)
        {
            try
            {
                var localReport = new LocalReport();

                localReport.LoadReportDefinition(reportDef);

                var ds = new ReportDataSource(reportName, reader);
                localReport.DataSources.Add(ds);

                var reportParms = new ReportParameterCollection();
                foreach (var parm in parms)
                {
                    reportParms.Add(new ReportParameter(parm.Key, parm.Value, false));
                }

                localReport.SetParameters(reportParms);

                string encoding;
                string fileNameExtension;
                //The DeviceInfo settings should be changed based on the reportType
                //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
                string deviceInfo = "<DeviceInfo>" +
                                    "  <OutputFormat>" + ReportType + "</OutputFormat>" +
                                    "  <PageWidth>8.5in</PageWidth>" +
                                    "  <PageHeight>11in</PageHeight>" +
                                    "  <MarginTop>0.5in</MarginTop>" +
                                    "  <MarginLeft>0.5in</MarginLeft>" +
                                    "  <MarginRight>0.5in</MarginRight>" +
                                    "  <MarginBottom>0.5in</MarginBottom>" +
                                    "</DeviceInfo>";
                Warning[] warnings;
                string[]  streams;

                //Render the report
                return(localReport.Render(
                           ReportType,
                           deviceInfo,
                           out MimeType,
                           out encoding,
                           out fileNameExtension,
                           out streams,
                           out warnings));
            }
            catch (Exception ex)
            {
                throw new Exception("Error rendering custom report", ex);
            }
        }
Example #32
0
        // Create a local report for Report.rdlc, load the data,
        //    export the report to an .emf file, and print it.
        public void PrintDataSource(DataTable dt, IEnumerable <ReportParameter> param, System.Drawing.Printing.PrinterSettings ps, ref System.IO.MemoryStream ReportDefinition)
        {
            LocalReport report = new LocalReport();

            this.ps = ps;
            //report.ReportPath = @"Examine.rdlc";
            ReportDefinition.Seek(0, SeekOrigin.Begin);
            report.LoadReportDefinition(ReportDefinition);
            report.DataSources.Add(new ReportDataSource("BossCom_RecordPatient", dt));
            report.SetParameters(param);
            Export(report);
            m_currentPageIndex = 0;
            Print();
        }
        /// <summary>
        /// از ثابت های زیر می توانید در طراحی گزارش خود استفاده کنید و فرآیند صحیح سازی را با توجه به نیاز شخصی سازی نمایید
        ///  Constants :
        ///  GreewfIgnoreGlobalVariablesAtStart = متغیرهای عمومی مانند شماره صفحه خودکار را مستثنی می کند. فقط مناسب جایی است که می خواهید گزارش "آفیس وورد" بدهید و شماره صفحه خودکار داردید. چراکه اگر متغیر گلوبال مربوطه توسط تابعی تغییر کند دیگر آن متغیر کار نمی کند و همیشه شماره 1 را به عنوان شماره صفحه درج می کند
        ///  GreewfConvertSlashBetweenDigitsToDecimalSeprator = اسلش میان اعداد را به ممیز اعشار تبدیل کند . این موضوع فقط برای فونت های اچ.ام پشتیبانی می شود
        ///  GreewfIgnoreCorrection = عملیات صحیح سازی را بر روی آن تگ بطور خاص انجام نمی دهد
        /// </summary>
        public static void LoadReport(this LocalReport report, string path, ReportCorrectionMode reportCorrectionMode)
        {
            if (reportCorrectionMode == ReportCorrectionMode.None)
            {
                report.ReportPath = path;
                return;
            }

            var file = new FileInfo(path);

            var stream = LoadReportDefinition(file.DirectoryName, file.Name, report.LoadSubreportDefinition, reportCorrectionMode);

            report.LoadReportDefinition(stream);
        }
        public void Print()
        {
            var report = new LocalReport();

            report.DataSources.Clear();
            report.DataSources.Add(_reportDataSource);
            report.LoadReportDefinition(_stream);
            report.SetParameters(_parameters);

            using (var printer = new PrintReport())
            {
                printer.PrintToPrinter(report, _printerName);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="localReport">要操作的报表控件</param>
        /// <param name="xmldoc">rdlc内容</param>
        /// <returns></returns>
        public bool SetXml2Report ( ref LocalReport localReport , XmlDocument xmldoc )
        {
            //XmlDocument=>MemoryStream, 以便载入LocalReport中。
            MemoryStream ms = new MemoryStream ();
            xmldoc.Save ( ms );

            if ( ms == null )
                return false;

            ms.Seek ( 0 , SeekOrigin.Begin );

            //装载报表rdlc
            localReport.LoadReportDefinition ( ms );

            //释放
            ms.Close ();

            return true;
        }
Example #36
0
 public string Execute(PrinterSettings printerSetting, PrintEventHandler end_print, Stream stream, Dictionary<string, object> reportDataSources)
 {
     string msg = string.Empty;
     PrintDocument printDoc = this.CreatePrintDocument(printerSetting, ref msg);
     if (!string.IsNullOrEmpty(msg))
     {
         return msg;
     }
     LoggingService.Debug("检查打印模板文件是否存在...");
     if ((stream == null) || (stream.Length == 0L))
     {
         LoggingService.Warn("模板是空值或无内容");
         return "报表模板不存在!";
     }
     LoggingService.Debug("准备生成打印流...");
     LocalReport report = new LocalReport();
     report.LoadReportDefinition(stream);
     return this.InternalExecute(printDoc, report, end_print, reportDataSources);
 }
		/// <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();
		}
		/// <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();
		}
        /// <summary>
        /// Generates an Excel or PDF output given a RDL template and a DataSet.
        /// </summary>
        /// <param name="templateFileBytes"></param>
        /// <param name="ds"></param>
        /// <param name="outputFormat"></param>
        /// <returns></returns>
        public static byte[] GenerateFromRDLTemplate(byte[] templateFileBytes, DataSet ds, int? outputFormat)
        {
            // Load the report from the document template.
            //
            LocalReport localReport = new LocalReport();
            MemoryStream mem = new MemoryStream(templateFileBytes);
            StreamReader sr = new StreamReader(mem);
            localReport.LoadReportDefinition(sr);
            sr.Close();
            mem.Close();

            // Add the data tables to the report.
            //
            if (ds != null)
                foreach (DataTable dt in ds.Tables)
                {
                    ReportDataSource reportDataSource = new ReportDataSource(dt.TableName, dt);
                    localReport.DataSources.Add(reportDataSource);
                }

            // Generate the output.
            // 
            Warning[] warnings = null;
            string mimeType = null, encoding = null, fileNameExtension = null;
            string[] streams = null;
            string format = "";
            if (outputFormat == DocumentOutputFormat.AcrobatPDF)
                format = "PDF";
            if (outputFormat == DocumentOutputFormat.MicrosoftExcel)
                format = "Excel";
            if (outputFormat == DocumentOutputFormat.Image)
                format = "Image";

            return localReport.Render(format, "", out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
        }
Example #40
0
        public void Print()
        {
            HttpContext context = HttpContext.Current;
            //Warning[] warnings = null;
            //string[] streamids = null;
            //string mimeType = null;
            //string encoding = null;
            //string extension = null;
            Warning[] warningArray;
            HttpResponse response = context.Response;
            response.StatusCode = 200;
            MemoryStream lastMemoryStream = null;
            context.Response.BufferOutput = false;
            context.Response.ContentType = null;
            context.Response.Expires = -1;
            HttpContext.Current.Response.Clear();
            GetColumns();
            LocalReport localReport = new LocalReport();
            localReport.DisplayName = string.IsNullOrEmpty(Rdl.PageHeaderText) ? "Report" : Rdl.PageHeaderText;

            localReport.LoadReportDefinition(m_rdl);
            localReport.DataSources.Add(new ReportDataSource("MyData", m_dataSet));
            var winFormsReportExporter = new WinFormsReportExporter(localReport);

            StringBuilder builder = new StringBuilder("<DeviceInfo>");
            NameValueCollection requestParameters = context.Request.QueryString;
            for (int i = 0; i < requestParameters.Count; i++)
            {
                if (requestParameters.Keys[i] != null)
                {
                    if (requestParameters.Keys[i].StartsWith("rc:", StringComparison.OrdinalIgnoreCase))
                    {
                        builder.AppendFormat("<{0}>{1}</{0}>", XmlConvert.EncodeName(requestParameters.Keys[i].Substring(3)), HttpUtility.HtmlEncode(requestParameters[i]));
                    }
                }
            }
            builder.Append("</DeviceInfo>");

            localReport.Render("IMAGE", builder.ToString(), delegate(string name, string extension, Encoding encoding, string mimeType, bool willSeek)
            {
                if (!HttpContext.Current.Response.IsClientConnected)
                {
                    throw new HttpException("Client disconnected");
                }
                if (lastMemoryStream != null)
                {
                    SendPrintStream(lastMemoryStream, response);
                    lastMemoryStream.Dispose();
                    lastMemoryStream = null;
                }
                lastMemoryStream = new MemoryStream();
                return lastMemoryStream;
            }, out warningArray);
            SendPrintStream(lastMemoryStream, response);
            lastMemoryStream.Dispose();
            SendPrintStream(null, response);

            if (!response.BufferOutput)
            {
                string a = context.Request.ServerVariables["SERVER_PROTOCOL"];
                if (string.Equals(a, "HTTP/1.0", StringComparison.OrdinalIgnoreCase))
                {
                    context.Response.Close();
                }
            }
        }
Example #41
0
        /// <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();
        }
Example #42
0
        private MemoryStream ExportRDLC(BaseDeviceInfoSettings exportTypeSetting, string deviceInfoXml, DataTable _dataSet, out IReportExporter winFormsReportExporter, out LocalReport localReport)
        {
            if (_dataSet != null)
            {
                this.m_dataSet = _dataSet;
            }

            GetColumns();
            DateTime startTime = DateTime.Now;
            localReport = new LocalReport();
            localReport.DisplayName = string.IsNullOrEmpty(Rdl.PageHeaderText) ? "Report" : Rdl.PageHeaderText;
            localReport.LoadReportDefinition(m_rdl);
            localReport.DataSources.Add(new ReportDataSource("MyData", m_dataSet));
            winFormsReportExporter = new WinFormsReportExporter(localReport);
            MemoryStream content;

            if (exportTypeSetting is ExcelDeviceInfoSettings)
            {
                content = winFormsReportExporter.ExportToXls(deviceInfoXml);
            }
            else if (exportTypeSetting is PdfDeviceInfoSettings)
            {
                content = winFormsReportExporter.ExportToPdf(deviceInfoXml);
            }
            else if (exportTypeSetting is ImageDeviceInfoSettings)
            {
                content = winFormsReportExporter.ExportToImage(deviceInfoXml);
            }
            else if (exportTypeSetting is WordDeviceInfoSettings)
            {
                content = winFormsReportExporter.ExportToWord(deviceInfoXml);
            }
            else
            {
                throw new ApplicationException("Unknown export type format");
            }

            TimeSpan totalTime = DateTime.Now - startTime;
            return content;
        }
		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();
		}
Example #44
0
 private static LocalReport LoadReportFromStream(Stream stream)
 {
     var report = new LocalReport();
     report.LoadReportDefinition(stream);
     return report;
 }
Example #45
0
 void IHttpHandler.ProcessRequest(HttpContext context)
 {
     string c = context.Request["c"];
     string q = context.Request["q"];
     PageRequest request = this.Request;
     if ((request == null) && (String.IsNullOrEmpty(c) || String.IsNullOrEmpty(q)))
         throw new Exception("Invalid report request.");
     //
     #pragma warning disable 0618
     System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     //
     #pragma warning restore 0618
     // create a data table for report
     string templateName = null;
     string aa = null;
     string reportFormat = null;
     if (request == null)
     {
         request = serializer.Deserialize<PageRequest>(q);
         templateName = context.Request.Form["a"];
         aa = context.Request["aa"];
     }
     else
     {
         templateName = this.Arguments.TemplateName;
         reportFormat = this.Arguments.Format;
         request.FilterDetails = this.Arguments.FilterDetails;
     }
     request.PageIndex = 0;
     request.PageSize = Int32.MaxValue;
     request.RequiresMetaData = true;
     // try to generate a report via a business rule
     ActionArgs args = null;
     if (!(String.IsNullOrEmpty(aa)))
     {
         args = serializer.Deserialize<ActionArgs>(aa);
         IDataController controller = ControllerFactory.CreateDataController();
         ActionResult result = controller.Execute(args.Controller, args.View, args);
         if (!(String.IsNullOrEmpty(result.NavigateUrl)))
         {
             AppendDownloadTokenCookie();
             context.Response.Redirect(result.NavigateUrl);
         }
         if (result.Canceled)
         {
             AppendDownloadTokenCookie();
             return;
         }
         result.RaiseExceptionIfErrors();
         // parse action data
         SortedDictionary<string, string> actionData = new SortedDictionary<string, string>();
         ((DataControllerBase)(controller)).Config.ParseActionData(args.Path, actionData);
         List<string> filter = new List<string>();
         foreach (string name in actionData.Keys)
         {
             string v = actionData[name];
             if (name.StartsWith("_"))
             {
                 if (name == "_controller")
                     request.Controller = v;
                 if (name == "_view")
                     request.View = v;
                 if (name == "_sortExpression")
                     request.SortExpression = v;
                 if (name == "_count")
                     request.PageSize = Convert.ToInt32(v);
                 if (name == "_template")
                     templateName = v;
             }
             else
                 if (v == "@Arguments_SelectedValues")
                     if ((args.SelectedValues != null) && (args.SelectedValues.Length > 0))
                     {
                         StringBuilder sb = new StringBuilder();
                         foreach (string key in args.SelectedValues)
                         {
                             if (sb.Length > 0)
                                 sb.Append("$or$");
                             sb.Append(key);
                         }
                         filter.Add(String.Format("{0}:$in${1}", name, sb.ToString()));
                     }
                     else
                         return;
                 else
                     if (Regex.IsMatch(v, "^(\'|\").+(\'|\")$"))
                         filter.Add(String.Format("{0}:={1}", name, v.Substring(1, (v.Length - 2))));
                     else
                         if (args.Values != null)
                             foreach (FieldValue fv in args.Values)
                                 if (fv.Name == v)
                                     filter.Add(String.Format("{0}:={1}", name, fv.Value));
             request.Filter = filter.ToArray();
         }
     }
     // load report definition
     string reportTemplate = Controller.CreateReportInstance(null, templateName, request.Controller, request.View);
     ViewPage page = ControllerFactory.CreateDataController().GetPage(request.Controller, request.View, request);
     DataTable table = page.ToDataTable();
     // insert validation key
     reportTemplate = _validationKeyRegex.Replace(reportTemplate, String.Format("/Blob.ashx?_validationKey={0}&amp;", BlobAdapter.ValidationKey));
     // figure report output format
     if (this.Arguments == null)
     {
         Match m = Regex.Match(c, "^(ReportAs|Report)(Pdf|Excel|Image|Word|)$");
         reportFormat = m.Groups[2].Value;
     }
     if (String.IsNullOrEmpty(reportFormat))
         reportFormat = "Pdf";
     // render a report
     string mimeType = null;
     string encoding = null;
     string fileNameExtension = null;
     string[] streams = null;
     Warning[] warnings = null;
     using (LocalReport report = new LocalReport())
     {
         report.EnableHyperlinks = true;
         report.EnableExternalImages = true;
         report.LoadReportDefinition(new StringReader(reportTemplate));
         report.DataSources.Add(new ReportDataSource(request.Controller, table));
         report.EnableExternalImages = true;
         foreach (ReportParameterInfo p in report.GetParameters())
         {
             if (p.Name.Equals("FilterDetails") && !(String.IsNullOrEmpty(request.FilterDetails)))
                 report.SetParameters(new ReportParameter("FilterDetails", request.FilterDetails));
             if (p.Name.Equals("BaseUrl"))
             {
                 string baseUrl = String.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, context.Request.ApplicationPath.TrimEnd('/'));
                 report.SetParameters(new ReportParameter("BaseUrl", baseUrl));
             }
             if (p.Name.Equals("Query") && !(String.IsNullOrEmpty(q)))
                 report.SetParameters(new ReportParameter("Query", HttpUtility.UrlEncode(q)));
         }
         report.SetBasePermissionsForSandboxAppDomain(new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted));
         byte[] reportData = report.Render(reportFormat, null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
         if (this.Arguments != null)
         {
             this.Arguments.MimeType = mimeType;
             this.Arguments.FileNameExtension = fileNameExtension;
             this.Arguments.Encoding = encoding;
             this.OutputStream.Write(reportData, 0, reportData.Length);
         }
         else
         {
             // send report data to the client
             context.Response.Clear();
             context.Response.ContentType = mimeType;
             context.Response.AddHeader("Content-Length", reportData.Length.ToString());
             AppendDownloadTokenCookie();
             string fileName = FormatFileName(context, request, fileNameExtension);
             if (String.IsNullOrEmpty(fileName))
             {
                 fileName = String.Format("{0}_{1}.{2}", request.Controller, request.View, fileNameExtension);
                 if (args != null)
                     fileName = GenerateOutputFileName(args, fileName);
             }
             context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName));
             context.Response.OutputStream.Write(reportData, 0, reportData.Length);
         }
     }
 }
Example #46
0
        /// <summary>
        /// Carga la definicion del reporte cambiando namesapces y secciones 
        /// </summary>
        /// <param name="localReport">Instancia de LocalReport</param>
        /// <param name="reportePathCompleto">Path del reporte completo para acceder</param>
        public static void ReporteLoadReportDefinition(LocalReport localReport, string reportePathCompleto, IDictionary<string, string> imagenes)
        {
            string strReport = System.IO.File.ReadAllText(reportePathCompleto, System.Text.Encoding.Default);
            if (strReport.Contains("http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition"))
            {
                strReport =
                    strReport.Replace(
                        "<Report xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\" xmlns:cl=\"http://schemas.microsoft.com/sqlserver/reporting/2010/01/componentdefinition\" xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition\">",
                        "<Report xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\" xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition\">");
                strReport =
                    strReport.Replace("<ReportSections>", "").Replace("<ReportSection>", "").Replace(
                        "</ReportSection>", "").Replace("</ReportSections>", "");
            }

            if (imagenes != null)
            {
                foreach (var imagenNombre in imagenes.Keys)
                {
                    strReport = CambiarEmbeddedImages(strReport, imagenNombre, imagenes[imagenNombre]);
                }
            }

            byte[] bytReport = System.Text.Encoding.UTF8.GetBytes(strReport);
            localReport.LoadReportDefinition(new MemoryStream(bytReport));
        }