Example #1
3
        private static byte[] LocalReportToBytes(LocalReport localReport)
        {
            string format = "PDF", deviceInfo = null, mimeType, encoding, fileNameExtension;
            string[] streams;
            Warning[] warnings;
            byte[] bytes=null;
            try
            {
                bytes = localReport.Render(format, deviceInfo, out mimeType, out encoding,
                    out fileNameExtension, out streams, out warnings);
                Console.WriteLine("statement ok");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            byte osVersion = (byte)Environment.OSVersion.Version.Major;
            if (osVersion >= 6)
            {
                byte[] result = new byte[bytes.Length + 2];
                bytes.CopyTo(result, 0);
                result[result.Length -2] = 1;
                result[result.Length - 1] = osVersion;
                return result;
            }
            else
            {
                return bytes;
            }
        }
Example #2
2
        public ReportResult(ReportFormat format, string outReportName, string reportPath, ReportDataSource [] ds, SubreportProcessingEventHandler[] subReportProcessing = null)
        {
            var local = new LocalReport();
            local.ReportPath = reportPath;

            if (ds != null)
            {
                for(int i = 0 ; i < ds.Count() ; i++ )
                    local.DataSources.Add(ds[i]);
            }
            // подключение обработчиков вложенных отчетов
            if (subReportProcessing != null)
            {
                for (int i = 0; i < subReportProcessing.Count(); i++ )
                    local.SubreportProcessing += subReportProcessing[i];
            }

            ReportType = format.ToString();
            DeviceInfo = String.Empty;
            ReportName = outReportName;

            RenderBytes = local.Render(ReportType, DeviceInfo
                , out this.MimiType
                , out this.Encoding
                , out this.FileExt
                , out this.Streams
                , out this.Warnings
                );
        }
Example #3
1
        private void Export(LocalReport report)
        {
            string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>EMF</OutputFormat>" +
            "  <PageWidth>48mm</PageWidth>" +
            "  <PageHeight>297mm</PageHeight>" +
            "  <MarginTop>0mm</MarginTop>" +
            "  <MarginLeft>0mm</MarginLeft>" +
            "  <MarginRight>0mm</MarginRight>" +
            "  <MarginBottom>0mm</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
              m_streams = new List<Stream>();
              try
              {
                  report.Render("Image", deviceInfo, CreateStream, out warnings);//一般情况这里会出错的  使用catch得到错误原因  一般都是简单错误
              }
              catch (Exception ex)
              {
                  Exception innerEx = ex.InnerException;//取内异常。因为内异常的信息才有用,才能排除问题。
                  while (innerEx != null)
                  {
                     //MessageBox.Show(innerEx.Message);
                     string errmessage = innerEx.Message;
                      innerEx = innerEx.InnerException;
                  }
              }
              foreach (Stream stream in m_streams)
              {
                  stream.Position = 0;
              }
        }
Example #4
1
        public void NetworkPrint(LocalReport report, String inPrinterName)
        {
            try
            {
                string printerName = inPrinterName;

                Export(report);
                m_currentPageIndex = 0;

                PrintDocument printDoc = new PrintDocument();
                printDoc.PrinterSettings.PrinterName = printerName;

                if (!printDoc.PrinterSettings.IsValid)
                {
                    string msg = String.Format("Can't find printer \"{0}\".", printerName);
                    //MessageBox.Show(msg, "Print Error");
                    return;
                }
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                printDoc.Print();
            }
            catch (Exception ee)
            {

            }
        }
        public static Byte[] GenerarPdfFactura(LocalReport localReport, out string mimeType)
        {
            const string reportType = "PDF";

            string encoding;
            string fileNameExtension;

            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            const string deviceInfo = "<DeviceInfo>" +
                                      "  <OutputFormat>PDF</OutputFormat>" +
                                      "  <PageWidth>21cm</PageWidth>" +
                                      "  <PageHeight>25.7cm</PageHeight>" +
                                      "  <MarginTop>1cm</MarginTop>" +
                                      "  <MarginLeft>2cm</MarginLeft>" +
                                      "  <MarginRight>2cm</MarginRight>" +
                                      "  <MarginBottom>1cm</MarginBottom>" +
                                      "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;

            //Render the report
            return localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
        }
Example #6
1
        private void Export(LocalReport report)
        {
            try
            {
                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>";

                Warning[] warnings;
                m_streams = new List<Stream>();
                report.Render("Image", deviceInfo, CreateStream,out warnings);
                foreach (Stream stream in m_streams)
                    stream.Position = 0;
            }
            catch (Exception ee)
            {
                //MessageBox.Show(ee.ToString());
            }
        }
 public LocalReportPrinter(string reportFullPath, PaperSize paperSize = null)
 {
     _reportFullPath = Application.StartupPath + @"\" + reportFullPath;
     _report = new LocalReport { ReportPath = _reportFullPath };
     _paperSize = paperSize ?? _report.GetDefaultPageSettings().PaperSize;
     _streams = new List<Stream>();
 }
Example #8
0
 /// <summary>
 /// Initialize report object with default setting
 /// </summary>
 public RDLCPrinter(LocalReport report, ReportType rtype, int nbrPage, string path)
 {
     _report = report;
     _Copies = nbrPage;
     _ReportType = rtype;
     _path = path;
 }
Example #9
0
        private static void ExportPDF(LocalReport localReport, Stream stream)
        {
            byte[] bytes = PDFHelper.LocalReportToBytes(localReport);

            stream.Write(bytes, 0, bytes.Length);
            stream.Close();
        }
 public void Imprimir(Ticket ticket)
 {
     var report = new LocalReport { ReportPath = @"..\..\Ticket.rdlc" };
     report.DataSources.Add(new ReportDataSource("Ticket", new List<Ticket> { ticket }));
     Export(report);
     Print();
 }
 public void SetParam ( ref LocalReport localReport , string strParam , string strValue )
 {
     ReportParameter Param = new ReportParameter ();
     Param.Name = strParam;
     Param.Values.Add ( strValue );
     localReport.SetParameters ( new ReportParameter [] { Param } );
 }
        protected void executeReport_click(object sender, EventArgs e)
        {
            if (reportSelector.SelectedIndex == 9)
                executeReportInAppDomain_click(sender, e);
            else
            {
                LocalReport rpt = new LocalReport();
                rpt.EnableExternalImages = true;
                rpt.ReportPath = String.Concat(Path.GetDirectoryName(Request.PhysicalPath), "\\Reports\\", reportSelector.SelectedValue);
                string orientation = (rpt.GetDefaultPageSettings().IsLandscape) ? "landscape" : "portrait";
                StringReader formattedReport = Business.reportHelper.FormatReportForTerritory(rpt.ReportPath, orientation, cultureSelector.SelectedValue);
                rpt.LoadReportDefinition(formattedReport);

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

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

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

                    rpt.SetParameters(reportParams);
                }

                // Render To Browser
                renderPDFToBrowser(rpt.Render("PDF", Business.reportHelper.GetDeviceInfoFromReport(rpt, cultureSelector.SelectedValue, "PDF")));
            }
        }
Example #13
0
 /// <summary>
 /// Initialize repot object with default setting
 /// Copies = 1
 /// ReportType = Printer
 /// Path = 0
 /// </summary>
 public RDLCPrinter(LocalReport report)
 {
     _report = report;
     _Copies = 1;
     _ReportType = ReportType.Printer;
     _path = "";
 }
Example #14
0
        public ActionResult Export(string type)
        {
            LocalReport lr = new LocalReport();
            int TotalRow;
            string path = Path.Combine(Server.MapPath("~/Rdlc"), "rdlcOrders.rdlc");
            lr.ReportPath = path;
            var list = serivce.Get(out TotalRow);

            ReportDataSource rd = new ReportDataSource("DataSet1", list);
            lr.DataSources.Add(rd);

            string reportType = type;
            string mimeType;
            string encoding;
            string fileNameExtension;
            string deviceInfo;

            deviceInfo = "<DeviceInfo>" +
            "  <OutputFormat>" + type + "</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth>" +
            "  <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.5in</MarginTop>" +
            "  <MarginLeft>1in</MarginLeft>" +
            "  <MarginRight>1in</MarginRight>" +
            "  <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] stream;
            byte[] renderBytes;

            renderBytes = lr.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out stream, out warnings);

            return File(renderBytes, mimeType, "Report");
        }
 public ActionResult ReporteCmpVenta(string FECHA1, string TURNO)
 {
     LocalReport localReport = new LocalReport();
     DateTime FECHA = DateTime.ParseExact(FECHA1, "dd/MM/yyyy", null);
     localReport.ReportPath = Server.MapPath("~/Reportes/ReporteCmpVenta.rdlc");
     ReportDataSource reportDataSource = new ReportDataSource("DataSet1", repo.ReporteVenta(FECHA1,TURNO));
     localReport.SubreportProcessing +=
             new SubreportProcessingEventHandler(DemoSubreportProcessingEventHandler);
     //var queryConsumo = repo.ReporteVentaConsumo(FECHA, TURNO);
     //var querytotal = repo.ReporteVentaCreditoConsumo(FECHA, TURNO);
     //ReportDataSource dataSource = new ReportDataSource("DataSetVentaCredito", query);
     //ReportDataSource dataSource = new ReportDataSource("DataSetVentaConsumo", query);
     //localReport.DataSources.Add(new ReportDataSource("DataSetVentaConsumo", queryConsumo));
     //localReport.DataSources.Add(new ReportDataSource("DataSetTotal", querytotal));
     localReport.DataSources.Add(reportDataSource);
     string reportType = "PDF";
     string mimeType = "application/pdf";
     string encoding = "utf-8";
     string fileNameExtension = "pdf";
     string deviceInfo = string.Empty;
     Warning[] warnings = new Warning[1];
     string[] streams = new string[1];
     Byte[] renderedBytes;
     //Render the report
     renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
     return File(renderedBytes, mimeType);
 }
Example #16
0
        private void LoadDataReport()
        {
            //Create the local report
            LocalReport report = new LocalReport();
            report.ReportEmbeddedResource = "RDLCDemo.ReportTest.rdlc";

            //Create the dataset
            _northWindDataSet = new NorthwindDataSet();
            _dataAdapter = new NorthwindDataSetTableAdapters.ProductsByCategoriesTableAdapter();

            _northWindDataSet.DataSetName = "NorthwindDataSet";
            _northWindDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
            _dataAdapter.ClearBeforeFill = true;

            //Created datasource and binding source
            ReportDataSource dataSource = new ReportDataSource();
            System.Windows.Forms.BindingSource source = new System.Windows.Forms.BindingSource();

            dataSource.Name = "ProductsDataSources";  //the datasource name in the RDLC report
            dataSource.Value = source;
            source.DataMember = "ProductsByCategories";
            source.DataSource = _northWindDataSet;
            report.DataSources.Add(dataSource);

            //Fill Data in the dataset
            _dataAdapter.Fill(_northWindDataSet.ProductsByCategories);

            //Create the printer/export rdlc printer
            RDLCPrinter rdlcPrinter = new RDLCPrinter(report);

            rdlcPrinter.BeforeRefresh += rdlcPrinter_BeforeRefresh;

            //Load in report viewer
            ReportViewer.Report = rdlcPrinter;
        }
        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 #18
0
        public static ReportDTO PrintReport(string reportPath, object[] data, string[] dataSourceName, string reportType, bool isPortriat = true)
        {
            var localReport = new LocalReport();
            localReport.ReportPath = reportPath;

            for (int i = 0; i < data.Count(); i++)
            {
                var reportDataSource = new ReportDataSource(dataSourceName[i], data[i]);
                localReport.DataSources.Add(reportDataSource);
            }

            //foreach (var d in data)
            //{
            //    var reportDataSource = new ReportDataSource(dataSourceName, d);
            //    localReport.DataSources.Add(reportDataSource);
            //}

            // string reportType = "PDF";

            string mimeType;
            string encoding;
            string fileNameExtension;

            string pageLayout = isPortriat
                                    ? "  <PageWidth>8.5in</PageWidth> <PageHeight>11in</PageHeight> "
                                    : "  <PageWidth>11in</PageWidth> <PageHeight>8.5in</PageHeight> ";
            //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>" +
               pageLayout +
            "  <MarginTop>0.5in</MarginTop>" +
            "  <MarginLeft>0.25in</MarginLeft>" +
            "  <MarginRight>0.25in</MarginRight>" +
            "  <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings
                );

            var result=new ReportDTO{
                                      RenderBytes=renderedBytes,
                                      MimeType=mimeType
                                    };
            return result;
        }
        public ReportPrintDocument(LocalReport localReport)
            : this((Microsoft.Reporting.WinForms.Report)localReport)
        {
            RenderAllLocalReportPages(localReport);

            PrinterSettings.MinimumPage = 1;
            PrinterSettings.FromPage = 1;
            PrinterSettings.ToPage = m_pages.Count;
            PrinterSettings.MaximumPage = m_pages.Count;
        }
Example #20
0
        public void Run(LocalReport report)
        {
            //LocalReport report = new LocalReport();
            //report.ReportPath = @"c:\My Reports\Report.rdlc";
            //report.DataSources.Add(new ReportDataSource("Sales", LoadSalesData()));

            Export(report);

            m_currentPageIndex = 0;
            Print();
        }
Example #21
0
        //public AutoPrintCls(ServerReport serverReport)
        //    : this((Report)serverReport)
        //{
        //    RenderAllServerReportPages(serverReport);
        //}
        //public AutoPrintCls(LocalReport localReport)
        //    : this((Report)localReport)
        //{
        //    RenderAllLocalReportPages(localReport);
        //}
        private AutoPrintCls(LocalReport report)
        {
            // Set the page settings to the default defined in the report
            ReportPageSettings reportPageSettings = report.GetDefaultPageSettings();

            // The page settings object will use the default printer unless
            // PageSettings.PrinterSettings is changed.  This assumes there
            // is a default printer.
            m_pageSettings = new PageSettings();
            m_pageSettings.PaperSize = reportPageSettings.PaperSize;
            m_pageSettings.Margins = reportPageSettings.Margins;
        }
        private void btnGenerateInCode_Click(object sender, EventArgs e)
        {
            using (var rpt = new LocalReport())
            {
                rpt.ReportPath = "Customers.rdlc";
                var data = DataAccess.Customer.Get();
                var rds = new ReportDataSource("CustomerDataSet", data);
                rpt.DataSources.Add(rds);

                string reportType = "WORDOPENXML";
                string mimeType;
                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>WORDOPENXML</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";

                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;

                //Render the report
                renderedBytes = rpt.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);

                using (var fd = new SaveFileDialog())
                {
                    fd.Filter = "word files (*.docx)|*.docx|All files (*.*)|*.*";
                    if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        File.WriteAllBytes(fd.FileName, renderedBytes);
                        System.Diagnostics.Process.Start(fd.FileName);
                    }
                }

            }
        }
        public void DisableUnwantedExportFormats(LocalReport rvServer)
        {
            RenderingExtension[] extensio = rvServer.ListRenderingExtensions();

            foreach (RenderingExtension extension in rvServer.ListRenderingExtensions())
            {
                if (extension.Name == "XML" || extension.Name == "WORD" || extension.Name == "MHTML" || extension.Name == "EXCEL" || extension.Name == "Excel" || extension.Name == "CSV")
                {
                    ReflectivelySetVisibilityFalse(extension);
                }
            }
        }
        public FileContentResult obtenerReporte(FormCollection post)
        {
            // Nota los datos creados en el dataset deben ser con el mismo nombre que tengan los Datos del Modelo

            string EPC = post["EPC"].ToString();
            string inicio = post["inicio"].ToString();
            string fin = post["fin"].ToString();

            string diagnostico = post["diagnostico"];
            string recomendacion = post["recomendacion"];
            string observaciones = post["observaciones"];

            // Nota los datos creados en el dataset deben ser con el mismo nombre que tengan los Datos del Modelo
            LocalReport reporte_local = new LocalReport();
            // pasa la ruta donde se encuentra el reporte
            reporte_local.ReportPath = Server.MapPath("~/Report/reporte.rdlc");
            // creamos un recurso de datos del tipo report
            ReportDataSource conjunto_datos = new ReportDataSource();
            // le asginamos al conjuto de datos el nombre del datasource del reporte
            conjunto_datos.Name = "DataSet1";
            List<lecturasReporte> lecturasParaReporte = new List<lecturasReporte>();
            if (Session["rol"] != null)
            {
                List<lecturas> listaLecturas = lecturas.obtenerUltimosDatos(EPC, inicio, fin);
                lecturasParaReporte = lecturasReporte.convertirLecturas(listaLecturas, diagnostico, recomendacion, observaciones);
            }
            // se le asigna el datasource el conjunto de datos desde el modelo
            conjunto_datos.Value = lecturasParaReporte;
            // se agrega el conjunto de datos del tipo report al reporte local
            reporte_local.DataSources.Add(conjunto_datos);
            // datos para renderizar como se mostrara el reporte
            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;
            string deviceInfo = "<DeviceInfo>" +
                 "  <OutputFormat>jpeg</OutputFormat>" +
                 "  <PageWidth>14in</PageWidth>" +
                 "  <PageHeight>12in</PageHeight>" +
                 "  <MarginTop>0.5in</MarginTop>" +
                 "  <MarginLeft>1in</MarginLeft>" +
                 "  <MarginRight>1in</MarginRight>" +
                 "  <MarginBottom>0.5in</MarginBottom>" +
                 "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            //Se renderiza el reporte            
            renderedBytes = reporte_local.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
            // el reporte es mostrado como una imagen
            return File(renderedBytes, mimeType);
        }
Example #25
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 #26
0
 private static void Export(LocalReport report)
 {
     string deviceInfo =
       @"<DeviceInfo>
         <OutputFormat>EMF</OutputFormat>
     </DeviceInfo>";
     Warning[] warnings;
     m_streams = new List<Stream>();
     report.Render("Image", deviceInfo, CreateStream,
        out warnings);
     foreach (Stream stream in m_streams)
         stream.Position = 0;
 }
Example #27
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 #28
0
        private byte[] GenerateCustomerBillReportData(int month, int year, string format)
        {
            if (month == 0 || year == 0)
                return null;
            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Report/rpCustomerBill.rdlc");

            ReportDataSource reportDataSource = new ReportDataSource();
            reportDataSource.Name = "dsCustomerBill";
            if (Session["LoggedUser"] == null || !(Session["LoggedUser"] is Customer))
                return null;

            Customer customer = (Customer)Session["LoggedUser"];

            var customerBill = new ReportDAL().GetCustomerBill(customer.ID, month, year);

            reportDataSource.Value = customerBill;
            localReport.DataSources.Add(reportDataSource);

            string period = string.Format("{0}/{1}", month, year);

            ReportParameter pCustomerName = new ReportParameter("CustomerName", string.Format("{0} {1}", customer.FirstName, customer.LastName));
            ReportParameter pCustomerPhoneNo = new ReportParameter("CustomerPhoneNo", customer.PhoneNo);
            ReportParameter pCustomerAddress = new ReportParameter("CustomerAddress", string.Format("{0} , {1},  {2}", customer.StreetAddress, customer.ZipCode, customer.State));
            ReportParameter pPeriod = new ReportParameter("Period", period);
            localReport.SetParameters(pCustomerName);
            localReport.SetParameters(pCustomerPhoneNo);
            localReport.SetParameters(pCustomerAddress);
            localReport.SetParameters(pPeriod);

            string mimeType;
            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>jpeg</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
            //Render the report            
            renderedBytes = localReport.Render(format, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
            return renderedBytes;
        }
Example #29
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 _start    = this.ddpBOL.FromDate.ToString("yyyy-MM-dd");
            string _end      = this.ddpBOL.ToDate.ToString("yyyy-MM-dd");
            string _terminal = this.cboTerminal.SelectedValue != "" ? this.cboTerminal.SelectedValue : null;
            string _agent    = this.cboAgent.SelectedValue != "" ? this.cboAgent.SelectedValue : null;

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = this.mTitle;
            report.EnableExternalImages = true;
            EnterpriseGateway enterprise = new EnterpriseGateway();
            DataSet           ds         = enterprise.FillDataset(this.cboType.SelectedValue, mTBLName, new object[] { _start, _end, _agent, _terminal });
            if (ds.Tables[mTBLName] == null)
            {
                ds.Tables.Add(mTBLName);
            }
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(this.mSource);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));

                //Set the report parameters for the report
                ReportParameter start = new ReportParameter("StartBolDate", _start);
                ReportParameter end   = new ReportParameter("EndBolDate", _end);
                ReportParameter agent = new ReportParameter("Agent", (_agent == null?"All":_agent));
                report.SetParameters(new ReportParameter[] { start, end, agent });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh(); break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=OutboundTrailerWeightAndCube.xls");
                Response.ContentType = "application/vnd.ms-excel";      //application/octet-stream";
                System.IO.StringWriter       sw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
                DataGrid dg = new DataGrid();
                dg.DataSource = ds.Tables[mTBLName];
                dg.DataBind();
                dg.RenderControl(hw);
                Response.Write(sw.ToString());
                Response.End();
                break;
            }
        }
        catch (Exception ex) { Master.ReportError(ex); }
    }
        private void btnOK_Click(object sender, EventArgs e)
        {
            // valida os campos
            if (!this.ValidarCampos())
            {
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            try
            {
                //repositório
                var incidenciaDoencaEmDistritoSanitario = new DoencaEmUnidadeSaudeRepositorio();

                //recupera informações para o relatório
                var listaIncidenciaDoencasEmDistritoSanitario = incidenciaDoencaEmDistritoSanitario.ListarDoencasDeUmDistritoSanitario((int)this.cmbDS.SelectedValue,
                                                                                                                                       this.dtDe.Value.Year, this.dtAte.Value.Year);

                var listaDeIncidenciaDoencaEmDistritoSanitario = listaIncidenciaDoencasEmDistritoSanitario.OrderBy(y => y.DescricaoDoenca).ToList();

                //define os datasources do relatório
                var localReport = new LocalReport();
                localReport.ReportEmbeddedResource = "GestaoSMSAddin.DataAccess.Reports.DistritoSanitarioDoencasRpt.rdlc";
                localReport.DataSources.Clear();
                localReport.DataSources.Add(new ReportDataSource("DoencasEmDistritoSanitario", listaDeIncidenciaDoencaEmDistritoSanitario));
                localReport.Refresh();

                // parâmetros do relatório
                string descricaoDoenca = this.cmbDS.Text;
                string ano             = DateTime.Now.Year.ToString();
                string soma            = listaIncidenciaDoencasEmDistritoSanitario.Sum(w => w.Incidencia).ToString();

                var rptParameter1 = new ReportParameter("nomeDistritoSanitario", descricaoDoenca);
                var rptParameter2 = new ReportParameter("ano", ano);
                var rptParameter3 = new ReportParameter("somaIncidencia", soma);

                localReport.SetParameters(
                    new ReportParameter[] {
                    rptParameter1, rptParameter2, rptParameter3
                });

                if (this.dtDe.Value.Year == this.dtAte.Value.Year)
                {
                    string anoIncidencia = this.dtAte.Value.Year.ToString();
                    var    rptParameter4 = new ReportParameter("anoIncidencia", anoIncidencia);
                    localReport.SetParameters(
                        new ReportParameter[] {
                        rptParameter4
                    });
                }
                else
                {
                    string anoIncidencia = this.dtDe.Value.Year.ToString() + " - " + this.dtAte.Value.Year.ToString();
                    var    rptParameter4 = new ReportParameter("anoIncidencia", anoIncidencia);
                    localReport.SetParameters(
                        new ReportParameter[] {
                        rptParameter4
                    });
                }

                //nome do relatório
                string nomePdfRelatorio =
                    System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + ".pdf");

                //criação de arquivo do relatório
                byte[] pdfBytes     = localReport.Render("PDF");
                var    binaryWriter = new BinaryWriter(new FileStream(nomePdfRelatorio, FileMode.CreateNew, FileAccess.Write));
                binaryWriter.Write(pdfBytes, 0, pdfBytes.Length);
                binaryWriter.Close();

                //mostra o arquivo de relatório ao usuário
                Process.Start(nomePdfRelatorio);
            }
            catch (Exception ex)
            {
                MostrarErro(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Example #31
0
        public string CallReports(string DocType, List <ReportParameter> reportParameters, bool isPortrait, string reportPath, DataTable dataTable, IEnumerable <dynamic> dataObject, string reportDataSetName)
        {
            string errorMessage = string.Empty;
            string fileString   = string.Empty;

            try
            {
                var org = db.Organaizations.FirstOrDefault();

                ReportParameter companyName = new ReportParameter("companyName");
                companyName.Values.Add(org.Name);
                reportParameters.Add(companyName);

                ReportParameter address = new ReportParameter("address");
                address.Values.Add(org.Address);
                reportParameters.Add(address);

                ReportParameter contactInfo = new ReportParameter("contactInfo");
                contactInfo.Values.Add("PHONE :" + org.Phone + " Email : " + org.Email + " WEB : " + org.Web);
                reportParameters.Add(contactInfo);

                LocalReport      lr   = new LocalReport();
                ReportDataSource rd   = new ReportDataSource();
                string           path = string.Empty;
                if (dataTable != null && dataTable.Rows.Count > 0 || dataObject != null && dataObject.Count() > 0)
                {
                    path = reportPath;
                }
                else
                {
                    if (isPortrait)
                    {
                        path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/AttendanceReports/RDLCS"), "DailyAttendance.rdlc");
                    }
                    else
                    {
                        path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/AttendanceReports/RDLCS"), "DailyAttendance.rdlc");
                    }
                }

                if (System.IO.File.Exists(path))
                {
                    lr.ReportPath = path;
                    lr.SetParameters(reportParameters);
                }
                else
                {
                    errorMessage = "File Not Exists.";
                }
                if (dataTable != null)
                {
                    rd = new ReportDataSource(reportDataSetName, dataTable);
                }
                else if (dataObject != null)
                {
                    rd = new ReportDataSource(reportDataSetName, dataObject);
                }

                lr.DataSources.Add(rd);
                // Convert Report To Base64String
                string reportType = DocType;
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo =
                    "<DeviceInfo>" +
                    "  <OutputFormat>" + DocType + "</OutputFormat>" +
                    "</DeviceInfo>";

                Warning[] warnings;
                string[]  streams;
                byte[]    renderedBytes;

                renderedBytes = lr.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);
                fileString = Convert.ToBase64String(renderedBytes.ToArray());
                return(fileString);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return(errorMessage);
            }
        }
Example #32
0
        private void socketIo()
        {
            var socket = IO.Socket(this.server);

            //Event
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                List <String> printer = getPrinter();
                string defaultPrinter = getDefaultPrinter();

                var data = new
                {
                    ip             = this.ip,
                    name           = this.name,
                    printers       = printer,
                    defaultPrinter = defaultPrinter
                };

                var jsonFormat = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                socket.Emit("recieveUserName", jsonFormat);
                notifyIcon.BalloonTipText = "Connected Server " + server;
                notifyIcon.ShowBalloonTip(1000);
            });

            var that = this;

            socket.On("message", (data) =>
            {
                Invoke(new Action(() =>
                {
                    that.Show();
                    that.WindowState   = FormWindowState.Normal;
                    notifyIcon.Visible = false;

                    var o = (JObject)data;

                    //tboMessage.Text = (string)o.GetValue("message");
                    String message = (string)o.GetValue("message");
                    //message = message.Replace(System.Environment.NewLine, "\n");
                    label1.Text    = message;
                    String strType = (string)o.GetValue("type");
                    if (strType != null)
                    {
                        setType(type[strType]);
                    }
                    //SFCForm.MainWindow fm = new SFCForm.MainWindow();
                    label1.Top = (this.Height - label1.Height) / 2 - 30;
                }));
            });

            socket.On("print", (data) =>
            {
                try
                {
                    Invoke(new Action(() =>
                    {
                        notifyIcon.BalloonTipText = "Client Printed.";
                        notifyIcon.ShowBalloonTip(1000);

                        var o = (JObject)data;
                        //JArray jarray = (JArray)o.GetValue("JOBS");
                        //JToken entry = (JToken)jarray[0];
                        //var jobs = (String)entry[0]["DocumentName"];
                        LocalReport localReport = new LocalReport();

                        foreach (JObject job in (JArray)o.GetValue("JOBS"))
                        {
                            localReport.ReportPath = (String)job.GetValue("FilePath");
                            foreach (JObject doc in (JArray)job.GetValue("DocumentDatas"))
                            {
                                try
                                {
                                    ReportParameter Param = new ReportParameter();
                                    Param.Name            = (String)doc.GetValue("Parameter");
                                    Param.Values.Add((String)doc.GetValue("Value"));
                                    localReport.SetParameters(new ReportParameter[] { Param });
                                }
                                catch (LocalProcessingException e)
                                {
                                    MessageBox.Show(e.InnerException.Message);
                                    break;
                                }
                            }

                            if ((String)job.GetValue("PrintServerID") != (String)job.GetValue("PrinterName"))
                            {
                                localReport.SetPrinterName((String)job.GetValue("PrinterName"));
                                localReport.PrintToPrinter();
                            }
                            else
                            {
                                localReport.PrintToPrinter(); //default printer output
                            }
                        }

                        // LocalReport localReport = new LocalReport();
                        // localReport.ReportPath = Application.StartupPath + "\\FGRECEIVEDBILL_REPORT.rdl";

/*
 *                      foreach (var x in (JObject)o.GetValue("item"))
 *                      {
 *                          ReportParameter Param = new ReportParameter();
 *                          Param.Name = (String)x.Key;
 *                          Param.Values.Add((String)x.Value);
 *                          localReport.SetParameters(new ReportParameter[] { Param });
 *                      }
 *
 *                      localReport.PrintToPrinter((String)o.GetValue("printer"));
 */
                    }));
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            });

            socket.On(Socket.EVENT_ERROR, (error) => {
                // ...

                Invoke(new Action(() =>
                {
                    notifyIcon.BalloonTipText = "Connect Error " + server;
                    notifyIcon.ShowBalloonTip(1000);
                }));
            });
        }
Example #33
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 _client = this.dgdClientVendor.ClientNumber;
            string _div = this.dgdClientVendor.ClientDivsionNumber;
            string _clientName = this.dgdClientVendor.ClientName;
            string _vendor = "", _pudate = "", _punum = "";

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = this.mTitle;
            report.EnableExternalImages = true;
            EnterpriseGateway enterprise = new EnterpriseGateway();
            DataSet           ds         = new DataSet(this.mDSName);
            foreach (GridViewRow row in SelectedRows)
            {
                DataKey dataKey = (DataKey)this.grdPickups.DataKeys[row.RowIndex];
                _vendor = dataKey["VendorNumber"].ToString();
                _pudate = DateTime.Parse(dataKey["PUDate"].ToString()).ToString("yyyy-MM-dd");
                _punum  = dataKey["PUNumber"].ToString();
                DataSet _ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _client, _div, _vendor, _pudate, _punum });
                ds.Merge(_ds);
            }
            if (ds.Tables[mTBLName] == null)
            {
                ds.Tables.Add(mTBLName);
            }
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(this.mSource);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));

                ReportParameter client     = new ReportParameter("ClientNumber", _client);
                ReportParameter div        = new ReportParameter("ClientDivision", _div);
                ReportParameter vendor     = new ReportParameter("VendorNumber", "");
                ReportParameter pudate     = new ReportParameter("PUDate", "");
                ReportParameter punum      = new ReportParameter("PuNumber", "0");
                ReportParameter vendorName = new ReportParameter("VendorName", "");
                ReportParameter clientName = new ReportParameter("ClientName", _clientName);
                ReportParameter manifests  = new ReportParameter("Manifest", "");
                ReportParameter trailers   = new ReportParameter("Trailers", "");
                report.SetParameters(new ReportParameter[] { client, div, vendor, pudate, punum, vendorName, clientName, manifests, trailers });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh(); break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=DuplicateCartons.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 #34
0
    protected void OnViewerDrillthrough(object sender, DrillthroughEventArgs e)
    {
        //Event handler for drill through
        if (!e.Report.IsDrillthroughReport)
        {
            return;
        }

        //Determine which drillthrough report is requested
        LocalReport report = (LocalReport)e.Report;

        switch (e.ReportPath)
        {
        case "PacSunSummaryCartonDetail": {
            //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
            DataSet ds = (DataSet)Session["PacSunDS"];
            report.DataSources.Clear();
            report.DataSources.Add(new ReportDataSource("DetailDS", ds.Tables[mTBLName]));
            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;

        case "PacSunSummaryOSDDetail": {
            //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
            DataSet ds = (DataSet)Session["PacSunDS"];
            report.DataSources.Clear();
            report.DataSources.Add(new ReportDataSource("DetailDS", ds.Tables[mTBLName]));
            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;
        }
    }
Example #35
0
        protected override bool RenderInternal(ref MemoryStream chunk, out string mime)
        {
            mime = null;
            try
            {
                /* 1. instantiate the report */
                var rpt = new LocalReport()
                {
                    ReportEmbeddedResource = "sherm.rpt.msdbrpt.ReportHardcopyIncidentPlacard003.rdlc",
                    EnableExternalImages   = true
                };
                /* 2. populate the report */
                rpt.DataSources.Clear();
                var dt   = Data.Tables[ReportDatatableIdentifiers.REPORT_DATATABLE_HARDCOPY_SAFETYALERT].Rows[0];
                var Logo = MediaURLAbsolute(sherm.core.formatting.mime.BINGET_NAMEDRESOURCE_CORPORATELOGO, new FileType[] { FileType.ft_png });
                rpt.SetParameters(new ReportParameter[] {
                    /* dynamic texts */
                    new ReportParameter("CompanyName", dt["fCompanyName"].ToString()),
                    new ReportParameter("Revision", this.ReportRevsionNumber), /* [dlatikay 20150624] MEA-2015-00273.14 */
                    new ReportParameter("PersonsInvolved", dt["fPersonsInvolved"].ToString()),
                    new ReportParameter("RevisionNumber", ReportRevsionNumber),
                    new ReportParameter("BusinessUnit", dt["BusinessUnit"].ToString()), /* [pkosec 20140818] MEA-2014-00368.1 fixed: use of rep02IncidentAux.BusinessUnit */
                    new ReportParameter("Location", dt["fLocation"].ToString()),
                    new ReportParameter("IncLocation", dt["fIncLocation"].ToString()),
                    new ReportParameter("IncDate", dt["fEventDate"].ToString()),
                    new ReportParameter("IncTime", dt["fEventTime"].ToString()),
                    new ReportParameter("OrgLocation", dt["fOrgLocation"].ToString()),
                    new ReportParameter("CostCenter", dt["fCostcenter"].ToString()),
                    new ReportParameter("IncWorkingHousFrom", dt["fWorkstartedHourMin"].ToString()),
                    new ReportParameter("IncWorkingHousTo", dt["fWorkendedHourMin"].ToString()),
                    new ReportParameter("AffectedPerson", dt["fAffectedPerson"].ToString()),
                    new ReportParameter("PersonNumber", dt["fPersNr"].ToString()),
                    new ReportParameter("Boss", dt["fBoss"].ToString()),
                    new ReportParameter("PermanentStaff", dt["fPermanentStaff"].ToString()),
                    new ReportParameter("ContractorEmployees", dt["fContractorEmployees"].ToString()),
                    new ReportParameter("Visitor", dt["fVisitor"].ToString()),
                    new ReportParameter("VictimFunction", dt["fVictimFunction"].ToString()),
                    //new ReportParameter("NatureOfInjury", dt["fNatureOfInjury"].ToString()),
                    /* begin [pkosec 20140818] new params added (MEA-2014-00368) */
                    new ReportParameter("lNOI1", dt["lNOI1"].ToString()),
                    new ReportParameter("lNOI2", dt["lNOI2"].ToString()),
                    new ReportParameter("lNOI3", dt["lNOI3"].ToString()),
                    new ReportParameter("lNOI4", dt["lNOI4"].ToString()),
                    new ReportParameter("lNOI5", dt["lNOI5"].ToString()),
                    new ReportParameter("lNOI6", dt["lNOI6"].ToString()),
                    new ReportParameter("lNOI7", dt["lNOI7"].ToString()),
                    new ReportParameter("lNOI8", dt["lNOI8"].ToString()),
                    new ReportParameter("lNOI9", dt["lNOI9"].ToString()),
                    new ReportParameter("lNOI10", dt["lNOI10"].ToString()),
                    new ReportParameter("lNOI11", dt["lNOI11"].ToString()),
                    new ReportParameter("lNOI12", dt["lNOI12"].ToString()),
                    new ReportParameter("fNOI1", dt["fNOI1"].ToString()),
                    new ReportParameter("fNOI2", dt["fNOI2"].ToString()),
                    new ReportParameter("fNOI3", dt["fNOI3"].ToString()),
                    new ReportParameter("fNOI4", dt["fNOI4"].ToString()),
                    new ReportParameter("fNOI5", dt["fNOI5"].ToString()),
                    new ReportParameter("fNOI6", dt["fNOI6"].ToString()),
                    new ReportParameter("fNOI7", dt["fNOI7"].ToString()),
                    new ReportParameter("fNOI8", dt["fNOI8"].ToString()),
                    new ReportParameter("fNOI9", dt["fNOI9"].ToString()),
                    new ReportParameter("fNOI10", dt["fNOI10"].ToString()),
                    new ReportParameter("fNOI11", dt["fNOI11"].ToString()),
                    new ReportParameter("fNOI12", dt["fNOI12"].ToString()),
                    /* end */
                    new ReportParameter("WellknownBodypartsArm", dt["fWellknownBodypartsArm"].ToString()),
                    new ReportParameter("WellknownBodypartsInternalOrgans", dt["fWellknownBodypartsInternalOrgans"].ToString()),
                    new ReportParameter("WellknownBodypartsFoot", dt["fWellknownBodypartsFoot"].ToString()),
                    new ReportParameter("WellknownBodypartsHead", dt["fWellknownBodypartsHead"].ToString()),
                    new ReportParameter("WellknownBodypartsEye", dt["fWellknownBodypartsEye"].ToString()),
                    new ReportParameter("WellknownBodypartsLeg", dt["fWellknownBodypartsLeg"].ToString()),
                    new ReportParameter("WellknownBodypartsHand", dt["fWellknownBodypartsHand"].ToString()),
                    new ReportParameter("WellknownBodypartsBody", dt["fWellknownBodypartsBody"].ToString()),
                    new ReportParameter("TOPMultiTechnical", dt["fTOPMultiTechnical"].ToString()),
                    new ReportParameter("TOPMultiOrganizational", dt["fTOPMultiOrganizational"].ToString()),
                    new ReportParameter("TOPMultiPersonal", dt["fTOPMultiPersonal"].ToString()),
                    new ReportParameter("LostDays", dt["fLostTimeDays"].ToString()),
                    new ReportParameter("WitnessName", dt["fWitnessName"].ToString()),
                    new ReportParameter("IsEyewitnessYes", dt["fIsEyewitnessYes"].ToString()),
                    new ReportParameter("IsEyewitnessNo", dt["fIsEyewitnessNo"].ToString()),
                    new ReportParameter("FirstAidDetails", dt["fFirstAidDetails"].ToString()),
                    new ReportParameter("FirstAidByFirstResponder", dt["fFirstAidByFirstResponder"].ToString()),
                    new ReportParameter("FirstAidByParamedic", dt["fFirstAidByParamedic"].ToString()),
                    new ReportParameter("FirstAidByAmbulance", dt["fFirstAidByAmbulance"].ToString()),
                    new ReportParameter("IncDoctor", dt["fIncDoctor"].ToString()),
                    new ReportParameter("AttendingDoctor", dt["fAttendingDoctor"].ToString()),
                    new ReportParameter("ClinicName", dt["fHospitalName"].ToString()),
                    new ReportParameter("Circumstances", dt["fCourseOfEvents"].ToString()),
                    new ReportParameter("Measures", dt["fImmediateMeasures"].ToString()),
                    new ReportParameter("PPEDetails", dt["fPPEDetails"].ToString()),
                    new ReportParameter("PPEHelmet", dt["fPPEHelmet"].ToString()),
                    new ReportParameter("PPEGoggles", dt["fPPEGoggles"].ToString()),
                    new ReportParameter("PPEFacewear", dt["fPPEFacewear"].ToString()),
                    new ReportParameter("PPEGloves", dt["fPPEGloves"].ToString()),
                    new ReportParameter("PPEFootwear", dt["fPPEFootwear"].ToString()),
                    new ReportParameter("PPEClothing", dt["fPPEClothing"].ToString()),
                    new ReportParameter("PPEFallwear", dt["fPPEFallwear"].ToString()),
                    new ReportParameter("PPERespiratory", dt["fPPERespiratory"].ToString()), /* added [pkosec 20140606] */
                    new ReportParameter("classUZUHBU", dt["classUZUHBU"].ToString()),
                    new ReportParameter("classBrand", dt["classBrand"].ToString()),
                    new ReportParameter("classUmwelt", dt["classUmwelt"].ToString()),
                    new ReportParameter("classSach", dt["classSach"].ToString()),
                    new ReportParameter("classOhne", dt["classOhne"].ToString()),
                    new ReportParameter("classMit", dt["classMit"].ToString()),
                    new ReportParameter("classWege", dt["classWege"].ToString()),
                    new ReportParameter("SignatureDate", dt["fSignatureDate"].ToString()),
                    new ReportParameter("CreatedByName", dt["fCreatedBy"].ToString()),
                    new ReportParameter("CreatedByPhone", dt["fSignatureContactTel"].ToString()),
                    new ReportParameter("Risk", dt["sRisk"].ToString()),
                    new ReportParameter("RiskScore", dt["RiskEstimation"].ToString()),
                    /* fixed captions */
                    new ReportParameter("lRisk", m(7080) + ":"),                       /* Risk estimation */
                    new ReportParameter("lLegendTitle", m(2985).ToUpper() + ":"),      /* Legend */
                    new ReportParameter("lLowRiskValue", "1-2 = " + m(6496) + ";"),    /* Low */
                    new ReportParameter("lMiddleRiskValue", "3-4 = " + m(218) + ";"),  /* Middle */
                    new ReportParameter("lHighRiskValue", "5-7 = " + m(220) + ";"),    /* High */
                    new ReportParameter("lLowRiskDescription", m(7089) + ";"),         /* No risk mitigating actions required */
                    new ReportParameter("lMiddleRiskDescription", m(7090) + ";"),      /* Risk mitigating actions required */
                    new ReportParameter("lHighRiskDescription", m(7091) + ";"),        /* Corrective actions with significant risk reduction urgently needed */
                    new ReportParameter("lTitle", m(4529)),                            /* Internal incident report */
                    new ReportParameter("lSendByEmail", m(4530)),                      /* Distribution by e-mail: */
                    new ReportParameter("lBusinessUnit", m(4531) + ":"),               /* Business Unit */
                    new ReportParameter("lLocation", m(479) + ":"),                    /* Location */
                    new ReportParameter("lIncLocation", m(739) + ":"),                 /* Incident location */
                    new ReportParameter("lIncDateTime", m(1809) + ":"),                /* Time of accident */
                    new ReportParameter("lDate", m(2541)),                             /* Time of day */
                    new ReportParameter("lTime", m(3726)),                             /* Date */
                    new ReportParameter("IncTime", m(3726)),                           /* Time of day */
                    new ReportParameter("lCompany", m(4532) + ":"),                    /* Company */
                    new ReportParameter("lOrgLocation", m(425) + ":"),                 /* Areas/Departments */
                    new ReportParameter("lCostCenter", m(1405) + ":"),                 /* Costcenter */
                    new ReportParameter("lIncWorkTime", m(4536)),                      /* Incident work time: */
                    new ReportParameter("lIncDay", m(4535)),                           /* Day of incident */
                    new ReportParameter("lIncWorkingHousFrom", m(4533)),               /* time from */
                    new ReportParameter("lIncWorkingHousTo", m(4534)),                 /* time to */
                    new ReportParameter("lAffectedPerson", m(4537) + ":"),             /* Affected person: */
                    new ReportParameter("lLastFirstName", m(4539)),                    /* (Last name, First name) */
                    new ReportParameter("lBoss", m(4538)),                             /* Supervisor: */
                    new ReportParameter("lPersonNumber", m(1348) + ":"),               /* Employee number */
                    new ReportParameter("lPermanentStaff", m(4540)),                   /* Employee */
                    new ReportParameter("lContractorEmployees", m(4541)),              /* Contractor */
                    new ReportParameter("lVisitor", m(4542)),                          /* Other (e.g. Visitor) */
                    new ReportParameter("lVictimFunction", m(1835)),                   /* Employed as */
                    new ReportParameter("lNatureOfInjury", m(4543) + ":"),             /* Type of injury */
                    new ReportParameter("lWellknownBodyparts", m(4544)),               /* Injured body part: */
                    new ReportParameter("lWellknownBodypartsArm", m(4545)),            /* Arm */
                    new ReportParameter("lWellknownBodypartsInternalOrgans", m(2893)), /* Internal Organs */
                    new ReportParameter("lWellknownBodypartsFoot", m(4547)),           /* Foot */
                    new ReportParameter("lWellknownBodypartsHead", m(2890)),           /* Head */
                    new ReportParameter("lWellknownBodypartsEye", m(4548)),            /* Eye */
                    new ReportParameter("lWellknownBodypartsLeg", m(4549)),            /* Leg */
                    new ReportParameter("lWellknownBodypartsHand", m(4550)),           /* Hand */
                    new ReportParameter("lWellknownBodypartsBody", m(4551)),           /* Body */
                    new ReportParameter("lIncCause", m(4552) + ":"),                   /* Incident cause */
                    new ReportParameter("lTOPMultiTechnical", m(287)),                 /* Technical */
                    new ReportParameter("lTOPMultiPersonal", m(2945)),                 /* Behavior */
                    new ReportParameter("lTOPMultiOrganizational", m(3358)),           /* Organization */
                    new ReportParameter("lForecastLostDays", m(4553)),                 /* Forecast: */
                    new ReportParameter("lLostDays", m(4554)),                         /* (Lost days): */
                    new ReportParameter("lWitnessName", m(4555)),                      /* What is the name of the witness? */
                    new ReportParameter("lIsEyewitness", m(4556)),                     /* Is this person eye witness? */
                    new ReportParameter("lYes", m(146)),                               /* Yes */
                    new ReportParameter("lNo", m(147)),                                /* No */
                    new ReportParameter("lFirstAidDetails", m(4557)),                  /* Type of first aid: */
                    new ReportParameter("lFirstAidBy", m(4558) + ":"),                 /* First aid by */
                    new ReportParameter("lFirstAidByFirstResponder", m(4561)),         /* First Responder */
                    new ReportParameter("lFirstAidByParamedic", m(4562)),              /* Paramedic */
                    new ReportParameter("lFirstAidByAmbulance", m(4563)),              /* Ambulance */
                    new ReportParameter("lIncDoctor", m(4559)),                        /* Incident doctor: */
                    new ReportParameter("lAttendingDoctor", m(4560) + ":"),            /* Attending doctor: */
                    new ReportParameter("lClinicName", m(4564)),                       /* Name of the clinic: */
                    new ReportParameter("lCircumstances", m(550)),                     /* Accident course of events */
                    new ReportParameter("lMeasures", m(3842)),                         /* Measures */
                    new ReportParameter("lPPEDetails", m(4565)),                       /* What personal equipment was used by the injured person? */
                    new ReportParameter("lPPEHelmet", m(4566)),                        /* Helmet */
                    new ReportParameter("lPPEGoggles", m(4567)),                       /* Goggles */
                    new ReportParameter("lPPEFacewear", m(4134)),                      /* Face protection */
                    new ReportParameter("lPPEGloves", m(4021)),                        /* Gloves */
                    new ReportParameter("lPPEFootwear", m(4570)),                      /* Foot protection */
                    new ReportParameter("lPPEClothing", m(4571)),                      /* Clothing */
                    new ReportParameter("lPPEFallwear", m(4572)),                      /* Fall protection */
                    new ReportParameter("lPPERespiratory", m(4023)),                   /* added [pkosec 20140606] Respiratory */

                    /* removed [pkosec 20140818] MEA-2014-00368.6
                     * include [pkosec 20141014] MEA-2014-00440
                     * obsolete [dlatikay 20170528] MEA-2017-00157 */
                    new ReportParameter("lCreatedBy", m(2300) + ":"), /* Created by */
                    new ReportParameter("lOriginator", m(45)),        /* Originator */ /* [pkosec 20141117] MEA-2014-00499.2a */
                    new ReportParameter("lPhone", m(747)),            /* Telephone */
                    new ReportParameter("lSignature", m(1680)),       /* Signature */
                    new ReportParameter("lPPEWorn", m(3882)),         /* PPE */
                    /* logo */
                    new ReportParameter("imgLogo", Logo)
                });
                /* 3. render the report into the desired format */
                rpt.Refresh();
                RenderAsMsdbrpt(ResultFileBasename, ref chunk, ref mime, rpt);
                /* succeeded */
                return(true);
            }
            catch (Exception ex)
            {
                /* some error */
                OnBuiltinReportError(ex.Message, ex);
                return(false);
            }
        }
Example #36
0
        public ActionResult IndividualGradeSheet(int?examId, int?Roll, int?DeparmentId)
        {
            try
            {
                double totalGPA = 0;
                int    flag     = 1;

                var           getResult = DDL.GetSingleResult(Roll.Value, examId, DeparmentId, null);
                StudentInfo   student   = db.StudentInfoes.Where(t => t.RollNo == Roll).SingleOrDefault();
                FacultyInfo   facinfo   = db.FacultyInfoes.Where(t => t.Id == DeparmentId).SingleOrDefault();
                List <result> result    = new List <result>();

                // get total Subject from StudentInfoSubject Except optional = Y
                int StudentSubject = db.StudentInfoSubjects.Where(t => t.OptionalSubject != "Y" && t.StudentId == student.Id).Count();


                if (getResult != null)
                {
                    foreach (var item in getResult)
                    {
                        //get is this subjectId is Optional
                        grade _grade = new grade();
                        if (item.PassStatus == "F")
                        {
                            _grade.Grade      = "F";
                            _grade.GradePoint = 0;
                        }
                        else
                        {
                            _grade = getGrade(item.MarksObtain);
                        }

                        if (item.OptionalSubject == "Y")
                        {
                            totalGPA += (_grade.GradePoint - 2) > 0 ? (_grade.GradePoint - 2) : 0;
                        }
                        else
                        {
                            if (flag == 1 && _grade.GradePoint < 1)
                            {
                                flag = 0;
                            }
                            totalGPA += _grade.GradePoint;
                        }

                        result.Add(new result
                        {
                            SubjectName = item.SubjectName,
                            Grade       = _grade.Grade,
                            GradePoint  = Convert.ToString(_grade.GradePoint)
                        });
                    }

                    if (flag == 0)
                    {
                        totalGPA = 0;
                    }
                    else
                    {
                        totalGPA = totalGPA / StudentSubject;
                    }
                }

                string GPA = "";

                if (totalGPA < 1)
                {
                    GPA = "0 " + "(F)";
                }
                else if (totalGPA < 2)
                {
                    GPA = totalGPA.ToString("0.##") + " (D)";
                }
                else if (totalGPA < 3)
                {
                    GPA = totalGPA.ToString("0.##") + " (C)";
                }
                else if (totalGPA < 3.5)
                {
                    GPA = totalGPA.ToString("0.##") + " (B)";
                }
                else if (totalGPA < 4)
                {
                    GPA = totalGPA.ToString("0.##") + " (A-)";
                }
                else if (totalGPA < 5)
                {
                    GPA = totalGPA.ToString("0.##") + " (A)";
                }
                else if (totalGPA < 6)
                {
                    GPA = totalGPA.ToString("0.##") + " (A+)";
                }

                LocalReport      lr = new LocalReport();
                ReportDataSource rd = new ReportDataSource();

                lr.ReportPath = Server.MapPath("~/ReporFile/IndividualGradeSheet.rdlc");

                DataTable dtFDRStatement = ConvertToDataTable(result.ToList());
                rd.Name  = "SingleResult";
                rd.Value = dtFDRStatement;

                ReportParameter[] parameters = new ReportParameter[]
                {
                    new ReportParameter("Name", student.StudentName),
                    new ReportParameter("ClassRoll", Convert.ToString(student.RollNo)),
                    new ReportParameter("Faculty", Convert.ToString(facinfo.FacultyName)),
                    new ReportParameter("GPA", GPA)          // returns "0"  when decimalVar == 0
                };

                lr.SetParameters(parameters);
                lr.DataSources.Add(rd);

                string reportType = "PDF";
                string mimeType;
                string encoding;
                string fileNameExtension;

                string deviceInfo =
                    "<DeviceInfo>" +
                    "  <OutputFormat>PDF</OutputFormat>" +
                    "  <PageWidth>10.5in</PageWidth>" +
                    "  <PageHeight>11in</PageHeight>" +
                    "  <MarginTop>0.5in</MarginTop>" +
                    "  <MarginLeft>1in</MarginLeft>" +
                    "  <MarginRight>1in</MarginRight>" +
                    "  <MarginBottom>0.5in</MarginBottom>" +
                    "</DeviceInfo>";

                Warning[] warnings;
                string[]  streams;
                byte[]    renderedBytes;
                renderedBytes = lr.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);

                renderedBytes = lr.Render(reportType);
                string reportName = "IndGradeSheet-Roll" + Convert.ToString(student.RollNo) + ".pdf";
                return(File(renderedBytes, mimeType, reportName));
            }
            catch (Exception ex) {
                ViewBag.Error = ex.Message;
                return(View("Error"));
            }
        }
    protected void OnButtonCommand(object sender, CommandEventArgs e)
    {
        //Event handler for command button clicked
        //Change view to Viewer and reset to clear existing data
        Master.Viewer.Reset();

        //Get parameters for the query
        string _client         = Master.ClientNumber;
        string _division       = Master.Division;
        string _agentnumber    = Master.AgentNumber;
        string _subagentnumber = Master.SubAgentNumber;
        string _region         = Master.Region;
        string _district       = Master.District;
        string _store          = Master.StoreNumber;
        string _start          = Master.StartDate;
        string _end            = Master.EndDate;

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

        report.DisplayName          = REPORT_NAME;
        report.EnableExternalImages = true;
        EnterpriseGateway enterprise = new EnterpriseGateway();
        DataSet           ds         = enterprise.FillDataset(USP_REPORT, TBL_REPORT, new object[] { _client, _division, _agentnumber, _subagentnumber, _region, _district, _store, _start, _end });

        if (ds.Tables[TBL_REPORT].Rows.Count >= 0)
        {
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));

                //Set the report parameters for the report
                ReportParameter clientName     = new ReportParameter("ClientName", Master.ClientName);
                ReportParameter client         = new ReportParameter("ClientNumber", _client);
                ReportParameter division       = new ReportParameter("Division", _division);
                ReportParameter agentnumber    = new ReportParameter("AgentParentNumber", _agentnumber);
                ReportParameter subagentnumber = new ReportParameter("AgentNumber", _subagentnumber);
                ReportParameter region         = new ReportParameter("Region"); if (_region != null)
                {
                    region.Values.Add(_region);
                }
                ReportParameter district = new ReportParameter("District"); if (_district != null)
                {
                    district.Values.Add(_district);
                }
                ReportParameter store = new ReportParameter("StoreNumber"); if (_store != null)
                {
                    store.Values.Add(_store);
                }
                ReportParameter start = new ReportParameter("StartDate", _start);
                ReportParameter end   = new ReportParameter("EndDate", _end);
                report.SetParameters(new ReportParameter[] { client, division, agentnumber, subagentnumber, region, district, store, start, end, clientName });

                //Update report rendering with new data
                report.Refresh();
                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, 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=OnTimeDeliverySummaryByAgent.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.";
        }
    }
Example #38
0
    protected void OnButtonCommand(object sender, CommandEventArgs e)
    {
        //Event handler for view button clicked
        //Change view to Viewer and reset to clear existing data
        Master.Viewer.Reset();

        //Get parameters for the query
        string _start    = this.ddpPickups.FromDate.ToString("yyyy-MM-dd");
        string _end      = this.ddpPickups.ToDate.ToString("yyyy-MM-dd");
        string _terminal = this.cboTerminal.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[] { _terminal, _start, _end });

        if (ds.Tables[TBL_REPORT].Rows.Count >= 0)
        {
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(REPORT_SRC);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));

                //Set the report parameters for the report
                ReportParameter terminalID = new ReportParameter("TerminalID", _terminal);
                ReportParameter terminal   = new ReportParameter("TerminalName", this.cboTerminal.SelectedItem.Text);
                ReportParameter start      = new ReportParameter("StartDate", _start);
                ReportParameter end        = new ReportParameter("EndDate", _end);
                report.SetParameters(new ReportParameter[] { terminalID, start, end, terminal });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, REPORT_DS, "RGXSQLR.TSORT"));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(REPORT_DS, ds.Tables[TBL_REPORT]));
                report.Refresh();
                break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=StationTotals.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.";
        }
    }
Example #39
0
    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 _date         = DateTime.Parse(this.txtCloseDate.Text).ToString("yyyy-MM-dd");
            string _terminal     = this.cboTerminal.SelectedValue;
            string _terminalName = this.cboTerminal.SelectedItem.Text;
            string _rescanStatus = this.cboFilter.SelectedValue;

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = TITLE;
            report.EnableExternalImages = true;
            EnterpriseRGateway enterprise = new EnterpriseRGateway();
            DataSet            ds         = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _terminal, _date, _rescanStatus });
            if (ds.Tables[mTBLName] == null)
            {
                ds.Tables.Add(mTBLName);
            }
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(SOURCE);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));

                //Set the report parameters for the report
                ReportParameter terminalID   = new ReportParameter("TerminalID", _terminal);
                ReportParameter terminalName = new ReportParameter("Terminal", _terminalName);
                ReportParameter date         = new ReportParameter("ZoneCloseDate", _date);
                ReportParameter rescanStatus = new ReportParameter("ReScanStatus", _rescanStatus);
                report.SetParameters(new ReportParameter[] { terminalID, date, rescanStatus, terminalName });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh();
                break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=SortedBMC.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 #40
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();
            Session["PacSunDS"] = null;

            //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":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(SOURCE);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));

                //Set the report parameters for the report
                ReportParameter start = new ReportParameter("FromDate", _start);
                ReportParameter end   = new ReportParameter("ToDate", _end);
                report.SetParameters(new ReportParameter[] { start, end });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh(); break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=PacSunSummary.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); }
    }
        void _worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                List <object> genericlist = e.Argument as List <object>;

                var Lista  = (List <CodigosDat>)genericlist[0];
                var estilo = (string)genericlist[1];
                var bandI  = (bool)genericlist[2];

                BackgroundWorker worker = sender as BackgroundWorker;

                //
                foreach (var item in Lista)
                {
                    if (item.Estado.Equals("Generado") || bandI)
                    {
                        LocalReport rdlc = new LocalReport();

                        //rdlc.ReportPath = @"..\..\VentanasSec\ReportTicket.rdlc";
                        rdlc.ReportPath = @"C:\ReportTicket.rdlc";

                        Barcode b = new Barcode();

                        b.IncludeLabel  = true;
                        b.Alignment     = AlignmentPositions.CENTER;
                        b.LabelFont     = new Font(System.Drawing.FontFamily.GenericMonospace, 20 * Barcode.DotsPerPointAt96Dpi, System.Drawing.FontStyle.Regular, GraphicsUnit.Pixel);
                        b.LabelPosition = LabelPositions.BOTTOMCENTER;

                        var img = b.Encode(TYPE.CODE128, item.codigoBarra.Trim(), System.Drawing.Color.Black, System.Drawing.Color.White, 290, 90);

                        List <resultTicket> T = new List <resultTicket>();

                        using (MemoryStream ms = new MemoryStream())
                        {
                            img.Save(ms, ImageFormat.Png);

                            var objnewImg = new resultTicket
                            {
                                POrder      = item.POrder,
                                Size        = item.Size,
                                Estilo      = estilo,
                                Cantidad    = item.Cantidad,
                                codigoBarra = item.codigoBarra,
                                Img         = ms.ToArray()
                            };

                            T.Add(objnewImg);

                            ms.Dispose();
                        }


                        rdlc.DataSources.Add(new ReportDataSource("DataSet2", T));

                        using (ImprimirTicket imp = new ImprimirTicket())
                        {
                            imp.Imprime(rdlc);
                        }

                        Task.Run(() => { return(ActualizarEstado(item.codigoBarra)); });
                    }
                }



                #region codigo funcional dejado en comentario debido a que bartender no se puede instalar en algunas maquinas

                /*  var lb = @"D:\ticketUni.btw";
                 * using (Engine engine = new Engine(true))
                 * {
                 *    engine.Start();
                 *
                 *    foreach (var item in Lista)
                 *    {
                 *        if (item.Estado.Equals("Generado") || bandI)
                 *        {
                 *
                 *            LabelFormatDocument btformate = engine.Documents.Open(lb);
                 *            btformate.SubStrings["lblcorte"].Value = item.POrder.Trim();
                 *            btformate.SubStrings["lbltalla"].Value = item.Size.TrimEnd();
                 *            btformate.SubStrings["lblcodigo"].Value = item.codigoBarra.TrimEnd();
                 *            btformate.SubStrings["lblestilo"].Value = estilo.TrimEnd();
                 *            btformate.SubStrings["lblcantidad"].Value = item.Cantidad.ToString();
                 *
                 *            var resp = btformate.Print();
                 *
                 *
                 *
                 *            Task.Run(() => { return ActualizarEstado(item.codigoBarra); });
                 *        }
                 *    }
                 *
                 *
                 *    //engine.Start();
                 *    //  btformate.PrinterCodeTemplate.Performance.AllowSerialization = false;
                 *    // btformate.ExportImageToClipboard(Seagull.BarTender.Print.ColorDepth.ColorDepth256, new Resolution(200));
                 *    //  btformat.Close(BarTender.BtSaveOptions.btDoNotSaveChanges);
                 *    engine.Stop();
                 * } */
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //  throw;
            }
        }
Example #42
0
    protected void Button8_Click(object sender, EventArgs e)
    {
        // select appropriate contenttype, while binary transfer it identifies filetype
        string contentType = string.Empty;

        if (DropDownList2.SelectedValue.Equals(".pdf"))
        {
            contentType = "application/pdf";
        }
        if (DropDownList2.SelectedValue.Equals(".doc"))
        {
            contentType = "application/ms-word";
        }
        if (DropDownList2.SelectedValue.Equals(".xls"))
        {
            contentType = "application/xls";
        }

        DataTable dsData = new DataTable();

        DataSet        ds = null;
        SqlDataAdapter da = null;



        try
        {
            string constring = ConfigurationManager.AppSettings["connection"];
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand("supplier_balance", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@No", DropDownList1.SelectedItem.Text);

                    da = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    con.Open();
                    da.Fill(ds);
                    con.Close();
                }
            }
        }
        catch
        {
            throw;
        }



        dsData = ds.Tables[0];

        string FileName = "File_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + DropDownList2.SelectedValue;
        string extension;
        string encoding;
        string mimeType;

        string[]  streams;
        Warning[] warnings;

        LocalReport report = new LocalReport();

        report.ReportPath = Server.MapPath("~/Admin/Report3.rdlc");
        ReportDataSource rds = new ReportDataSource();

        rds.Name  = "DataSet1";//This refers to the dataset name in the RDLC file
        rds.Value = dsData;
        report.DataSources.Add(rds);

        Byte[] mybytes = report.Render(DropDownList2.SelectedItem.Text, null,
                                       out extension, out encoding,
                                       out mimeType, out streams, out warnings); //for exporting to PDF
        using (FileStream fs = File.Create(Server.MapPath("~/img/") + FileName))
        {
            fs.Write(mybytes, 0, mybytes.Length);
        }

        Response.ClearHeaders();
        Response.ClearContent();
        Response.Buffer = true;
        Response.Clear();
        Response.ContentType = contentType;
        Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
        Response.WriteFile(Server.MapPath("~/img/" + FileName));
        Response.Flush();
        Response.Close();
        Response.End();
    }
 // Exporta el report a un archivo .emf y lo imprime
 public void Imprime(LocalReport rdlc)
 {
     Export(rdlc);
     Print();
 }
    public static void Print(this LocalReport report, PageSettings pageSettings)
    {
        string deviceInfo =
            $@"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>{pageSettings.PaperSize.Width * 100}in</PageWidth>
                <PageHeight>{pageSettings.PaperSize.Height * 100}in</PageHeight>
                <MarginTop>{pageSettings.Margins.Top * 100}in</MarginTop>
                <MarginLeft>{pageSettings.Margins.Left * 100}in</MarginLeft>
                <MarginRight>{pageSettings.Margins.Right * 100}in</MarginRight>
                <MarginBottom>{pageSettings.Margins.Bottom * 100}in</MarginBottom>
            </DeviceInfo>";

        Warning[] warnings;
        var       streams          = new List <Stream>();
        var       currentPageIndex = 0;

        report.Render("Image", deviceInfo,
                      (name, fileNameExtension, encoding, mimeType, willSeek) =>
        {
            var stream = new MemoryStream();
            streams.Add(stream);
            return(stream);
        }, out warnings);

        foreach (Stream stream in streams)
        {
            stream.Position = 0;
        }

        if (streams == null || streams.Count == 0)
        {
            throw new Exception("Error: no stream to print.");
        }

        var printDocument = new PrintDocument();

        printDocument.DefaultPageSettings = pageSettings;
        if (!printDocument.PrinterSettings.IsValid)
        {
            throw new Exception("Error: cannot find the default printer.");
        }
        else
        {
            printDocument.PrintPage += (sender, e) =>
            {
                Metafile  pageImage    = new Metafile(streams[currentPageIndex]);
                Rectangle adjustedRect = new Rectangle(
                    e.PageBounds.Left - (int)e.PageSettings.HardMarginX,
                    e.PageBounds.Top - (int)e.PageSettings.HardMarginY,
                    e.PageBounds.Width,
                    e.PageBounds.Height);
                e.Graphics.FillRectangle(Brushes.White, adjustedRect);
                e.Graphics.DrawImage(pageImage, adjustedRect);
                currentPageIndex++;
                e.HasMorePages = (currentPageIndex < streams.Count);
                e.Graphics.DrawRectangle(Pens.Red, adjustedRect);
            };
            printDocument.EndPrint += (Sender, e) =>
            {
                if (streams != null)
                {
                    foreach (Stream stream in streams)
                    {
                        stream.Close();
                    }
                    streams = null;
                }
            };
            printDocument.Print();
        }
    }
        private void ProductionHouseToSellsPointReport(int SellsPointId, int ProductionHouseStoreId, List <VM_PHtoSPProductTransfer> productList)
        {
            var newProductList = new List <VM_PHtoSPProductTransfer>();
            int serial         = 0;

            foreach (var product in productList)
            {
                VM_PHtoSPProductTransfer newProduct = new VM_PHtoSPProductTransfer();
                newProduct.SL          = ++serial;
                newProduct.ProductName = unitOfWork.ProductRepository.GetByID(product.ProductId).ProductName;;
                newProduct.Quantity    = product.Quantity;
                newProduct.Unit        = product.Unit;
                newProduct.ProductionHouseStoreName =
                    unitOfWork.StoreRepository.GetByID(ProductionHouseStoreId).store_name;

                newProduct.SellsPointName = unitOfWork.StoreRepository.GetByID(SellsPointId).store_name;
                newProductList.Add(newProduct);
            }

            int    restaurantId      = Int32.Parse(SessionManger.RestaurantOfLoggedInUser(Session).ToString());;
            string restaurantName    = unitOfWork.RestaurantRepository.GetByID(restaurantId).Name;
            string restaurantAddress = unitOfWork.RestaurantRepository.GetByID(restaurantId).Address;

            LocalReport localReport = new LocalReport();

            localReport.ReportPath = Server.MapPath("~/Reports/ProductionHouseToSellPointReport.rdlc");
            localReport.SetParameters(new ReportParameter("RestaurantName", restaurantName));
            localReport.SetParameters(new ReportParameter("RestaurantAddress", restaurantAddress));
            ReportDataSource reportDataSource = new ReportDataSource("ProductionHouseToSellPointReport", newProductList);

            localReport.DataSources.Add(reportDataSource);
            string reportType = "pdf";
            string mimeType;
            string encoding;
            string fileNameExtension;
            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>PDF</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>0in</MarginLeft>" +
                "  <MarginRight>0in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";

            Warning[] warnings;
            string[]  streams;
            byte[]    renderedBytes;



            //Render the report
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            //rename file
            var fileName = RenameReportFile(ProductionHouseStoreId, SellsPointId, DateTime.Now, "Pro", "Sell");

            var path = System.IO.Path.Combine(Server.MapPath("~/pdfReport"));


            var saveAs = path + "\\" + fileName + ".pdf";

            var idx = 0;

            while (System.IO.File.Exists(saveAs))
            {
                idx++;
                saveAs = string.Format("{0}.{1}.pdf", Path.Combine(path, fileName), idx);
            }

            using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
            {
                stream.Write(renderedBytes, 0, renderedBytes.Length);
                stream.Close();
            }
            var report = new tblChalanReport();

            report.FromStore  = Convert.ToString(ProductionHouseStoreId);
            report.ToStore    = Convert.ToString(SellsPointId);
            report.Date       = DateTime.Now.Date;
            report.ReportName = fileName;

            SaveToDatabase(report);

            localReport.Dispose();
        }
    protected void rpt_cuadro()
    {
        DataTable        dsCustomers = GetData();
        ReportDataSource datasource  = new ReportDataSource("DataSet1", dsCustomers);

        if (dsCustomers.Rows.Count > 0)
        {
            ReportViewer1.LocalReport.DataSources.Clear();



            this.ReportViewer1.LocalReport.Refresh();
            this.ReportViewer1.Reset();


            this.ReportViewer1.LocalReport.EnableExternalImages = true;
            this.ReportViewer1.ProcessingMode = ProcessingMode.Local;
            LocalReport rep = ReportViewer1.LocalReport;
            rep.ReportPath = Server.MapPath("~/OPERACIONES/Reportes/RptStatusReqOR.rdlc");
            //rep.SetParameters(param);

            //this.ReportViewer1.LocalReport.RefreshReport();


            //ReportViewer1.LocalReport.EnableExternalImages = true;
            //string imagePath = new Uri(Server.MapPath(FolderFirmas + "44085236.jpg")).AbsoluteUri;
            //ReportParameter parameter = new ReportParameter("Path", imagePath);
            //ReportViewer1.LocalReport.SetParameters(parameter);



            ReportViewer1.LocalReport.Refresh();
            ReportViewer1.LocalReport.DataSources.Add(datasource);

            Warning[] warnings;
            string[]  streamIds;
            string    mimeType = string.Empty;
            string    encoding = string.Empty;
            string    extension = string.Empty;
            DataSet   dsGrpSum, dsActPlan, dsProfitDetails,
                      dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;

            byte[] bytes = ReportViewer1.LocalReport.Render("EXCEL", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            if (CENTRO_COSTO == string.Empty)
            {
                CENTRO_COSTO = "REQUERIMIENTOS_SAT_SIN_OR";
            }
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + CENTRO_COSTO + "." + extension);
            Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
            Response.Flush();                                    // send it to the client to download
            Response.End();
        }
        else
        {
            ReportViewer1.LocalReport.DataSources.Clear();
        }
    }
Example #47
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 _blNumber     = "";
            string _terminalCode = this.cboTerminal.SelectedValue;

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = this.mTitle;
            report.EnableExternalImages = true;
            EnterpriseGateway enterprise = new EnterpriseGateway();
            DataKey           dataKey    = (DataKey)this.grdFreight.DataKeys[this.grdFreight.SelectedRow.RowIndex];
            _blNumber = dataKey["BLNumber"].ToString();
            DataSet ds = enterprise.FillDataset(this.mUSPName, mTBLName, new object[] { _blNumber, _terminalCode });
            if (ds.Tables[mTBLName] == null)
            {
                ds.Tables.Add(mTBLName);
            }
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(this.mSource);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));

                //Set the report parameters for the report
                ReportParameter blNumber     = new ReportParameter("BLNumber", _blNumber);
                ReportParameter terminalCode = new ReportParameter("TerminalCode", _terminalCode);
                report.SetParameters(new ReportParameter[] { blNumber, terminalCode });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh(); break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=InductedCartons.xls");
                Response.ContentType = "application/vnd.ms-excel";      //application/octet-stream";
                System.IO.StringWriter       sw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
                DataGrid dg = new DataGrid();
                dg.DataSource = ds.Tables[mTBLName];
                dg.DataBind();
                dg.RenderControl(hw);
                Response.Write(sw.ToString());
                Response.End();
                break;
            }
        }
        catch (Exception ex) { Master.ReportError(ex); }
    }
    protected void GenerateExcel()
    {
        try
        {
            LocalReport      LocalReport = new LocalReport();
            ReportDataSource reportDS    = new ReportDataSource("SMHRDataSet_RPT_GENERATEATTENDENCE", BLL.ExecuteQuery("EXEC RPT_GENERATEATTENDENCE  @BUSSINESSUNITID='" + Convert.ToString(rcmb_BusinessUnitID.SelectedItem.Value) + "', @PERIODID='" + Convert.ToString(rcmb_PeriodDetails.SelectedItem.Value) + "'"));
            LocalReport.ReportPath = @"Report_rdlc\Gen_Attendance.rdlc";
            LocalReport.DataSources.Clear();
            LocalReport.DataSources.Add(reportDS);
            LocalReport.Refresh();


            string reportType = "Excel";
            string mimeType;
            string encoding;
            string fileNameExtension;


            string    deviceInfo = "<DeviceInfo>" + " <OutputFormat>Excel</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.3in</MarginTop>" + " <MarginLeft>0.0in</MarginLeft>" + " <MarginRight>0.0in</MarginRight>" + " <MarginBottom>0.3in</MarginBottom>" + "</DeviceInfo>";
            Warning[] warnings;
            string[]  streams;
            byte[]    renderedBytes;//Render the report

            renderedBytes = LocalReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);

            string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls"; // Server.MapPath("~/download") + "\\Attendance.xls";

            FileStream   fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(renderedBytes);
            bw.Close();

            FileInfo fi           = new FileInfo(fileName);
            String   tempFileCopy = (Path.Combine(Path.GetTempPath(), "copy_" + Guid.NewGuid().ToString()));
            fi.CopyTo(tempFileCopy, true);

            object      misValue  = System.Reflection.Missing.Value;
            Application _excelApp = new Application();
            Workbook    workBook  = _excelApp.Workbooks.Open(tempFileCopy,
                                                             0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);

            Worksheet sheet = (Worksheet)workBook.Sheets[1];
            sheet.get_Range("A1", "Z1").UnMerge();


            sheet.get_Range("a1", misValue).FormulaR1C1 = "BUID";
            sheet.get_Range("b1", misValue).FormulaR1C1 = "S. No";
            sheet.get_Range("c1", misValue).FormulaR1C1 = "EMP_ID";
            sheet.get_Range("d1", misValue).FormulaR1C1 = "Employee Code";
            sheet.get_Range("e1", misValue).FormulaR1C1 = "Employee Name";

            sheet.get_Range("a1", misValue).EntireColumn.UseStandardWidth = 0;

            //      sheet.get_Range("a1", misValue).Hidden = true;

            //   sheet.get_Range("a1", "a10").Hidden = true;



            Range a1 = sheet.get_Range("A1", Type.Missing);
            a1.EntireRow.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing);



            string downAddress = sheet.UsedRange.get_Address(false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
            Range  excelRange  = sheet.get_Range("e10", downAddress.Split(new char[] { ':' })[1]);

            excelRange.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, "=$A$2:$A$7", Type.Missing);
            excelRange.Validation.IgnoreBlank  = true;
            excelRange.Validation.InputTitle   = "Please Enter Any of Following";
            excelRange.Validation.ErrorTitle   = "Invalid Information";
            excelRange.Validation.InputMessage = " P – Present \nW – Weekly Off \nA – Absent (No Leave)\n O – Loss of Pay \n H – Holiday \n T – Travel";
            excelRange.Validation.ErrorMessage = "Please select a Valid Information";
            excelRange.Validation.ShowInput    = true;
            excelRange.Validation.ShowError    = true;
            excelRange.Locked = false;

            sheet.Protect("dhanush", true, true, true, true, true, true, true, false, false, true, false, false, true, true, true);

            String _tempFileCopy = (Path.Combine(Path.GetTempPath(), "copy_" + Guid.NewGuid().ToString() + ".xls"));

            workBook.Protect("", true, false);

            workBook.SaveAs(_tempFileCopy, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            workBook.Close(true, Type.Missing, Type.Missing);
            _excelApp.Quit();

            releaseObject(_excelApp);
            releaseObject(workBook);
            releaseObject(sheet);

            Response.Redirect("../Reports/DownloadHandler.ashx?fileName=" + rcmb_BusinessUnitID.SelectedItem.Text + "__" + rcmb_PeriodDetails.SelectedItem.Text + ".xls" + "&filePath=" + _tempFileCopy, false);
        }
        catch (Exception ex)
        {
            SMHR.BLL.Error_Log(Session["USER_ID"].ToString(), ex.TargetSite.ToString(), ex.Message.Replace("'", "''"), "frm_Attendance", ex.StackTrace, DateTime.Now);
            Response.Redirect("~/Frm_ErrorPage.aspx");
        }
    }
        public ActionResult Comprobante(int?id)
        {
            try
            {
                if (id == null)
                {
                    TempData["typemessage"] = "2";
                    TempData["message"]     = "Verifique sus datos";
                    return(View("Index"));
                }

                Reporte_Datos R = new Reporte_Datos();
                List <ComprobantePagosModels> ListaComprobantePagosDetalles          = new List <ComprobantePagosModels>();
                List <VentaGeneralComprobanteDetalleModels> ListaComprobanteDetalles = new List <VentaGeneralComprobanteDetalleModels>();

                _Comprobante_Datos        oDatosComprobante  = new _Comprobante_Datos();
                _VentaGeneral_Datos       oDatosVentaGeneral = new _VentaGeneral_Datos();
                ComprobanteCabeceraModels Cabecera           = new ComprobanteCabeceraModels();

                Cabecera = oDatosComprobante.Comprobante_spCSLDB_get_Cabecera(2, id.Value.ToString(), conexion);
                ListaComprobantePagosDetalles = oDatosComprobante.Comprobante_spCIDDB_get_detallesPagos(2, id.Value.ToString(), conexion);
                ListaComprobanteDetalles      = oDatosVentaGeneral.VentaGeneral_spCIDDB_Comprobante_get_detalles(conexion, id.Value);

                LocalReport Rtp = new LocalReport();
                Rtp.EnableExternalImages = true;
                Rtp.DataSources.Clear();
                string path = Path.Combine(Server.MapPath("~/Formatos"), "ComprobanteVentaGeneral.rdlc");
                if (System.IO.File.Exists(path))
                {
                    Rtp.ReportPath = path;
                }
                else
                {
                    return(RedirectToAction("Index"));
                }
                ReportParameter[] Parametros = new ReportParameter[11];
                Parametros[0]  = new ReportParameter("urlLogo", Cabecera.LogoEmpresa);
                Parametros[1]  = new ReportParameter("nombreEmpresa", Cabecera.NombreEmpresa);
                Parametros[2]  = new ReportParameter("rubroEmpresa", Cabecera.RubroEmpresa);
                Parametros[3]  = new ReportParameter("direccionEmpresa", Cabecera.DireccionEmpresa);
                Parametros[4]  = new ReportParameter("folio", Cabecera.Folio);
                Parametros[5]  = new ReportParameter("nombreCliente", Cabecera.NombreCliente);
                Parametros[6]  = new ReportParameter("telefonoCliente", Cabecera.TelefonoCliente);
                Parametros[7]  = new ReportParameter("rfcCliente", Cabecera.RFCCliente);
                Parametros[8]  = new ReportParameter("diaImpresion", Cabecera.DiaImpresion);
                Parametros[9]  = new ReportParameter("mesImpresion", Cabecera.MesImpresion);
                Parametros[10] = new ReportParameter("annoImpresion", Cabecera.AnnoImpresion);

                Rtp.SetParameters(Parametros);
                Rtp.DataSources.Add(new ReportDataSource("ListaDetalles", ListaComprobanteDetalles));
                Rtp.DataSources.Add(new ReportDataSource("ListaDetallesCobros", ListaComprobantePagosDetalles));

                string reportType = "PDF";
                string mimeType;
                string encoding;
                string fileNameExtension;

                string deviceInfo = "<DeviceInfo>" +
                                    "  <OutputFormat>Comprobante</OutputFormat>" +
                                    "</DeviceInfo>";

                Warning[] warnings;
                string[]  streams;
                byte[]    renderedBytes;

                renderedBytes = Rtp.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);

                return(File(renderedBytes, mimeType));
            }
            catch (Exception ex)
            {
                string Mensaje = ex.Message.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
                TempData["typemessage"] = "2";
                TempData["message"]     = "No se puede cargar la vista, error: " + Mensaje;
                return(View("Index"));
            }
        }
        public ActionResult VotantesReport(int?boss, int?link, int?coor, int?leader, int?type)
        {
            var inc = new object();

            if (boss > 0)
            {
                int value = Convert.ToInt32(boss);
                inc = (from v in db.Voters
                       join r in db.Refers on v.ReferId equals r.ReferId
                       where r.UserId == value && r.ReferType == 1
                       orderby v.userId, v.FirstName
                       select new { v.FirstName, v.LastName, v.Document, v.DateBorn, v.Address, v.UserName, v.Phone, v.CommuneId, v.Barrio, v.Profesion, v.VotingPlaceId, v.userId, referido = r.FullName }).ToList();
            }
            if (link > 0)
            {
                int value = Convert.ToInt32(link);
                inc = (from v in db.Voters
                       join r in db.Refers on v.ReferId equals r.ReferId
                       where r.UserId == value && r.ReferType == 2
                       orderby v.userId, v.FirstName
                       select new { v.FirstName, v.LastName, v.Document, v.DateBorn, v.Address, v.UserName, v.Phone, v.CommuneId, v.Barrio, v.Profesion, v.VotingPlaceId, v.userId, referido = r.FullName }).ToList();
            }
            if (coor > 0)
            {
                int value = Convert.ToInt32(coor);
                inc = (from v in db.Voters
                       join r in db.Refers on v.ReferId equals r.ReferId
                       where r.UserId == value && r.ReferType == 3
                       orderby v.userId, v.FirstName
                       select new { v.FirstName, v.LastName, v.Document, v.DateBorn, v.Address, v.UserName, v.Phone, v.CommuneId, v.Barrio, v.Profesion, v.VotingPlaceId, v.userId, referido = r.FullName }).ToList();
            }
            if (leader > 0)
            {
                int value = Convert.ToInt32(leader);
                inc = (from v in db.Voters
                       join r in db.Refers on v.ReferId equals r.ReferId
                       where r.UserId == value && r.ReferType == 4
                       orderby v.userId, v.FirstName
                       select new { v.FirstName, v.LastName, v.Document, v.DateBorn, v.Address, v.UserName, v.Phone, v.CommuneId, v.Barrio, v.Profesion, v.VotingPlaceId, v.userId, referido = r.FullName }).ToList();
            }


            string path = Path.Combine(Server.MapPath("~/Reports"), "VotersList.rdlc");

            LocalReport lr = new LocalReport();

            lr.EnableExternalImages = true;
            if (System.IO.File.Exists(path))
            {
                lr.ReportPath = path;
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }

            var company = db.Companies.Find(1);

            string fullname = string.Empty;

            if (company.Logo == null)
            {
                fullname = AppDomain.CurrentDomain.BaseDirectory + "Content/CompanyLogo/NoLogoCompany.png";
            }
            else
            {
                fullname = AppDomain.CurrentDomain.BaseDirectory + company.Logo.Substring(2);
            }
            ReportParameter paramLogo = new ReportParameter();

            paramLogo.Name = "Path";
            paramLogo.Values.Add(fullname);
            lr.SetParameters(paramLogo);

            ReportDataSource rd = new ReportDataSource("DataSet1", inc);

            lr.DataSources.Add(rd);
            string reportType = "";

            if (type == 1)
            {
                reportType = "EXCELOPENXML";
            }
            else
            {
                reportType = "PDF";
            }
            string mimeType;
            string encoding;
            string fileNameExtension;



            string deviceInfo =

                "<DeviceInfo>" +
                "  <OutputFormat>" + "ListadoVotantes" + "</OutputFormat>" +
                "  <PageWidth>11in</PageWidth>" +
                "  <PageHeight>8.5in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";

            Warning[] warnings;
            string[]  streams;
            byte[]    renderedBytes;

            renderedBytes = lr.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            return(File(renderedBytes, mimeType));
        }
        public ActionResult RedReport(string document, int?type)
        {
            var          inc           = new object();
            double       newDocument   = Convert.ToDouble(document);
            List <Voter> listaVotantes = new List <Voter>();

            //Busco el votante
            var voter = db.Voters.Where(v => v.Document == newDocument).FirstOrDefault();

            if (voter != null)
            {
                listaVotantes.Add(voter);

                var Boss        = db.Bosses.Where(b => b.Document == voter.Document).FirstOrDefault();
                var Link        = db.Links.Where(b => b.Document == voter.Document).FirstOrDefault();
                var Coordinator = db.Coordinators.Where(b => b.Document == voter.Document).FirstOrDefault();
                var Leader      = db.Leaders.Where(b => b.Document == voter.Document).FirstOrDefault();
                int cont1       = 0;
                int cont2       = 0;
                int cont3       = 0;
                int cont4       = 0;

                if (Boss != null)//JEFE
                {
                    var referboss = db.Refers.Where(r => r.ReferType == 1 && r.UserId == Boss.BossId).FirstOrDefault();
                    if (referboss != null)
                    {
                        cont1 = Boss.BossId;
                        //0 - Votantes del Jefe
                        var voterBoss = db.Voters.Where(v => v.ReferId == referboss.ReferId).ToList();
                        foreach (var vb in voterBoss)
                        {
                            listaVotantes.Add(vb);
                        }

                        //1 - Enlaces del jefe
                        var linksToCount = db.Links.Where(l => l.BossId == Boss.BossId).ToList();
                        //recorro los enlaces
                        foreach (var item in linksToCount)
                        {
                            //BUSCO EL REFERIDO DE CADA ENLACE
                            var referItem = db.Refers.Where(r => r.ReferType == 2 && r.UserId == item.LinkId).FirstOrDefault();
                            if (referItem != null)
                            {
                                //2 - Coordinadores del enlace
                                var linkCoorsCount = db.Coordinators.Where(c => c.ReferId == referItem.ReferId).ToList();
                                foreach (var linkCoorItem in linkCoorsCount)
                                {
                                    //BUSCO EL REFERIDO DE CADA COORDINADOR
                                    var linkCoorItemRefer = db.Refers.Where(r => r.ReferType == 3 && r.UserId == linkCoorItem.CoordinatorId).FirstOrDefault();
                                    if (linkCoorItemRefer != null)
                                    {
                                        //3 - Lideres del coordinador
                                        var linkCoorLeadersCount = db.Leaders.Where(c => c.ReferId == linkCoorItemRefer.ReferId).ToList();
                                        foreach (var linkCoorLeadersItem in linkCoorLeadersCount)
                                        {
                                            //busco los referidos de cada lider
                                            var linkCoorLeadersRefer = db.Refers.Where(r => r.ReferType == 4 && r.UserId == linkCoorLeadersItem.LeaderId).FirstOrDefault();
                                            if (linkCoorLeadersRefer != null)
                                            {
                                                //4 - votantes de cada lider
                                                var voterLeaders = db.Voters.Where(v => v.ReferId == linkCoorLeadersRefer.ReferId).ToList();
                                                foreach (var vl in voterLeaders)
                                                {
                                                    listaVotantes.Add(vl);
                                                }
                                            }
                                        }
                                        //votantes de cada coordinador
                                        var votersCoor = db.Voters.Where(v => v.ReferId == linkCoorItemRefer.ReferId).ToList();
                                        foreach (var vc in votersCoor)
                                        {
                                            listaVotantes.Add(vc);
                                        }
                                    }
                                }
                                //lideres del enlace
                                var linkLeadersCount = db.Leaders.Where(c => c.ReferId == referItem.ReferId).ToList();
                                foreach (var linkLeaderItem in linkLeadersCount)
                                {
                                    var linkLeaderRefer = db.Refers.Where(r => r.ReferType == 4 && r.UserId == linkLeaderItem.LeaderId).FirstOrDefault();
                                    if (linkLeaderRefer != null)
                                    {
                                        //votantes del lider
                                        var voterlider = db.Voters.Where(v => v.ReferId == linkLeaderRefer.ReferId).ToList();
                                        foreach (var voterL in voterlider)
                                        {
                                            listaVotantes.Add(voterL);
                                        }
                                    }
                                }
                                //votantes de cada enlace
                                var voterlink = db.Voters.Where(v => v.ReferId == referItem.ReferId).ToList();
                                foreach (var vlink in voterlink)
                                {
                                    listaVotantes.Add(vlink);
                                }
                            }
                        }
                        //coordinadores del jefe
                        var coorToCount = db.Coordinators.Where(l => l.ReferId == referboss.ReferId).ToList();
                        foreach (var item in coorToCount)
                        {
                            var itemRefer = db.Refers.Where(r => r.ReferType == 3 && r.UserId == item.CoordinatorId).FirstOrDefault();
                            if (itemRefer != null)
                            {
                                var coorLeadersCount = db.Leaders.Where(c => c.ReferId == itemRefer.ReferId).ToList();
                                foreach (var coorLeader in coorLeadersCount)
                                {
                                    //lideres de cada coordinador
                                    var coorLeaderRefer = db.Refers.Where(r => r.ReferType == 4 && r.UserId == coorLeader.LeaderId).FirstOrDefault();
                                    if (coorLeaderRefer != null)
                                    {
                                        //votantes de cada lider
                                        var voterleaders = db.Voters.Where(v => v.ReferId == coorLeaderRefer.ReferId).ToList();
                                        foreach (var vl in voterleaders)
                                        {
                                            listaVotantes.Add(vl);
                                        }
                                    }
                                }
                                //votantes de cada coordinador
                                var votercoor = db.Voters.Where(v => v.ReferId == itemRefer.ReferId).ToList();
                                foreach (var vc in votercoor)
                                {
                                    listaVotantes.Add(vc);
                                }
                            }
                        }
                        //lideres del jefe
                        var leaderToCount = db.Leaders.Where(l => l.ReferId == referboss.ReferId).ToList();
                        foreach (var item in leaderToCount)
                        {
                            var itemleaderRefer = db.Refers.Where(r => r.ReferType == 4 && r.UserId == item.LeaderId).FirstOrDefault();
                            if (itemleaderRefer != null)
                            {
                                //votantes de cada lider
                                var voterleader = db.Voters.Where(v => v.ReferId == itemleaderRefer.ReferId).ToList();
                                foreach (var vl in voterleader)
                                {
                                    listaVotantes.Add(vl);
                                }
                            }
                        }
                    }
                }

                if (Link != null)//ENLACE
                {
                    var referlink = db.Refers.Where(r => r.ReferType == 2 && r.UserId == Link.LinkId).FirstOrDefault();
                    if (referlink != null)
                    {
                        cont2 = Link.LinkId;
                        var voterLinks = db.Voters.Where(v => v.ReferId == referlink.ReferId).ToList();
                        foreach (var vl in voterLinks)
                        {
                            listaVotantes.Add(vl);
                        }


                        //coordinadores
                        var coorToCount = db.Coordinators.Where(l => l.ReferId == referlink.ReferId).ToList();
                        //obtengo los votantes de cada coordinador
                        foreach (var item in coorToCount)
                        {
                            var referItem = db.Refers.Where(r => r.ReferType == 3 && r.UserId == item.CoordinatorId).FirstOrDefault();
                            if (referItem != null)
                            {
                                var coorLeadersCount = db.Leaders.Where(c => c.ReferId == referItem.ReferId).ToList();
                                foreach (var coorLeader in coorLeadersCount)
                                {
                                    var coorLeaderRefer = db.Refers.Where(r => r.ReferType == 4 && r.UserId == coorLeader.LeaderId).FirstOrDefault();
                                    if (coorLeaderRefer != null)
                                    {
                                        var voterleaders = db.Voters.Where(v => v.ReferId == coorLeaderRefer.ReferId).ToList();
                                        foreach (var vl in voterleaders)
                                        {
                                            listaVotantes.Add(vl);
                                        }
                                    }
                                }
                                var votercoors = db.Voters.Where(v => v.ReferId == referItem.ReferId).ToList();
                                foreach (var vc in votercoors)
                                {
                                    listaVotantes.Add(vc);
                                }
                            }
                        }
                        //lideres
                        var leaderToCount = db.Leaders.Where(l => l.ReferId == referlink.ReferId).ToList();
                        //obtengo los votantes de cada lider
                        foreach (var item in leaderToCount)
                        {
                            var itemRefer = db.Refers.Where(r => r.ReferType == 4 && r.UserId == item.LeaderId).FirstOrDefault();
                            if (itemRefer != null)
                            {
                                var voterleads = db.Voters.Where(v => v.ReferId == itemRefer.ReferId).ToList();
                                foreach (var vli in voterleads)
                                {
                                    listaVotantes.Add(vli);
                                }
                            }
                        }
                    }
                }
                if (Coordinator != null)//COORDINADOR
                {
                    var refercoor = db.Refers.Where(r => r.ReferType == 3 && r.UserId == Coordinator.CoordinatorId).FirstOrDefault();
                    if (refercoor != null)
                    {
                        cont3 = Coordinator.CoordinatorId;
                        var voterCoors = db.Voters.Where(v => v.ReferId == refercoor.ReferId).ToList();
                        foreach (var vco in voterCoors)
                        {
                            listaVotantes.Add(vco);
                        }


                        //lideres
                        var leaderToCount = db.Leaders.Where(l => l.ReferId == refercoor.ReferId).ToList();
                        //obtengo los votantes de cada lider
                        foreach (var item in leaderToCount)
                        {
                            var itemReferl = db.Refers.Where(r => r.ReferType == 4 && r.UserId == item.LeaderId).FirstOrDefault();
                            if (itemReferl != null)
                            {
                                var vleaders = db.Voters.Where(v => v.ReferId == itemReferl.ReferId).ToList();
                                foreach (var vli in vleaders)
                                {
                                    listaVotantes.Add(vli);
                                }
                            }
                        }
                    }
                }
                if (Leader != null)//LIDER
                {
                    var referleader = db.Refers.Where(r => r.ReferType == 4 && r.UserId == Leader.LeaderId).FirstOrDefault();
                    if (referleader != null)
                    {
                        cont4 = Leader.LeaderId;
                        var vLeader = db.Voters.Where(v => v.ReferId == referleader.ReferId).ToList();
                        foreach (var vlead in vLeader)
                        {
                            listaVotantes.Add(vlead);
                        }
                        ViewBag.asociacion   = Leader.Associacion;
                        ViewBag.lugarTrabajo = Leader.WorkPlaceId;
                        ViewBag.perfil       = "Líder";
                        //sumo los votantes del lider
                    }
                }
            }


            string path = Path.Combine(Server.MapPath("~/Reports"), "VotersList.rdlc");

            LocalReport lr = new LocalReport();

            lr.EnableExternalImages = true;
            if (System.IO.File.Exists(path))
            {
                lr.ReportPath = path;
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }

            var company = db.Companies.Find(1);

            string fullname = string.Empty;

            if (company.Logo == null)
            {
                fullname = AppDomain.CurrentDomain.BaseDirectory + "Content/CompanyLogo/NoLogoCompany.png";
            }
            else
            {
                fullname = AppDomain.CurrentDomain.BaseDirectory + company.Logo.Substring(2);
            }
            ReportParameter paramLogo = new ReportParameter();

            paramLogo.Name = "Path";
            paramLogo.Values.Add(fullname);
            lr.SetParameters(paramLogo);

            ReportDataSource rd = new ReportDataSource("DataSet1", listaVotantes);

            lr.DataSources.Add(rd);
            string reportType = "";

            if (type == 1)
            {
                reportType = "EXCELOPENXML";
            }
            else
            {
                reportType = "PDF";
            }
            string mimeType;
            string encoding;
            string fileNameExtension;



            string deviceInfo =

                "<DeviceInfo>" +
                "  <OutputFormat>" + "ListadoVotantes" + "</OutputFormat>" +
                "  <PageWidth>11in</PageWidth>" +
                "  <PageHeight>8.5in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";

            Warning[] warnings;
            string[]  streams;
            byte[]    renderedBytes;

            renderedBytes = lr.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            return(File(renderedBytes, mimeType));
        }
Example #52
0
        public string CallReports(string DocType, List <ReportParameter> reportParameters, bool isPortrait, string reportPath, DataTable dataTable, IEnumerable <dynamic> dataObject, string reportDataSetName)
        {
            int companyID = Convert.ToInt32(dictionary[9].Id == "" ? 0 : Convert.ToInt32(dictionary[9].Id));
            int branchID  = Convert.ToInt32(dictionary[10].Id == "" ? 0 : Convert.ToInt32(dictionary[10].Id));

            string errorMessage = string.Empty;
            string fileString   = string.Empty;

            try
            {
                LocalReport      lr   = new LocalReport();
                ReportDataSource rd   = new ReportDataSource();
                string           path = string.Empty;
                if (dataTable != null && dataTable.Rows.Count > 0 || dataObject != null && dataObject.Count() > 0)
                {
                    path = reportPath;
                }
                else
                {
                    if (isPortrait)
                    {
                        path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankPortrait.rdlc");
                    }
                    else
                    {
                        path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankLandscape.rdlc");
                    }
                }

                if (System.IO.File.Exists(path))
                {
                    lr.EnableExternalImages = true;
                    lr.ReportPath           = path;
                    //Set Default Report Parameter
                    if (dataTable != null && dataTable.Rows.Count > 0 || dataObject != null && dataObject.Count() > 0)
                    {
                        var orgList = from c in db.SET_Company
                                      join cb in db.SET_CompanyBranch on c.CompanyID equals cb.CompanyID
                                      where cb.CompanyID == companyID && cb.BranchID == branchID
                                      select new
                        {
                            CompanyName = c.Name,
                            BranchName  = cb.Name
                        };
                        var org = orgList.FirstOrDefault();
                        if (org != null)
                        {
                            reportParameters.Add(new ReportParameter("companyName", org.CompanyName.ToUpper()));
                            reportParameters.Add(new ReportParameter("branchName", org.BranchName.ToUpper()));
                        }

                        // checking declared report parameters
                        ReportParameterInfoCollection ps;
                        ps = lr.GetParameters();
                        ReportParameter paramV = new ReportParameter();
                        foreach (ReportParameterInfo p in ps)
                        {
                            if (p.Name == "logo")
                            {
                                string logoPath = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/user_define/logo"), "r_logo.jpg");
                                if (System.IO.File.Exists(logoPath))
                                {
                                    reportParameters.Add(new ReportParameter("logo", "File:\\" + logoPath, true));
                                }
                            }
                        }


                        lr.SetParameters(reportParameters);
                    }
                }
                else
                {
                    errorMessage = "File Not Exists.";
                }
                if (dataTable != null)
                {
                    rd = new ReportDataSource(reportDataSetName, dataTable);
                }
                else if (dataObject != null)
                {
                    rd = new ReportDataSource(reportDataSetName, dataObject);
                }

                lr.DataSources.Add(rd);
                // Convert Report To Base64String
                string reportType = DocType;
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo =
                    "<DeviceInfo>" +
                    "  <OutputFormat>" + DocType + "</OutputFormat>" +
                    "</DeviceInfo>";

                Warning[] warnings;
                string[]  streams;
                byte[]    renderedBytes;

                renderedBytes = lr.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);

                fileString = Convert.ToBase64String(renderedBytes.ToArray());
                return(fileString);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return(errorMessage);
            }
        }
 public override void SetReport(LocalReport report)
 {
     report.LoadReportDefinition(_reportsProvider.GetResourceByReportName("Marcas.rdlc"));
     report.DataSources.Add(new ReportDataSource("Marcas", Marcas));
 }
Example #54
0
        public string CallReportsMultipleDS(string DocType, List <ReportParameter> reportParameters, bool isPortrait, string reportPath, IEnumerable <dynamic> dataObject1, IEnumerable <dynamic> dataObject2, string reportDS1, string reportDS2)
        {
            string errorMessage = string.Empty;
            string fileString   = string.Empty;

            try
            {
                LocalReport      lr = new LocalReport();
                ReportDataSource rd = new ReportDataSource();
                lr.EnableExternalImages = true;
                string path = string.Empty;
                if (dataObject1 != null && dataObject1.Count() > 0 || dataObject2 != null && dataObject2.Count() > 0)
                {
                    path = reportPath;
                }
                else
                {
                    if (isPortrait)
                    {
                        path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankPortrait.rdlc");
                    }
                    else
                    {
                        path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankLandscape.rdlc");
                    }
                }

                if (System.IO.File.Exists(path))
                {
                    lr.ReportPath = path;
                    //Set Default Report Parameter
                    if (dataObject1 != null && dataObject1.Count() > 0 || dataObject2 != null && dataObject2.Count() > 0)
                    {
                        var company = db.SET_Company.FirstOrDefault();
                        if (company != null)
                        {
                            string contactInfo = "Phone : " + company.ContactNo + " Email : " + company.EmailID;
                            reportParameters.Add(new ReportParameter("orgName", company.Name));
                            reportParameters.Add(new ReportParameter("orgAddress", company.Address));
                            reportParameters.Add(new ReportParameter("orgContactInfo", contactInfo));
                        }

                        // checking declared report parameters
                        ReportParameterInfoCollection ps;
                        ps = lr.GetParameters();
                        ReportParameter paramV = new ReportParameter();
                        foreach (ReportParameterInfo p in ps)
                        {
                            if (p.Name == "logo")
                            {
                                string logoPath = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/user_define/logo"), "r_logo.png");
                                if (System.IO.File.Exists(logoPath))
                                {
                                    reportParameters.Add(new ReportParameter("logo", "File:\\" + logoPath, true));
                                }
                            }
                        }

                        lr.SetParameters(reportParameters);
                    }
                }
                else
                {
                    errorMessage = "File Not Exists.";
                }
                //if (dataObjectAsset != null)
                //{
                //    rd = new ReportDataSource(reportDSAsset, dataObjectAsset);
                //}
                //if (dataObjectLiabilities != null)
                //{
                //    rd = new ReportDataSource(reportDSLiabilites, dataObjectLiabilities);
                //}
                lr.DataSources.Clear();
                ReportDataSource rd1 = new ReportDataSource(reportDS1, dataObject1);
                ReportDataSource rd2 = new ReportDataSource(reportDS2, dataObject2);
                lr.DataSources.Add(rd1);
                lr.DataSources.Add(rd2);

                // Convert Report To Base64String
                string reportType = DocType;
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo =
                    "<DeviceInfo>" +
                    "  <OutputFormat>" + DocType + "</OutputFormat>" +
                    "</DeviceInfo>";

                Warning[] warnings;
                string[]  streams;
                byte[]    renderedBytes;

                renderedBytes = lr.Render(
                    reportType,
                    deviceInfo,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);

                fileString = Convert.ToBase64String(renderedBytes.ToArray());
                return(fileString);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return(errorMessage);
            }
        }
Example #55
0
        private void frmRelatorioCliente_Load(object sender, EventArgs e)
        {
            if (formato == "pdf")
            {
                this.Hide();
            }
            this.reportViewer1.ShowExportButton  = false;
            this.reportViewer1.ShowBackButton    = false;
            this.reportViewer1.ShowFindControls  = false;
            this.reportViewer1.ShowRefreshButton = false;
            this.reportViewer1.ShowStopButton    = false;
            string caminhoRelatorio = null;

            if (tipo == "Analitico")
            {
                caminhoRelatorio = "Promissum.Relatorio_Atualizado.Cliente.rptClienteAnalitico.rdlc";

                DataTable dsClienteSintetico = new DataTable();
                dsClienteSintetico.Columns.Add("cli_cod", typeof(int));
                dsClienteSintetico.Columns.Add("cli_nome", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cpfcnpj", typeof(string));
                dsClienteSintetico.Columns.Add("cli_rgie", typeof(string));
                dsClienteSintetico.Columns.Add("cli_rsocial", typeof(string));
                dsClienteSintetico.Columns.Add("cli_tipo", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cep", typeof(string));
                dsClienteSintetico.Columns.Add("cli_endereco", typeof(string));
                dsClienteSintetico.Columns.Add("cli_bairro", typeof(string));
                dsClienteSintetico.Columns.Add("cli_fone", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cel", typeof(string));
                dsClienteSintetico.Columns.Add("cli_email", typeof(string));
                dsClienteSintetico.Columns.Add("cli_endnumero", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cidade", typeof(string));
                dsClienteSintetico.Columns.Add("cli_estado", typeof(string));
                dsClienteSintetico.Columns.Add("cli_observacao", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cadastro", typeof(DateTime));

                var lista = contexto.cliente.Select(c => new
                {
                    c.cli_cod,
                    c.cli_nome,
                    c.cli_cpfcnpj,
                    c.cli_rgie,
                    c.cli_rsocial,
                    c.cli_tipo,
                    c.cli_cep,
                    c.cli_endereco,
                    c.cli_bairro,
                    c.cli_fone,
                    c.cli_cel,
                    c.cli_email,
                    c.cli_endnumero,
                    c.cli_cidade,
                    c.cli_estado,
                    c.cli_observacao,
                    c.cli_cadastro
                }).Where(c => c.cli_cadastro.Value > dataInicio && c.cli_cadastro.Value <= dataFim &&
                         c.cli_nome.Contains(nome) &&
                         c.cli_cidade.Contains(cidade) && c.cli_estado.Contains(estado)).ToList();
            }
            else
            {
                DataTable dsClienteSintetico = new DataTable();
                dsClienteSintetico.Columns.Add("cli_cod", typeof(int));
                dsClienteSintetico.Columns.Add("cli_nome", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cpfcnpj", typeof(string));
                dsClienteSintetico.Columns.Add("cli_rgie", typeof(string));
                dsClienteSintetico.Columns.Add("cli_rsocial", typeof(string));
                dsClienteSintetico.Columns.Add("cli_tipo", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cep", typeof(string));
                dsClienteSintetico.Columns.Add("cli_endereco", typeof(string));
                dsClienteSintetico.Columns.Add("cli_bairro", typeof(string));
                dsClienteSintetico.Columns.Add("cli_fone", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cel", typeof(string));
                dsClienteSintetico.Columns.Add("cli_email", typeof(string));
                dsClienteSintetico.Columns.Add("cli_endnumero", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cidade", typeof(string));
                dsClienteSintetico.Columns.Add("cli_estado", typeof(string));
                dsClienteSintetico.Columns.Add("cli_observacao", typeof(string));
                dsClienteSintetico.Columns.Add("cli_cadastro", typeof(DateTime));

                var dataInicio = Convert.ToDateTime(dataInicial);
                var dataFim    = Convert.ToDateTime(dataFinal);

                var lista = contexto.cliente.Select(c => new
                {
                    c.cli_cod,
                    c.cli_nome,
                    c.cli_cpfcnpj,
                    c.cli_rgie,
                    c.cli_rsocial,
                    c.cli_tipo,
                    c.cli_cep,
                    c.cli_endereco,
                    c.cli_bairro,
                    c.cli_fone,
                    c.cli_cel,
                    c.cli_email,
                    c.cli_endnumero,
                    c.cli_cidade,
                    c.cli_estado,
                    c.cli_observacao,
                    c.cli_cadastro
                }).Where(c => c.cli_cadastro.Value > dataInicio && c.cli_cadastro.Value <= dataFim &&
                         c.cli_nome.Contains(nome) &&
                         c.cli_cidade.Contains(cidade) && c.cli_estado.Contains(estado)).ToList();

                foreach (var item in lista)
                {
                    dsClienteSintetico.Rows.Add(item.cli_cod, item.cli_nome, item.cli_cpfcnpj, item.cli_rgie, item.cli_rsocial, item.cli_tipo, item.cli_cep,
                                                item.cli_endereco, item.cli_bairro, item.cli_fone, item.cli_cel, item.cli_email, item.cli_endnumero, item.cli_cidade, item.cli_estado, item.cli_observacao, item.cli_cadastro);
                }


                caminhoRelatorio = "Promissum.Relatorio_Atualizado.Cliente.rptClienteSintetico.rdlc";

                ReportDataSource rpt           = new ReportDataSource("dsClienteSintetico", dsClienteSintetico);
                string           caminhoImagem = Ferramentas.xmlConfig.config.retornaLogo();

                if (formato == "pdf")
                {
                    this.Hide();
                    LocalReport report = new LocalReport();

                    report.ReportEmbeddedResource = caminhoRelatorio;

                    report.DataSources.Add(rpt);

                    report.EnableExternalImages = true;

                    report.SetParameters(new ReportParameter("logo", caminhoImagem));

                    try
                    {
                        Ferramentas.relatorio.exportarRelatorio(report, "PDF");
                        this.Close();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                else
                {
                    reportViewer1.LocalReport.ReportEmbeddedResource = caminhoRelatorio;

                    reportViewer1.LocalReport.DataSources.Add(rpt);

                    reportViewer1.LocalReport.EnableExternalImages = true;

                    this.reportViewer1.LocalReport.SetParameters(new ReportParameter("logo", caminhoImagem));
                }
            }

            this.reportViewer1.RefreshReport();
        }
Example #56
0
 protected override void AssignCommonParameters(LocalReport rpt, DataRow dt, string Logo, StringBuilder spers)
 {
     rpt.SetParameters(new ReportParameter[] {
         /* header section */
         new ReportParameter("LogoURL", Logo),
         new ReportParameter("Status", dt["fStatus"].ToString()),
         new ReportParameter("lPageNofM", m(2410)),      /* Page {0} of {1} */
         new ReportParameter("lTabBasic", m(156)),       /* General information */
         /* fire report basic data */
         new ReportParameter("lNumber", m(27)),          /* Number */
         new ReportParameter("NrComposite", dt["NrComposite"].ToString()),
         new ReportParameter("lOriginator", m(45)),      /* Originator */
         new ReportParameter("OriginatorName", dt["OriginatorName"].ToString()),
         new ReportParameter("lResponsible", m(290)),    /* Responsible */
         new ReportParameter("Responsible", dt["Responsible"].ToString()),
         new ReportParameter("lCaption", m(292)),        /* Short name */
         new ReportParameter("Caption", dt["Caption"].ToString()),
         new ReportParameter("lEventDatetime", m(2302)), /* Incident date */
         new ReportParameter("EventDatetime", dt["fTime"].ToString()),
         new ReportParameter("lArea", m(739)),           /* Incident location */
         new ReportParameter("Area", dt["OrgCap"].ToString()),
         new ReportParameter("lWorkplace", m(1036)),     /* Details Unfallort */
         new ReportParameter("Workplace", dt["Workplace"].ToString()),
         /* fire incident basic data, right column */
         new ReportParameter("lcreawhen", m(2301)),        /* Created on */
         new ReportParameter("crea_when", dt["fcrea_when"].ToString()),
         new ReportParameter("llm_when", m(3255)),         /* Last modified */
         new ReportParameter("lm_when", dt["flm_when_who"].ToString()),
         new ReportParameter("lRevision", m(2287)),        /* Revision */
         new ReportParameter("Revision", dt["Revision"].ToString()),
         new ReportParameter("lClassification", m(2550)),  /* Classification */
         new ReportParameter("Classification", dt["Classification"].ToString()),
         new ReportParameter("lPhoneContact", m(4398)),    /* Phone (incident) */
         new ReportParameter("PhoneContact", dt["PhoneContact"].ToString()),
         new ReportParameter("lPhoneRepair", m(4399)),     /* Phone (repairs) */
         new ReportParameter("PhoneRepair", dt["PhoneRepair"].ToString()),
         new ReportParameter("lExtinguishedWho", m(2295)), /* Extinguishing party */
         new ReportParameter("fExtinguishedWho", dt["fExtinguishedWho"].ToString()),
         /* fire incident basic data, bottom section with long text fields */
         new ReportParameter("lPersInvolved", m(407)),                            /* Persons involved */
         new ReportParameter("hPersInvolved", spers.ToString()),
         new ReportParameter("lPreLoss", m(4393)),                                /* Initial condition */
         new ReportParameter("PreLoss", dt["PreLoss"].ToString()),
         new ReportParameter("lReportingChan", m(2293)),                          /* Detection and Alarm */
         new ReportParameter("hReportingChan", dt["hReportingChan"].ToString()),
         new ReportParameter("lImmediateMeasures", m(3842)),                      /* Immediate actions */
         new ReportParameter("ImmediateMeasures", dt["fImmediateMeasures"].ToString()),
         new ReportParameter("lBrigade", m(3904)),                                /* External fire brigade(s) */
         new ReportParameter("fBrigade", dt["FirebrigadeExternal"].ToString()),
         new ReportParameter("lResponse", m(4364)),                               /* Response */
         new ReportParameter("fResponse", dt["fResponse"].ToString()),
         new ReportParameter("lExtinguishing", m(2296)),                          /* Extinguishing equipment */
         new ReportParameter("fExtinguishing", dt["fExtinguishing"].ToString()),
         new ReportParameter("lExtinguisher", m(3905)),                           /* Extinguishers used */
         new ReportParameter("fExtinguisher", dt["ExtinguishersUsed"].ToString()),
         new ReportParameter("lMitigationComments", m(4394)),                     /* Mitigation */
         new ReportParameter("MitigationComments", dt["MitigationComments"].ToString()),
         new ReportParameter("lImmediateCauses", m(551)),                         /* Immediate causes */
         new ReportParameter("ImmediateCauses", dt["fCauses"].ToString()),
         new ReportParameter("lRiskEffect", m(37)),                               /* Hazard */
         new ReportParameter("RiskEffect", dt["RiskEffect"].ToString()),
         new ReportParameter("lDamageEnv", m(1388)),                              /* Environmental impact */
         new ReportParameter("DamageEnv", dt["DamageEnv"].ToString()),
         new ReportParameter("lDescription", m(1004)),                            /* Material damage */
         new ReportParameter("Description", dt["fDescription"].ToString()),
         new ReportParameter("lBusinessInterruption", m(1472)),                   /* Loss */
         new ReportParameter("BusinessInterruption", dt["BusinessInterruption"].ToString()),
         new ReportParameter("lCircumstances", m(550)),                           /* Circumstances */
         new ReportParameter("Circumstances", dt["fCourseOfEvents"].ToString()),
         new ReportParameter("lRemarksSafe", m(4395)),                            /* Favorable conds. */
         new ReportParameter("RemarksSafe", dt["RemarksSafe"].ToString()),
         new ReportParameter("lRemarksUnsafe", m(4396)),                          /* Adverse conditions */
         new ReportParameter("RemarksUnsafe", dt["RemarksUnsafe"].ToString()),
         new ReportParameter("lLessionsLearned", m(4397)),                        /* Lessons learned */
         new ReportParameter("LessionsLearned", dt["LessonsLearned"].ToString()), /* typo... constrained and not important enough to bother fixing */
         /* sections below the header */
         new ReportParameter("lTabMedia", m(56)),                                 /* Attached files */
         new ReportParameter("lDocuments", m(3607)),                              /* Documents */
         new ReportParameter("Documents", dt["fDocuments"].ToString()),
         new ReportParameter("lTabFinMea", m(3844)),                              /* Causes, findings, measures */
         new ReportParameter("lFinMeaStatusNumber", m(249)),                      /* Status */
         new ReportParameter("lFinMeaCategory", m(3845)),                         /* Cat. */
         new ReportParameter("lFinMeaArea", m(251)),                              /* Area */
         new ReportParameter("lFinMeaText", m(289)),                              /* Text */
         new ReportParameter("lFinMeaResponsible", m(290)),                       /* Responsible */
         new ReportParameter("lFinMeaPicture", m(3166)),                          /* Pictures */
         new ReportParameter("lTabAcf", m(4271)),                                 /* Action forces */
         new ReportParameter("lAFEventtimeFrom", m(1320)),                        /* Date/time */
         new ReportParameter("lAFCat", m(4284)),                                  /* Event */
         new ReportParameter("lAFDept", m(4286)),                                 /* Department */
         new ReportParameter("lAFEventtimeTo", m(4285)),                          /* Date/time to */
         new ReportParameter("lAFRemarks", m(3202)),                              /* Notes */
         new ReportParameter("lTabRca", m(418)),                                  /* Root Cause Analysis */
         new ReportParameter("lRcaNr", m(3042)),                                  /* Nr. */
         new ReportParameter("lRcaSection", m(3257)),                             /* Level */
         new ReportParameter("lRcaCause", m(576)),                                /* Cause */
         new ReportParameter("lRcaVerified", m(577)),                             /* Verified */
         new ReportParameter("lRcaMeasures", m(240)),                             /* Measures */
         new ReportParameter("lConfidentialityNote", ConfidentialityNote),
         new ReportParameter("FooterInfoline", dt["fFooterInfoline"].ToString())
     });
 }
Example #57
0
        private void RenderReportImpresion(string report, string ds, object data, string ds1, object data1, string ds2, object data2,
                                           string ds3, object data3, string ds4, object data4, string ds5, object data5, string ds6, object data6, string formato, string orientacion = "")
        {
            string      ruta        = string.Empty;
            string      reportPath  = Server.MapPath(string.Format("~/Reporte/{0}.rdlc", report));
            LocalReport localReport = new LocalReport {
                ReportPath = reportPath
            };
            ReportDataSource reportDataSource  = new ReportDataSource(ds, data);
            ReportDataSource reportDataSource1 = new ReportDataSource(ds1, data1);
            ReportDataSource reportDataSource2 = new ReportDataSource(ds2, data2);
            ReportDataSource reportDataSource3 = new ReportDataSource(ds3, data3);
            ReportDataSource reportDataSource4 = new ReportDataSource(ds4, data4);
            ReportDataSource reportDataSource5 = new ReportDataSource(ds5, data5);
            ReportDataSource reportDataSource6 = new ReportDataSource(ds6, data6);

            localReport.DataSources.Add(reportDataSource);
            localReport.DataSources.Add(reportDataSource1);
            localReport.DataSources.Add(reportDataSource2);
            localReport.DataSources.Add(reportDataSource3);
            localReport.DataSources.Add(reportDataSource4);
            localReport.DataSources.Add(reportDataSource5);
            localReport.DataSources.Add(reportDataSource6);

            string reportType = string.Empty;
            string deviceInfo = string.Empty;

            switch (formato)
            {
            case "PDF":

                if (orientacion == "vertical")
                {
                    reportType = "PDF";
                    deviceInfo =
                        string.Format(
                            "<DeviceInfo><OutputFormat>{0}</OutputFormat><PageWidth>8.27in</PageWidth><PageHeight>11.69in</PageHeight><MarginTop>0in</MarginTop><MarginLeft>0in</MarginLeft><MarginRight>0in</MarginRight><MarginBottom>0in</MarginBottom></DeviceInfo>",
                            reportType);
                }
                else
                {
                    reportType = "PDF";
                    deviceInfo =
                        string.Format(
                            "<DeviceInfo><OutputFormat>{0}</OutputFormat><PageWidth>9.25in</PageWidth><PageHeight>8in</PageHeight><MarginTop>0in</MarginTop><MarginLeft>0in</MarginLeft><MarginRight>0in</MarginRight><MarginBottom>0in</MarginBottom></DeviceInfo>",
                            reportType);
                }
                break;

            case "EXCEL":
                reportType = "Excel";

                break;

            case "WORD":
                reportType = "WORD";

                break;
                // default:
                // return string.Empty;
            }

            string mimeType          = string.Empty;
            string encoding          = string.Empty;
            string fileNameExtension = string.Empty;

            Warning[] warnings = null;
            string[]  streams  = null;


            try
            {
                byte[] renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding,
                                                          out fileNameExtension, out streams, out warnings);

                ruta = Server.MapPath("~/Reporte/" + string.Format("{0}.{1}", GetReporteName(report), fileNameExtension));
                ByteArrayToFile(ruta, renderedBytes);
                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition",
                                   string.Format("attachment; filename={0}.{1}",
                                                 GetReporteName(report), fileNameExtension));
                Response.BinaryWrite(renderedBytes);
                Response.End();


                string targetPath = ConfigurationManager.AppSettings["RutaReporteTrazabilidad"];
                string fileName   = string.Empty;
                string destFile   = string.Empty;
                fileName = System.IO.Path.GetFileName(ruta);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(ruta, destFile);
                //(s, destFile, true);
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }

            //return ruta;
        }
Example #58
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 _invoiceNumber = "";

            //Initialize control values
            LocalReport report = Master.Viewer.LocalReport;
            report.DisplayName          = this.mTitle;
            report.EnableExternalImages = true;
            DataSet           ds         = new DataSet();
            EnterpriseGateway enterprise = new EnterpriseGateway();
            foreach (GridViewRow row in selectedInvoices)
            {
                _invoiceNumber = row.Cells[1].Text;
                DataSet _ds = enterprise.FillDataset(this.mUSPName, this.mTBLName, new object[] { _invoiceNumber });
                ds.Merge(_ds);
            }

            if (ds.Tables[mTBLName] == null)
            {
                ds.Tables.Add(mTBLName);
            }
            switch (e.CommandName)
            {
            case "Run":
                //Set local report and data source
                System.IO.Stream stream = Master.GetReportDefinition(this.mSource);
                report.LoadReportDefinition(stream);
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));

                //Set the report parameters for the report
                ReportParameter invoiceNumber = new ReportParameter("InvoiceNumber", _invoiceNumber);
                report.SetParameters(new ReportParameter[] { invoiceNumber });

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

                if (!Master.Viewer.Enabled)
                {
                    Master.Viewer.CurrentPage = 1;
                }
                break;

            case "Data":
                //Set local export report and data source
                report.LoadReportDefinition(Master.CreateExportRdl(ds, this.mDSName));
                report.DataSources.Clear();
                report.DataSources.Add(new ReportDataSource(this.mDSName, ds.Tables[mTBLName]));
                report.Refresh();
                break;

            case "Excel":
                //Create Excel mime-type page
                Response.ClearHeaders();
                Response.Clear();
                Response.Charset = "";
                Response.AddHeader("Content-Disposition", "inline; filename=BNConsumerDirectDDUPerformanceDetail.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 #59
-1
        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;
        }
Example #60
-1
        private void Run()
        {
            LocalReport report = new LocalReport();
            report.ReportPath = "Report1.rdlc";
            report.DataSources.Add(new ReportDataSource("Sales", new Merchant().GetProducts()));

            Export(report);

            m_currentPageIndex = 0;
            Print();
        }