protected void btnImprimir_Click(object sender, EventArgs e)
    {
        string Ciclo = this.ddlCiclo.SelectedValue;
        int Zona = int.Parse(this.ddlZonas.SelectedValue);
        int PlantelID = int.Parse(this.ddlPlanteles.SelectedValue);
        byte Turno = byte.Parse(this.ddlTurnos.SelectedValue);
        int Estatus = int.Parse(ddlEstatus.SelectedValue);

        string NomPlantel = this.ddlPlanteles.SelectedItem.Text;

        db = new DBEscolarDataContext();
        var res = (from A in db.vwRPTEstadisticaPreInscritos011s
                   where A.Ciclo == Ciclo && A.Zona == Zona && A.PlantelID == PlantelID && A.Turno == (Turno == 0 ? A.Turno : Turno)
                    && A.Estatus == (Estatus == -1 ? A.Estatus : Estatus)
                   orderby A.Zona, A.Plantel, A.Turno, A.Nombre
                   select A).ToList();

        this.lblMensaje.Visible = res.Count() == 0;
        if (res.Count() == 0)
            return;

        ReportDocument rptDoc = new ReportDocument();

        rptDoc.Load(Server.MapPath("../Reportes/rptEstPre01.rpt"));
        rptDoc.SetDataSource(res);
        rptDoc.SetParameterValue("NomPlantel", NomPlantel);

        MemoryStream stream = (MemoryStream)rptDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);
        rptDoc.Close();
        rptDoc.Dispose();

        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "inline; filename=Alumnos.xls");
        Response.BinaryWrite(stream.ToArray());
        Response.End();
        stream.Close();
        stream.Dispose();
    }
Example #2
1
		private void GeneratePDF()
		{
            ReportDocument rpt = new ReportDocument();
            switch (cboView.SelectedItem.Value)
            {
                case "0":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/ChartOfAccountsDetails.rpt"));
                    break;
                case "1":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/ChartOfAccountsSummary.rpt"));
                    break;
            }

			ExportOptions exportop = new ExportOptions();
			DiskFileDestinationOptions dest = new DiskFileDestinationOptions();
			
			string strPath = Server.MapPath(@"\RetailPlus\temp\");

			string strFileName = "chartofacc_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + ".pdf";
			if (System.IO.File.Exists(strPath + strFileName))
				System.IO.File.Delete(strPath + strFileName);

			dest.DiskFileName = strPath + strFileName;

			exportop = rpt.ExportOptions;
	
			SetDataSource(rpt);

			exportop.DestinationOptions = dest;
			exportop.ExportDestinationType = ExportDestinationType.DiskFile;
			exportop.ExportFormatType = ExportFormatType.PortableDocFormat;
			rpt.Export();   rpt.Close();    rpt.Dispose();
			
			fraViewer.Attributes.Add("src","/RetailPlus/temp/" + strFileName);
		}
    protected void Page_Load(object sender, EventArgs e)
    {
        String qs = Request.QueryString.Get("bid");
        Response.Write("Query String = " + qs);
        SqlConnection sql = new SqlConnection();
        sql.ConnectionString = "Data Source=(local);Initial Catalog=Hotel;Integrated Security=True";
        sql.Open();

        ReportDocument rpd = new ReportDocument();
        rpd.Load(Server.MapPath("itcreport.rpt"));
        rpd.SetDatabaseLogon("sa", "ak");
        rpd.SetParameterValue(0, qs);
        CrystalReportViewer1.ReportSource = rpd;

        //to convert report in pdf format
        MemoryStream ostream = new MemoryStream();
        Response.Clear();
        Response.Buffer = true;
        ostream = (MemoryStream)rpd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        rpd.Close();
        rpd.Dispose();
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(ostream.ToArray());
        ostream.Flush();
        ostream.Close();
        ostream.Dispose();
    }
		private void GeneratePDF()
		{
            ReportDocument rpt = new ReportDocument();
            rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/GeneralLedger.rpt"));

			ExportOptions exportop = new ExportOptions();
			DiskFileDestinationOptions dest = new DiskFileDestinationOptions();
			
			string strPath = Server.MapPath(@"\RetailPlus\temp\");

			string strFileName = "generalledger_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + ".pdf";
			if (System.IO.File.Exists(strPath + strFileName))
				System.IO.File.Delete(strPath + strFileName);

			dest.DiskFileName = strPath + strFileName;

			exportop = rpt.ExportOptions;
	
			SetDataSource(rpt);

			exportop.DestinationOptions = dest;
			exportop.ExportDestinationType = ExportDestinationType.DiskFile;
			exportop.ExportFormatType = ExportFormatType.PortableDocFormat;
			rpt.Export();   rpt.Close();    rpt.Dispose();
			
			fraViewer.Attributes.Add("src","/RetailPlus/temp/" + strFileName);
		}
Example #5
0
        public static void GenerateReport(string FileName, ReportDocument rpt, System.Web.UI.Control ClientScriptBlockControl, ExportFormatType pvtExportFormatType)
        {
            try
            {
                ExportOptions exportop = new ExportOptions();
                DiskFileDestinationOptions dest = new DiskFileDestinationOptions();

                string strFileExtensionName = ".pdf";
                switch (pvtExportFormatType)
                {
                    case ExportFormatType.PortableDocFormat: strFileExtensionName = ".pdf"; exportop.ExportFormatType = ExportFormatType.PortableDocFormat; break;
                    case ExportFormatType.WordForWindows: strFileExtensionName = ".doc"; exportop.ExportFormatType = ExportFormatType.WordForWindows; break;
                    case ExportFormatType.Excel: strFileExtensionName = ".xls"; exportop.ExportFormatType = ExportFormatType.Excel; break;
                }

                string strPath = System.Web.HttpContext.Current.Server.MapPath(@"\retailplus\temp\");
                string strFileName = FileName + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + strFileExtensionName;

                if (System.IO.File.Exists(strPath + strFileName))
                    System.IO.File.Delete(strPath + strFileName);

                dest.DiskFileName = strPath + strFileName;
                exportop.DestinationOptions = dest;
                exportop.ExportDestinationType = ExportDestinationType.DiskFile;
                rpt.Export(exportop); //rpt.Close(); rpt.Dispose();
                
                // remove the error
                if (pvtExportFormatType == ExportFormatType.WordForWindows || pvtExportFormatType == ExportFormatType.Excel || pvtExportFormatType == ExportFormatType.PortableDocFormat)
                {
                    // the maximum report processing jobs limit configured by your system administrator has been reached.
                    rpt.Close(); rpt.Dispose();
                }

                if (pvtExportFormatType == ExportFormatType.PortableDocFormat)
                {
                    string newWindowUrl = Constants.ROOT_DIRECTORY + "/temp/" + strFileName;
                    string javaScript = "window.open('" + newWindowUrl + "');";
                    System.Web.UI.ScriptManager.RegisterClientScriptBlock(ClientScriptBlockControl, ClientScriptBlockControl.GetType(), "openwindow", javaScript, true);
                }
                else
                {
                    string newWindowUrl = Constants.ROOT_DIRECTORY + "/temp/" + strFileName;
                    string javaScript = "window.open('" + newWindowUrl + "','_self');";
                    System.Web.UI.ScriptManager.RegisterClientScriptBlock(ClientScriptBlockControl, ClientScriptBlockControl.GetType(), "openwindow", javaScript, true);

                    //System.Diagnostics.Process p = new System.Diagnostics.Process();
                    //p.StartInfo.FileName = System.Web.HttpContext.Current.Server.MapPath(Constants.ROOT_DIRECTORY + "/temp/" + strFileName);
                    //p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    //p.Start();
                }
            }
            catch (Exception ex) { throw ex; }
        }
    private void Imprimir(int AlumnoID)
    {
        DBEscolarDataContext db = new DBEscolarDataContext();
        var Pago = (from P in db.vwRPTPagosEncabezados join D in db.vwRPTPagosDetalles on P.PagoID equals D.PagoID
                    where P.AlumnoID == AlumnoID && P.Ciclo == Utils.CicloActual && (P.Estatus != 0)
                    && D.Clave == "A01"
                    select P).FirstOrDefault();

        if (Pago == null)
        {
            this.lblMensaje.Text = "No se ha encontrado la ficha de pago.<br />Nota: Para poder generar la Ficha de Pago, debes de estar validado.";
            return;
        }
        else if (Pago.Estatus == 3) {

            Alumno Alumno = (from A in db.Alumnos
                             where A.AlumnoID == AlumnoID
                             select A).FirstOrDefault();

            this.lblMensaje.Text = "Felicidades. Tú ficha ha sido pagada y ya te encuentras inscrito con matrícula: " + Alumno.Matricula;
            return;

        }

        var Detalle = (from D in db.vwRPTPagosDetalles
                       where D.PagoID == Pago.PagoID
                       select D).ToList();

        //Actualiza el estatus del pago a 2:Impreso
        db.spEXEPagosCambiaEstatus(AlumnoID, Pago.PagoID, 2, Utils.CicloActual);

        ArrayList col = new ArrayList();
        col.Add(Pago);
        ReportDocument rptDoc = new ReportDocument();

        rptDoc.Load(Server.MapPath("Reportes/rptFichaDePago.rpt"));
        //set dataset to the report viewer.
        rptDoc.SetDataSource(col);
        rptDoc.Subreports["Detalle"].SetDataSource(Detalle);
        rptDoc.Subreports["Detalle2"].SetDataSource(Detalle);

        MemoryStream stream = (MemoryStream)rptDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        rptDoc.Close();
        rptDoc.Dispose();
        Response.Clear();
        Response.ContentType = @"Application/pdf";
        Response.AddHeader("Content-Disposition", "inline; filename=FichaDePago.pdf");
        Response.AddHeader("content-length", stream.Length.ToString());
        Response.BinaryWrite(stream.ToArray());
        Response.Flush();
        stream.Close();
        stream.Dispose();
    }
        //Exporta a Excel el grid
        protected void ExportEt(object sender, EventArgs e)
        {
            string sucursal = cmbSucursal.Value.ToString();

            //1. Configurar la conexión y el tipo de comando
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSEF"].ConnectionString);
            try
            {
                SqlCommand comando = new SqlCommand("web_spS_ObtenerRItemsAdicionales", conn);

                SqlDataAdapter adaptador = new SqlDataAdapter(comando);

                DataTable dt = new DataTable();
                adaptador.SelectCommand.CommandType = CommandType.StoredProcedure;
                adaptador.SelectCommand.Parameters.Add(@"Sucursal", SqlDbType.Char).Value = sucursal;
                adaptador.Fill(dt);

                ReportDocument reporteCuadrila = new ReportDocument();
                reporteCuadrila.Load(Server.MapPath("reportess/ResumenOC.rpt"));
                reporteCuadrila.SetDataSource(dt);

                reporteCuadrila.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "Resumen de OC: " + sucursal);

                reporteCuadrila.Close();
                reporteCuadrila.Dispose();

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();

            }
        }
Example #8
0
        private void Export(ExportFormatType pvtExportFormatType)
        {
            ReportDocument rpt = new ReportDocument();
            rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/_StockTransactionReport.rpt"));

            SetDataSource(rpt);

            ExportOptions exportop = new ExportOptions();
            DiskFileDestinationOptions dest = new DiskFileDestinationOptions();
            string strPath = Server.MapPath(@"\retailplus\temp\");
            string strFileExtensionName = ".pdf";
            switch (pvtExportFormatType)
            {
                case ExportFormatType.PortableDocFormat: strFileExtensionName = ".pdf"; exportop.ExportFormatType = ExportFormatType.PortableDocFormat; break;
                case ExportFormatType.WordForWindows: strFileExtensionName = ".doc"; exportop.ExportFormatType = ExportFormatType.WordForWindows; break;
                case ExportFormatType.Excel: strFileExtensionName = ".xls"; exportop.ExportFormatType = ExportFormatType.Excel; break;
            }
            string strFileName = "tranreport_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + strFileExtensionName;
            if (System.IO.File.Exists(strPath + strFileName))
                System.IO.File.Delete(strPath + strFileName);

            dest.DiskFileName = strPath + strFileName;
            exportop.DestinationOptions = dest;
            exportop.ExportDestinationType = ExportDestinationType.DiskFile;
            rpt.Export(exportop); //rpt.Close(); rpt.Dispose(); 

            if (pvtExportFormatType == ExportFormatType.PortableDocFormat)
            {
                rpt.Close(); rpt.Dispose();
                Response.Redirect(Constants.ROOT_DIRECTORY + "/temp/" + strFileName, false);
            }
            else 
            {
                CRViewer.ReportSource = rpt;
                Session["ReportDocument"] = rpt;
                CRSHelper.OpenExportedReport(strFileName); // OpenExportedReport(strFileName);
            }
            
        }
        //protected Boolean CheckAccessAble()
        //{
        //    if (m_perimission_array[(int)Authentication.FUN_INTERFACE.wzxqjh_jjd_report][0] == '1') return true;
        //    return false;
        //}
        private void PrintPDF()
        {
            ReportDocument rpt_doc = new ReportDocument();
            DataSet ds = new DataSet();
            StringBuilder sqlstr = new StringBuilder();

            sqlstr.Append("select requisition_id req_id,matr_seq_no mtr_no, to_char(matr_seq_line_no)||' ' line_no,");//2013-03-22 ming.li ����������ת��Ϊ�ַ����������кŸ�ʽΪ1.00
            sqlstr.Append(" part_no, part_description part_name,project_id proj_id, nvl(project_block,'') proj_block,req_qty qty, part_unit, zh_qty,");//2013-03-22 ming.li �ֶ�Ϊ�գ���ӡ�ո񣬶�����ӡ����
            sqlstr.Append(string.Format("xh_qty from jp_jjd_line where jjd_no ='{0}'", m_jjd_no));

            OleDbConnection conn = new OleDbConnection(DBHelper.OleConnectionString);
            OleDbCommand cmd = new OleDbCommand();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            //DeliveryVoucher dvchr = (DeliveryVoucher)Session["delivery_voucher"];

            Jjd objJjd = new Jjd(m_jjd_no);

            //sqlstr.Append(" and requisition_id in (");
            //for (int i = 0; i < dvchr.DeliveryItems.Count; i++)
            //{
            //    if (i == dvchr.DeliveryItems.Count - 1)
            //    {
            //        sqlstr.Append(string.Format("'{0}'", dvchr.DeliveryItems[i].ToString()));
            //    }
            //    else
            //    {
            //        sqlstr.Append(string.Format("'{0}',", dvchr.DeliveryItems[i].ToString()));
            //    }
            //}
            //sqlstr.Append(" )");

            cmd.Connection = conn;
            cmd.CommandText = sqlstr.ToString();

            da.Fill(ds);

            rpt_doc.Load(Request.PhysicalApplicationPath+"\\UI\\Report\\CrysJj.rpt");
            rpt_doc.SetDataSource(ds.Tables[0]);
            //dvchr.SetDeliveryVoucherNo();
            rpt_doc.SetParameterValue("jjd_no", m_jjd_no);
            //rpt_doc.SetParameterValue("kuwei", "");
            rpt_doc.SetParameterValue("place", objJjd.PlaceName);
            rpt_doc.SetParameterValue("receiver", objJjd.ReceiptPerson);
            rpt_doc.SetParameterValue("recieve_date", objJjd.ReceiptDateStr);
            rpt_doc.SetParameterValue("receiver_contact", objJjd.ReceiptContract);
            rpt_doc.SetParameterValue("ZHd",objJjd.ZhPlace);
            rpt_doc.SetParameterValue("ZHr",objJjd.ZhPerson);
            rpt_doc.SetParameterValue("ZHdh",objJjd.ZhContract);
            rpt_doc.SetParameterValue("ZHArrTime",objJjd.ZhArrTime);
            rpt_doc.SetParameterValue("XQbm",objJjd.XQDept);
            rpt_doc.SetParameterValue("XQlxr",objJjd.XQPerson);
            rpt_doc.SetParameterValue("XQdh",objJjd.XQContract);
            rpt_doc.SetParameterValue("CYgs",objJjd.CyCompany);
            rpt_doc.SetParameterValue("CYr",objJjd.CyPerson);
            rpt_doc.SetParameterValue("CYdh",objJjd.CyContract);
            rpt_doc.SetParameterValue("CYpz",objJjd.CycCarNo);
            rpt_doc.SetParameterValue("CYjz", objJjd.CyDoc);

            rpt_doc.PrintOptions.PaperOrientation = PaperOrientation.Landscape;
            rpt_doc.PrintOptions.PaperSize = PaperSize.PaperA4;

            using (MemoryStream fp = (MemoryStream)(rpt_doc.ExportToStream(ExportFormatType.PortableDocFormat)))
            {
                Response.Clear();
                Response.Buffer = true;
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(fp.ToArray());
                fp.Close();
                Response.End();
            }

            rpt_doc.Close();
            rpt_doc.Dispose();
        }
 protected void CrystalReportViewer1_Unload(object sender, EventArgs e)
 {
     crystalReport.Close();
     crystalReport.Dispose();
     CrystalReportViewer1.Dispose();
 }
Example #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["ReportData"] != null)
            {
                string rptFullPath = "";
                if (Session["option"].ToString() == "radSectionIntersects")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\UDI\rptMainStPavementStatus.rpt");
                }
                else if (Session["option"].ToString() == "radRegions")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\UDI\rptRegionsPavementStatus.rpt");
                }

                DataTable      dt  = (DataTable)Session["ReportData"];
                ReportDocument rpt = new ReportDocument();

                rpt.Load(rptFullPath);
                rpt.SetDataSource(dt);

                Session.Remove("ReportData");

                Stream memStream;
                Response.Buffer = false;
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();

                if (Request.QueryString["type"] == "x")
                {
                    ExcelFormatOptions excelOptions = new ExcelFormatOptions();
                    excelOptions.ExcelUseConstantColumnWidth = false;
                    rpt.ExportOptions.FormatOptions          = excelOptions;

                    memStream            = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.ExcelRecord);
                    Response.ContentType = "application/vnd.ms-excel";
                }
                else if (Request.QueryString["type"] == "w")
                {
                    memStream            = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);
                    Response.ContentType = "application/doc";
                }
                else
                {
                    memStream            = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    Response.ContentType = "application/pdf";
                    //memStream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);
                    //Response.ContentType = "application/msword";
                }



                byte[] ArryStream = new byte[memStream.Length + 1];
                memStream.Read(ArryStream, 0, System.Convert.ToInt32(memStream.Length));
                Response.BinaryWrite(ArryStream);
                Response.End();

                memStream.Flush();
                memStream.Close();
                memStream.Dispose();
                rpt.Close();
                rpt.Dispose();
                GC.Collect();
            }
            else
            {
                Response.Redirect("ViewPavementStatusReport.aspx", false);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Session["ReportData"] = null;
        }
    }
    private void GenerarPDF(bool EsNuevo)
    {
        try
        {
            PreInscrito PreInsc = (PreInscrito)Session["PreInsc"];
            if (PreInsc == null)//Nunca debe de pasar
                return;

            DBEscolarDataContext db = new DBEscolarDataContext();
            var Alumno = (from A in db.vwRPTPreInscripcions
                          where A.Folio == PreInsc.Folio
                          select A).FirstOrDefault();

            if (Alumno == null)
                return;

            System.Collections.ArrayList col = new System.Collections.ArrayList();
            col.Add(Alumno);
            ReportDocument rptDoc = new ReportDocument();

            if (EsNuevo)
                rptDoc.Load(Server.MapPath("Reportes/rptPreInscripcion.rpt"));
            else rptDoc.Load(Server.MapPath("Reportes/rptPreInscripcion_Re.rpt"));
            //set dataset to the report viewer.
            rptDoc.SetDataSource(col);

            MemoryStream stream = (MemoryStream)rptDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            rptDoc.Close();
            rptDoc.Dispose();

            Response.Clear();
            Response.ContentType = @"Application/pdf";
            Response.AddHeader("Content-Disposition", "inline; filename=File.pdf");
            //Response.AddHeader("Content-Disposition", "attachment; filename=File.pdf");
            Response.AddHeader("content-length", stream.Length.ToString());
            Response.BinaryWrite(stream.ToArray());
            Response.Flush();
            stream.Close();
            stream.Dispose();
        }
        catch (Exception e) { }
    }
        private void getreq()
        {
            try
            {
                string reqid, ReqDat;
                reqid  = Request.QueryString["REQID"];
                ReqDat = Request.QueryString["ReqDat"];

                cryRpt.Load(Server.MapPath("rpt_Req.rpt"));
                cryRpt.SetDatabaseLogon("sa", "friend", "ASAD-PC", "OrionFoods");
                //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["D"].ToString());

                if (reqid != null && ReqDat != "")
                {
                    cmd = new SqlCommand("SELECT * from v_Req where MReq_sono = '" + reqid + "' and MReq_dat = '" + ReqDat + "' and isactive = 1", con);
                }
                else if (reqid != null)
                {
                    cmd = new SqlCommand("SELECT * from v_Req where MReq_sono = '" + reqid + "' and isactive = 1 ", con);
                }
                else if (ReqDat != "")
                {
                    cmd = new SqlCommand("SELECT * from v_Req where MReq_dat = '" + ReqDat + "' and isactive = 1", con);
                }
                else if (reqid == null)
                {
                    cmd = new SqlCommand("SELECT * from v_Req where isactive = 1", con);
                }

                con.Open();
                //cmd.CommandType = CommandType.StoredProcedure;
                //cmd.Parameters.AddWithValue("@PurNo", "PO009");

                //cmd.CommandText = proc;
                //cmd.Parameters.Add("@PurNo", SqlDbType.VarChar).Value = "PO009";

                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable      dt  = new DataTable();
                sda.Fill(dt);
                cryRpt.SetDataSource(dt);
                //cryRpt.RecordSelectionFormula =
                cryRpt.SetParameterValue("Report Name", "Requisition Report");
                //cryRpt.SetParameterValue("ComName", "Orion Foods");
                //CrystalReportViewer1.ReportSource = cryRpt;
                //CrystalReportViewer1.DataBind();
                //ReportDocument rpt = (ReportDocument)Session[sessid];
                System.IO.Stream oStream   = null;
                byte[]           byteArray = null;
                oStream =
                    cryRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                byteArray = new byte[oStream.Length];
                oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(byteArray);
                Response.Flush();
                Response.Close();
                cryRpt.Close();
                cryRpt.Dispose();
                //rprt.Load(Server.MapPath("~/CrystalReport.rpt"));
                con.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void btnPrint_OnClickStep( IRNReportDetails form,  EventArgs args)
        {
            // TODO: Complete business rule implementation
            IAttachment attachment = null;
              		string pluginid = string.Empty;

               Sage.Entity.Interfaces.IRNReport parentEntity = form.CurrentEntity as Sage.Entity.Interfaces.IRNReport;

              if (ReportsHelper.GetPluginId("RNReport:Irnreport", out pluginid))
              {
              WebReportingClass reporting = new WebReportingClass();

            Sage.Platform.Data.IDataService datasvc = MySlx.Data.CurrentConnection;
              Sage.Entity.Interfaces.IUser user = MySlx.Security.CurrentSalesLogixUser;

              string tempPath = Rules.GetTempAttachmentPath();
            string ConnectionString = datasvc.GetConnectionString();

              string report = reporting.GenerateReport(ConnectionString,datasvc.Server,DatabaseServer.dsMSSQL,tempPath,false,false,"RNREPORT.RNREPORTID", "", pluginid, "", "",  "", "SELECT RNREPORT.RNREPORTID FROM RNREPORT", string.Format("(RNREPORT.RNREPORTID = '{0}')", parentEntity.Id), user.Id.ToString(),  user.UserName.ToString());

                ReportDocument doc = new ReportDocument();

                report = string.Format("{0}run\\{1}", tempPath, report);

                doc.Load(report);

                string filename = string.Format("{0}\\{1}_v{2}.pdf", Rules.GetAttachmentPath(), parentEntity.ReferenceNumber.Replace(" ", "_"), 1);

                doc.ExportToDisk(ExportFormatType.PortableDocFormat,filename);

              		doc.Close();

              attachment = Sage.Platform.EntityFactory.Create<IAttachment>();
              attachment.Description = string.Format("{0} v{1}", parentEntity.ReferenceNumber, 1);
              attachment.InsertFileAttachment(filename);
            attachment.RNREPORTID =Convert.ToString(parentEntity.Id);

              attachment.Save();

             System.IO.File.Delete(report);

              }
        }
Example #15
0
    protected void btnShow_Click(object sender, EventArgs e)
    {
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream();


        DateTime start   = new DateTime();
        DateTime Enddate = new DateTime();

        try
        {
            if (txtStrtDate.Text.ToString() != "")
            {
                string[] date = new string[3];
                date  = txtStrtDate.Text.Trim().Split('/');
                start = new DateTime(Convert.ToInt16(date[2]), Convert.ToInt16(date[1]), Convert.ToInt16(date[0]));
            }
            if (txtEndDate.Text.ToString() != "")
            {
                string[] enddate = new string[3];
                enddate = txtEndDate.Text.Trim().Split('/');
                Enddate = new DateTime(Convert.ToInt16(enddate[2]), Convert.ToInt16(enddate[1]), Convert.ToInt16(enddate[0]));
            }

            if (ChkExportExcel.Checked == true)
            {
                ArrayList pa = new ArrayList();
                ArrayList pv = new ArrayList();
                pa.Add("@EventTitle");
                pa.Add("@Category1");
                pa.Add("@Category2");
                pa.Add("@Year");
                pa.Add("@semester");
                pa.Add("@ItemType");
                pa.Add("@CalName");
                pa.Add("@StartDate");
                pa.Add("@EndDate");
                pv.Add(drpEvent.SelectedValue);
                pv.Add(DrpCat1.SelectedValue);
                pv.Add(drpCat2.SelectedValue);
                pv.Add(drpYear.SelectedValue);
                pv.Add(drpSem.SelectedValue);
                pv.Add(DrpType.SelectedValue);
                pv.Add(DrpCalendar.SelectedValue);
                pv.Add(txtStrtDate.Text.ToString() != "" ? start.ToString("yyyy/MM/dd") : "");
                pv.Add(txtStrtDate.Text.ToString() != "" ? Enddate.ToString("yyyy/MM/dd") : "");
                DataTable Dtb1 = new DataTable();
                DBH.CreateDataTableCalender(Dtb1, "SP_DeptwiseEvent", true, pa, pv);
                ExportToExcel(Dtb1);
            }
            else
            {
                string Path = Server.MapPath("DeptWiseCalendar.rpt");
                Path = Path.Substring(0, Path.LastIndexOf('\\'));
                Path = Path.Substring(0, Path.LastIndexOf('\\'));
                Path = Path + "\\Report\\DeptWiseCalendar.rpt";
                myReportDocument.Load(Path);
                //myReportDocument.SetDatabaseLogon("software", "DelFirMENA$idea", "192.168.167.207", "DB_SkylineCalendarEvents");
                myReportDocument.SetDatabaseLogon("software", "DelFirMENA$idea");
                myReportDocument.SetParameterValue("@DeptName", DrpCalendar.SelectedItem.Text);
                if (txtStrtDate.Text.ToString() != "")
                {
                    myReportDocument.SetParameterValue("@StartDate", start.ToString("yyyy/MM/dd"));
                }
                else
                {
                    myReportDocument.SetParameterValue("@StartDate", "");
                }
                if (txtStrtDate.Text.ToString() != "")
                {
                    myReportDocument.SetParameterValue("@EndDate", Enddate.ToString("yyyy/MM/dd"));
                }
                else
                {
                    myReportDocument.SetParameterValue("@EndDate", "");
                }

                myReportDocument.SetParameterValue("@EventTitle", drpEvent.SelectedValue);
                myReportDocument.SetParameterValue("@Category1", DrpCat1.SelectedValue);
                myReportDocument.SetParameterValue("@Category2", drpCat2.SelectedValue);
                myReportDocument.SetParameterValue("@Year", drpYear.SelectedValue);
                myReportDocument.SetParameterValue("@semester", drpSem.SelectedValue);
                myReportDocument.SetParameterValue("@ItemType", DrpType.SelectedValue);
                myReportDocument.SetParameterValue("@CalName", DrpCalendar.SelectedValue);

                System.IO.Stream oStream   = null;
                byte[]           byteArray = null;
                oStream   = myReportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                byteArray = new byte[oStream.Length];
                oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(byteArray);
                Response.Flush();
                Response.Close();
                myReportDocument.Close();
                myReportDocument.Dispose();
            }
        }
        catch (Exception Ex)
        {
            Response.Write(Ex.Message);
        }

        finally
        {
        }
    }
Example #16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["ReportData"] != null)
            {
                string rptFullPath = "";

                if (Session["type"].ToString() == "radByMainLanes" && Session["option"].ToString() == "radDetails")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptSectionsMaintenanceDecision.rpt");
                }
                else if (Session["type"].ToString() == "radByIntersections" && Session["option"].ToString() == "radDetails")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptIntersectMaintenancePriority.rpt");
                }
                else if (Session["type"].ToString() == "regions" && Session["option"].ToString() == "radDetails")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptRegionMaintenancePriority.rpt");
                }

                else if (Session["type"].ToString() == "radByMainLanes" && Session["option"].ToString() == "radTotal")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptSectionsMaintenanceDecisionSummary.rpt");
                }
                else if (Session["type"].ToString() == "radByIntersections" && Session["option"].ToString() == "radTotal")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptIntersectMaintenancePrioritySummary.rpt");
                }
                else if (Session["type"].ToString() == "regions" && Session["option"].ToString() == "radTotal")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptRegionMaintenancePrioritySummary.rpt");
                }

                else if (Session["option"].ToString() == "radMaintLengths")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\MD_Prio_cost\rptMaintDecAreaSummary.rpt");
                }
                else
                {
                    throw new Exception("Invalid report option!");
                }

                //else if (Session["type"].ToString() == "radByMainLanes" && Session["option"].ToString() == "radMaintLengths")
                //    rptFullPath = Server.MapPath(@".\RptFiles\rptSectionMainDecisionCostingSummary.rpt");
                //else if (Session["type"].ToString() == "radByIntersections" && Session["option"].ToString() == "radMaintLengths")
                //    rptFullPath = Server.MapPath(@".\RptFiles\rptIntersectMainDecisionCostingSummary.rpt");
                //else if (Session["type"].ToString() == "regions" && Session["option"].ToString() == "radMaintLengths")
                //    rptFullPath = Server.MapPath(@".\RptFiles\rptRegionMainDecisionCostingSummary.rpt");



                DataTable      dt  = (DataTable)Session["ReportData"];
                ReportDocument rpt = new ReportDocument();

                rpt.Load(rptFullPath);
                rpt.SetDataSource(dt);
                if (Session["type"].ToString() == "radByMainLanes" && Session["option"].ToString() == "radDetails")
                {
                    rpt.SetParameterValue("Title", "");
                }


                Session.Remove("ReportData");

                MemoryStream memStream;
                Response.Buffer = false;
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();

                if (Request.QueryString["type"] == "x")
                {
                    ExcelFormatOptions excelOptions = new ExcelFormatOptions();
                    excelOptions.ExcelUseConstantColumnWidth = false;
                    rpt.ExportOptions.FormatOptions          = excelOptions;

                    memStream            = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.ExcelRecord);
                    Response.ContentType = "application/vnd.ms-excel";
                }
                else
                {
                    memStream            = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    Response.ContentType = "application/pdf";
                    //memStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);
                    //Response.ContentType = "application/msword";
                }



                Response.BinaryWrite(memStream.ToArray());
                Response.End();

                memStream.Flush();
                memStream.Close();
                memStream.Dispose();
                rpt.Close();
                rpt.Dispose();
                GC.Collect();
            }
            else
            {
                Response.Redirect("BudgetMaintDecisions.aspx", false);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
        private string ExportarPDF()
        {
            DataSet                      GenDS = new DataSet();
            ReportDocument               oRD   = new ReportDocument();
            ExportOptions                oExO;
            DiskFileDestinationOptions   oExDo   = new DiskFileDestinationOptions();
            DsGuiasPlanillaRemitoCliente dsGuias = (DsGuiasPlanillaRemitoCliente)Session["DsGuiasPlanillaRemitoCliente"];
            DsGuiasPlanillaRemitoCliente dsag    = new DsGuiasPlanillaRemitoCliente();
            //IUnidadVenta unidadVenta = UnidadVentaFactory.GetUnidadVenta();
            //DsUnidadVentaTEntregaProductoServicio dsUVProductosServicios =unidadVenta.GetUnidadesProductosServicios();
            int nroPlanilla = Convert.ToInt32(this.lblNroPlanillaRemitoCliente.Text);

            try
            {
                string sNombrePDF = Server.MapPath(".") + "/ReportesPDF/" + "PlanReCliente_" + nroPlanilla + "_" + this.AgenciaConectadaID + ".pdf";
                string nombrePDf  = "PlanReCliente_" + nroPlanilla + "_" + this.AgenciaConectadaID + ".pdf";
                //Load report
                oRD.Load(Server.MapPath("." + "/Reportes/PlanillaRemCliente.rpt"));

                DsGuiasPlanillaRemitoCliente.GuiasRow[]        dv = (DsGuiasPlanillaRemitoCliente.GuiasRow[])dsGuias.Guias.Select("");
                DsGuiasPlanillaRemitoCliente.ComprobantesRow[] dw = (DsGuiasPlanillaRemitoCliente.ComprobantesRow[])dsGuias.Comprobantes.Select("");
                //Creo un nuevo registro Datos
                DsGuiasPlanillaRemitoCliente.DatosRow db = (DsGuiasPlanillaRemitoCliente.DatosRow)dsag.Datos.NewDatosRow();
                db.PlanillaRemitoClienteID = this.planillaRemitoClienteID;
                db.NroPlanillaRemito       = nroPlanilla;
                db.RazonSocial             = this.lblRazonSocial.Text;
                db.Fecha = Convert.ToDateTime(this.lblFecha.Text);

                dsag.Datos.AddDatosRow(db);

                foreach (DsGuiasPlanillaRemitoCliente.GuiasRow dr in dv)
                {
                    dsag.Guias.ImportRow(dr);
                }
                foreach (DsGuiasPlanillaRemitoCliente.ComprobantesRow dr in dw)
                {
                    dsag.Comprobantes.ImportRow(dr);
                }


                //dsag.Datos.ImportRow(db);
                oRD.SetDataSource(dsag);


                //Export to PDF
                oExDo.DiskFileName = sNombrePDF;
                oExO = oRD.ExportOptions;
                oExO.ExportDestinationType = ExportDestinationType.DiskFile;
                oExO.ExportFormatType      = ExportFormatType.PortableDocFormat;
                oExO.DestinationOptions    = oExDo;
                oRD.Export();
                oRD.Close();
                oRD.Dispose();

                return(nombrePDf);
            }
            catch (Exception ex)
            {
                string mensaje = "Error al exportar a PDF: " + ex.Message;

                ((ErrorWeb)this.phErrores.Controls[0]).setMensaje(mensaje);
                return("");
            }
            finally
            {
                oRD.Close();
                oRD.Dispose();
            }
        }
Example #18
0
 private void frmPrintPreview_FormClosing(object sender, FormClosingEventArgs e)
 {
     RptDoc.Close();
     //CleanTemporaryFolders();
     Dispose(true);
 }
Example #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //txtTitle.BackColor = Color.Transparent;
                string reportName = Session["ReportName"] as string;

                #region Test-Successed No Need

                /* if (!string.IsNullOrEmpty(reportName))
                 * {
                 * switch (reportName)
                 * {
                 *  case "InvestorPortfolioStatement":
                 *      InvestorPortfolioStatementLoader oLoader = Session["ReportObj"] as InvestorPortfolioStatementLoader;
                 *      crvReport.ReportSource = oLoader.GetReportSource();
                 *      txtTitle.Text = "Investor Portfolio Statement";
                 *      break;
                 *  case "StockBalancebyInvestor":
                 *      StockBalancebyInvestorLoader oStockBalancebyInvestorLoader = Session["ReportObj"] as StockBalancebyInvestorLoader;
                 *      crvReport.ReportSource = oStockBalancebyInvestorLoader.GetReportSource();
                 *      txtTitle.Text = "Stock Balance by Investor";
                 *      break;
                 *
                 *  case "InvestorLedgerStatement":
                 *      InvestorLedgerStatementLoader oInvestorLedgerStatementLoader = Session["ReportObj"] as InvestorLedgerStatementLoader;
                 *      crvReport.ReportSource = oInvestorLedgerStatementLoader.GetReportSource();
                 *      txtTitle.Text = "Investor Ledger Statement";
                 *      break;
                 *  case "ClientwiseTransactionSummaryStatement":
                 *      ClientwiseTransactionSummaryStatementLoader oClientwiseTransactionSummaryStatementLoader = Session["ReportObj"] as ClientwiseTransactionSummaryStatementLoader;
                 *      crvReport.ReportSource = oClientwiseTransactionSummaryStatementLoader.GetReportSource();
                 *      txtTitle.Text = "Clientwise Transaction Summary Statement Loader";
                 *      break;
                 *  case "InvestorsImmaturedCashBalance":
                 *
                 *      InvestorsImmatureCashBalanceLoader oInvestorsImmatureCashBalanceLoader = Session["ReportObj"] as InvestorsImmatureCashBalanceLoader;
                 *      crvReport.ReportSource = oInvestorsImmatureCashBalanceLoader.GetReportSource();
                 *      txtTitle.Text = "Investors Immatured Cash Balance";
                 *      break;
                 *  case "InstrumentWiseLedger":
                 *
                 *      InstrumentWiseLedgerLoader oInstrumentWiseLedgerLoader = Session["ReportObj"] as InstrumentWiseLedgerLoader;
                 *      crvReport.ReportSource = oInstrumentWiseLedgerLoader.GetReportSource();
                 *      txtTitle.Text = "Instrument Wise Ledger";
                 *      break;
                 *  case "InvestorLessCashBalance":
                 *      InvestorLessCashBalanceLoader oInvestorLessCashBalanceLoader = Session["ReportObj"] as InvestorLessCashBalanceLoader;
                 *      crvReport.ReportSource = oInvestorLessCashBalanceLoader.GetReportSource();
                 *      txtTitle.Text = "Investor Less Cash Balancer";
                 *      break;
                 *  case "InvestorsProfitandLossStatement":
                 *      InvestorsProfitandLossStatementLoader oInvestorsProfitandLossStatementLoader = Session["ReportObj"] as InvestorsProfitandLossStatementLoader;
                 *      crvReport.ReportSource = oInvestorsProfitandLossStatementLoader.GetReportSource();
                 *      txtTitle.Text = "Investors Profit and Loss Statement";
                 *      break;
                 *  default:
                 *      break;
                 * }*/
                #endregion

                ReportDocument rd = Session["ReportDocumentObj"] as ReportDocument;
                //ReportDocument rd = (ReportDocument)oReportLoader.GetReportSource();

                MemoryStream oStream;
                oStream = (MemoryStream)rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                Response.Clear();
                Response.Buffer      = true;
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(oStream.ToArray());
                Response.End();
                Response.Close();
                oStream.Dispose();
                rd.Close();
                rd.Dispose();
                GC.Collect();

                // txtTitle.Text = System.Text.RegularExpressions.Regex.Replace(reportName, "([A-Z])", " $1");
                // crvReport.Zoom(150);
                //crvReport.DisplayGroupTree = false;
                //crvReport.DisplayToolbar = true;
                //crvReport.HasPrintButton = true;
                //crvReport.DataBind();
                //crvReport.PrintMode = PrintMode.ActiveX;
                // CrystalReportViewer
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                throw ex;
            }
        }
Example #20
0
        public string Serialize(string rptPath, string filepath = null, int reportOrder = 1)//, OutputFormat fmt = OutputFormat.json)
        {
            var rpt = new ReportDocument();

            rpt.Load(rptPath);
            var rptClient = rpt.ReportClientDocument;

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CustomJsonResolver(),
                Formatting       = Formatting.Indented
            };

            string rptName = string.IsNullOrEmpty(rpt.Name)
                ? Path.GetFileNameWithoutExtension(rptPath)
                : rpt.Name;

            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (JsonWriter jw = new JsonTextWriter(sw))
            {
                jw.Formatting = Formatting.Indented;

                jw.WriteStartObject();

                jw.WriteObjectHierarchy("Entire Report Object", rpt);

                jw.WriteProperty("SerializeVersion", CRSerializeProductVersion());

                jw.WriteProperty("ReportName", rptName);

                jw.WriteParameters("Parameters", rpt);

                jw.WriteObjectHierarchy("SummaryInfo", rpt.SummaryInfo);

                // experimental properties:
                jw.WriteObjectHierarchy("DataSourceConnections", rpt.DataSourceConnections);

                jw.WriteObjectHierarchy("ParameterFields", rpt.ParameterFields);

                jw.WriteObjectHierarchy("ReportOptions", rptClient.ReportOptions);

                jw.WriteDataSource("DataSource", rptClient.Database.Tables);

                jw.WriteObjectHierarchy("DatabaseTables", rpt.Database.Tables);

                jw.WriteObjectHierarchy("DataDefinition", rpt.DataDefinition);

                jw.WritePrintOptions(rpt.PrintOptions);

                jw.WriteObjectHierarchy("CustomFunctions", rptClient.CustomFunctionController.GetCustomFunctions());

                jw.WriteObjectHierarchy("ReportDefinition", rpt.ReportDefinition);

                jw.WritePropertyName("Subreports");
                var subReports = rpt.Subreports;
                if (subReports.Count > 0)
                {
                    jw.WriteStartArray();
                    foreach (ReportDocument subReport in subReports)
                    {
                        var subReportClient = rptClient.SubreportController.GetSubreport(subReport.Name);

                        jw.WriteStartObject();
                        jw.WriteProperty("SubreportName", subReport.Name);

                        jw.WriteParameters("Parameters", subReport);

                        jw.WriteDataSource("DataSource", subReportClient.DataDefController.Database.Tables);

                        jw.WriteObjectHierarchy("DatabaseTables", subReport.Database.Tables);

                        jw.WriteObjectHierarchy("DataDefinition", subReport.DataDefinition);

                        jw.WriteObjectHierarchy("CustomFunctions", rptClient.CustomFunctionController.GetCustomFunctions());

                        jw.WriteObjectHierarchy("ReportDefinition", subReport.ReportDefinition);

                        jw.WriteEndObject();
                    }
                }

                jw.WriteEndObject(); // final end
                rpt.Close();

                return(sb.ToString());
            }
        }
        private string ExportarPDF(int solicitud)
        {                       //cuando venga 0 en solicitud se han pedidos todas
            string empresa = System.Configuration.ConfigurationSettings.AppSettings["empresa"];
            DsSolicitudRetiroImpresion dsSolicitud = new DsSolicitudRetiroImpresion();
            //el dataset que le voy a pasar al generador de reportes crystal
            ISolicitudRetiro sol = SolicitudRetiroFactory.GetSolicitudRetiroFactory();


            if (solicitud == 0)           //quiero todas
            {
                if (Session["DsSolicitudRetiro"] != null)
                {
                    sol.ClienteID       = Utiles.Validaciones.obtieneEntero(busqCliente.ClienteID);
                    sol.NumeroSolicitud = Utiles.Validaciones.obtieneEntero(txtNumSolicitud.Text);
                    sol.AgenciaRetiroID = usuario.AgenciaID;                   //la agencia conectada

                    /*if (chCerradas.Checked)
                     *      sol.EstadoSolicitudID=(int)NegociosSisPackInterface.SisPack.EstadoSolicitud.Cerrada;
                     * else if (chControladas.Checked)
                     *      sol.EstadoSolicitudID=(int)NegociosSisPackInterface.SisPack.EstadoSolicitud.Controlada;
                     * else
                     *      sol.EstadoSolicitudID=0;//todas
                     */

                    if (this.ddlTipo.SelectedValue == "1")                     // Web
                    {
                        if ((chCerradas.Checked) && (chControladas.Checked == false))
                        {
                            sol.EstadoSolicitudID = (int)NegociosSisPackInterface.SisPack.EstadoSolicitud.CerradaWeb;
                        }
                        else if ((chControladas.Checked) && (chCerradas.Checked == false))
                        {
                            sol.EstadoSolicitudID = (int)NegociosSisPackInterface.SisPack.EstadoSolicitud.ControladaWeb;
                        }
                        else if ((chControladas.Checked) && (chCerradas.Checked))
                        {
                            sol.EstadoSolicitudID = 0;                          //todas
                        }
                    }
                    else if (this.ddlTipo.SelectedValue == "2")                     // Autogestión
                    {
                        if ((chCerradas.Checked) && (chControladas.Checked == false))
                        {
                            sol.EstadoSolicitudID = (int)NegociosSisPackInterface.SisPack.EstadoSolicitud.Cerrada;
                        }
                        else if ((chControladas.Checked) && (chCerradas.Checked == false))
                        {
                            sol.EstadoSolicitudID = (int)NegociosSisPackInterface.SisPack.EstadoSolicitud.Controlada;
                        }
                        else if ((chControladas.Checked) && (chCerradas.Checked))
                        {
                            sol.EstadoSolicitudID = 0;                          //todas
                        }
                    }
                    int desdeWeb = (this.ddlTipo.SelectedValue == "1")?1:0;

                    //dsSolicitud = sol.GetSolicitudRetiroALLDataSet(desdeWeb);
                }
            }
            else             //quiero solo una
            {
                sol.SolicitudRetiroID = solicitud;
                dsSolicitud           = (DsSolicitudRetiroImpresion)sol.ConsultarSolicitudAImprimir();
            }

            /*para guardar la imagen del codigo de barra correspondiente en el dataset descomentar */
            //			for (int i=0; i<dsSolicitud.Orden.Count;i++)
            //			{
            //				byte[] d= null;
            //				DsSolicitudRetiroImpresion.OrdenRow drOrden= (DsSolicitudRetiroImpresion.OrdenRow) dsSolicitud.Orden.Rows[i];
            //				d = ConversionImagen(Server.MapPath("." + "/Reportes/images/CB/"+ drOrden["OrdenRetiroID"].ToString() + ".JPG"));
            //				drOrden["Codigo"]=d;
            //			}
            /*para guardar la imagen del logo de la empresa en el dataset */
            for (int i = 0; i < dsSolicitud.Orden.Count; i++)
            {
                byte[] d = null;
                DsSolicitudRetiroImpresion.OrdenRow drOrden = (DsSolicitudRetiroImpresion.OrdenRow)dsSolicitud.Orden.Rows[i];
                d = ConversionImagen(Server.MapPath("." + "/Reportes/images/" + empresa + ".JPG"));
                drOrden["Codigo"] = d;
            }

            byte[] im = null;
            DsSolicitudRetiroImpresion.SolicitudRow dr = (DsSolicitudRetiroImpresion.SolicitudRow)dsSolicitud.Solicitud.Rows[0];
            im = ConversionImagen(Server.MapPath("." + "/Reportes/images/blanco.JPG"));
            for (int i = 0; i < dsSolicitud.Solicitud.Count; i++)
            {
                dr["Imagen"] = im;
            }

            if ((dsSolicitud.Solicitud.Count > 0) && (dsSolicitud.Orden.Count > 0))
            {
                ReportDocument             oRD = new ReportDocument();
                ExportOptions              oExO;
                DiskFileDestinationOptions oExDo = new DiskFileDestinationOptions();
                string nombArchi  = "SolicitudRetiro_" + solicitud + "_" + this.AgenciaConectadaID + ".pdf";
                string sNombrePDF = Server.MapPath(".") + "/ReportesPDF/" + nombArchi;
                if (System.IO.File.Exists(sNombrePDF))
                {
                    System.IO.File.Delete(sNombrePDF);
                }
                oRD.Load(Server.MapPath("." + "/Reportes/ReporteSolicitudRetiro.rpt"));
                oRD.SetDataSource(dsSolicitud);
                oExDo.DiskFileName = sNombrePDF;
                oExO = oRD.ExportOptions;
                oExO.ExportDestinationType = ExportDestinationType.DiskFile;
                oExO.ExportFormatType      = ExportFormatType.PortableDocFormat;
                oExO.DestinationOptions    = oExDo;
                oRD.Export();
                oRD.Close();
                oRD.Dispose();
                return(nombArchi);
            }
            else
            {
                ((ErrorWeb)this.phErrores.Controls[0]).setMensaje("No se ha podido consultar los datos de la solicitud");
                return("");
            }
        }
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            DataTable dtSavAmt = (DataTable)Session["SavAmt"];

            DataSet1TableAdapters.SP_fundAmtTableAdapter fundsAmtAdapter;
            fundsAmtAdapter = new DataSet1TableAdapters.SP_fundAmtTableAdapter();


            /*Check subreport*/
            string chkSubRep = string.Empty;

            /*Show both*/
            if (ddlSavYear.SelectedValue.ToString() != "00" && ddlSavYearP.SelectedValue.ToString() != "00")
            {
                chkSubRep = "1";
            }
            /*Show Surrender*/
            else if (ddlSavYear.SelectedValue.ToString() != "00" && ddlSavYearP.SelectedValue.ToString() == "00")
            {
                chkSubRep = "2";
            }
            /*Show Paidup*/
            else if (ddlSavYear.SelectedValue.ToString() == "00" && ddlSavYearP.SelectedValue.ToString() != "00")
            {
                chkSubRep = "3";
            }
            /*Don't show*/
            else
            {
                chkSubRep = "0";
            }

            DataSet1.SP_fundAmtDataTable a;
            a = fundsAmtAdapter.GetData(dtSavAmt.Rows[0]["gender"].ToString(), dtSavAmt.Rows[0]["age"].ToString(), dtSavAmt.Rows[0]["savamt"].ToString(), chkSubRep);
            DataTable b = new DataTable();

            b = a;

            DataSet1TableAdapters.SP_BenefitTableAdapter benAdp;
            benAdp = new DataSet1TableAdapters.SP_BenefitTableAdapter();
            DataSet1.SP_BenefitDataTable ben;
            ben = benAdp.GetData(dtSavAmt.Rows[0]["gender"].ToString(), dtSavAmt.Rows[0]["age"].ToString(), dtSavAmt.Rows[0]["savamt"].ToString());
            DataTable repBen = new DataTable();

            repBen = ben;

            DataSet1TableAdapters.SP_SurrenderTableAdapter surrenderAdp;
            surrenderAdp = new DataSet1TableAdapters.SP_SurrenderTableAdapter();
            DataSet1.SP_SurrenderDataTable c;
            c = surrenderAdp.GetData(dtSavAmt.Rows[0]["gender"].ToString(), dtSavAmt.Rows[0]["age"].ToString(), ddlSavYear.SelectedValue.ToString(), dtSavAmt.Rows[0]["savamt"].ToString());
            DataTable d = new DataTable();

            d = c;

            DataSet1TableAdapters.SP_PaidUpTableAdapter paidupAdp;
            paidupAdp = new DataSet1TableAdapters.SP_PaidUpTableAdapter();
            DataSet1.SP_PaidUpDataTable f;
            f = paidupAdp.GetData(dtSavAmt.Rows[0]["gender"].ToString(), dtSavAmt.Rows[0]["age"].ToString(), ddlSavYearP.SelectedValue.ToString(), dtSavAmt.Rows[0]["savamt"].ToString());
            DataTable g = new DataTable();

            g = f;

            ReportDocument rpt         = new ReportDocument();
            string         _pathReport = Server.MapPath("~/R001_fundAmt.rpt");

            rpt.Load(_pathReport);

            rpt.SetDataSource(b);
            rpt.Subreports["sub_benefit"].SetDataSource(repBen);
            rpt.Subreports["sub_surrender"].SetDataSource(d);
            rpt.Subreports["sub_paidup"].SetDataSource(g);

            BinaryReader stream = new BinaryReader(rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat));

            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename=" + "BaaclifePer2.pdf");
            Response.AddHeader("content-length", stream.BaseStream.Length.ToString());
            Response.BinaryWrite(stream.ReadBytes(Convert.ToInt32(stream.BaseStream.Length)));
            Response.Flush();
            Response.Close();
            rpt.Close();
            rpt.Dispose();
        }
Example #23
0
 public void Dispose()
 {
     try
     {
         reportDocument.Dispose();
         reportDocument = null;
         reportDocument.Close();
     }
     catch
     {
     }
 }
Example #24
0
        void initialize_report(int type)
        {
            string[] rptCred = null;
            System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(
                ConfigurationManager.ConnectionStrings["SmartConcepcion"].ConnectionString);

            rptCred = GetConfigSetting("rptbackoffice").Split('$');
            long?  recid;
            string _title;
            string _reason = "";

            switch (type)
            {
            case 1:
                #region Barangay Cert
                recid      = convert_long(Request.QueryString["id"], false);
                _title     = Request.QueryString["title"];
                this.Title = _title;
                rpt        = new ReportDocument();
                rpt.Load(Server.MapPath("~/portal/Reports/barangayclearance.rpt"));
                rpt.SetParameterValue("@id", recid);

                rptCred = GetConfigSetting("rptbackoffice").Split('$');
                rpt.DataSourceConnections.Clear();
                rpt.DataSourceConnections[0].SetConnection(cn.DataSource, cn.Database, rptCred[0], rptCred[1]);
                rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, this.Title + " (" + DateTime.Now.ToString("MM/dd/yy hh:mm tt") + ")");
                rpt.Close();
                rpt.Dispose();
                #endregion

                break;

            case 2:
                #region Barangay Indigency
                recid = convert_long(Request.QueryString["id"], false);

                _title     = Request.QueryString["title"];
                _reason    = Request.QueryString["reason"];
                this.Title = _title;
                rpt        = new ReportDocument();
                rpt.Load(Server.MapPath("~/portal/Reports/indigency.rpt"));
                rpt.SetParameterValue("@id", recid);
                rpt.SetParameterValue("Reason", _reason);

                rptCred = GetConfigSetting("rptbackoffice").Split('$');
                rpt.DataSourceConnections.Clear();
                rpt.DataSourceConnections[0].SetConnection(cn.DataSource, cn.Database, rptCred[0], rptCred[1]);
                rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, this.Title + " (" + DateTime.Now.ToString("MM/dd/yy hh:mm tt") + ")");
                rpt.Close();
                rpt.Dispose();
                #endregion

                break;

            case 3:
                #region Summon Letter
                recid      = convert_long(Request.QueryString["id"], false);
                _title     = Request.QueryString["title"];
                this.Title = _title;
                rpt        = new ReportDocument();
                rpt.Load(Server.MapPath("~/portal/Reports/IRLetterOfInvitation.rpt"));
                rpt.SetParameterValue("@id", recid);

                rptCred = GetConfigSetting("rptbackoffice").Split('$');
                rpt.DataSourceConnections.Clear();
                rpt.DataSourceConnections[0].SetConnection(cn.DataSource, cn.Database, rptCred[0], rptCred[1]);
                rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, this.Title + " (" + DateTime.Now.ToString("MM/dd/yy hh:mm tt") + ")");
                rpt.Close();
                rpt.Dispose();
                #endregion

                break;
            }
        }
    public void PrintReport(Page _Page, string _ReportName, string _FileName, DataTable[] dts, string[] _DSTableName,
        string[] paramNames = null, string[] paramValues = null)
    {
        paramNames = paramNames == null ? new string[] { } : paramNames;
        paramValues = paramValues == null ? new string[] { } : paramValues;
        dts = dts == null ? new DataTable[] { } : dts;
        _DSTableName = _DSTableName == null ? new string[] { } : _DSTableName;

        ReportDocument rptDoc = new ReportDocument();
        try
        {
            rptDoc.Load(_Page.Server.MapPath("~/Reports/" + _ReportName));

            dsPSMS ds = new dsPSMS();
            for (int i = 0; i < dts.Length; i++)
            {
                ds.Tables[_DSTableName[i]].Merge(dts[i]);
            }
            if (dts.Length > 0)
                rptDoc.SetDataSource(ds);

            if (paramNames.Length == paramValues.Length)
            {
                for (int i = 0; i < paramNames.Length; i++)
                    rptDoc.SetParameterValue(paramNames[i], paramValues[i]);
            }

            rptDoc.SetDatabaseLogon(dbINFO._UID, dbINFO._PWD, dbINFO._SRV, dbINFO._CAT);
            _Page.Response.Buffer = false;
            _Page.Response.ClearContent();
            _Page.Response.ClearHeaders();
            //Export the Report to Response stream in PDF format and file name Customers
            rptDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, _Page.Response, true, _FileName);

            _Page.Response.ClearContent();
            _Page.Response.ClearHeaders();
            _Page.Response.Clear();
            _Page.Response.Close();
        }
        catch (Exception ex)
        {
            //DO NOTHING
        }
        finally
        {
            rptDoc.Close();
            rptDoc.Dispose();
        }
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        string userType = "";
        string userName = "";

        if (Session["userName"] == null)
        {
            Response.Redirect("Default.aspx");
        }
        else
        {
            userName            = Session["userName"].ToString();
            userType            = Session["userType"].ToString();
            loginLink.Visible   = false;
            logoutLink.Visible  = true;
            reportsLink.Visible = true;
            addinfoLink.Visible = true;
            mapLink.Visible     = true;
            faqLink.Visible     = true;
        }
        if (userType == null)
        {
            Response.Redirect("Default.aspx");
        }
        else if (userType == "Super-Admin")
        {
            addUser.Visible    = true;
            dl.Visible         = true;
            adminPanel.Visible = true;
            user.InnerText     = "Super-Admin";
        }
        else if (userType == "Sesip-Admin")
        {
            addUser.Visible    = true;
            dl.Visible         = true;
            adminPanel.Visible = true;
            user.InnerText     = "Sesip-Admin";
        }
        else if (userType == "Programmer")
        {
            addUser.Visible = true;
            dl.Visible      = true;
            user.InnerText  = "Programmer";
        }
        else if (userType == "Assistant-Programmer")
        {
            dl.Visible     = true;
            user.InnerText = "Assistant-Programmer";
        }
        else if (userType == "ILC-Admin")
        {
            faqLink.Visible = false;
            Response.Redirect("Default.aspx");
            user.InnerText = "ILC-Admin";
        }
        if (!IsPostBack)
        {
        }
        else
        {
            string        districtName = ilcDistrictDDL.SelectedValue.ToString();
            string        districtID   = "";
            SqlConnection con          = new SqlConnection(ConfigurationManager.ConnectionStrings["ILCDBConnectionString"].ToString());
            SqlDataReader dr;
            SqlCommand    cmd;
            con.Open();
            string query = "SELECT DistCode FROM tblDistrict WHERE DistName = '" + districtName + "'";
            cmd = new SqlCommand(query, con);
            dr  = cmd.ExecuteReader();
            if (dr.Read())
            {
                districtID = dr[0].ToString();
            }
            Session["districtID"] = districtID;
            con.Close();

            rprt.Load(Server.MapPath("~/rptDistrictWiseTodaysILCReport.rpt"));
            rprt.SetDatabaseLogon("sa", "sqladmin@123", "103.234.26.37", "SESIP", true);
            SqlConnection conRpt = new SqlConnection(ConfigurationManager.ConnectionStrings["ILCDBConnectionString"].ToString());
            SqlCommand    cmdRpt = new SqlCommand("SP_ILC_Server_Active_Status_District", conRpt);
            cmdRpt.CommandType = CommandType.StoredProcedure;
            cmdRpt.Parameters.AddWithValue("@vDistCode", districtID);
            SqlDataAdapter sda = new SqlDataAdapter(cmdRpt);
            DataSet        ds  = new DataSet();
            sda.Fill(ds);
            rprt.SetDataSource(ds);
            crv.ReportSource = rprt;
            ParameterField         field1 = this.crv.ParameterFieldInfo[0];
            ParameterDiscreteValue val1   = new ParameterDiscreteValue();
            val1.Value = districtID;
            field1.CurrentValues.Add(val1);
            rprt.Close();
            rprt.Dispose();
        }
    }
Example #27
0
 protected void Page_Unload(object sender, EventArgs e)
 {
     report.Close();
     report.Dispose();
 }
    override protected void OnInit(EventArgs e)
    {
        InitializeComponent();
        base.OnInit(e);

        try
        {
            bool   bMostrar = true;
            int    int_pinicio;
            int    int_pfin;
            string strServer;
            string strDataBase;
            string strUid;
            string strPwd;

            string pf = "ctl00$CPHC$";

//            pf = "";
//				obtengo de la cadena de conexión los parámetros para luego
//				modificar localizaciones

            string strconexion = Utilidades.CadenaConexion;
            int_pfin  = strconexion.IndexOf(";database=", 0);
            strServer = strconexion.Substring(7, int_pfin - 7);

            int_pinicio = int_pfin + 10;
            int_pfin    = strconexion.IndexOf(";uid=", int_pinicio);
            strDataBase = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            int_pinicio = int_pfin + 5;
            int_pfin    = strconexion.IndexOf(";pwd=", int_pinicio);
            strUid      = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            int_pinicio = int_pfin + 5;
            int_pfin    = strconexion.IndexOf(";Trusted_Connection=", int_pinicio);
            strPwd      = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            //creo un objeto ReportDocument
            ReportDocument rdInforme = new ReportDocument();

            try
            {
                rdInforme.Load(Server.MapPath(".") + @"\sup_salprov.rpt");
            }
            catch (Exception ex)
            {
                rdInforme.Close();
                rdInforme.Dispose();
                Response.Write("Error al abrir el report: " + ex.Message);
            }

            try
            {
                rdInforme.SetDatabaseLogon(strUid, strPwd, strServer, strDataBase);
            }
            catch (Exception ex)
            {
                rdInforme.Close();
                rdInforme.Dispose();
                Response.Write("Error al logarse al report: " + ex.Message);
            }

            //creo un objeto logon .

            CrystalDecisions.Shared.TableLogOnInfo tliCurrent;
            try
            {
                foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in rdInforme.Database.Tables)
                {
                    //obtengo el logon por tabla
                    tliCurrent = tbCurrent.LogOnInfo;

                    tliCurrent.ConnectionInfo.DatabaseName = strDataBase;
                    tliCurrent.ConnectionInfo.UserID       = strUid;
                    tliCurrent.ConnectionInfo.Password     = strPwd;
                    tliCurrent.ConnectionInfo.ServerName   = strServer;

                    //aplico los cambios hechos al objeto TableLogonInfo
                    tbCurrent.ApplyLogOnInfo(tliCurrent);
                }
            }
            catch (Exception ex)
            {
                rdInforme.Close();
                rdInforme.Dispose();
                Response.Write("Error al actualizar la localización: " + ex.Message);
            }
            string strTipoFormato = Request.Form[pf + "FORMATO"]; // ESTO LO RECOGERE COMO PARAMETRO
            strControl = strTipoFormato;

            DiskFileDestinationOptions diskOpts = ExportOptions.CreateDiskFileDestinationOptions();
            ExportOptions exportOpts            = new ExportOptions();

            try
            {
                rdInforme.SetParameterValue("CABECERA", "PROVISIONES DE GASTO");


                rdInforme.SetParameterValue("path", Server.MapPath(".") + "//");

                string sConcepto = "";
                if (Request.Form[pf + "cboConceptoEje"] == "0")
                {
                    sConcepto = "Estructura organizativa";                                         //Estructura.getDefCorta(Estructura.sTipoElem.NODO) ;
                }
                else if (Request.Form[pf + "cboConceptoEje"] == "7")
                {
                    sConcepto = "Cliente";
                }
                else if (Request.Form[pf + "cboConceptoEje"] == "8")
                {
                    sConcepto = "Naturaleza";
                }
                else if (Request.Form[pf + "cboConceptoEje"] == "9")
                {
                    sConcepto = "Responsable de proyecto";
                }
                else if (Request.Form[pf + "cboConceptoEje"] == "10")
                {
                    sConcepto = "Proyecto";
                }

                rdInforme.SetParameterValue("CONCEPTO", sConcepto);

                rdInforme.SetParameterValue("@nOpcion", Request.Form[pf + "hdnConcepto"]);

                if (SUPER.Capa_Negocio.Utilidades.EsAdminProduccion())
                {
                    rdInforme.SetParameterValue("@t314_idusuario", 0);
                }
                else
                {
                    rdInforme.SetParameterValue("@t314_idusuario", Session["UsuarioActual"].ToString());
                }

                rdInforme.SetParameterValue("FechaDesde", Request.Form[pf + "hdntxtFecDesde"]);
                rdInforme.SetParameterValue("FechaHasta", Request.Form[pf + "hdntxtFecHasta"]);
                rdInforme.SetParameterValue("@nDesde", Request.Form[pf + "hdnDesde"]);
                rdInforme.SetParameterValue("@nHasta", Request.Form[pf + "hdnHasta"]);

                rdInforme.SetParameterValue("@nNivelEstructura", Request.Form[pf + "hdnNivelEstructura"]);
                rdInforme.SetParameterValue("@t301_categoria", Request.Form[pf + "cboCategoria"]);
                rdInforme.SetParameterValue("@t305_cualidad", Request.Form[pf + "cboCualidad"]);
                rdInforme.SetParameterValue("@sPSN", Request.Form[pf + "hdnPSNs"]);
                rdInforme.SetParameterValue("@sClientes", Request.Form[pf + "hdnClientes"]);
                rdInforme.SetParameterValue("@sResponsables", Request.Form[pf + "hdnResponsables"]);
                rdInforme.SetParameterValue("@sNaturalezas", Request.Form[pf + "hdnNaturalezas"]);
                rdInforme.SetParameterValue("@sHorizontal", Request.Form[pf + "hdnHorizontales"]);
                rdInforme.SetParameterValue("@sModeloContrato", Request.Form[pf + "hdnModeloCons"]);
                rdInforme.SetParameterValue("@sContrato", Request.Form[pf + "hdnContratos"]);
                rdInforme.SetParameterValue("@sIDEstructura", Request.Form[pf + "hdnEstrucAmbitos"]);
                rdInforme.SetParameterValue("@sSectores", Request.Form[pf + "hdnSectores"]);
                rdInforme.SetParameterValue("@sSegmentos", Request.Form[pf + "hdnSegmentos"]);

                rdInforme.SetParameterValue("@bComparacionLogica", Request.Form[pf + "rdbOperador"]);

                rdInforme.SetParameterValue("@sCNP", Request.Form[pf + "hdnCNP"]);
                rdInforme.SetParameterValue("@sCSN1P", Request.Form[pf + "hdnCSN1P"]);
                rdInforme.SetParameterValue("@sCSN2P", Request.Form[pf + "hdnCSN2P"]);
                rdInforme.SetParameterValue("@sCSN3P", Request.Form[pf + "hdnCSN3P"]);
                rdInforme.SetParameterValue("@sCSN4P", Request.Form[pf + "hdnCSN4P"]);
                rdInforme.SetParameterValue("@t329_idclaseeco", (Request.Form[pf + "hdnConceptoContable"] == "")? null:(int?)int.Parse(Request.Form[pf + "hdnConceptoContable"].ToString()));
                rdInforme.SetParameterValue("@sProveedores", Request.Form[pf + "hdnProveedores"]);

                rdInforme.SetParameterValue("@t422_idmoneda", Session["MONEDA_VDC"].ToString());
                rdInforme.SetParameterValue("ImportesEn", "* Importes en " + Session["DENOMINACION_VDC"].ToString());

                //rdInforme.SetParameterValue("path", Server.MapPath(".") + "\\..\\..\\Rpts//");
            }
            catch (Exception ex)
            {
                rdInforme.Close();
                rdInforme.Dispose();
                Response.Write("Error al actualizar los parámetros del report: " + ex.Message);
            }
            try
            {
                System.IO.Stream oStream;
                byte[]           byteArray = null;

                switch (strTipoFormato)
                {
                //			PDF
                case "PDF":
                    oStream   = rdInforme.ExportToStream(ExportFormatType.PortableDocFormat);
                    byteArray = new byte[oStream.Length];
                    oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                    break;

                case "EXC":
                    oStream   = rdInforme.ExportToStream(ExportFormatType.Excel);
                    byteArray = new byte[oStream.Length];
                    oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                    break;

                case "EXC2":
                    //
                    rdInforme.ExportToHttpResponse(ExportFormatType.Excel, Response, true, "Exportacion");
                    bMostrar = false;
                    break;
                }

                // FIN
                if (bMostrar)
                {
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();

                    //String nav = HttpContext.Current.Request.Browser.Browser.ToString();
                    //if (nav.IndexOf("IE") == -1)
                    //{
                    switch (strTipoFormato)
                    {
                    case "PDF":
                        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "Filename.pdf"));
                        break;

                    case "EXC":
                        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "Filename.xls"));
                        break;
                    }
                    //}
                    switch (strTipoFormato)
                    {
                    //			PDF
                    case "PDF":
                        Response.ContentType = "application/pdf";
                        break;

                    case "EXC":
                        //		EXCEL
                        Response.ContentType = "application/xls";
                        break;
                    }
                    Response.BinaryWrite(byteArray);

                    //Response.Flush();
                    //Response.Close();
                    //HttpContext.Current.Response.End();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                rdInforme.Close();
                rdInforme.Dispose();
                Response.Write("Error al exportar el report: " + ex.Message);
            }
        }
        //handle any exceptions
        catch (Exception ex)
        {
            Response.Write("No se puede crear el report: " + ex.Message);
        }
    }
		private void GeneratePDF()
		{
			ReportDocument rpt = new ReportDocument();

			switch (cboReportType.SelectedItem.Text)
			{
                case "Posted PO":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PostedPO.rpt"));
                    break;
                case "Posted PO Returns":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PostedPOReturns.rpt"));
                    break;
                case "Posted Debit Memo":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PostedDebitMemo.rpt"));
                    break;
                case "By Vendor":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PurchaseAnalysis.rpt"));
                    break;
                default:
                    return;
					
			}

			ExportOptions exportop = new ExportOptions();
			DiskFileDestinationOptions dest = new DiskFileDestinationOptions();
			
			string strPath = Server.MapPath(@"\retailplus\temp\");

			string strFileName = cboReportType.SelectedItem.Text.Replace(" ", "").ToLower() + "_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + ".pdf";
			if (System.IO.File.Exists(strPath + strFileName))
				System.IO.File.Delete(strPath + strFileName);

			dest.DiskFileName = strPath + strFileName;

			exportop = rpt.ExportOptions;
	
			SetDataSource(rpt);

			exportop.DestinationOptions = dest;
			exportop.ExportDestinationType = ExportDestinationType.DiskFile;
			exportop.ExportFormatType = ExportFormatType.PortableDocFormat;
			rpt.Export();   rpt.Close();    rpt.Dispose();

			fraViewer.Attributes.Add("src",Constants.ROOT_DIRECTORY + "/temp/" + strFileName);
		}
 private void GPreportdatewise_Unload(object sender, System.EventArgs e)
 {
     rpt.Close();
     rpt.Dispose();
     GC.Collect();
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["ReportData"] != null && Session["option"] != null)
            {
                string rptFullPath = "";

                if (Session["option"].ToString() == "radByRegion" || Session["option"].ToString() == "radbyMunicName")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\UDI\JPMMS_SecST_UDI_REG.RPT");
                }
                else if (Session["option"].ToString() == "radByRegionTotal")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\UDI\JPMMS_Reg_avg_UDI.RPT");
                }
                else if (Session["option"].ToString() == "radByRegionName" || Session["option"].ToString() == "radByRegionsAreaName")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\UDI\jpmms_secst_udi_subdist.RPT");
                }
                //else if ()
                //    rptFullPath = Server.MapPath(@".\RptFiles\jpmms_secst_udi_subdist.RPT"); //JPMMS_Reg_avg_UDI_Subdist.RPT");
                else if (Session["option"].ToString() == "radByRegionDistress")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\UDI\rptRegionsSecStDists.rpt");
                }
                else
                {
                    throw new Exception("Invalid report option!");
                }


                DataTable      dt  = (DataTable)Session["ReportData"];
                ReportDocument rpt = new ReportDocument();

                rpt.Load(rptFullPath);
                rpt.SetDataSource(dt);

                Session.Remove("ReportData");

                MemoryStream memStream;
                Response.Buffer = false;
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();

                if (Request.QueryString["type"] == "x")
                {
                    ExcelFormatOptions excelOptions = new ExcelFormatOptions();
                    excelOptions.ExcelUseConstantColumnWidth = false;
                    rpt.ExportOptions.FormatOptions          = excelOptions;

                    memStream            = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.ExcelRecord);
                    Response.ContentType = "application/vnd.ms-excel";
                }
                else
                {
                    memStream            = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    Response.ContentType = "application/pdf";
                    //memStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);
                    //Response.ContentType = "application/msword";
                }



                Response.BinaryWrite(memStream.ToArray());
                Response.End();

                memStream.Flush();
                memStream.Close();
                memStream.Dispose();
                rpt.Close();
                rpt.Dispose();
                GC.Collect();
            }
            else
            {
                Response.Redirect("PavementEvalRegionReport.aspx", false);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Session["ReportData"] = null;
        }
    }
        public string ImprimirVenta(VentaBE obe)//List<CodigoBarraBE> lstReporteCodigoBarras)
        {
            try
            {
                //List<CodigoBarraBE> lstReporteCodigoBarrasF = new List<CodigoBarraBE>();
                List <ImprimirComprobanteBE> lobj = new List <ImprimirComprobanteBE>();
                ImprimirComprobanteBE        obj  = new ImprimirComprobanteBE();

                if (obe != null)
                {
                    if (obe.loDetalle.Count > 0)
                    {
                        for (var i = 0; i < obe.loDetalle.Count; i += 1)
                        {
                            obj = new ImprimirComprobanteBE();
                            obj.NombreComercial   = obe.c_emisor_nombre_comercial;
                            obj.NombreLegal       = obe.c_emisor_nombre_legal;
                            obj.RUC               = obe.c_emisor_numero_documento;
                            obj.Direccion         = obe.c_emisor_direccion;
                            obj.DireccionL1       = obe.c_emisor_urbanizacion;
                            obj.DireccionL2       = obe.c_emisor_distrito.Substring(3);
                            obj.DireccionL3       = obe.c_emisor_provincia.Substring(3);
                            obj.DireccionL4       = obe.c_emisor_departamento.Substring(3);
                            obj.DireccionL5       = obe.c_emisor_direccion;
                            obj.NombreComprobante = obe.c_tipo_documento_nombre;
                            obj.NumeroComprobante = obe.c_id_documento;
                            obj.FechaEmision      = DateTime.Now.ToString("dd/MM/yyyy"); // obe.c_fecha_emision;
                            //obj.HoraEmision = obe.XXXXXX;
                            obj.CodigoProducto      = Convert.ToString(obe.loDetalle[i].c_id_producto);
                            obj.DescripcionProducto = Convert.ToString(obe.loDetalle[i].c_decripcion);
                            obj.Cantidad            = Convert.ToString(obe.loDetalle[i].n_cantidad);
                            obj.Preciounitario      = Convert.ToString(obe.loDetalle[i].n_precio_unitario);
                            obj.Subtotal            = Convert.ToString(obe.loDetalle[i].n_total_venta);
                            obj.OperacionGravada    = Convert.ToString(obe.n_total_venta - obe.n_total_igv);
                            obj.IGV   = Convert.ToString(obe.n_total_igv);
                            obj.Total = Convert.ToString(obe.n_total_venta);
                            //obj.PiePagina = obe.XXXXXX;
                            //obj.PiePagina1 = obe.XXXXXX;
                            //obj.PiePagina2 = obe.XXXXXX;
                            //obj.PiePagina3 = obe.XXXXXX;
                            //obj.PiePagina4 = obe.XXXXXX;
                            //obj.PiePagina5 = obe.XXXXXX;
                            //obj.PiePaginaL1 = obe.XXXXXX;
                            //obj.PiePaginaL2 = obe.XXXXXX;
                            //obj.PiePaginaL3 = obe.XXXXXX;
                            //obj.PiePaginaL4 = obe.XXXXXX;
                            //obj.PiePaginaL5 = obe.XXXXXX;
                            obj.NumeroNotaVenta = obe.c_id_documentoNV;
                            //obj.Tienda = obe.XXXXXX;
                            //obj.Vendedor = obe.XXXXXX;
                            obj.NroDocumentoReceptor = obe.c_receptor_numero_documento;
                            obj.NombreLegalReceptor  = obe.c_receptor_nombre_legal;
                            obj.DireccionRecepctor   = obe.c_receptor_direccion;
                            //obj.NroGuiaRemision = obe.XXXXXX;
                            lobj.Add(obj);
                        }
                    }
                }
                if (lobj.Count > 0)
                {
                    //Inicio de reporte
                    ReportDocument rd = new ReportDocument();
                    if (obe.t_impresion == "A4")
                    {
                        rd.Load(Path.Combine(HttpContext.Current.Server.MapPath("~/Reportes/Gmail"), "Rpt_KRL_ComprobanteFactura.rpt"));
                    }
                    else
                    {
                        rd.Load(Path.Combine(HttpContext.Current.Server.MapPath("~/Reportes/Gmail"), "Rpt_Chelita_ComprobanteFactura.rpt"));
                    }
                    rd.SetDataSource(lobj);

                    byte[] byteArray = null;
                    Stream stream    = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    stream.Seek(0, SeekOrigin.Begin);
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        byteArray = br.ReadBytes((int)stream.Length);
                    }

                    rd.Close();
                    rd.Dispose();

                    return(Convert.ToBase64String(byteArray));
                }
                else
                {
                    return(""); // new HttpResponseMessage(HttpStatusCode.BadRequest);
                }
            }
            catch (Exception ex)
            {
                //return new HttpResponseMessage(HttpStatusCode.BadRequest);
                return("");// Ok(Models.Util.GetBodyResponse(400, ex.Message));
            }
        }
Example #33
0
        private string ExportarPDF()
        {
            DsLiquidacionResumenImpresion ds = new DsLiquidacionResumenImpresion();
            ReportDocument oRD = new ReportDocument();

            ExportOptions oExO;
            DiskFileDestinationOptions oExDo = new DiskFileDestinationOptions();

            /*
             * ILiquidacionEntidad liq =LiquidacionEntidadFactory.GetLiquidacionEntidad();
             * liq.LiquidacionEntidadID=Convert.ToInt32(this.txtLiquidacionEntidadID.Text);
             *
             * DsLiquidacionEntidad ds = (DsLiquidacionEntidad)liq.GetPeriodosAnterioresConsul();
             * DsLiquidacionEntidad dsag=new DsLiquidacionEntidaod();
             * DsReclamo dsRe=(DsReclamo)this.dsReclamos;
             */

            // voy a tener que escribir sí o sí el número de la liquidación
            int nroLiquidacion = Utiles.Validaciones.obtieneEntero(this.txtNroLiquidacion.Text);

            try
            {
                string sNombrePDF = Server.MapPath(".") + "/ReportesPDF/" + "LiquidacionResumen_" + nroLiquidacion + "_" + Session.SessionID + ".pdf";
                if (System.IO.File.Exists(sNombrePDF))
                {
                    System.IO.File.Delete(sNombrePDF);
                }
                string nombrePDf = "LiquidacionResumen_" + nroLiquidacion + "_" + Session.SessionID + ".pdf";

                //Load report
                oRD.Load(Server.MapPath("." + "/Reportes/ResumenLiquidacion.rpt"));

                DsParametrosLiquidacion dsRendicion = (DsParametrosLiquidacion)Session["dsRendicion"];

                foreach (DsParametrosLiquidacion.DatosRow dr in dsRendicion.Datos.Rows)
                {
                    DsLiquidacionResumenImpresion.DatosRendicionRow drr = (DsLiquidacionResumenImpresion.DatosRendicionRow)ds.DatosRendicion.NewDatosRendicionRow();

                    drr.BaseCalculoDescrip           = dr.IsBaseCalculoDescripNull() ? "" : dr.BaseCalculoDescrip;
                    drr.BaseCalculoID                = dr.IsBaseCalculoIDNull() ? 0 : dr.BaseCalculoID;
                    drr.ClienteID                    = dr.IsClienteIDNull() ? 0 : dr.ClienteID;
                    drr.Codigo                       = dr.IsCodigoNull() ? "" : dr.Codigo;
                    drr.ConceptoComisionDescrip      = dr.IsConceptoComisionDescripNull() ? "" : dr.ConceptoComisionDescrip;
                    drr.ConceptoComisionID           = dr.IsConceptoComisionIDNull() ? 0 : dr.ConceptoComisionID;
                    drr.ConceptoLiquidacionDescrip   = dr.IsConceptoLiquidacionDescripNull() ? "" : dr.ConceptoLiquidacionDescrip;
                    drr.ConceptoLiquidacionDetalleID = dr.IsConceptoLiquidacionDetalleIDNull() ? 0 : dr.ConceptoLiquidacionDetalleID;
                    drr.ConceptoLiquidacionID        = dr.IsConceptoLiquidacionIDNull() ? 0 : dr.ConceptoLiquidacionID;
                    drr.EntidadID                    = dr.IsEntidadIDNull() ? 0 : dr.EntidadID;
                    drr.FechaDesde                   = dr.IsFechaDesdeNull() ? new DateTime() : dr.FechaDesde;
                    drr.FechaHasta                   = dr.IsFechaHastaNull() ? new DateTime() : dr.FechaHasta;
                    drr.Importe                      = dr.IsImporteNull() ? 0 : dr.ImportePagado;
                    drr.ImporteBaseCalculo           = dr.IsImporteBaseCalculoNull() ? 0 : dr.ImporteBaseCalculo;
                    drr.ImporteNoPagado              = dr.IsImporteNoPagadoNull() ? 0 : dr.ImporteNoPagado;
                    drr.LiquidacionEntidadID         = dr.IsLiquidacionEntidadIDNull() ? 0 : dr.LiquidacionEntidadID;
                    drr.NombreEntidad                = dr.IsNombreEntidadNull() ? "" : dr.NombreEntidad;
                    drr.NroEntidad                   = dr.IsNroEntidadNull() ? "" : dr.NroEntidad;
                    drr.PorcentajeAplicado           = dr.IsPorcentajeAplicadoNull() ? 0 : dr.PorcentajeAplicado;
                    drr.RazonSocial                  = dr.IsRazonSocialNull() ? "" : dr.RazonSocial;
                    drr.UnidadVentaDescrip           = dr.IsUnidadVentaDescripNull() ? "" : dr.UnidadVentaDescrip;
                    drr.UnidadVentaID                = dr.IsUnidadVentaIDNull() ? 0 : dr.UnidadVentaID;

                    ds.DatosRendicion.AddDatosRendicionRow(drr);
                }


                DsParametrosLiquidacion dsAdministracion = (DsParametrosLiquidacion)Session["dsAdministracion"];

                foreach (DsParametrosLiquidacion.DatosRow dr in dsAdministracion.Datos.Rows)
                {
                    DsLiquidacionResumenImpresion.DatosAdministracionRow drr = (DsLiquidacionResumenImpresion.DatosAdministracionRow)ds.DatosAdministracion.NewDatosAdministracionRow();

                    drr.BaseCalculoDescrip           = dr.IsBaseCalculoDescripNull() ? "" : dr.BaseCalculoDescrip;
                    drr.BaseCalculoID                = dr.IsBaseCalculoIDNull() ? 0 : dr.BaseCalculoID;
                    drr.ClienteID                    = dr.IsClienteIDNull() ? 0 : dr.ClienteID;
                    drr.Codigo                       = dr.IsCodigoNull() ? "" : dr.Codigo;
                    drr.ConceptoComisionDescrip      = dr.IsConceptoComisionDescripNull() ? "" : dr.ConceptoComisionDescrip;
                    drr.ConceptoComisionID           = dr.IsConceptoComisionIDNull() ? 0 : dr.ConceptoComisionID;
                    drr.ConceptoLiquidacionDescrip   = dr.IsConceptoLiquidacionDescripNull() ? "" : dr.ConceptoLiquidacionDescrip;
                    drr.ConceptoLiquidacionDetalleID = dr.IsConceptoLiquidacionDetalleIDNull() ? 0 : dr.ConceptoLiquidacionDetalleID;
                    drr.ConceptoLiquidacionID        = dr.IsConceptoLiquidacionIDNull() ? 0 : dr.ConceptoLiquidacionID;
                    drr.EntidadID                    = dr.IsEntidadIDNull() ? 0 : dr.EntidadID;
                    drr.FechaDesde                   = dr.IsFechaDesdeNull() ? new DateTime() : dr.FechaDesde;
                    drr.FechaHasta                   = dr.IsFechaHastaNull() ? new DateTime() : dr.FechaHasta;
                    drr.Importe                      = dr.IsImporteNull() ? 0 : dr.ImportePagado;
                    drr.ImporteBaseCalculo           = dr.IsImporteBaseCalculoNull() ? 0 : dr.ImporteBaseCalculo;
                    drr.ImporteNoPagado              = dr.IsImporteNoPagadoNull() ? 0 : dr.ImporteNoPagado;
                    drr.LiquidacionEntidadID         = dr.IsLiquidacionEntidadIDNull() ? 0 : dr.LiquidacionEntidadID;
                    drr.NombreEntidad                = dr.IsNombreEntidadNull() ? "" : dr.NombreEntidad;
                    drr.NroEntidad                   = dr.IsNroEntidadNull() ? "" : dr.NroEntidad;
                    drr.PorcentajeAplicado           = dr.IsPorcentajeAplicadoNull() ? 0 : dr.PorcentajeAplicado;
                    drr.RazonSocial                  = dr.IsRazonSocialNull() ? "" : dr.RazonSocial;
                    drr.UnidadVentaDescrip           = dr.IsUnidadVentaDescripNull() ? "" : dr.UnidadVentaDescrip;
                    drr.UnidadVentaID                = dr.IsUnidadVentaIDNull() ? 0 : dr.UnidadVentaID;
                    drr.ImportePagado                = dr.IsImportePagadoNull() ? 0 : dr.ImportePagado;

                    ds.DatosAdministracion.AddDatosAdministracionRow(drr);
                }

                DsReclamo dsReclamo     = (DsReclamo)Session["dsReclamo"];
                int       i             = 0;
                int       totalReclamos = dsReclamo.Datos.Count;

                foreach (DsReclamo.DatosRow dr in dsReclamo.Datos.Rows)
                {
                    DsLiquidacionResumenImpresion.DatosReclamosRow drr = (DsLiquidacionResumenImpresion.DatosReclamosRow)ds.DatosReclamos.NewDatosReclamosRow();
                    drr.ReclamoID        = dr.ReclamoID;
                    drr.FechaComprobante = dr.FechaComprobante;
                    drr.Importe          = dr.Importe;
                    if (i < totalReclamos - 1)
                    {
                        drr.NroComprobante = "";
                    }
                    else
                    {
                        drr.NroComprobante = dr.NroComprobante;
                    }

                    drr.ComprobanteID     = "";
                    drr.AgenciaID         = 0;
                    drr.CajaAsociada      = "";
                    drr.ClaseComprobante  = "";
                    drr.CodigoComprobante = "";
                    drr.EstadoReclamoID   = 0;
                    drr.ValorAsociado     = "";

                    ds.DatosReclamos.AddDatosReclamosRow(drr);
                    i++;
                }

                oRD.SetDataSource(ds);

                oRD.SetParameterValue("Sucursal", this.busqAgencia.Sucursal);
                oRD.SetParameterValue("RazonSocial", this.busqAgencia.RazonSocial);
                oRD.SetParameterValue("FechaDesde", this.txtFechaDesde.Text);
                oRD.SetParameterValue("FechaHasta", this.txtFechaHasta.Text);
                oRD.SetParameterValue("NroLiquidacion", this.txtNroLiquidacion.Text);
                oRD.SetParameterValue("ImporteTotal", Utiles.Validaciones.obtieneDouble(this.lblImportePago.Text.Substring(1, this.lblImportePago.Text.Length - 1)));

                //Export to PDF
                oExDo.DiskFileName = sNombrePDF;
                oExO = oRD.ExportOptions;
                oExO.ExportDestinationType = ExportDestinationType.DiskFile;
                oExO.ExportFormatType      = ExportFormatType.PortableDocFormat;
                oExO.DestinationOptions    = oExDo;
                oRD.Export();
                oRD.Close();
                oRD.Dispose();

                return(nombrePDf);
            }
            catch (Exception ex)
            {
                string mensaje = "Error al exportar a PDF: " + ex.Message;

                ((ErrorWeb)this.phErrores.Controls[0]).setMensaje(mensaje);
                return("");
            }
            finally
            {
                oRD.Close();
                oRD.Dispose();
            }
        }
Example #34
0
        public static Stream Exec(OrderList.OrderListDataTable datatable,
                                  int language,
                                  string totalOrderNo,
                                  string totalSize,
                                  string totalContainerSize,
                                  string totalUnitPrice,
                                  string fromDate,
                                  string toDate
                                  )
        {
            try
            {
                ReportDocument report;
                string         strPath;

                strPath = HttpContext.Current.Request.MapPath("~/FileRpt/Order/OrderListEn.rpt");
                if (language == 3)
                {
                    strPath = HttpContext.Current.Request.MapPath("~/FileRpt/Order/OrderListJp.rpt");
                }
                else if (language == 1)
                {
                    strPath = HttpContext.Current.Request.MapPath("~/FileRpt/Order/OrderListVi.rpt");
                }

                report = new ReportDocument();
                report.Load(strPath);
                report.Database.Tables[0].SetDataSource((DataTable)datatable);
                // set period time
                if (language == 1)
                {
                    report.SetParameterValue("currentDate", "Ngày " + DateTime.Now.Day + " tháng " + DateTime.Now.Month + " năm " + DateTime.Now.Year);
                    report.SetParameterValue("period", "Từ ngày " + fromDate + " đến ngày " + toDate);
                }
                else if (language == 2)
                {
                    CultureInfo cul = CultureInfo.GetCultureInfo("en-US");
                    report.SetParameterValue("currentDate", cul.DateTimeFormat.GetMonthName(DateTime.Now.Month) + " " + DateTime.Now.Day + ", " + DateTime.Now.Year);
                    report.SetParameterValue("period", "Period " + fromDate + " to " + toDate);
                }
                else
                {
                    report.SetParameterValue("currentDate", DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日");
                    report.SetParameterValue("period", fromDate + "から" + toDate + "まで");
                }
                // set parameter currentDate
                if (language == 1)
                {
                    report.SetParameterValue("currentDate", "Ngày " + DateTime.Now.Day + " tháng " + DateTime.Now.Month + " năm " + DateTime.Now.Year);
                }
                else if (language == 2)
                {
                    CultureInfo cul = CultureInfo.GetCultureInfo("en-US");
                    report.SetParameterValue("currentDate", cul.DateTimeFormat.GetMonthName(DateTime.Now.Month) + " " + DateTime.Now.Day + ", " + DateTime.Now.Year);
                }
                else
                {
                    report.SetParameterValue("currentDate", DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日");
                }

                report.SetParameterValue("totalOrderNo", totalOrderNo);
                report.SetParameterValue("totalSize", totalSize);
                report.SetParameterValue("totalContainerSize", totalContainerSize);
                report.SetParameterValue("totalUnitPrice", totalUnitPrice);

                Stream stream = report.ExportToStream(ExportFormatType.PortableDocFormat);
                report.Close();
                report.Dispose();
                GC.Collect();
                return(stream);
            }
            catch (NullReferenceException)
            {
                throw new NullReferenceException();
            }
        }
Example #35
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["ReportData"] != null && Session["option"] != null && Session["type"] != null)
            {
                string rptFullPath = "";
                if (Session["option"].ToString() == "radSection" && Session["type"].ToString() == "Details")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptSurveySectionInfo.rpt");
                }
                else if (Session["option"].ToString() == "radSection" && Session["type"].ToString() == "Survey")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptSectionSurveyForm.rpt");
                }
                else if (Session["option"].ToString() == "radSection" && Session["type"].ToString() == "Map")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptSectionMap.rpt");
                }

                else if (Session["option"].ToString() == "radIntersects" && Session["type"].ToString() == "Details")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptSurveyIntersectionInfo.rpt");
                }
                else if (Session["option"].ToString() == "radIntersects" && Session["type"].ToString() == "Survey")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptIntersectSurveyForms.rpt");
                }

                else if (Session["option"].ToString() == "radRegions" && Session["type"].ToString() == "Details")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptSurveySecondaryStInfo.rpt");
                }
                else if (Session["option"].ToString() == "radRegions" && Session["type"].ToString() == "Survey")
                {
                    rptFullPath = Server.MapPath(@".\RptFiles\Descriptive\rptRegionSurveyForm.rpt");
                }
                else
                {
                    throw new Exception("Invalid report option!");
                }


                DataTable      dt  = (DataTable)Session["ReportData"];
                ReportDocument rpt = new ReportDocument();

                rpt.Load(rptFullPath);
                rpt.SetDataSource(dt);

                Session.Remove("ReportData");

                MemoryStream memStream;
                Response.Buffer = false;
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();

                if (Request.QueryString["type"] == "x")
                {
                    ExcelFormatOptions excelOptions = new ExcelFormatOptions();
                    excelOptions.ExcelUseConstantColumnWidth = false;
                    rpt.ExportOptions.FormatOptions          = excelOptions;

                    memStream            = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.ExcelRecord);
                    Response.ContentType = "application/vnd.ms-excel";
                }
                else
                {
                    memStream            = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    Response.ContentType = "application/pdf";
                    //memStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.WordForWindows);
                    //Response.ContentType = "application/msword";
                }



                Response.BinaryWrite(memStream.ToArray());
                Response.End();

                memStream.Flush();
                memStream.Close();
                memStream.Dispose();
                rpt.Close();
                rpt.Dispose();
                GC.Collect();
            }
            else
            {
                Response.Redirect("SurveyingFormsReport.aspx", false);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Session["ReportData"] = null;
        }
    }
Example #36
0
        public static Stream Exec(OrderList.OrderGeneralDataTable datatable,
                                  int language,
                                  string fromDate,
                                  string toDate,
                                  string companyName,
                                  string companyAddress,
                                  string fileName,
                                  string user,
                                  Dictionary <string, string> dicLanguage
                                  )
        {
            try
            {
                ReportDocument report;
                string         strPath;

                strPath = HttpContext.Current.Request.MapPath("~/FileRpt/Order/OrderGeneralList.rpt");

                report = new ReportDocument();
                report.Load(strPath);
                report.Database.Tables[0].SetDataSource((DataTable)datatable);
                // set period time
                if (language == 1)
                {
                    //report.SetParameterValue("currentDate", "Ngày " + DateTime.Now.Day + " tháng " + DateTime.Now.Month + " năm " + DateTime.Now.Year);
                    report.SetParameterValue("period", "Từ ngày " + fromDate + " đến ngày " + toDate);
                }
                else if (language == 2)
                {
                    CultureInfo cul = CultureInfo.GetCultureInfo("en-US");
                    //report.SetParameterValue("currentDate", cul.DateTimeFormat.GetMonthName(DateTime.Now.Month) + " " + DateTime.Now.Day + ", " + DateTime.Now.Year);
                    report.SetParameterValue("period", "Period " + fromDate + " to " + toDate);
                }
                else
                {
                    //report.SetParameterValue("currentDate", DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日");
                    report.SetParameterValue("period", fromDate + "から" + toDate + "まで");
                }
                // set parameter currentDate
                if (language == 1)
                {
                    report.SetParameterValue("currentDate", "Ngày " + DateTime.Now.Day + " tháng " + DateTime.Now.Month + " năm " + DateTime.Now.Year);
                }
                else if (language == 2)
                {
                    CultureInfo cul = CultureInfo.GetCultureInfo("en-US");
                    report.SetParameterValue("currentDate", cul.DateTimeFormat.GetMonthName(DateTime.Now.Month) + " " + DateTime.Now.Day + ", " + DateTime.Now.Year);
                }
                else
                {
                    report.SetParameterValue("currentDate", DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日");
                }
                // set datatable images
                var path = HttpContext.Current.Request.MapPath("~/Images/" + fileName);
                report.SetParameterValue("companyName", companyName ?? "");
                report.SetParameterValue("companyAddress", companyAddress ?? "");
                report.SetParameterValue("imageUrl", path);
                report.SetParameterValue("user", user);

                report.SetParameterValue("hdReport", dicLanguage["TLTORDERREPORT"]);
                report.SetParameterValue("hdOrderNo", dicLanguage["LBLORDERNODISPATCH"]);
                report.SetParameterValue("hdOrderType", dicLanguage["LBLORDERTYPEREPORT"]);
                report.SetParameterValue("hdOrderD", dicLanguage["LBLORDERDATEDISPATCH"]);
                report.SetParameterValue("hdCustomer", dicLanguage["LBLCUSTOMERREPORT"]);
                report.SetParameterValue("hdBKBL", dicLanguage["LBLBLBKREPORT"]);
                report.SetParameterValue("hdJobNo", dicLanguage["LBLJOBNO"]);
                report.SetParameterValue("hdShippingCompany", dicLanguage["LBLSHIPPINGAGENCY"]);
                report.SetParameterValue("hdVessel", dicLanguage["MNUVESSEL"]);
                report.SetParameterValue("hdRoute", dicLanguage["TLTROUTE"]);
                report.SetParameterValue("hdContainer", dicLanguage["RPHDCONTSIZE"]);
                report.SetParameterValue("hdNetWeight", dicLanguage["LBLNETWEIGHT"]);
                report.SetParameterValue("hdTon", dicLanguage["LBLTON"]);
                report.SetParameterValue("hdUnitPrice", dicLanguage["LBLTEUNITPRICE"]);
                report.SetParameterValue("hdTotalPrice", dicLanguage["LBLTOL"]);
                report.SetParameterValue("lbSum", dicLanguage["RPLBLTOTAL"]);

                report.SetParameterValue("ftPrintTime", dicLanguage["RPFTPRINTTIME"]);
                report.SetParameterValue("ftPrintBy", dicLanguage["RPFTPRINTBY"]);
                report.SetParameterValue("ftPage", dicLanguage["RPFTPAGE"]);
                report.SetParameterValue("ftCreator", dicLanguage["RPFTCREATOR"]);

                Stream stream = report.ExportToStream(ExportFormatType.PortableDocFormat);
                report.Close();
                report.Dispose();
                GC.Collect();
                return(stream);
            }
            catch (NullReferenceException)
            {
                throw new NullReferenceException();
            }
        }
Example #37
0
 protected void Page_UnLoad(object sender, EventArgs e)
 {
     rptStudent.Close();
     rptStudent.Dispose();
 }
Example #38
0
 protected override void OnUnload(EventArgs e)
 {
     rpt.Close();
     rpt.Dispose();
     base.OnUnload(e);
 }
Example #39
0
        private void Generar(Conexion Datos, string reporte, Reportes report)
        {
            reportDocument = new ReportDocument();

            string sql = null;

            switch (report)
            {
                case Reportes.Lps:
                    sql = "usp_lps_reporte ";
                    sql += IdLpsEmpleado.ToString();
                    sql += ", " + IdEmpresa;
                    break;
                case Reportes.Acumulados:
                    sql = "usp_lps_acumulados_porIdEmpleado ";
                    sql += IdEmpleado.ToString();
                    break;
            }
            reportDocument.Load(reporte);
            reportDocument.SetDataSource(Datos.ExecuteReaderConTransaccion(sql).Tables[0]);
            reportDocument.DataSourceConnections[0].SetConnection("192.168.16.252", "siser_v3", "sa", "Acceso2013");

            switch (report)
            {
                case Reportes.Lps:
                    Reporte = (MemoryStream)reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    break;
                case Reportes.Acumulados:
                    Acumulados = (MemoryStream)reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                    break;
            }

            try
            {
                reportDocument.Dispose();
                reportDocument = null;
                reportDocument.Close();
            }
            catch
            {
            }
        }
    private void GenerarReporteXGrupo(int Zona, int Plantel, string Ciclo, int Periodo, byte Turno, byte Semestre)
    {
        EscolarModel.EstaEntities db = new EscolarModel.EstaEntities();

        var Alumnos = (from A in db.vwRPTParcial1XGPO
                       join P in db.vwPlanteles on new { z = A.or_zona, pl = A.or_plant } equals new { z = (byte)P.idZona, pl = (int)P.idPlantel }
                       where A.Ciclo == Ciclo && A.Periodo == Periodo &&
                            A.or_zona == (Zona == 0 ? A.or_zona : Zona) && A.or_plant == (Plantel == 0 ? A.or_plant : Plantel)
                            && A.or_turno == (Turno == 0 ? A.or_turno : Turno) && A.or_semest == (Semestre == 0 ? A.or_semest : Semestre)
                            && P.EsEmsad == 0
                       orderby A.or_zona, A.or_plant, A.or_turno, A.or_semest, A.or_grupo, A.or_asigna
                       select A).ToList();

        if (Alumnos.Count == 0)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", string.Format("alert('{0}');", "No hay registros encontrados"), true);
            return;
        }

        ReportDocument rptDoc = new ReportDocument();
        rptDoc.Load(Server.MapPath("../Reportes/rptEstCalXGpo01.rpt"));
        rptDoc.SetDataSource(Alumnos);
        rptDoc.SetParameterValue("Periodo", Periodo);
        rptDoc.SetParameterValue("Ciclo", Ciclo);

        MemoryStream stream = (MemoryStream)rptDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);
        rptDoc.Close();
        rptDoc.Dispose();

        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "inline; filename=rptEstCalXGpo01.xls");
        Response.BinaryWrite(stream.ToArray());
        Response.End();
        stream.Close();
        stream.Dispose();
    }
        protected void imgbtnVistaPreviaReporteVolumetrias_Click(object sender, EventArgs e)
        {
            //Parametros del store procedure
            string strID = Cookies.GetCookie("cookieEditarVolumetria").Value;
            string strPreciario = Cookies.GetCookie("cookiePreciario").Value;

            string path = AppDomain.CurrentDomain.BaseDirectory;
            //1. Configurar la conexión y el tipo de comando
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSEF"].ConnectionString);
            try
            {
                using (var comando = new SqlCommand("web_spS_ObtenerCambiosPreciarioPorVolumetria", conn))
                {
                    using (var adaptador = new SqlDataAdapter(comando))
                    {
                        DataTable dt = new DataTable();
                        adaptador.SelectCommand.CommandType = CommandType.StoredProcedure;
                        adaptador.SelectCommand.Parameters.Add(@"idpreciario", SqlDbType.NVarChar).Value = strPreciario;
                        adaptador.SelectCommand.Parameters.Add(@"Volumetria", SqlDbType.Int).Value = Convert.ToInt32(strID);
                        adaptador.Fill(dt);

                        var reporte = new ReportDocument();
                        reporte.Load(Server.MapPath("reportess/CPreciarioV.rpt"));
                        reporte.SetDataSource(dt);
                        reporte.SetParameterValue("path", path);
                        reporte.SetParameterValue("pathlogo", path + "\\images\\clientes\\");
                        reporte.SetParameterValue("pathlogopro", path + "\\images\\proveedores\\");

                        string strDireccion = Server.MapPath(" ") + "\\reportess\\Volumetrias\\" + strID;

                        //2. Validar si existe el directorio donde se guardaran
                        if (Directory.Exists(strDireccion))
                        {
                            reporte.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("reportess/Volumetrias/" + strID + "/Volumetria " + strID + ".pdf"));

                            ClientScript.RegisterStartupScript(this.Page.GetType(), "popupOpener", "var popup=window.open('reportess/Volumetrias/" + strID + "/Volumetria " + strID + ".pdf',null,'height=700,width=660');popup.focus();", true);
                           // reporte.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "Resumen de OC: ");

                        }
                        else
                        {
                            Directory.CreateDirectory(strDireccion);
                            reporte.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("reportess/Volumetrias/" + strID + "/Volumetria " + strID + ".pdf"));
                            ClientScript.RegisterStartupScript(this.Page.GetType(), "popupOpener", "var popup=window.open('reportess/Volumetrias/" + strID + "/Volumetria " + strID + ".pdf',null,'height=700,width=660');popup.focus();", true);
                        }
                        reporte.Dispose();
                        reporte.Close();
                    } // end using adaptador
                } // end using comando

            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();
            }
        }
        //Exporta a Excel el grid
        protected void ExportEt(object sender, EventArgs e)
        {
            string parametro = cmbClasificacion.Value.ToString();

            //1. Configurar la conexión y el tipo de comando
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSEF"].ConnectionString);
            try
            {
                SqlCommand comando = new SqlCommand("web_spS_ObtenerReportesPorClasificacion", conn);
                SqlDataAdapter adaptador = new SqlDataAdapter(comando);
                DataTable dt = new DataTable();
                adaptador.SelectCommand.CommandType = CommandType.StoredProcedure;
                adaptador.SelectCommand.Parameters.Add(@"CLASIFICACION", SqlDbType.VarChar).Value = parametro;
                adaptador.Fill(dt);
                ReportDocument reporteCuadrila = new ReportDocument();
                reporteCuadrila.Load(Server.MapPath("reportess/rMantenimientosFacturador.rpt"));
                reporteCuadrila.SetDataSource(dt);
                reporteCuadrila.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.Excel, Response, true, "Reportes Mantenimiento " + parametro);
                reporteCuadrila.Close();
                reporteCuadrila.Dispose();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
                conn.Dispose();
            }
        }
    //dbINFO._SRV, dbINFO._CAT, dbINFO._UID, dbINFO._PWD
    public void PrintReport(Page _Page, string _ReportName, string _FileName, DataTable dt)
    {
        ReportDocument rptDoc = new ReportDocument();
        try
        {
            rptDoc.Load(_Page.Server.MapPath("~/Reports/" + _ReportName));
            rptDoc.SetDataSource(dt);

            rptDoc.SetDatabaseLogon(dbINFO._UID, dbINFO._PWD, dbINFO._SRV, dbINFO._CAT);
            _Page.Response.Buffer = false;
            _Page.Response.ClearContent();
            _Page.Response.ClearHeaders();
            //Export the Report to Response stream in PDF format and file name Customers
            rptDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, _Page.Response, true, _FileName);
        }
        catch (Exception ex)
        {
            Utility.ShowHTMLMessage(_Page, "100", ex.Message);
        }
        finally
        {
            rptDoc.Close();
            rptDoc.Dispose();
        }
    }
		private void GenerateHTML()
		{
            ReportDocument rpt = new ReportDocument();
            rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/GeneralLedger.rpt"));

			HTMLFormatOptions htmlOpts = new HTMLFormatOptions();
 
			ExportOptions exportop = new ExportOptions();
			DiskFileDestinationOptions dest = new DiskFileDestinationOptions();
			
			string strPath = Server.MapPath(@"\RetailPlus\temp\html\");
//			DeleteTempDirectory(strPath);

			string strFileName = "generalledger_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + ".htm";
			if (System.IO.File.Exists(strPath + strFileName))
				System.IO.File.Delete(strPath + strFileName);

			htmlOpts.HTMLFileName = strFileName;
			htmlOpts.HTMLEnableSeparatedPages = true;;
			htmlOpts.HTMLHasPageNavigator = true;
			htmlOpts.HTMLBaseFolderName = strPath;
			rpt.ExportOptions.FormatOptions = htmlOpts;

			exportop = rpt.ExportOptions;

			exportop.ExportDestinationType = ExportDestinationType.DiskFile;
			exportop.ExportFormatType = ExportFormatType.HTML40;
			
			dest.DiskFileName = strFileName.ToString();
			exportop.DestinationOptions = dest;

			SetDataSource(rpt);

			rpt.Export();   rpt.Close();    rpt.Dispose();

			strFileName = "//" + Request.ServerVariables["SERVER_NAME"].ToString() + FindHTMLFile(strPath,strFileName);	
			
			fraViewer.Attributes.Add("src",strFileName);
		}
    override protected void OnInit(EventArgs e)
    {
        InitializeComponent();
        base.OnInit(e);

        try
        {
            bool   bMostrar = true;
            int    int_pinicio;
            int    int_pfin;
            string strServer;
            string strDataBase;
            string strUid;
            string strPwd;
            //				obtengo de la cadena de conexión los parámetros para luego
            //				modificar localizaciones

            string strconexion = Utilidades.CadenaConexion;
            int_pfin  = strconexion.IndexOf(";database=", 0);
            strServer = strconexion.Substring(7, int_pfin - 7);

            int_pinicio = int_pfin + 10;
            int_pfin    = strconexion.IndexOf(";uid=", int_pinicio);
            strDataBase = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            int_pinicio = int_pfin + 5;
            int_pfin    = strconexion.IndexOf(";pwd=", int_pinicio);
            strUid      = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            int_pinicio = int_pfin + 5;
            int_pfin    = strconexion.IndexOf(";Trusted_Connection=", int_pinicio);
            strPwd      = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            //creo un objeto ReportDocument
            ReportDocument rdFormulario = new ReportDocument();

            try
            {
                rdFormulario.Load(Server.MapPath(".") + @"\detalle.rpt");
            }
            catch (Exception ex)
            {
                rdFormulario.Close();
                rdFormulario.Dispose();
                Response.Write("Error al abrir el report: " + ex.Message);
            }

            try
            {
                rdFormulario.SetDatabaseLogon(strUid, strPwd, strServer, strDataBase);
            }
            catch (Exception ex)
            {
                rdFormulario.Close();
                rdFormulario.Dispose();
                Response.Write("Error al logarse al report: " + ex.Message);
            }

            //creo un objeto logon
            CrystalDecisions.Shared.TableLogOnInfo tliCurrent;

            try
            {
                foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in rdFormulario.Database.Tables)
                {
                    //obtengo el logon por tabla
                    tliCurrent = tbCurrent.LogOnInfo;

                    tliCurrent.ConnectionInfo.DatabaseName = strDataBase;
                    tliCurrent.ConnectionInfo.UserID       = strUid;
                    tliCurrent.ConnectionInfo.Password     = strPwd;
                    tliCurrent.ConnectionInfo.ServerName   = strServer;

                    //aplico los cambios hechos al objeto TableLogonInfo
                    tbCurrent.ApplyLogOnInfo(tliCurrent);
                }
            }
            catch (Exception ex)
            {
                rdFormulario.Close();
                rdFormulario.Dispose();

                Response.Write("Error al actualizar la localización: " + ex.Message);
            }

            rdFormulario.SetParameterValue("@nRef", Utilidades.decodpar(Request.QueryString["ing"].ToString()));
            //rdFormulario.SetParameterValue("@nRef", "39273");

            DiskFileDestinationOptions diskOpts = ExportOptions.CreateDiskFileDestinationOptions();

            //string strTipoFormato = Request.QueryString["FORMATO"]; // ESTO LO RECOGERE COMO PARAMETRO

            string strTipoFormato = "PDF";

            ExportOptions exportOpts = new ExportOptions();

            try
            {
                System.IO.Stream oStream;
                byte[]           byteArray = null;

                switch (strTipoFormato)
                {
                //			PDF
                case "PDF":
                    oStream   = rdFormulario.ExportToStream(ExportFormatType.PortableDocFormat);
                    byteArray = new byte[oStream.Length];
                    oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                    break;

                case "RTF":
                    //			RTF
                    rdFormulario.ExportToHttpResponse(ExportFormatType.EditableRTF, Response, false, "Exportacion");
                    bMostrar = false;
                    break;
                }

                rdFormulario.Close();
                rdFormulario.Dispose();

                // FIN

                if (bMostrar)
                {
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.Buffer = true;

                    switch (strTipoFormato)
                    {
                    //			PDF
                    case "PDF":
                        Response.ContentType = "application/pdf";
                        break;

                    case "RTF":
                        //			RTF
                        Response.ContentType = "application/msword";
                        break;
                    }
                    Response.Clear();

                    //String nav = HttpContext.Current.Request.Browser.Browser.ToString();
                    //if (nav.IndexOf("IE") == -1)
                    //{
                    switch (strTipoFormato)
                    {
                    case "PDF":

                        Response.AddHeader
                            ("Content-Disposition", "attachment;filename=Filename.pdf");
                        break;

                    case "RTF":
                        Response.AddHeader
                            ("Content-Disposition", "attachment;filename=Filename.doc");
                        break;
                    }
                    //}
                    Response.BinaryWrite(byteArray);

                    Response.Flush();
                    Response.Close();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                rdFormulario.Close();
                rdFormulario.Dispose();
                Response.Write("Error al exportar el report: " + ex.Message);
            }
        }
        //handle any exceptions
        catch (Exception ex)
        {
            Response.Write("Report could not be created: " + ex.Message);
        }
    }
Example #46
0
        private void ExportarComprobanteButton_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = System.Windows.Forms.Cursors.WaitCursor;
                if (DetalleLoteDataGridView.SelectedRows.Count != 0)
                {
                    for (int i = 0; i < DetalleLoteDataGridView.SelectedRows.Count; i++)
                    {
                        int renglon = DetalleLoteDataGridView.SelectedRows[i].Index;
                        ReportDocument ReporteDocumento = new ReportDocument();
                        ProcesarComprobante(out ReporteDocumento, lote, renglon);

                        //Nombre del comprobante ( pdf )
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        sb.Append(lote.CuitVendedor);
                        sb.Append("-");
                        sb.Append(Convert.ToInt32(lote.PuntoVenta).ToString("0000"));
                        sb.Append("-");
                        sb.Append(Convert.ToInt32(lote.Comprobantes[renglon].IdTipoComprobante).ToString("00"));
                        sb.Append("-");
                        sb.Append(Convert.ToInt32(lote.Comprobantes[renglon].NumeroComprobante).ToString("00000000"));
                        sb.Append(".pdf");

                        //ExportOptions
                        DiskFileDestinationOptions crDiskFileDestinationOptions = new DiskFileDestinationOptions();
                        crDiskFileDestinationOptions.DiskFileName = Aplicacion.Aplic.ArchPathPDF + sb.ToString();
                        ReporteDocumento.ExportOptions.ExportDestinationOptions = crDiskFileDestinationOptions;
                        ReporteDocumento.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                        ReporteDocumento.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                        PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                        ReporteDocumento.ExportOptions.ExportFormatOptions = CrFormatTypeOptions;
                        ReporteDocumento.Export();
                        ReporteDocumento.Close();
                    }
                    if (DetalleLoteDataGridView.SelectedRows.Count == 1)
                    {
                        MessageBox.Show("El comprobante seleccionado se ha exportado satisfactoriamente.", "Exportar Comprobantes", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }
                    else
                    {
                        MessageBox.Show("Los comprobantes seleccionados se han exportado satisfactoriamente.", "Exportar Comprobantes", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Problemas al procesar el comprobante", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            finally
            {
                Cursor = System.Windows.Forms.Cursors.Default;
            }
        }
    protected void btninfoBitacora_Click(object sender, EventArgs e)
    {
        string Ciclo = this.ddlCiclo.SelectedValue;
        DBEstadisticas.Escolar db = new DBEstadisticas.Escolar();

        var Bitacora = (from P in db.Bitacora
                        where P.Ciclo == Ciclo
                        group P by new { P.Z, P.P, P.Descripcion } into g
                        select new { Z = g.Key.Z, P = g.Key.P, g.Key.Descripcion, Fecha = g.Max(x => x.Fecha) }).OrderByDescending(x => x.Fecha).ToList();

        if (Bitacora.Count == 0)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", string.Format("alert('{0}');", "No hay registros encontrados"), true);
            return;
        }

        ReportDocument rptDoc = new ReportDocument();
        rptDoc.Load(Server.MapPath("../Reportes/rptEstBitacora01.rpt"));
        rptDoc.SetDataSource(Bitacora);
        rptDoc.SetParameterValue("Ciclo", Ciclo);

        MemoryStream stream = (MemoryStream)rptDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);
        rptDoc.Close();
        rptDoc.Dispose();

        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "inline; filename=rptEstBitacora01.xls");
        Response.BinaryWrite(stream.ToArray());
        Response.End();
        stream.Close();
        stream.Dispose();
    }
Example #48
0
    private void ShowReport(DataTable dt, string format)
    {
        string strFileName = "";
        DataTable dt1 = new DataTable();
        dt1 = (DataTable)Session["UserInfo"];
        string Login_Name;
        if (dt1 != null)
        {
            Login_Name = dt1.Rows[0]["Name"].ToString();
        }
        else
        {
            Login_Name = "admin";
        }

        ReportDocument report = new ReportDocument();
        string programID = "";

        switch (rblReportType.SelectedIndex)
        {
            case 0:
                programID = "CAM04R01";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R01.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢檢核表_門市", System.Text.Encoding.UTF8);
                break;

            case 1:
                programID = "CAM04R02";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R02.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢檢核表_商品", System.Text.Encoding.UTF8);
                break;

            case 2:
                programID = "CAM04R03";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R03.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢檢核表_補帳金額", System.Text.Encoding.UTF8);
                break;

            case 3:
                programID = "CAM04R04";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R04.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢檢核表_原因", System.Text.Encoding.UTF8);
                break;

            case 4:
                programID = "CAM04R05";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R05.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢調整匯總表", System.Text.Encoding.UTF8);
                break;

            case 5:
                programID = "CAM04R06";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R06.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢調整明細表_牌價", System.Text.Encoding.UTF8);
                break;

            case 6:
                programID = "CAM04R06";
                report.Load(Server.MapPath("./REPORT/CAM04/CAM04R07.rpt"));
                strFileName = programID + "_" + HttpUtility.UrlEncode("門市短溢調整明細表_成本", System.Text.Encoding.UTF8);
                break;
        }

        string strGroupS = txtGroupS.Text + Request[((TextBox)txtGroupS.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "");
        string strGroupE = txtGroupE.Text + Request[((TextBox)txtGroupE.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "");
        if (strGroupS == "")
            strGroupS = strGroupE;
        if (strGroupE == "")
            strGroupE = strGroupS;

        string strProfitS = txtProfitS.Text.Trim() + Request[((TextBox)txtProfitS.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "");
        string strProfitE = txtProfitE.Text.Trim() + Request[((TextBox)txtProfitE.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "");
        if (strProfitS == "")
            strProfitS = strProfitE;
        if (strProfitE == "")
            strProfitE = strProfitS;

        string strStoreS = txtStoreS.Text.Trim() + Request[((TextBox)txtStoreS.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "");
        string strStoreE = txtStoreE.Text.Trim() + Request[((TextBox)txtStoreE.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "");
        if (strStoreS == "")
            strStoreS = strStoreE;
        if (strStoreE == "")
            strStoreE = strStoreS;

        report.SetDataSource(dt);

        report.SetParameterValue("par_Program_ID", programID);
        report.SetParameterValue("par_LoginUser", (Session["UID"].ToString()) + Login_Name);
        report.SetParameterValue("par_patchDate", slpDateRangePatch.StartDate +
            (string.IsNullOrEmpty(slpDateRangePatch.StartDate) ? "" : "~") + slpDateRangePatch.EndDate);
        report.SetParameterValue("par_signDate", txtSignDate.StartDate + "~" + txtSignDate.EndDate);
        report.SetParameterValue("par_acDate", txtACDateS.Text + "~" + txtACDateE.Text);
        report.SetParameterValue("par_group", strGroupS + (string.IsNullOrEmpty(strGroupE) ? "" : "~") + strGroupE);
        report.SetParameterValue("par_acInvNo", txtAcInvNo.Text);
        report.SetParameterValue("par_profit", strProfitS + (string.IsNullOrEmpty(strProfitS) ? "" : "~") + strProfitE);
        report.SetParameterValue("par_Store", strStoreS + (string.IsNullOrEmpty(strStoreS) ? "" : "~") + strStoreE);

        report.SetParameterValue("par_acUID", txtAccID.Text + Request[((TextBox)txtAccID.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_RootNo", txtRootNo.Text + Request[((TextBox)txtRootNo.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_item", txtItem.Text + Request[((TextBox)txtItem.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_period", txtPeriodS.Text +
            (string.IsNullOrEmpty(txtPeriodS.Text) ? "" : "~") + txtPeriodE.Text);
        report.SetParameterValue("par_checkReason", txtReasonS.Text +
            (string.IsNullOrEmpty(txtReasonS.Text) ? "" : "~") + txtReasonE.Text);
        report.SetParameterValue("par_descType", txtDescS.Text +
            (string.IsNullOrEmpty(txtDescS.Text) ? "" : "~") + txtDescE.Text);
        report.SetParameterValue("par_diffTimes", txtDiffTimes.Text);
        report.SetParameterValue("par_diffAmount", txtDiffAmount.Text);
        report.SetParameterValue("par_diffSource", rblDiffSource.SelectedItem.Text);

        Stream stream = null;
        byte[] b = null;
        switch (format)
        {
            case "PDF":
                stream = report.ExportToStream(ExportFormatType.PortableDocFormat);
                b = new byte[stream.Length];
                stream.Read(b, 0, b.Length);
                stream.Seek(0, SeekOrigin.Begin);

                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".pdf");
                Response.ContentType = "application/pdf";
                Response.OutputStream.Write(b, 0, b.Length);
                Response.Flush();
                Response.Close();
                break;

            case "EXCEL":
                stream = report.ExportToStream(ExportFormatType.Excel);
                b = new byte[stream.Length];
                stream.Read(b, 0, b.Length);
                stream.Seek(0, SeekOrigin.Begin);

                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".xls");
                Response.ContentType = "application/vnd.ms-excel";
                Response.OutputStream.Write(b, 0, b.Length);
                Response.Flush();
                Response.Close();
                break;
        }
        report.Close();

    }
    private void GenerarPDF()
    {
        DBEscolarDataContext db = new DBEscolarDataContext();
        var Alumno = (from A in db.vwRPTReinscripcions
                      where A.Matricula == this.Matricula
                      select A).FirstOrDefault();

        if (Alumno == null)//No se encontro
            return;

        System.Collections.ArrayList col = new System.Collections.ArrayList();
        col.Add(Alumno);
        ReportDocument rptDoc = new ReportDocument();

        rptDoc.Load(Server.MapPath("Reportes/rptReinscripcion.rpt"));
        //set dataset to the report viewer.
        rptDoc.SetDataSource(col);

        MemoryStream stream = (MemoryStream)rptDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        rptDoc.Close();
        rptDoc.Dispose();
        Response.Clear();
        Response.ContentType = @"Application/pdf";
        Response.AddHeader("Content-Disposition", "inline; filename=Solicitud.pdf");
        // Response.AddHeader("Content-Disposition", "attachment; filename=File.pdf");
        Response.AddHeader("content-length", stream.Length.ToString());
        Response.BinaryWrite(stream.ToArray());
        Response.Flush();
        stream.Close();
        stream.Dispose();
    }
        //protected Boolean CheckAccessAble()
        //{
        //    if (m_perimission_array[(int)Authentication.FUN_INTERFACE.wzxqjh_jjd_report][0] == '1') return true;
        //    return false;
        //}
        private void PrintPDF()
        {
            ReportDocument rpt_doc = new ReportDocument();
            DataSet ds = new DataSet();
            StringBuilder sqlstr = new StringBuilder();
            //sqlstr.Append("select a.jjd_no,a.requisition_id req_id,a.rowstate,a.remark,a.package_no,a.part_no,b.part_name part_name,");
            //sqlstr.Append("b.part_name_e part_name_e,gen_part_package_api.get_package_name(package_no) package_name,");
            //sqlstr.Append("gen_part_package_item_api.get_unit(package_no,part_no) part_unit,gen_part_package_item_api.get_part_spec(package_no,part_no) part_spec,");
            //sqlstr.Append("zh_qty,xh_qty,finish_time,rowversion,project_id proj_id from jp_pkg_jjd_line a,jp_pkg_requisition b where a.requisition_id=b.requisition_id");
            sqlstr.Append(@"select a.jjd_no,a.requisition_id req_id,a.rowstate,a.remark,a.package_no,a.part_no,
               b.part_name   part_name, b.part_name_e part_name_e,   b.package_name package_name,
               b.part_unit part_unit, b.part_spec part_spec, b.released_qty xq_qty,a.zh_qty,
               a.xh_qty, a.finish_time, a.rowversion,a.project_id proj_id
              from jp_pkg_jjd_line a, jp_pkg_requisition_v b where a.requisition_id = b.requisition_id");
            sqlstr.Append(string.Format(" and a.jjd_no ='{0}' order by a.part_no", m_jjd_no));

            OleDbConnection conn = new OleDbConnection(DBHelper.OleConnectionString);
            OleDbCommand cmd = new OleDbCommand();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            //DeliveryVoucher dvchr = (DeliveryVoucher)Session["delivery_voucher"];

            PkgJjd objJjd = new PkgJjd(m_jjd_no);

            //sqlstr.Append(" and requisition_id in (");
            //for (int i = 0; i < dvchr.DeliveryItems.Count; i++)
            //{
            //    if (i == dvchr.DeliveryItems.Count - 1)
            //    {
            //        sqlstr.Append(string.Format("'{0}'", dvchr.DeliveryItems[i].ToString()));
            //    }
            //    else
            //    {
            //        sqlstr.Append(string.Format("'{0}',", dvchr.DeliveryItems[i].ToString()));
            //    }
            //}
            //sqlstr.Append(" )");

            cmd.Connection = conn;
            cmd.CommandText = sqlstr.ToString();

            da.Fill(ds);

            rpt_doc.Load(Request.PhysicalApplicationPath + "\\UI\\Report\\CrysPkgJjd.rpt");
            rpt_doc.SetDataSource(ds.Tables[0]);
            //dvchr.SetDeliveryVoucherNo();
            rpt_doc.SetParameterValue("jjd_no", m_jjd_no);
            //rpt_doc.SetParameterValue("kuwei", "");
            rpt_doc.SetParameterValue("place", objJjd.PlaceName);
            rpt_doc.SetParameterValue("receiver", objJjd.ReceiptPerson);
            rpt_doc.SetParameterValue("recieve_date", objJjd.ReceiptDate);
            rpt_doc.SetParameterValue("receiver_contact", objJjd.ReceiptContract);
            rpt_doc.SetParameterValue("ZHd", objJjd.ZhPlace);
            rpt_doc.SetParameterValue("ZHr", objJjd.ZhPerson);
            rpt_doc.SetParameterValue("ZHdh", objJjd.ZhContract);
            rpt_doc.SetParameterValue("ZHArrTime", objJjd.ZhArrTime);
            rpt_doc.SetParameterValue("XQbm", objJjd.XQDept);
            rpt_doc.SetParameterValue("XQlxr", objJjd.XQPerson);
            rpt_doc.SetParameterValue("XQdh", objJjd.XQContract);
            rpt_doc.SetParameterValue("CYgs", objJjd.CyCompany);
            rpt_doc.SetParameterValue("CYr", objJjd.CyPerson);
            rpt_doc.SetParameterValue("CYdh", objJjd.CyContract);
            rpt_doc.SetParameterValue("CYpz", objJjd.CycCarNo);
            rpt_doc.SetParameterValue("CYjz", objJjd.CyDoc);

            rpt_doc.PrintOptions.PaperOrientation = PaperOrientation.Landscape;
            rpt_doc.PrintOptions.PaperSize = PaperSize.PaperA4;

            using (MemoryStream fp = (MemoryStream)(rpt_doc.ExportToStream(ExportFormatType.PortableDocFormat)))
            {
                Response.Clear();
                Response.Buffer = true;
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(fp.ToArray());
                fp.Close();
                Response.End();
            }

            rpt_doc.Close();
            rpt_doc.Dispose();
        }
 protected void Page_UnLoad(object sender, EventArgs e)
 {
     myReportDocument.Close();
     myReportDocument.Dispose();
     GC.Collect();
 }
Example #52
0
    private void ShowReport(DataTable dt, string format)
    {
        DataTable dt1 = new DataTable();
        dt1 = (DataTable)Session["UserInfo"];
        string Login_Name;
        if (dt1 != null)
        {
            Login_Name = dt1.Rows[0]["Name"].ToString();
        }
        else
        {
            Login_Name = "admin";
        }

        ReportDocument report = new ReportDocument();

        if (rblReportType.SelectedIndex == 0)
        {
            report.Load(Server.MapPath("./REPORT/CAM06/CAM06R01.rpt"));
        }
        else if (rblReportType.SelectedIndex == 1)
        {
            report.Load(Server.MapPath("./REPORT/CAM06/CAM06R02.rpt"));
        }
        else if (rblReportType.SelectedIndex == 2)
        {
            report.Load(Server.MapPath("./REPORT/CAM06/CAM06R03.rpt"));
        }

        report.SetDataSource(dt);

        string programID = string.Empty;
        string strFileName = string.Empty;
        if (rblReportType.SelectedIndex == 0)
        {
            programID = "CAM06R01";
            strFileName = programID + "_" + HttpUtility.UrlEncode("門市調撥差異檢核表(彙總)", System.Text.Encoding.UTF8);
        }
        else if (rblReportType.SelectedIndex == 1)
        {
            programID = "CAM06R02";
            strFileName = programID + "_" + HttpUtility.UrlEncode("門市調撥差異檢核表(明細-零售價)", System.Text.Encoding.UTF8);
        }
        else if (rblReportType.SelectedIndex == 2)
        {
            programID = "CAM06R03";
            strFileName = programID + "_" + HttpUtility.UrlEncode("門市調撥差異檢核表(明細-成本)", System.Text.Encoding.UTF8);
        }


        report.SetParameterValue("par_Program_ID", programID);
        report.SetParameterValue("par_LoginUser", (Session["UID"].ToString()) + Login_Name);
        report.SetParameterValue("par_TransferDate", slpDateRangeTransfer.StartDate +
            (string.IsNullOrEmpty(slpDateRangeTransfer.StartDate) ? "" : "~") + slpDateRangeTransfer.EndDate);
        report.SetParameterValue("par_BusDate", slpDateRangeBus.StartDate +
            (string.IsNullOrEmpty(slpDateRangeBus.StartDate) ? "" : "~") + slpDateRangeBus.EndDate);
        report.SetParameterValue("par_Group", txtGroupS.Text +
            Request[((TextBox)txtGroupS.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", "") +
            (string.IsNullOrEmpty(txtGroupS.Text) ? "" : "~") + txtGroupE.Text + Request[((TextBox)txtGroupE.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_Store", txtStore.Text + Request[((TextBox)txtStore.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_ZO", txtZO.Text + Request[((TextBox)txtZO.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_SAL_ID", txtSalID.Text + Request[((TextBox)txtSalID.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_AC_UID", txtAccID.Text + Request[((TextBox)txtAccID.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_RootNo", txtRootNo.Text + Request[((TextBox)txtRootNo.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_Item", txtItem.Text + Request[((TextBox)txtItem.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));
        report.SetParameterValue("par_Period", txtPeriodS.Text +
            (string.IsNullOrEmpty(txtPeriodS.Text) ? "" : "~") + txtPeriodE.Text);
        report.SetParameterValue("par_ReportContent", rblReportContent.SelectedItem.Text);
        report.SetParameterValue("par_CREATEUID", txtCREATEUID.Text + Request[((TextBox)txtCREATEUID.FindControl("TextBoxName")).UniqueID].ToString().Replace("查無資料", ""));

        Stream stream = null;
        byte[] b = null;
        switch (format)
        {
            case "PDF":
                stream = report.ExportToStream(ExportFormatType.PortableDocFormat);
                b = new byte[stream.Length];
                stream.Read(b, 0, b.Length);
                stream.Seek(0, SeekOrigin.Begin);

                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".pdf");
                Response.ContentType = "application/pdf";
                Response.OutputStream.Write(b, 0, b.Length);
                Response.Flush();
                Response.Close();
                break;

            case "EXCEL":
                stream = report.ExportToStream(ExportFormatType.Excel);
                b = new byte[stream.Length];
                stream.Read(b, 0, b.Length);
                stream.Seek(0, SeekOrigin.Begin);

                Response.ClearContent();
                Response.ClearHeaders();
                Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".xls");
                Response.ContentType = "application/vnd.ms-excel";
                Response.OutputStream.Write(b, 0, b.Length);
                Response.Flush();
                Response.Close();
                break;
        }
        report.Close();
    }
 //---PhongNT 04/12/2012
 public void Page_UnLoad ( object sender, EventArgs e )
 {
     rptDoc = new ReportDocument ( );
     //Fix lỗi report failed
     if (rptDoc != null)
     {
         try
         {
             this.CrystalReportViewer1.Dispose ( );
             this.CrystalReportViewer1 = null;
             rptDoc.Close ( );
             rptDoc.Dispose ( );
             GC.Collect ( );
         }
         catch
         {
             this.CrystalReportViewer1 = null;
             rptDoc.Close ( );
             rptDoc.Dispose ( );
             GC.Collect ( );
         }
     }
 }
Example #54
0
        private void CarsMovement(string model, string packingMonth, DateTime dateFrom, DateTime dateTo, string reportType)
        {
            conn = new SqlConnection(connTaap);
            var cmd = new SqlCommand();
            var dt  = new DataTable();
            var da  = new SqlDataAdapter();

            rptDoc = new ReportDocument();
            try
            {
                conn.Open();

                cmd.CommandText = "dbo.sp_rptCarsMovement";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@PackingMonth", packingMonth);
                cmd.Parameters.AddWithValue("@Model", model);
                cmd.Parameters.AddWithValue("@DateFrom", dateFrom.ToString("yyyy-MM-dd"));
                cmd.Parameters.AddWithValue("@DateTo", dateTo.ToString("yyyy-MM-dd"));
                cmd.Connection     = conn;
                cmd.CommandTimeout = 120;

                da.SelectCommand = cmd;
                da.Fill(dt);

                var file = reportType == "excel" ? "./CarsMovementExcel.rpt" : "./CarsMovement.rpt";

                rptDoc.Load(Server.MapPath(file));
                rptDoc.SetDataSource(dt);
                rptDoc.SetParameterValue("@PackingMonth", packingMonth);
                rptDoc.SetParameterValue("@Model", model);
                rptDoc.SetParameterValue("@DateFrom", dateFrom.ToString("yyyy-MM-dd"));
                rptDoc.SetParameterValue("@DateTo", dateTo.ToString("yyyy-MM-dd"));

                // Declare variables and get the export options.
                ExportOptions exportOpts            = new ExportOptions();
                DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
                exportOpts = rptDoc.ExportOptions;

                if (reportType == "excel")
                {
                    ExcelFormatOptions excelFormatOpts = new ExcelFormatOptions();
                    excelFormatOpts.ExcelUseConstantColumnWidth = true;
                    excelFormatOpts.ExcelAreaType = AreaSectionKind.Detail;
                    exportOpts.ExportFormatType   = ExportFormatType.Excel;
                    exportOpts.FormatOptions      = excelFormatOpts;
                }
                else
                {
                    exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat;
                }

                rptDoc.ExportToHttpResponse(exportOpts, Response, true, "Report-Cars-Finish-Good");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                conn.Close();
                rptDoc.Close();
            }
        }
Example #55
0
    /// <summary>
    /// 利用 CrystalReport 匯出 PDF 或是 EXCEL
    /// </summary>
    /// <param name="s_FileName">檔名</param>
    /// <param name="s_rptFilePath">rpt檔的路徑</param>
    /// <param name="dt_Source">要列印的資料</param>
    /// <param name="e_Type">PDF or EXCEL</param>
    private void LoadCrystalReport(string s_FileName, string s_rptFilePath, DataTable dt_Source, ExportFormatType e_Type)
    {
        ReportDocument report = new ReportDocument();

        report.Load(s_rptFilePath);
        report.SetDataSource(dt_Source);

        System.IO.Stream stream = report.ExportToStream(e_Type);
        byte[] bytes = new byte[stream.Length];
        stream.Read(bytes, 0, bytes.Length);
        stream.Seek(0, System.IO.SeekOrigin.Begin);

        //export file  
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", "attachment;filename=" + s_FileName);//檔名
        if (e_Type == ExportFormatType.Excel)
        { Response.ContentType = "application/vnd.ms-excel"; }
        else if (e_Type == ExportFormatType.PortableDocFormat)
        { Response.ContentType = "application/pdf"; }
        Response.OutputStream.Write(bytes, 0, bytes.Length);
        Response.Flush();
        Response.Close();
        report.Close();
    }
Example #56
0
        protected void Page_Load(object sender, EventArgs e)
        {
            bool isException = false;
            int  windno      = 0;

            try
            {
                windno = int.Parse(Request.QueryString["windno"]);
            }
            catch { }
            try
            {
                if (windno == 1)
                {
                    if (Session[Constants.SES_RPT_DATA] != null)
                    {
                        oRepDoc = (ReportDocument)Session[Constants.SES_RPT_DATA];
                    }
                }
                else if (windno == 2)
                {
                    if (Session[Constants.SES_RPT_DATA_2] != null)
                    {
                        oRepDoc = (ReportDocument)Session[Constants.SES_RPT_DATA_2];
                    }
                }
                else if (windno == 3)
                {
                    if (Session[Constants.SES_RPT_DATA_3] != null)
                    {
                        oRepDoc = (ReportDocument)Session[Constants.SES_RPT_DATA_3];
                    }
                }

                else
                {
                    if (Session[Constants.SES_RPT_DATA] != null)
                    {
                        oRepDoc = (ReportDocument)Session[Constants.SES_RPT_DATA];
                    }
                }
            }
            catch (System.Threading.ThreadAbortException lException)
            {
                // do nothing
            }
            catch (Exception Exp)
            {
                isException = true;
                ShowMessage();
            }

            #region Load Repoert
            MemoryStream oStream = null;

            if (!isException)
            {
                try
                {
                    if (oRepDoc != null)
                    {
                        CrystalParameterCheck(oRepDoc);
                    }
                    else
                    {
                        oRepDoc = new ReportDocument();
                        oRepDoc.Load(Request.MapPath("Reports/ErroOnReportt.rpt"));

                        // single parameter...
                        ParameterFields parameterFields = oRepDoc.ParameterFields;

                        CrystalParameterPassing(parameterFields, "sMsg", "No data available for preview.");
                    }

                    if (Convert.ToString(Session["ExportType"]) == "WRD")
                    {
                        //oRepDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat , Response, true, "PDFReport");
                        //Response.End();
                        oStream = (MemoryStream)oRepDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.RichText);
                        Response.Clear();
                        Response.Buffer      = true;
                        Response.ContentType = "application/msword";
                        Response.BinaryWrite(oStream.ToArray());
                        Response.End();
                    }
                    else if (Convert.ToString(Session["ExportType"]) == "XLS")
                    {
                        oStream = (MemoryStream)oRepDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.Excel);

                        Response.Clear();
                        Response.Buffer      = true;
                        Response.ContentType = "application/vnd.ms-excel";
                        Response.BinaryWrite(oStream.ToArray());
                        Response.End();
                    }
                    else if (Convert.ToString(Session["ExportType"]) == "XLR")
                    {
                        oStream = (MemoryStream)oRepDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.ExcelRecord);

                        Response.Clear();
                        Response.Buffer      = true;
                        Response.ContentType = "application/vnd.ms-excel";
                        Response.BinaryWrite(oStream.ToArray());
                        Response.End();
                    }
                    else
                    {
                        oStream = (MemoryStream)oRepDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

                        Response.Clear();
                        Response.Buffer      = true;
                        Response.ContentType = "application/pdf";
                        Response.BinaryWrite(oStream.ToArray());
                        Response.End();
                    }
                    //oStream = (MemoryStream)oRepDoc.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

                    //Response.Clear();
                    //Response.Buffer = true;
                    //Response.ContentType = "application/pdf";
                    //Response.BinaryWrite(oStream.ToArray());
                    //Response.End();

                    #endregion End of load report
                }
                catch (System.Threading.ThreadAbortException lException)
                {
                    // do nothing
                }
                catch (Exception Exp)
                {
                }
                finally
                {
                    if (oStream != null)
                    {
                        oStream.Flush();
                        oStream.Close();
                        oStream = null;
                        oRepDoc.Close();
                        oRepDoc = null;
                        Page.Dispose();
                    }
                }
            }
        }
		private void GenerateHTML()
		{
			ReportDocument rpt = new ReportDocument();

			switch (cboReportType.SelectedItem.Text)
			{
				case "Posted PO":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PostedPO.rpt"));
					break;
				case "Posted PO Returns":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PostedPOReturns.rpt"));
					break;
				case "Posted Debit Memo":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PostedDebitMemo.rpt"));
					break;
				case "By Vendor":
                    rpt.Load(Server.MapPath(Constants.ROOT_DIRECTORY + "/Reports/PurchaseAnalysis.rpt"));
					break;
				default:
					return;
					
			}

			HTMLFormatOptions htmlOpts = new HTMLFormatOptions();
 
			ExportOptions exportop = new ExportOptions();
			DiskFileDestinationOptions dest = new DiskFileDestinationOptions();
			
			string strPath = Server.MapPath(@"\retailplus\temp\html\");

			string strFileName = cboReportType.SelectedItem.Text.Replace(" ", "").ToLower() + "_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + ".htm";
			if (System.IO.File.Exists(strPath + strFileName))
				System.IO.File.Delete(strPath + strFileName);

			htmlOpts.HTMLFileName = strFileName;
			htmlOpts.HTMLEnableSeparatedPages = true;;
			htmlOpts.HTMLHasPageNavigator = true;
			htmlOpts.HTMLBaseFolderName = strPath;
			rpt.ExportOptions.FormatOptions = htmlOpts;

			exportop = rpt.ExportOptions;

			exportop.ExportDestinationType = ExportDestinationType.DiskFile;
			exportop.ExportFormatType = ExportFormatType.HTML40;
			
			dest.DiskFileName = strFileName.ToString();
			exportop.DestinationOptions = dest;

			SetDataSource(rpt);

            Session["ReportDocument"] = rpt;

			rpt.Export();   rpt.Close();    rpt.Dispose();

			strFileName = "//" + Request.ServerVariables["SERVER_NAME"].ToString() + FindHTMLFile(strPath,strFileName);	
			
			fraViewer.Attributes.Add("src",strFileName);
		}
    override protected void OnInit(EventArgs e)
    {
        InitializeComponent();
        base.OnInit(e);

        try
        {
            bool   bMostrar = true;
            int    int_pinicio;
            int    int_pfin;
            string strServer;
            string strDataBase;
            string strUid;
            string strPwd;

            string pf = "ctl00$CPHC$";
//            pf = "";
//				obtengo de la cadena de conexión los parámetros para luego
//				modificar localizaciones

            string strconexion = Utilidades.CadenaConexion;
            int_pfin  = strconexion.IndexOf(";database=", 0);
            strServer = strconexion.Substring(7, int_pfin - 7);

            int_pinicio = int_pfin + 10;
            int_pfin    = strconexion.IndexOf(";uid=", int_pinicio);
            strDataBase = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            int_pinicio = int_pfin + 5;
            int_pfin    = strconexion.IndexOf(";pwd=", int_pinicio);
            strUid      = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            int_pinicio = int_pfin + 5;
            int_pfin    = strconexion.IndexOf(";Trusted_Connection=", int_pinicio);
            strPwd      = strconexion.Substring(int_pinicio, int_pfin - int_pinicio);

            //creo un objeto ReportDocument
            ReportDocument rdProyecto = new ReportDocument();

            try
            {
                if (Request.Form[pf + "DESGLOSADO"] == "S")
                {
                    rdProyecto.Load(Server.MapPath(".") + @"\sup_profe_desglosados.rpt");
                }
                else
                {
                    rdProyecto.Load(Server.MapPath(".") + @"\sup_profe_agregados.rpt");
                }
            }
            catch (Exception ex)
            {
                rdProyecto.Close();
                rdProyecto.Dispose();
                Response.Write("Error al abrir el report: " + ex.Message);
            }

            try
            {
                rdProyecto.SetDatabaseLogon(strUid, strPwd, strServer, strDataBase);
            }
            catch (Exception ex)
            {
                rdProyecto.Close();
                rdProyecto.Dispose();
                Response.Write("Error al logarse al report: " + ex.Message);
            }

            //creo un objeto logon .

            CrystalDecisions.Shared.TableLogOnInfo tliCurrent;
            try
            {
                foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in rdProyecto.Database.Tables)
                {
                    //obtengo el logon por tabla
                    tliCurrent = tbCurrent.LogOnInfo;

                    tliCurrent.ConnectionInfo.DatabaseName = strDataBase;
                    tliCurrent.ConnectionInfo.UserID       = strUid;
                    tliCurrent.ConnectionInfo.Password     = strPwd;
                    tliCurrent.ConnectionInfo.ServerName   = strServer;

                    //aplico los cambios hechos al objeto TableLogonInfo
                    tbCurrent.ApplyLogOnInfo(tliCurrent);
                }
            }
            catch (Exception ex)
            {
                rdProyecto.Close();
                rdProyecto.Dispose();
                Response.Write("Error al actualizar la localización: " + ex.Message);
            }

            string strTipoFormato = Request.Form[pf + "FORMATO"]; // ESTO LO RECOGERE COMO PARAMETRO
            strControl = strTipoFormato;

            DiskFileDestinationOptions diskOpts = ExportOptions.CreateDiskFileDestinationOptions();
            ExportOptions exportOpts            = new ExportOptions();

            try
            {
                rdProyecto.SetParameterValue("@Concepto", Request.Form[pf + "hdnConcepto"]);
                rdProyecto.SetParameterValue("Cpto", Request.Form[pf + "hdnConcepto"]);
                //rdProyecto.SetParameterValue("@Concepto", Request.Form[pf + "CONCEPTO"]);
                //rdProyecto.SetParameterValue("Cpto", Request.Form[pf + "CONCEPTO"]);
                rdProyecto.SetParameterValue("@NivEstruc", Request.Form[pf + "NESTRUCTURA"]);
                rdProyecto.SetParameterValue("Estruc", Request.Form[pf + "NESTRUCTURA"]);
                rdProyecto.SetParameterValue("@Codigo", Request.Form[pf + "CODIGO"]);
                rdProyecto.SetParameterValue("@Tecnicos", Request.Form[pf + "TECNICOS"]);

                /*             string[] aFecha = Regex.Split(Request.Form["FECHADESDE"], @"/");
                 *             string mes = aFecha[0];
                 *             if (mes.Length==1) mes = "0" + mes;
                 *             string strFecha = "01" + "/" + mes +"/"+ aFecha[1];
                 *             rdProyecto.SetParameterValue("@FechaDesde", strFecha);
                 *             rdProyecto.SetParameterValue("FechaDesde", strFecha);
                 *
                 *             aFecha = Regex.Split(Request.Form["FECHAHASTA"], @"/");
                 *
                 *             DateTime dtFechaHasta = DateTime.Parse("01/" + aFecha[0] + "/" + aFecha[1]);
                 *             dtFechaHasta = dtFechaHasta.AddMonths(1);
                 *             dtFechaHasta = dtFechaHasta.AddDays(-1);
                 *
                 *             mes = dtFechaHasta.Month.ToString();
                 *             string dia = dtFechaHasta.Day.ToString();
                 *
                 *             if (dia.Length == 1) dia = "0" + dia;
                 *             if (mes.Length == 1) mes = "0" + mes;
                 *
                 *             strFecha = dia + "/" + mes + "/" + dtFechaHasta.Year.ToString();
                 *
                 *             rdProyecto.SetParameterValue("@FechaHasta", strFecha);
                 *             rdProyecto.SetParameterValue("FechaHasta", strFecha);
                 */
                rdProyecto.SetParameterValue("@FechaDesde", Request.Form[pf + "FECHADESDE"]);
                rdProyecto.SetParameterValue("FechaDesde", Request.Form[pf + "FECHADESDE"]);
                rdProyecto.SetParameterValue("@FechaHasta", Request.Form[pf + "FECHAHASTA"]);
                rdProyecto.SetParameterValue("FechaHasta", Request.Form[pf + "FECHAHASTA"]);

                if (Session["ADMINISTRADOR_PC_ACTUAL"].ToString() == "")
                {
                    rdProyecto.SetParameterValue("@nUsuario", Request.Form[pf + "hdnEmpleado"]);
                }
                else
                {
                    rdProyecto.SetParameterValue("@nUsuario", 0);
                }

                rdProyecto.SetParameterValue("path", Server.MapPath(".") + "//");

                rdProyecto.SetParameterValue("formato", strTipoFormato);
                //rdProyecto.SetParameterValue("CONCEPTO", Utilidades.unescape(Request.Form["DESCONCEPTO"]));
            }
            catch (Exception ex)
            {
                rdProyecto.Close();
                rdProyecto.Dispose();
                Response.Write("Error al actualizar los parámetros del report: " + ex.Message);
            }
            try
            {
                System.IO.Stream oStream;
                byte[]           byteArray = null;

                switch (strTipoFormato)
                {
                //			PDF
                case "PDF":
                    oStream   = rdProyecto.ExportToStream(ExportFormatType.PortableDocFormat);
                    byteArray = new byte[oStream.Length];
                    oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                    break;

                case "EXC":
                    oStream   = rdProyecto.ExportToStream(ExportFormatType.Excel);
                    byteArray = new byte[oStream.Length];
                    oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                    break;

                case "EXC2":
                    //
                    rdProyecto.ExportToHttpResponse(ExportFormatType.Excel, Response, true, "Exportacion");
                    bMostrar = false;
                    break;
                }


                // FIN

                if (bMostrar)
                {
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();

                    //String nav = HttpContext.Current.Request.Browser.Browser.ToString();
                    //if (nav.IndexOf("IE") == -1)
                    //{
                    switch (strTipoFormato)
                    {
                    case "PDF":
                        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "Filename.pdf"));
                        break;

                    case "EXC":
                        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", "Filename.xls"));
                        break;
                    }
                    //}
                    switch (strTipoFormato)
                    {
                    //			PDF
                    case "PDF":
                        Response.ContentType = "application/pdf";
                        break;

                    case "EXC":
                        //		EXCEL
                        Response.ContentType = "application/xls";
                        //Response.ContentType = "Application/vnd.ms-excel";

                        break;
                    }
                    Response.BinaryWrite(byteArray);
                    //Response.Flush();
                    //Response.Close();
                    //HttpContext.Current.Response.End();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                rdProyecto.Close();
                rdProyecto.Dispose();
                Response.Write("Error al exportar el report: " + ex.Message);
            }
        }
        //handle any exceptions
        catch (Exception ex)
        {
            Response.Write("No se puede crear el report: " + ex.Message);
        }
    }
    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        try
        {
            reporte.Dispose();
            reporte = null;
            reporte.Close();
        }
        catch
        {
        }

        try
        {
            GC.Collect();
        }
        catch
        {
        }
    }
Example #60
0
        private void getCre(string mobile)
        {
            try
            {
                cryRpt.Load(Server.MapPath("rpt_credsheet.rpt"));
                cryRpt.SetDatabaseLogon("sa", "friend", "ASAD-PC", "HumBros");

                DataTable dt_ = new DataTable();

                if (mobile != null)
                {
                    cmd = new SqlCommand("SELECT * from V_VPCustCred where CellNo1 ='" + mobile + "'", con);
                }
                con.Open();

                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dt_);
                cryRpt.SetDataSource(dt_);
                cryRpt.SetParameterValue("CompanyName", "View Point");
                cryRpt.SetParameterValue("address", "Shop # 2 Opposite Rafah-e-aam Post Office Malir Halt, Karachi");
                cryRpt.SetParameterValue("PhoneNo", "0321-2010080");
                cryRpt.SetParameterValue("ReportName", "Customer Credit Report");


                System.IO.Stream oStream   = null;
                byte[]           byteArray = null;
                oStream =
                    cryRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                byteArray = new byte[oStream.Length];
                oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(byteArray);
                Response.Flush();
                Response.Close();
                cryRpt.Close();
                cryRpt.Dispose();
                con.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }