ClearHeaders() public method

public ClearHeaders ( ) : void
return void
Example #1
0
        public static void ExportGridViewToExcel(string strFileName, DataTable dt, System.Web.HttpResponse response)
        {
            System.IO.StringWriter             tw     = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter       hw     = new System.Web.UI.HtmlTextWriter(tw);
            System.Web.UI.WebControls.DataGrid dgGrid = new System.Web.UI.WebControls.DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();

            //Get the HTML for the control.


            dgGrid.RenderControl(hw);

            ////Write the HTML back to the browser.
            ////Response.ContentType = application/vnd.ms-excel;
            //response.ContentType = "application/vnd.ms-excel";
            //response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls");
            //response.Write(tw.ToString());
            //response.End();


            byte[] bytes = System.Text.Encoding.Default.GetBytes(tw.ToString());
            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            response.Buffer = true;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType     = "application/vnd.ms-excel";
            response.ContentEncoding = System.Text.Encoding.Unicode;
            response.AddHeader("content-disposition", "attachment; filename=" + strFileName + ".xls");
            response.BinaryWrite(bytes); // create the file
            response.End();              // send it to the client to download
        }
Example #2
0
        /// <summary>
        /// Create MS-Report
        /// </summary>
        /// <param name="reportPath">string path</param>
        /// <param name="reportType">PDF,Excel</param>
        /// <param name="reportName">name of report</param>
        /// <param name="reportDataSource">Data source report</param>
        /// <param name="response">HttpResponse</param>
        public static void ExportMSReport(string reportPath, string reportType, string reportName, ReportDataSource reportDataSource, System.Web.HttpResponse response)
        {
            // Variables
            Warning[] warnings;
            string[]  streamIds;
            string    mimeType  = string.Empty;
            string    encoding  = string.Empty;
            string    extension = string.Empty;

            // Setup the report viewer object and get the array of bytes
            ReportViewer viewer = new ReportViewer();

            viewer.ProcessingMode = ProcessingMode.Local;
            viewer.LocalReport.DataSources.Add(reportDataSource);
            viewer.LocalReport.ReportPath = reportPath;

            byte[] bytes = viewer.LocalReport.Render(reportType, null, out mimeType, out encoding, out extension, out streamIds, out warnings);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            response.Buffer = true;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType     = mimeType;
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.AddHeader("content-disposition", "attachment; filename=" + reportName + "." + extension);
            response.BinaryWrite(bytes); // create the file
            response.End();              // send it to the client to download
        }
Example #3
0
        public bool ReturnXlsBytes(System.Web.HttpResponse resp, byte[] data, string fileName)
        {
            resp.ClearHeaders();
            resp.ClearContent();

            DialogUtils.SetCookieResponse(resp);

            resp.HeaderEncoding = System.Text.Encoding.Default;
            resp.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            resp.AddHeader("Content-Length", data.Length.ToString());
            resp.ContentType = "application/octet-stream";
            resp.Cache.SetCacheability(HttpCacheability.NoCache);

            /*
             * resp.BufferOutput = false;
             * resp.WriteFile(f.FullName);
             * resp.Flush();
             * resp.End();
             */

            resp.BufferOutput = true;
            resp.BinaryWrite(data);
            //resp.End();
            return(true);
        }
Example #4
0
        /// <summary>
        /// Creates a text version (mostly) of the Diagnostics data that is sent via the HttpResponse to the client.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDumpDiagnostics_Click(object sender, EventArgs e)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

            response.ClearHeaders();
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("content-disposition", "attachment; filename=RockDiagnostics-" + System.Environment.MachineName + ".txt");
            response.Charset = "";

            ResponseWrite("Version:", lRockVersion.Text, response);
            ResponseWrite("Database:", lDatabase.Text.Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Execution Location:", lExecLocation.Text, response);
            ResponseWrite("Migrations:", GetLastMigrationData().Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Cache:", lCacheOverview.Text.Replace("<br />", Environment.NewLine.ToString()), response);;
            ResponseWrite("Routes:", lRoutes.Text.Replace("<br />", Environment.NewLine.ToString()), response);

            // Last and least...
            ResponseWrite("Server Variables:", "", response);
            foreach (string key in Request.ServerVariables)
            {
                ResponseWrite(key, Request.ServerVariables[key], response);
            }

            response.Flush();
            response.End();
        }
Example #5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            List <EvaluacionEntidades.Empleados> list;
            if (!string.IsNullOrEmpty(Request.QueryString["idadmin"]))
            {
                DateTime?inicio = null;
                if (!string.IsNullOrEmpty(Request.QueryString["inicio"]))
                {
                    inicio = DateTime.Parse(Request.QueryString["inicio"]);
                }
                DateTime?fin = null;
                if (!string.IsNullOrEmpty(Request.QueryString["fin"]))
                {
                    fin = DateTime.Parse(Request.QueryString["fin"]);
                }
                int?idSuper = null;
                if (!string.IsNullOrEmpty(Request.QueryString["supervisorid"]))
                {
                    idSuper = int.Parse(Request.QueryString["supervisorid"]);
                }
                list = EvaluacionBL.EmpleadosBL.GetEmpleadoAdmin(int.Parse(Request.QueryString["idadmin"]), Request.QueryString["pais"], inicio, fin, Request.QueryString["departamento"], Request.QueryString["estado"], idSuper);
            }
            else
            {
                list = EvaluacionBL.EmpleadosBL.GetEmpleadosSupervisados(int.Parse(Request.QueryString["idSupervisor"]));
            }
            if (list != null && list.Count > 0)
            {
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();

                //Tipo de contenido para forzar la descarga
                response.ContentType    = "application/octet-stream";
                Response.HeaderEncoding = System.Text.Encoding.Default;
                response.AddHeader("Content-Disposition", "attachment; filename=" + "EmpleadosDesempeño.xlsx");
                System.IO.MemoryStream grilla = Helpers.funcionesGenerales.ConvierteCSVEmpleados(list);
                // System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                // byte[] bufferAux = grilla.ToArray();
                // byte[] buffer;
                //System.Text.Encoding utf8 = new System.Text.UTF8Encoding();
                // System.Text.Encoding win1252 = System.Text.Encoding.GetEncoding(1252);
                // buffer = System.Text.Encoding.Convert(utf8,win1252,bufferAux);
                //while (mContador < grilla.Length)
                //{
                //    buffer[mContador] = Chr grilla.Substring(mContador,1) Strings.Asc(Strings.Mid(pCSV, mContador + 1, 1));
                //    mContador = mContador + 1;
                //}

                //Envia los bytes
                response.BinaryWrite(grilla.ToArray());
                response.End();
            }
        }
        catch (Exception ex)
        { }
    }
 private static void SendFileNotFound(HttpResponse response)
 {
   response.ClearHeaders();
   response.StatusCode = 404; //not found
   response.StatusDescription = "Not Found";
   response.End();
 }
 public void prepareExcelFile(string name, System.Web.HttpResponse resp)
 {
     resp.ClearContent();
     resp.ClearHeaders();
     resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
     resp.ContentType = "application/vnd.ms-excel";
 }
Example #8
0
        /// <summary>
        /// Datatable数据填充如excel
        /// </summary>
        /// <param name="filename">excel文件名</param>
        /// <param name="dt"> 数据源</param>
        /// <param name="Response"> response响应</param>
        ///  <param name="headerStr"> 表头标题</param>
        public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr)
        {
            MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream  as用作转换,此处可以省略
            try
            {

                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.ContentEncoding = Encoding.UTF8;
                Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls"));
                Response.AddHeader("content-length", ms.Length.ToString());
                Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组
                Response.BinaryWrite(data);
            }
            catch
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>");
            }
            Response.Flush();
            Response.Close();
            Response.End();
            ms = null;
        }
Example #9
0
        public void ExportCSV(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response)
        {
            string        strFileName = "Report" + System.DateTime.Now.Date.ToString("dd") + System.DateTime.Now.AddMonths(0).ToString("MM") + System.DateTime.Now.AddYears(0).ToString("yyyy") + System.DateTime.Now.Millisecond.ToString("0000");
            StringBuilder sb          = new StringBuilder();

            System.Web.UI.WebControls.GridViewRow grHeader = exportGV.HeaderRow;
            int counter = 0;

            foreach (System.Web.UI.WebControls.TableCell tc in grHeader.Cells)
            {
                sb.Append("\"" + exportGV.Columns[counter].HeaderText.Trim() + "\",");
                counter++;
            }
            sb.AppendLine();

            foreach (System.Web.UI.WebControls.GridViewRow gr in exportGV.Rows)
            {
                foreach (System.Web.UI.WebControls.TableCell tc in gr.Cells)
                {
                    sb.Append("\"" + getGridCellText(tc) + "\",");
                }
                sb.AppendLine();
            }

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
            Response.ContentType = "text/csv";
            Response.AddHeader("Pragma", "public");
            Response.Write(sb.ToString());
            Response.End();
        }
Example #10
0
        private static void DownloadFile(string FileLoc)
        {
            FileInfo objFile = new FileInfo(FileLoc);

            System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response;
            string filename = objFile.Name;

            if (HttpContext.Current.Request.UserAgent.IndexOf("; MSIE ") > 0)
            {
                filename = HttpUtility.UrlEncode(filename);
            }

            if (objFile.Exists)
            {
                objResponse.ClearContent();
                objResponse.ClearHeaders();
                objResponse.AppendHeader("Content-Length", objFile.Length.ToString());
                objResponse.ContentType = GetContentType(objFile.Extension.Replace(".", ""));
                if (objResponse.ContentType.Contains("x-shockwave-flash") || objResponse.ContentType.Contains("video"))
                {
                    objResponse.AddHeader("Content-Disposition", "inline;filename=\"" + filename + "\"");
                }
                else
                {
                    objResponse.AppendHeader("content-disposition", "attachment; filename=\"" + filename + "\"");
                }

                WriteFile(objFile.FullName);

                objResponse.Flush();
                objResponse.End();
            }
        }
Example #11
0
        private int StreamFile(string FilePath, string DownloadAs)
        {
            DownloadAs = DownloadAs.Replace(" ", "_");

            System.IO.FileInfo objFile = new System.IO.FileInfo(FilePath);
            if (!objFile.Exists)
            {
                return(0);
            }

            System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response;
            objResponse.ClearContent();
            objResponse.ClearHeaders();
            objResponse.AppendHeader("Content-Disposition", "attachment; filename=" + DownloadAs);
            objResponse.AppendHeader("Content-Length", objFile.Length.ToString());

            string strContentType;

            strContentType          = "application/octet-stream";
            objResponse.ContentType = strContentType;
            WriteFile(objFile.FullName);

            objResponse.Flush();
            objResponse.Close();
            return(1);
        }
 private static void SendNotModified(HttpResponse response)
 {
   response.ClearHeaders();
   setCacheHeaders(response);
   response.StatusCode = 304; // not modified
   response.StatusDescription = "Not Modified";
   response.End();
 }
Example #13
0
 internal void WriteToHttpResponse(HttpResponse httpResponse)
 {
     httpResponse.ClearContent();
     httpResponse.ClearHeaders();
     httpResponse.ContentType = model.ContentType;
     httpResponse.AddHeader("Content-Disposition", ContentDisposition);
     WriteToStream(httpResponse.OutputStream);
 }
Example #14
0
 public void SetupResponse(System.Web.HttpResponse response, string fileName)
 {
     response.ClearHeaders();
     response.Clear();
     response.Cache.SetCacheability(System.Web.HttpCacheability.Private);
     response.Cache.SetMaxAge(new TimeSpan(0));
     response.Cache.SetExpires(new DateTime(0));
     response.Cache.SetNoServerCaching();
     response.AppendHeader("Content-Disposition", ("attachment; filename=\"" + (fileName + "\"")));
 }
 /// <summary>
 /// Sends the file to the response with content-length header
 /// Works with all types of files, not image specific
 /// </summary>
 /// <param name="response"></param>
 /// <param name="file"></param>
 /// <param name="mimetype"></param>
 private static void SendToResponse(HttpResponse response, byte[] fileContent, DateTime lastWriteTime, string mimetype)
 {
   response.ClearHeaders();
   setCacheHeaders(response);
   
   response.Cache.SetLastModified(lastWriteTime); // to avoid rounding problems with header (no millisecs there)
   response.ContentType = mimetype;      
   response.AppendHeader("Content-Length", fileContent.Length.ToString());
   response.BinaryWrite(fileContent);
   response.End();
 }
Example #16
0
		public static void JsonResponse(HttpResponse response, Action<JsonWriter> writeAction)
		{
			response.ClearHeaders();
			response.ClearContent();

			JsonWriter writer = new JsonWriter(response.Output);

			writeAction(writer);

			writer.Flush();
		}
    public static void XmlResponse(HttpResponse response, Action<XmlTextWriter> writeAction)
    {
      response.ClearHeaders();
      response.ClearContent();
      response.ContentType = "text/xml";

      XmlTextWriter writer = new XmlTextWriter(response.Output);

      writeAction(writer);

      writer.Flush();
    }
    /// <summary>
    /// Sends the file to the response with content-length header. will check last-writetime for sending modified header
    /// </summary>
    /// <param name="Response"></param>
    /// <param name="file"></param>
    /// <param name="mimetype"></param>
    /// <remarks>Works with all types of files, not image specific</remarks>
    public void SendToResponse(HttpResponse Response, FileInfo file, string mimetype)
    {
      Response.ClearHeaders();
      setCacheHeaders(Response);   

      //Response.Cache.SetETag("\"999ed196eeb0cc1:9\"");
      Response.Cache.SetLastModified(file.LastWriteTime);
      Response.ContentType = mimetype;      
      Response.AppendHeader("Content-Length", file.Length.ToString());
      Response.WriteFile(file.FullName);
      Response.End();
    }
Example #19
0
        /// <summary>
        /// Export CSV File
        /// </summary>
        /// <param name="fileName">Name of file</param>
        /// <param name="dataSource">Data source report</param>
        /// <param name="response">HttpResponse</param>
        public static void ExportCSVFile(string fileName, DataTable dataSource, System.Web.HttpResponse response)
        {
            byte[] bytes;
            if ((dataSource.Rows.Count == 0))
            {
                string text = "";
                if (dataSource.Columns.Count != 0)
                {
                    text = dataSource.Columns[0].ColumnName;
                    for (int i = 1; i < dataSource.Columns.Count; i++)
                    {
                        text = string.Format("{0},{1}", text, dataSource.Columns[i].ColumnName);
                    }
                }
                text  = string.Format("{0}\r\n", text);
                bytes = System.Text.Encoding.UTF8.GetBytes(text);
            }
            else
            {
                string text = dataSource.Columns[0].ColumnName;
                for (int i = 1; i < dataSource.Columns.Count; i++)
                {
                    text = string.Format("{0},{1}", text, dataSource.Columns[i].ColumnName);
                }
                text = string.Format("{0}", text);

                for (int i = 0; i < dataSource.Rows.Count; i++)
                {
                    string txtStr = StripCommaCharArray(dataSource.Rows[i][0].ToString());
                    for (int j = 1; j < dataSource.Columns.Count; j++)
                    {
                        txtStr = string.Format("{0},{1}", txtStr, ReportUtil.StripAllTagsCharArray(StripCommaCharArray(dataSource.Rows[i][j].ToString())));
                    }
                    text   = string.Format("{0}\r\n{1}", text, txtStr);
                    txtStr = "";
                }

                text  = string.Format("{0}\r\n", text);
                bytes = System.Text.Encoding.UTF8.GetBytes(text);
            }
            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            response.Buffer = true;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType     = "text/csv";
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
            response.BinaryWrite(bytes); // create the file
            response.End();              // send it to the client to download
        }
Example #20
0
        private static void ResponseWrite(string Result, string FileName, string ContentType)
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;

            byte[] lstByte = System.Text.Encoding.UTF8.GetBytes(Result);

            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = string.Format("{0}; charset=utf-8", ContentType);
            Response.AppendHeader("Content-disposition", string.Format("attachment; filename=\"{0}\"", FileName));
            Response.AppendHeader("Content-Length", lstByte.Length.ToString());
            Response.BinaryWrite(lstByte);
            Response.Flush();
            Response.End();
        }
Example #21
0
        /// <summary>
        /// Method to provide create Plain Text for download from website
        /// </summary>
        /// <param name="reportName">Report name</param>
        /// <param name="plainText">Data text</param>
        /// <param name="response">HttpResponse</param>
        /// /// <summary>
        public static void ExportPlainText(string reportName, string plainText, System.Web.HttpResponse response)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(plainText);

            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            response.Buffer = true;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType     = "text/plain";
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.AddHeader("content-disposition", "attachment; filename=" + reportName + ".txt");
            response.BinaryWrite(bytes); // create the file
            response.End();              // send it to the client to download
        }
Example #22
0
        public static void ExportExcel(System.Web.HttpResponse response, string excelLocation)
        {
            byte[] bytes = File.ReadAllBytes(excelLocation);
            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Length", bytes.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Path.GetFileName(excelLocation), System.Text.Encoding.UTF8).Replace("+", "%20"));

            response.BinaryWrite(bytes);
            if (response.IsClientConnected)
            {
                response.Flush();
            }
        }
 /// <summary>
 /// Disables the response cache.
 /// </summary>
 /// <param name="httpResponse">The HTTP response.</param>
 public static void DisableCache(this HttpResponse httpResponse)
 {
     httpResponse.Cache.SetCacheability(HttpCacheability.NoCache);
     httpResponse.Expires = -1;
     httpResponse.ClearHeaders();
     httpResponse.AppendHeader(@"Cache-Control", @"no-cache");                // HTTP 1.1
     httpResponse.AppendHeader(@"Cache-Control", @"private");                 // HTTP 1.1
     httpResponse.AppendHeader(@"Cache-Control", @"no-store");                // HTTP 1.1
     httpResponse.AppendHeader(@"Cache-Control", @"must-revalidate");         // HTTP 1.1
     httpResponse.AppendHeader(@"Cache-Control", @"max-stale=0");             // HTTP 1.1
     httpResponse.AppendHeader(@"Cache-Control", @"post-check=0");            // HTTP 1.1
     httpResponse.AppendHeader(@"Cache-Control", @"pre-check=0");             // HTTP 1.1
     httpResponse.AppendHeader(@"Pragma", @"no-cache");                       // HTTP 1.1
     httpResponse.AppendHeader(@"Keep-Alive", @"timeout=3, max=993");         // HTTP 1.1
     httpResponse.AppendHeader(@"Expires", @"Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1
 }
Example #24
0
        /// <summary>
        /// Creates a text version (mostly) of the Diagnostics data that is sent via the HttpResponse to the client.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDumpDiagnostics_Click(object sender, EventArgs e)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

            response.ClearHeaders();
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("content-disposition", "attachment; filename=RockDiagnostics-" + System.Environment.MachineName + ".txt");
            response.Charset = "";

            ResponseWrite("Version:", lRockVersion.Text, response);
            ResponseWrite("Database:", lDatabase.Text.Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Execution Location:", lExecLocation.Text, response);
            ResponseWrite("Migrations:", GetLastMigrationData().Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Cache:", lCacheOverview.Text.Replace("<br />", Environment.NewLine.ToString()), response);;
            ResponseWrite("Routes:", lRoutes.Text.Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Threads:", lThreads.Text.Replace("<br />", Environment.NewLine.ToString()), response);

            // Last and least...
            ResponseWrite("Server Variables:", "", response);
            foreach (string key in Request.ServerVariables)
            {
                bool isCookieOrPassword = key.Equals("HTTP_COOKIE", StringComparison.OrdinalIgnoreCase) || key.Equals("AUTH_PASSWORD", StringComparison.OrdinalIgnoreCase);
                // Skip cookies
                if (isCookieOrPassword)
                {
                    continue;
                }

                bool isSensitiveData = key.IndexOf("ALL_HTTP", StringComparison.OrdinalIgnoreCase) >= 0 || key.IndexOf("ALL_RAW", StringComparison.OrdinalIgnoreCase) >= 0;
                if (isSensitiveData)
                {
                    // strip out any sensitive data
                    ResponseWrite(key, Regex.Replace(Request.ServerVariables[key], @"ASP.NET_SessionId=\S*;|\.ROCK=\S*;", string.Empty, RegexOptions.Multiline), response);
                }
                else
                {
                    ResponseWrite(key, Request.ServerVariables[key], response);
                }
            }

            response.Flush();
            response.End();
        }
Example #25
0
 protected void ClientBigfileOk_Click(object sender, EventArgs e)
 {
     try
     {
         string fileName = "FileUpLoadSetup.exe";
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.Clear();
         response.ClearHeaders();
         response.ClearContent();
         response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
         response.ContentType = "text/plain";
         response.TransmitFile(System.Web.HttpContext.Current.Server.MapPath(fileName));
         response.Flush();
         response.End();
     }
     catch (Exception ex)
     {
     }
 }
 private static void doRender(string PlaceholderType, string RenderFunction, HtmlTextWriter writer, CmsPage page, int identifier, CmsLanguage langToRenderFor, string[] subParamsArray, string templateFilename)
 {
     try
     {
         // Render() parameters are set in BaseCmsPlaceholder
         PlaceholderUtils.InvokePlaceholderFunction(PlaceholderType, RenderFunction, new object[] { writer, page, identifier, langToRenderFor, subParamsArray });
     }
     catch (Exception ex)
     {
         if (ex is System.Threading.ThreadAbortException)
         {
             // the placeholder or control did a Response.End
             return;
         }
         else if (ex is CmsPageNotFoundException || ex.InnerException is CmsPageNotFoundException)
         {
             CmsContext.HandleNotFoundException();
         }
         else if (ex is CmsPlaceholderNeedsRedirectionException || ex.InnerException is CmsPlaceholderNeedsRedirectionException)
         {
             // due to the dynamic nature of placeholders,
             // placeholders can not redirect on their own, so must raise an Exception to do so.
             if (HttpContext.Current != null && HttpContext.Current.Response != null)
             {
                 System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
                 resp.Clear();
                 resp.ClearContent();
                 resp.ClearHeaders();
                 string targetUrl = (ex.InnerException as CmsPlaceholderNeedsRedirectionException).TargetUrl;
                 resp.StatusCode = 301; // Moved Permanently
                 resp.AddHeader("Location", targetUrl);
                 resp.Redirect(targetUrl, true);
             }
         }
         else
         {
             throw new TemplateExecutionException(ex.InnerException, templateFilename, "Error in Placeholder, or Unknown Placeholder in " + PlaceholderType + " Template<p>root exception: " + ex.Message);
         }
     }
 } // callExternalPlaceholderRender
Example #27
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="FileLoc">文件真实路径</param>
        /// <param name="FileName">显示文件名</param>
        public static void DownloadFile(string FileLoc, string FileName)
        {
            System.IO.FileInfo      objFile     = new System.IO.FileInfo(FileLoc);
            System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response;
            string truefilename = objFile.Name;

            if (HttpContext.Current.Request.UserAgent.IndexOf("; MSIE ") > 0)
            {
                truefilename = HttpUtility.UrlEncode(truefilename, System.Text.Encoding.UTF8);
            }
            if (objFile.Exists)
            {
                objResponse.ClearContent();
                objResponse.ClearHeaders();
                objResponse.AppendHeader("content-disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(FileName) + "\"");
                objResponse.AppendHeader("Content-Length", objFile.Length.ToString());
                objResponse.ContentType = GetContentType(objFile.Extension.Replace(".", ""));
                WriteFile(objFile.FullName);
                objResponse.Flush();
                objResponse.End();
            }
        }
        public static void Run()
        {
            // ExStart:SendingPdfToBrowser
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_AdvanceFeatures();

            // Instantiate Pdf instance by calling its empty constructor
            Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf();

            MemoryStream stream = new MemoryStream();
            HttpResponse Response = new HttpResponse(null);
            pdf1.Save(stream);
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.Charset = "UTF-8";
            Response.AddHeader("Content-Length", stream.Length.ToString());
            Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", dataDir + "SendingPdfToBrowser.pdf"));
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(stream.ToArray());
            Response.Flush();
            Response.End();
            // ExEnd:SendingPdfToBrowser           
        }
Example #29
0
        private static void SetupResponse( HttpResponse response )
        {
            // Cleans the response buffer.
            response.ClearHeaders();
            response.Clear();

            // Prevent the browser from caching the result.
            response.CacheControl = "no-cache";

            // Set the response format.
            response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
            response.ContentType = "text/xml";
        }
 private void ReturnMessage(byte message, HttpResponse response)
 {
     response.StatusCode = 200;
     response.ClearHeaders();
     response.AppendHeader("Connection", "Keep-Alive");
     response.AppendHeader("Content-Length", "1");
     response.Cache.SetCacheability(HttpCacheability.NoCache);
     response.ContentType = ContentType.RTMPT;
     response.Write((char)message);
     response.Flush();
 }
Example #31
0
		public void Methods_Deny_Unrestricted ()
		{
			HttpResponse response = new HttpResponse (writer);
			response.AddCacheItemDependencies (new ArrayList ());
			response.AddCacheItemDependency (String.Empty);
			response.AddFileDependencies (new ArrayList ());
			response.AddFileDependency (fname);
			response.AddCacheDependency (new CacheDependency[0]);
			response.AddCacheItemDependencies (new string [0]);
			response.AddFileDependencies (new string [0]);

			try {
				response.AppendCookie (new HttpCookie ("mono"));
			}
			catch (NullReferenceException) {
				// ms 
			}

			try {
				Assert.IsNull (response.ApplyAppPathModifier (null), "ApplyAppPathModifier");
			}
			catch (NullReferenceException) {
				// ms 
			}

			try {
				response.Clear ();
			}
			catch (NullReferenceException) {
				// ms 
			}
		
			try {
				response.ClearContent ();
			}
			catch (NullReferenceException) {
				// ms 
			}
		
			try {
				response.ClearHeaders ();
			}
			catch (NullReferenceException) {
				// ms 
			}

			try {
				response.Redirect ("http://www.mono-project.com");
			}
			catch (NullReferenceException) {
				// ms 
			}
			try {
				response.Redirect ("http://www.mono-project.com", false);
			}
			catch (NullReferenceException) {
				// ms 
			}

			try {
				response.SetCookie (new HttpCookie ("mono"));
			}
			catch (NullReferenceException) {
				// ms 
			}

			response.Write (String.Empty);
			response.Write (Char.MinValue);
			response.Write (new char[0], 0, 0);
			response.Write (this);
			response.WriteSubstitution (new HttpResponseSubstitutionCallback (Callback));

			response.Flush ();

			response.Close ();

			try {
				response.End ();
			}
			catch (NullReferenceException) {
				// ms 
			}
		}
 public override void ClearHeaders()
 {
     _httpResponse.ClearHeaders();
 }
        /// <summary>
        /// Writes file to response.
        /// </summary>
        public void DownloadFile(String path, String localFileName, String originalFileName,
            String contentType, HttpResponse response)
        {
            if (!System.IO.File.Exists(path + localFileName))
            {
                return;
            }
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType = contentType;
            response.AddHeader("content-disposition",
                               "attachment; filename=" + originalFileName);

            response.WriteFile(path + localFileName);
            response.End();
        }
Example #34
0
        protected virtual void PrepareContent(ref HttpResponse response)
        {
            List<HttpCookie> cookies = new List<HttpCookie>(response.Cookies.Count);
            for (int i = 0; i < response.Cookies.Count; i++)
                cookies.Add(response.Cookies[i]);

            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "text/html";
            for (int i = 0; i < cookies.Count; i++)
                response.AppendCookie(cookies[i]);
            response.Cache.SetCacheability(HttpCacheability.NoCache);
        }
Example #35
0
 //private SvgDocument CreateSvgDocument()
 //{
 //    SvgDocument svgDoc;
 //    XmlDocument xml = new XmlDocument();
 //    xml.LoadXml(this.Svg);
 //    XmlNodeList nodeListAllg = xml.GetElementsByTagName("g");
 //    Dictionary<int, XmlNode[,]> dic = new Dictionary<int, XmlNode[,]>();
 //    int i = 0;
 //    foreach (XmlNode xNod in nodeListAllg)
 //    {
 //        i++;
 //        XmlNode xmlvisibility = xNod.Attributes.GetNamedItem("class");
 //        if (xmlvisibility != null && xmlvisibility.Value == "highcharts-series-group")
 //        {
 //            foreach (XmlNode xNod2 in xNod.ChildNodes)
 //            {
 //                i++;
 //                XmlNode xmlvisibility1 = xNod2.Attributes.GetNamedItem("visibility");
 //                if (xmlvisibility1 != null && xmlvisibility1.Value == "hidden")
 //                {
 //                    XmlNode[,] xmln = new XmlNode[1, 2];
 //                    xmln[0, 0] = xNod;
 //                    xmln[0, 1] = xNod2;
 //                    dic.Add(i, xmln);
 //                }
 //            }
 //        }
 //        else if (xmlvisibility != null && xmlvisibility.Value == "highcharts-tooltip")
 //        {
 //            XmlNode[,] xmln = new XmlNode[1, 2];
 //            xmln[0, 0] = xml.FirstChild;
 //            xmln[0, 1] = xNod;
 //            dic.Add(i, xmln);
 //        }
 //    }
 //    foreach (KeyValuePair<int, XmlNode[,]> a in dic)
 //    {
 //        a.Value[0, 0].RemoveChild(a.Value[0, 1]);
 //    }
 //    this.Svg = xml.OuterXml;
 //    // Create a MemoryStream from SVG string.
 //    using (MemoryStream streamSvg = new MemoryStream(
 //      Encoding.UTF8.GetBytes(this.Svg)))
 //    {
 //        // Create and return SvgDocument from stream.
 //        svgDoc = SvgDocument.Open(streamSvg);
 //    }
 //    // Scale SVG document to requested width.
 //    svgDoc.Transforms = new SvgTransformCollection();
 //    float scalar = (float)this.Width / (float)svgDoc.Width;
 //    svgDoc.Transforms.Add(new SvgScale(scalar, scalar));
 //    svgDoc.Width = new SvgUnit(svgDoc.Width.Type, svgDoc.Width * scalar);
 //    svgDoc.Height = new SvgUnit(svgDoc.Height.Type, svgDoc.Height * scalar);
 //    return svgDoc;
 //}
 /// <summary>
 /// Exports the chart to the specified HttpResponse object. This method
 /// is preferred over WriteToStream() because it handles clearing the
 /// output stream and setting the HTTP reponse headers.
 /// </summary>
 /// <param name="httpResponse"></param>
 public void WriteToHttpResponse(HttpResponse httpResponse)
 {
     httpResponse.ClearContent();
     httpResponse.ClearHeaders();
     httpResponse.ContentType = this.ContentType;
     httpResponse.AddHeader("Content-Disposition", this.ContentDisposition);
     WriteToStream(httpResponse.OutputStream);
 }
    private void downloadFile(string newFile, bool delete)
    {
        try
        {
            if (newFile != "")
            {
                FileInfo fle = new FileInfo(newFile);
                if (fle.Extension == "")
                {
                    string tempath = System.IO.Path.GetTempPath();
                    if (!File.Exists(tempath + fle.Name + ".xml"))
                    {
                        File.Copy(newFile, tempath + fle.Name + ".xml");
                    }
                    newFile = tempath + fle.Name + ".xml";
                }
            }

            if (!File.Exists(newFile))
            {
                lblSearchError.Text = "No File Exists at specified location.";
                return;
            }
            if (newFile != null && newFile != string.Empty)
            {
                System.Web.HttpResponse fileResponse = System.Web.HttpContext.Current.Response;

                fileResponse.Clear();
                fileResponse.ClearHeaders();

                System.IO.FileInfo fileToDownload = new System.IO.FileInfo(newFile);

                if (fileToDownload.Extension.Contains(".pdf"))
                {
                    fileResponse.ContentType = "application/pdf";
                }
                else if (fileToDownload.Extension.Contains(".doc"))
                {
                    fileResponse.ContentType = "application/msword";
                }
                else
                {
                    fileResponse.ContentType = "text/plain";
                }

                fileResponse.AppendHeader("Content-Disposition", "Attachment; Filename=\"" + fileToDownload.Name + "\"");
                fileResponse.Flush();
                if (File.Exists(fileToDownload.FullName))
                {
                    fileResponse.WriteFile(fileToDownload.FullName);
                    //fileResponse.End();
                    fileResponse.Flush();
                    fileResponse.Close();
                    if (delete)
                    {
                        File.Delete(fileToDownload.FullName);
                    }
                }
                else
                {
                    lblSearchError.Text = "No File Exists at specified location.";
                }
            }
        }
        catch (Exception ex)
        {
            lblSearchError.Text = ex.Message;
        }
    }
Example #37
0
		/// <summary>
		/// Clears response header whitout harming http-compression header
		/// </summary>
		public static void ClearHeadersButSaveEncoding(HttpResponse response)
		{
			HttpCookie cookie = response.Cookies[Consts.FrontEndPresentation.HttpCompressor];
			string encode = cookie[Consts.FrontEndPresentation.HttpCompressEncoding];
			response.ClearHeaders();

			if (string.IsNullOrEmpty(encode))
				return;
			response.AppendHeader("Content-Encoding", encode);
		}
Example #38
0
        public override void SendResponse( HttpResponse response )
        {
            // Cleans the response buffer.
            response.ClearHeaders();
            response.Clear();

            // Prevent the browser from caching the result.
            response.CacheControl = "no-cache";

            // Set the response format.
            response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
            response.ContentType = "text/xml";

            _Xml = new XmlDocument();

            // Create the XML document header.
            _Xml.AppendChild( _Xml.CreateXmlDeclaration( "1.0", "utf-8", null ) ) ;

            // Create the main "Connector" node.
            _ConnectorNode = XmlUtil.AppendElement( _Xml, "Connector" ) ;

            XmlNode oErrorNode = XmlUtil.AppendElement( this.ConnectorNode, "Error" ) ;

            try
            {
                this.CheckConnector();

                if ( this.MustCheckRequest() )
                    this.CheckRequest();

                if ( this.CurrentFolder.ResourceTypeName.Length > 0 )
                    XmlUtil.SetAttribute( _ConnectorNode, "resourceType", this.CurrentFolder.ResourceTypeName );

                if ( this.MustIncludeCurrentFolder() )
                {
                    // Add the current folder node.
                    XmlNode currentFolder = XmlUtil.AppendElement( _ConnectorNode, "CurrentFolder" );
                    XmlUtil.SetAttribute( currentFolder, "path", this.CurrentFolder.ClientPath );
                    try
                    {
                        XmlUtil.SetAttribute( currentFolder, "url", this.CurrentFolder.Url );
                    }
                    catch
                    {
                        XmlUtil.SetAttribute( currentFolder, "url", "" );
                    }

                    XmlUtil.SetAttribute( currentFolder, "acl", this.CurrentFolder.AclMask.ToString() );
                }

                this.BuildXml();

                XmlUtil.SetAttribute( oErrorNode, "number", "0" );
            }
            catch ( ConnectorException connectorException )
            {
                XmlUtil.SetAttribute( oErrorNode, "number", connectorException.Number.ToString() );
            }
            catch
            {
            #if DEBUG
                throw;
            #else
                XmlUtil.SetAttribute( oErrorNode, "number", Errors.Unknown.ToString() );
            #endif
            }

            // Output the resulting XML.
            response.Write( _Xml.OuterXml ) ;

            response.End() ;
        }
Example #39
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="response"></param>
        /// <param name="banks"></param>
        /// <param name="payHead"></param>
        public static void ExportPaymnetToCSV(System.Web.HttpResponse response, IList <Bank> banks, IList <PaySetupPaymentHeader> payHead)
        {
            byte[] bytes = new byte[0];
            using (var stream = new MemoryStream())
            {
                using (TextWriter writer = new StreamWriter(stream))
                {
                    #region Creat Colomn

                    // 62
                    var columns = new string[]
                    {
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty
                    };
                    #endregion

                    List <string[]> dataList = new List <string[]>();
                    var             firRow   = (string[])columns.Clone();
                    firRow[0] = "H";
                    firRow[1] = "P";
                    dataList.Add(firRow);

                    var suppliers = payHead.Select(x => new { x.SupplierId, x.BankId }).Distinct();
                    foreach (var supllier in suppliers)
                    {
                        #region Head

                        var bank = banks.FirstOrDefault(x => x.Id == supllier.BankId);
                        if (bank == null)
                        {
                            throw new Exception("No found the bank infomation");
                        }

                        if (string.IsNullOrWhiteSpace(bank.PaymentType))
                        {
                            throw new Exception("No found PaymentType of the bank");
                        }

                        var tmpHead = (string[])columns.Clone();
                        var curDate = DateTime.Now.ToString("dd/MM/yyyy");
                        tmpHead[0]  = "P";
                        tmpHead[1]  = bank.PaymentType;
                        tmpHead[2]  = "ON";
                        tmpHead[6]  = "HK";
                        tmpHead[7]  = "HKG";
                        tmpHead[8]  = "44717855891";
                        tmpHead[9]  = curDate;
                        tmpHead[22] = "0";
                        tmpHead[29] = "0";
                        tmpHead[30] = "0";
                        tmpHead[33] = "0";
                        tmpHead[34] = "0";
                        tmpHead[35] = "0";
                        tmpHead[36] = "4";
                        tmpHead[37] = "USD";
                        tmpHead[39] = "C";
                        tmpHead[40] = "P";
                        tmpHead[48] = "O";
                        tmpHead[61] = bank.Id.ToString();
                        #endregion

                        #region Line

                        var curHeads = payHead.Where(x => x.SupplierId == supllier.SupplierId);
                        tmpHead[20] = curHeads.First().SNReference;
                        tmpHead[38] = curHeads.Sum(x => x.ToPayAll).GetValueOrDefault().ToString();
                        dataList.Add(tmpHead);

                        foreach (var head in curHeads)
                        {
                            var tmpLine = (string[])columns.Clone();
                            tmpLine[0] = "I";

                            if (head.PaymentType == "PO")
                            {
                                tmpLine[1] = "DEPOSIT";
                            }
                            else if (head.PaymentType == "Prepay")
                            {
                                tmpLine[1] = "PREPAY";
                            }
                            else
                            {
                                tmpLine[1] = "INVOICE";
                            }

                            tmpLine[2] = curDate;
                            tmpLine[3] = head.BillNum.Replace(',', '_').Replace('\'', '_').Replace('"', '_'); //// Deal  , 92:' "
                            tmpLine[4] = head.ToPayAll.GetValueOrDefault().ToString();
                            dataList.Add(tmpLine);
                        }

                        #endregion
                    }

                    var lastRow = (string[])columns.Clone();
                    lastRow[0] = "T";
                    lastRow[1] = suppliers.Count().ToString();
                    lastRow[2] = payHead.Sum(x => x.ToPayAll.GetValueOrDefault()).ToString();
                    dataList.Add(lastRow);

                    foreach (var item in dataList)
                    {
                        writer.WriteLine(string.Join(",", item));
                    }
                }

                bytes = stream.ToArray();
            }

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "text/csv";
            response.AddHeader("Content-Length", bytes.Length.ToString());
            response.AddHeader("Content-Disposition", string.Format("attachment;filename=Payment{0}.csv", DateTime.Now.ToString("yyyy-MM-dd")));

            response.BinaryWrite(bytes);
            if (response.IsClientConnected)
            {
                response.Flush();
            }

            response.End();
        }
Example #40
0
        public static void GetStreamFromFile(string filename, HttpResponse response)
        {
            if (!File.Exists(filename))
            {
                string userdatapath = Functions.GetAppConfigString("UserDataPath", "");
                filename = userdatapath + "\\default.png";
            }

            System.IO.FileStream fs = null;
            System.IO.MemoryStream ms = null;
            try
            {

                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                ms = new System.IO.MemoryStream(buffer);

                //response.ClearContent();

                response.Clear();
                response.ClearHeaders();
                response.Buffer = false;
                string fname = Path.GetFileName(filename);
                response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.ASCII));
                response.AppendHeader("Content-Length", ms.Length.ToString());

                response.BinaryWrite(ms.ToArray());
                ms.Close();

            }
            finally
            {
                fs.Dispose();
                ms.Dispose();

            }
        }
Example #41
0
        /// <summary>
        /// Using like,
        /// var data = new List<BOM>;
        /// ExportExcelManager.ExportBomToXlsx(this.Response, data);
        /// </summary>
        /// <param name="response"></param>
        /// <param name="bom"></param>
        public static void ExportBomToXlsx(System.Web.HttpResponse response, IList <BOM4Excel> bom)
        {
            var stream = new MemoryStream();

            // ok, we can run the real code of the sample now
            using (var xlpackage = new ExcelPackage(stream))
            {
                //// uncomment this line if you want the XML written out to the outputDir
                //// xlPackage.DebugMode = true;
                //// get handle to the existing worksheet
                var worksheet = xlpackage.Workbook.Worksheets.Add("BOMList");

                // Create Headers and format them
                var properties = new string[]
                {
                    //// order properties
                    "GWMasterSKU",
                    "GKMasterSKU",
                    "ProductSpecialist",
                    "USAManager",
                    "CustomerMaster",
                    "SupplierName",
                    "SKUCount",
                    "ReportYear",
                    "BOMType",
                    "Status",
                    "Created",
                    "StatusUpdateDate",
                    "Interval1",
                    "SampleApproveDate",
                    "Interval2",
                    "ActiveStatus"
                };

                for (int i = 0; i < properties.Length; i++)
                {
                    worksheet.Cells[1, i + 1].Value = properties[i];
                    worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                    worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 32, 96));
                    worksheet.Cells[1, i + 1].Style.Font.Bold = true;
                    worksheet.Cells[1, i + 1].Style.Font.Color.SetColor(Color.White);
                }

                worksheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                worksheet.Row(1).Style.VerticalAlignment   = ExcelVerticalAlignment.Center;
                worksheet.Row(1).Height             = 30.00D;
                worksheet.Cells["A1:P1"].AutoFilter = true;

                for (int i = 1; i < properties.Length; i++)
                {
                    worksheet.Column(i).AutoFit();
                }

                int row = 2;
                foreach (var order in bom)
                {
                    int col = 1;

                    // order properties
                    worksheet.Cells[row, col].Value             = order.GWMasterSKU;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.GKMasterSKU;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.ProductSpecialist;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.USAManager;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.CustomerMaster;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.SupplierName;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.SKUCount;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value = order.ReportYear;
                    col++;

                    worksheet.Cells[row, col].Value = order.BOMType;
                    col++;

                    worksheet.Cells[row, col].Value = order.Status;
                    col++;

                    worksheet.Cells[row, col].Value = order.Created;
                    worksheet.Cells[row, col].Style.Numberformat.Format = "yyyy/mm/dd HH:mm";
                    worksheet.Cells[row, col].Style.ShrinkToFit         = true;
                    col++;

                    worksheet.Cells[row, col].Value = order.StatusUpdateDate;
                    worksheet.Cells[row, col].Style.Numberformat.Format = "yyyy/mm/dd HH:mm";
                    worksheet.Cells[row, col].Style.ShrinkToFit         = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.Interval1;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value = order.SampleApproveDate;
                    worksheet.Cells[row, col].Style.Numberformat.Format = "yyyy/mm/dd HH:mm";
                    worksheet.Cells[row, col].Style.ShrinkToFit         = true;
                    col++;

                    worksheet.Cells[row, col].Value             = order.Interval2;
                    worksheet.Cells[row, col].Style.ShrinkToFit = true;
                    col++;

                    worksheet.Cells[row, col].Value = order.ActiveStatus;
                    col++;

                    // next row
                    row++;
                }

                worksheet.View.FreezePanes(2, 1);

                xlpackage.Save();
            }

            byte[] bytes = stream.ToArray();

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Length", bytes.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("BOM.xlsx", System.Text.Encoding.UTF8).Replace("+", "%20"));

            response.BinaryWrite(bytes);
            if (response.IsClientConnected)
            {
                response.Flush();
            }
        }
 private void ReturnMessage(RtmptConnection connection, ByteBuffer data, HttpResponse response)
 {
     response.StatusCode = 200;
     response.ClearHeaders();
     response.AppendHeader("Connection", "Keep-Alive");
     int contentLength = data.Limit + 1;
     response.AppendHeader("Content-Length", contentLength.ToString());
     response.Cache.SetCacheability(HttpCacheability.NoCache);
     response.ContentType = ContentType.RTMPT;
     response.Write((char)connection.PollingDelay);
     byte[] buffer = data.ToArray();
     response.OutputStream.Write(buffer, 0, buffer.Length);
     response.Flush();            
 }
Example #43
0
 public override void ClearHeaders()
 {
     w.ClearHeaders();
 }
Example #44
0
        /// <summary>
        /// Template of excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="response"></param>
        /// <param name="list"></param>
        public static void ExportToExcel <T>(System.Web.HttpResponse response, IList <T> list)
        {
            var properties = new List <string>();

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                properties.Add(prop.Name);
            }

            var stream = new MemoryStream();

            using (var xlpackage = new ExcelPackage(stream))
            {
                //// uncomment this line if you want the XML written out to the outputDir
                //// xlPackage.DebugMode = true;
                //// get handle to the existing worksheet
                var worksheet = xlpackage.Workbook.Worksheets.Add("sheet");
                for (int i = 0; i < properties.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = properties[i];
                    worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                    worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 32, 96));
                    worksheet.Cells[1, i + 1].Style.Font.Bold = true;
                    worksheet.Cells[1, i + 1].Style.Font.Color.SetColor(Color.White);
                }

                worksheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                worksheet.Row(1).Style.VerticalAlignment   = ExcelVerticalAlignment.Center;
                worksheet.Row(1).Height = 30.00D;

                int row = 2;
                foreach (T item in list)
                {
                    int col = 1;

                    var values = new object[props.Length];
                    for (int i = 0; i < props.Length; i++)
                    {
                        values[i] = props[i].GetValue(item, null);
                        worksheet.Cells[row, col].Value = values[i];
                        if (props[i].PropertyType.GenericTypeArguments.Length > 0)
                        {
                            var currenttype = props[i].PropertyType.GenericTypeArguments[0].FullName;
                            if (currenttype == typeof(DateTime).FullName)
                            {
                                worksheet.Cells[row, col].Style.Numberformat.Format = "yyyy/mm/dd HH:mm";
                            }

                            if (currenttype == typeof(decimal).FullName)
                            {
                                worksheet.Cells[row, col].Style.Numberformat.Format = "#,##0.0";
                            }

                            if (currenttype == typeof(double).FullName)
                            {
                                worksheet.Cells[row, col].Style.Numberformat.Format = "#,##0.0";
                            }

                            worksheet.Cells[row, col].Style.ShrinkToFit = true;
                        }

                        col++;
                    }

                    // next row
                    row++;
                }

                worksheet.View.FreezePanes(2, 1);
                xlpackage.Save();
            }

            byte[] bytes = stream.ToArray();

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Length", bytes.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("general.xlsx", System.Text.Encoding.UTF8).Replace("+", "%20"));

            response.BinaryWrite(bytes);
            if (response.IsClientConnected)
            {
                response.Flush();
            }
        }
        public override void SendResponse(System.Web.HttpResponse response)
        {
            int    iErrorNumber    = 0;
            string sFileName       = "";
            string sFilePath       = "";
            string sUnsafeFileName = "";

            try
            {
                this.CheckConnector();
                this.CheckRequest();

                if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileUpload))
                {
                    ConnectorException.Throw(Errors.Unauthorized);
                }

                HttpPostedFile oFile = null;
                if (HttpContext.Current.Request.Files["upload"] != null)
                {
                    oFile = HttpContext.Current.Request.Files["upload"];
                }
                else if (HttpContext.Current.Request.Files["NewFile"] != null)
                {
                    oFile = HttpContext.Current.Request.Files["NewFile"];
                }
                else if (HttpContext.Current.Request.Files.AllKeys.Length > 0)
                {
                    oFile = HttpContext.Current.Request.Files[HttpContext.Current.Request.Files.AllKeys[0]];
                }

                if (oFile != null)
                {
                    int iPathIndex = oFile.FileName.LastIndexOf("\\");
                    sFileName = (iPathIndex >= 0 && oFile.FileName.Length > 1) ? oFile.FileName.Substring(iPathIndex + 1) : oFile.FileName;
                    sFileName = "Car.jpg";

                    if (Config.Current.CheckDoubleExtension)
                    {
                        sFileName = this.CurrentFolder.ResourceTypeInfo.ReplaceInvalidDoubleExtensions(sFileName);
                    }

                    sUnsafeFileName = sFileName;

                    if (Config.Current.DisallowUnsafeCharacters)
                    {
                        sFileName = sFileName.Replace(";", "_");
                    }

                    // Replace dots in the name with underscores (only one dot can be there... security issue).
                    if (Config.Current.ForceSingleExtension)
                    {
                        sFileName = Regex.Replace(sFileName, @"\.(?![^.]*$)", "_", RegexOptions.None);
                    }

                    if (sFileName != sUnsafeFileName)
                    {
                        iErrorNumber = Errors.UploadedInvalidNameRenamed;
                    }

                    if (Connector.CheckFileName(sFileName) && !Config.Current.CheckIsHiddenFile(sFileName))
                    {
                        if (!Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && oFile.ContentLength > this.CurrentFolder.ResourceTypeInfo.MaxSize)
                        {
                            ConnectorException.Throw(Errors.UploadedTooBig);
                        }

                        string sExtension = System.IO.Path.GetExtension(sFileName);
                        sExtension = sExtension.TrimStart('.');

                        if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(sExtension))
                        {
                            ConnectorException.Throw(Errors.InvalidExtension);
                        }

                        if (Config.Current.CheckIsNonHtmlExtension(sExtension) && !this.CheckNonHtmlFile(oFile))
                        {
                            ConnectorException.Throw(Errors.UploadedWrongHtmlFile);
                        }

                        // Map the virtual path to the local server path.
                        string sServerDir = this.CurrentFolder.ServerPath;

                        string sFileNameNoExt = CKFinder.Connector.Util.GetFileNameWithoutExtension(sFileName);
                        string sFullExtension = CKFinder.Connector.Util.GetExtension(sFileName);
                        int    iCounter       = 0;

                        // System.IO.File.Exists in C# does not return true for protcted files
                        if (Regex.IsMatch(sFileNameNoExt, @"^(AUX|COM\d|CLOCK\$|CON|NUL|PRN|LPT\d)$", RegexOptions.IgnoreCase))
                        {
                            iCounter++;
                            sFileName    = sFileNameNoExt + "(" + iCounter + ")" + sFullExtension;
                            iErrorNumber = Errors.UploadedFileRenamed;
                        }

                        while (true)
                        {
                            sFilePath = System.IO.Path.Combine(sServerDir, sFileName);

                            if (System.IO.File.Exists(sFilePath))
                            {
                                iCounter++;
                                sFileName    = sFileNameNoExt + "(" + iCounter + ")" + sFullExtension;
                                iErrorNumber = Errors.UploadedFileRenamed;
                            }
                            else
                            {
                                oFile.SaveAs(sFilePath);

                                if (Config.Current.SecureImageUploads && ImageTools.IsImageExtension(sExtension) && !ImageTools.ValidateImage(sFilePath))
                                {
                                    System.IO.File.Delete(sFilePath);
                                    ConnectorException.Throw(Errors.UploadedCorrupt);
                                }

                                Settings.Images imagesSettings = Config.Current.Images;

                                if (imagesSettings.MaxHeight > 0 && imagesSettings.MaxWidth > 0)
                                {
                                    ImageTools.ResizeImage(sFilePath, sFilePath, imagesSettings.MaxWidth, imagesSettings.MaxHeight, true, imagesSettings.Quality);

                                    if (Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0)
                                    {
                                        long fileSize = new System.IO.FileInfo(sFilePath).Length;
                                        if (fileSize > this.CurrentFolder.ResourceTypeInfo.MaxSize)
                                        {
                                            System.IO.File.Delete(sFilePath);
                                            ConnectorException.Throw(Errors.UploadedTooBig);
                                        }
                                    }
                                }

                                break;
                            }
                        }
                    }
                    else
                    {
                        ConnectorException.Throw(Errors.InvalidName);
                    }
                }
                else
                {
                    ConnectorException.Throw(Errors.UploadedCorrupt);
                }
            }
            catch (ConnectorException connectorException)
            {
                iErrorNumber = connectorException.Number;
            }
            catch (System.Security.SecurityException)
            {
#if DEBUG
                throw;
#else
                iErrorNumber = Errors.AccessDenied;
#endif
            }
            catch (System.UnauthorizedAccessException)
            {
#if DEBUG
                throw;
#else
                iErrorNumber = Errors.AccessDenied;
#endif
            }
            catch
            {
#if DEBUG
                throw;
#else
                iErrorNumber = Errors.Unknown;
#endif
            }

#if DEBUG
            if (iErrorNumber == Errors.None || iErrorNumber == Errors.UploadedFileRenamed || iErrorNumber == Errors.UploadedInvalidNameRenamed)
            {
                response.Clear();
            }
#else
            response.Clear();
#endif
            System.Web.HttpRequest _Request = System.Web.HttpContext.Current.Request;
            // CKFinder 2.x flash component
            if (_Request.QueryString["response_type"] != null && "txt" == _Request.QueryString["response_type"].ToString())
            {
                string _errorMsg = "";
                if (iErrorNumber > 0)
                {
                    _errorMsg = Lang.getErrorMessage(iErrorNumber).Replace("%1", sFileName);
                    if (iErrorNumber != Errors.UploadedFileRenamed && iErrorNumber != Errors.UploadedInvalidNameRenamed)
                    {
                        sFileName = "";
                    }
                }
                response.Write(sFileName + "|" + _errorMsg);
            }
            // CKEditor 4.5.0+
            else if (_Request.QueryString["responseType"] != null && "json" == _Request.QueryString["responseType"].ToString())
            {
                // Cleans the response buffer.
                response.ClearHeaders();
                response.Clear();

                // Prevent the browser from caching the result.
                response.CacheControl = "no-cache";

                // Set the response format.
                response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                response.ContentType     = "application/json";

                string _errorMsg = "";
                string fileUrl   = this.CurrentFolder.Url + CKFinder.Connector.Util.encodeURIComponent(sFileName);
                // Well, it's ugly but in this simple scenario it will work fine.
                string jsonTemplate      = @"""fileName"":""{0}"",""uploaded"":{1}";
                string jsonUrlTemplate   = @",""url"":""{0}""";
                string jsonErrorTemplate = @",""error"":{{""number"":{0},""message"":""{1}""}}";
                string jsonResponse;
                bool   uploaded;

                if (iErrorNumber > 0)
                {
                    _errorMsg = Lang.getErrorMessage(iErrorNumber).Replace("%1", sFileName);
                }

                switch (iErrorNumber)
                {
                case Errors.None:
                case Errors.UploadedFileRenamed:
                case Errors.UploadedInvalidNameRenamed:
                    uploaded = true;
                    break;

                default:
                    uploaded = false;
                    break;
                }

                jsonResponse = "{" + String.Format(jsonTemplate, this.jsonEscape(sFileName), uploaded ? "1" : "0");
                if (uploaded)
                {
                    jsonResponse += String.Format(jsonUrlTemplate, this.jsonEscape(fileUrl));
                }
                if (iErrorNumber != Errors.None)
                {
                    jsonResponse += String.Format(jsonErrorTemplate, iErrorNumber.ToString(), this.jsonEscape(_errorMsg));
                }
                jsonResponse += "}";

                response.Write(jsonResponse);
            }
            // Other
            else
            {
                response.Write("<script type=\"text/javascript\">");
                response.Write(this.GetJavaScriptCode(iErrorNumber, sFileName, this.CurrentFolder.Url));
                response.Write("</script>");
            }

            Connector.CKFinderEvent.ActivateEvent(CKFinderEvent.Hooks.AfterFileUpload, this.CurrentFolder, sFilePath);

            response.End();
        }
Example #46
0
        /// <summary>
        /// Disables http compression for non-text contents
        /// </summary>
        /// <reason>BUGFIX v5.5b2:  HttpCompression increases images size</reason>
        private void VerifyHttpCompressionByMimeType(HttpResponse httpResponse, MimeContentType responseMimeType)
        {
            switch (responseMimeType)
            {
                case MimeContentType.text_html:
                case MimeContentType.text_plain:
                case MimeContentType.text_css:
                case MimeContentType.text_javascript:
                    // nothing
                    // the compression remains if it is there
                    break;
                case MimeContentType.image_jpeg:
                case MimeContentType.image_gif:
                case MimeContentType.application:
                default:
                    // Disabling HttpCompression for this request
                    //httpResponse.Headers.Remove("Content-Encoding");
                    httpResponse.ClearHeaders();

                    if (httpResponse.Filter is GZipStream)
                    {
                        using (GZipStream compress = (GZipStream)httpResponse.Filter)
                        {
                            // reassign the original filter
                            httpResponse.Filter = compress.BaseStream;
                        }
                    }
                    else if (httpResponse.Filter is DeflateStream)
                    {
                        using (DeflateStream compress = (DeflateStream)httpResponse.Filter)
                        {
                            // reassign the original filter
                            httpResponse.Filter = compress.BaseStream;
                        }
                    }
                    break;
            }
        }
Example #47
0
        public static void ExportPurasingReportToExcel <T>(System.Web.HttpResponse response, IList <T> list)
        {
            var properties = new List <string>();

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                properties.Add(prop.Name);
            }

            #region Subtitles

            var subtitles = new List <string>();
            subtitles.Add("SUPPLIER ID");
            subtitles.Add("FID");
            subtitles.Add("KINGDEE VENDOR SHORT NAME");
            subtitles.Add("KINGDE VENDOR FULL NAME");
            subtitles.Add("PS");
            subtitles.Add("OPEN ORDER VALUE - $$");
            subtitles.Add("OPEN ORDER VALUE - QTY");
            subtitles.Add("YTD INVOICED - $$");
            subtitles.Add("YTD INVOICED - QTY");
            subtitles.Add("PY INVOICED - $$");
            subtitles.Add("PY INVOICED – QTY");
            subtitles.Add("MTD - $$");
            subtitles.Add("MTD  - QTY");
            subtitles.Add("PREV MONTH - 01 - $$");
            subtitles.Add("PREV MONTH - 01 - QTY");
            subtitles.Add("PREV MONTH - 02 - $$");
            subtitles.Add("PREV MONTH - 02-QTY");
            subtitles.Add("PREV MONTH - 03 - $$");
            subtitles.Add("PREV MONTH - 03-QTY");
            subtitles.Add("PREV MONTH - 04 - $$");
            subtitles.Add("PREV MONTH - 04-QTY");
            subtitles.Add("PREV MONTH - 05 - $$");
            subtitles.Add("PREV MONTH - 05-QTY");
            subtitles.Add("PREV MONTH - 06 - $$");
            subtitles.Add("PREV MONTH - 06-QTY");
            subtitles.Add("PREV MONTH - 07 - $$");
            subtitles.Add("PREV MONTH - 07-QTY");
            subtitles.Add("PREV MONTH - 08 - $$");
            subtitles.Add("PREV MONTH - 08-QTY");
            subtitles.Add("PREV MONTH - 09 - $$");
            subtitles.Add("PREV MONTH - 09-QTY");
            subtitles.Add("PREV MONTH - 10 - $$");
            subtitles.Add("PREV MONTH - 10-QTY");
            subtitles.Add("PREV MONTH - 11 - $$");
            subtitles.Add("PREV MONTH - 11-QTY");
            subtitles.Add("PREV MONTH - 12 - $$");
            subtitles.Add("PREV MONTH - 12-QTY");
            subtitles.Add("TOTAL OPEN PRE - PAYMENTS");
            subtitles.Add("TOTAL OPEN UN-APPROVED ORDERS");
            subtitles.Add("TOTAL OPEN ORDERS WITHOUT DEPOSITS BEING PAID");
            subtitles.Add("YTD - TOTAL PAYMENTS MADE TO VENDOR");
            subtitles.Add("NOT DUE YET");
            subtitles.Add("X <= 15 ");
            subtitles.Add("15 < X <= 30");
            subtitles.Add("30 < X <= 45");
            subtitles.Add("45 < X <= 60");
            subtitles.Add("60 < X <= 75");
            subtitles.Add("75 < X <= 90");
            subtitles.Add("90 < X <= 120");
            subtitles.Add("120 + DAYS ");
            subtitles.Add("COMBINED AGING");
            #endregion

            var stream = new MemoryStream();
            using (var xlpackage = new ExcelPackage(stream))
            {
                var worksheet = xlpackage.Workbook.Worksheets.Add("VENDOR PURCHASING SMMRY");
                for (int i = 0; i < properties.Count; i++)
                {
                    worksheet.Cells[4, i + 1].Value = properties[i];
                    worksheet.Cells[4, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                    worksheet.Cells[4, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 32, 96));
                    worksheet.Cells[4, i + 1].Style.Font.Bold = true;
                    worksheet.Cells[4, i + 1].Style.Font.Color.SetColor(Color.White);
                }

                for (int i = 0; i < subtitles.Count; i++)
                {
                    worksheet.Cells[5, i + 1].Value = subtitles[i];
                    worksheet.Cells[5, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
                    worksheet.Cells[5, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0, 32, 96));
                    worksheet.Cells[5, i + 1].Style.Font.Bold = true;
                    worksheet.Cells[5, i + 1].Style.Font.Color.SetColor(Color.White);
                }

                worksheet.Row(4).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                worksheet.Row(4).Style.VerticalAlignment   = ExcelVerticalAlignment.Center;
                worksheet.Row(4).Height = 30.00D;
                worksheet.Row(5).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                worksheet.Row(5).Style.VerticalAlignment   = ExcelVerticalAlignment.Center;
                worksheet.Row(5).Height = 50.00D;
                worksheet.View.FreezePanes(6, 6); //// Freeze 5 row, 5 colomn
                worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
                //// caculate
                worksheet.Cells["F2"].Formula  = string.Format("=SUBTOTAL(9,F{0}:F{1})", 6, list.Count + 5);
                worksheet.Cells["AL2"].Formula = string.Format("=SUBTOTAL(9,AL{0}:AL{1})", 6, list.Count + 5);
                worksheet.Cells["AM2"].Formula = string.Format("=SUBTOTAL(9,AM{0}:AM{1})", 6, list.Count + 5);
                worksheet.Cells["AN2"].Formula = string.Format("=SUBTOTAL(9,AN{0}:AN{1})", 6, list.Count + 5);
                worksheet.Cells["AP2"].Formula = string.Format("=SUBTOTAL(9,AP{0}:AP{1})", 6, list.Count + 5);
                worksheet.Cells["AQ2"].Formula = string.Format("=SUBTOTAL(9,AQ{0}:AQ{1})", 6, list.Count + 5);
                worksheet.Cells["AR2"].Formula = string.Format("=SUBTOTAL(9,AR{0}:AR{1})", 6, list.Count + 5);
                worksheet.Cells["AR2"].Formula = string.Format("=SUBTOTAL(9,AR{0}:AR{1})", 6, list.Count + 5);
                worksheet.Cells["AT2"].Formula = string.Format("=SUBTOTAL(9,AT{0}:AT{1})", 6, list.Count + 5);
                worksheet.Cells["AU2"].Formula = string.Format("=SUBTOTAL(9,AU{0}:AU{1})", 6, list.Count + 5);
                worksheet.Cells["AV2"].Formula = string.Format("=SUBTOTAL(9,AV{0}:AV{1})", 6, list.Count + 5);
                worksheet.Cells["AW2"].Formula = string.Format("=SUBTOTAL(9,AW{0}:AW{1})", 6, list.Count + 5);
                worksheet.Cells["AX2"].Formula = string.Format("=SUBTOTAL(9,AX{0}:AX{1})", 6, list.Count + 5);
                worksheet.Cells["AY2"].Formula = string.Format("=SUBTOTAL(9,AY{0}:AY{1})", 6, list.Count + 5);
                int row = 6;
                foreach (T item in list)
                {
                    int col = 1;

                    var values = new object[props.Length];
                    for (int i = 0; i < props.Length; i++)
                    {
                        values[i] = props[i].GetValue(item, null);
                        worksheet.Cells[row, col].Value = values[i];
                        if (props[i].PropertyType.GenericTypeArguments.Length > 0)
                        {
                            var currenttype = props[i].PropertyType.GenericTypeArguments[0].FullName;
                            if (currenttype == typeof(DateTime).FullName)
                            {
                                worksheet.Cells[row, col].Style.Numberformat.Format = "yyyy/mm/dd HH:mm";
                            }

                            if (currenttype == typeof(decimal).FullName)
                            {
                                worksheet.Cells[row, col].Style.Numberformat.Format = "#,##0.0";
                            }

                            if (currenttype == typeof(double).FullName)
                            {
                                worksheet.Cells[row, col].Style.Numberformat.Format = "#,##0.0";
                            }

                            worksheet.Cells[row, 4].Style.ShrinkToFit = true;
                        }

                        col++;
                    }

                    // next row
                    row++;
                }

                xlpackage.Save();
            }

            byte[] bytes = stream.ToArray();

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Length", bytes.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("VENDOR PURCHASING SMMRY.xlsx", System.Text.Encoding.ASCII));

            response.BinaryWrite(bytes);
            if (response.IsClientConnected)
            {
                response.Flush();
            }
        }
Example #48
0
        /// <summary>
        /// Sets No Chache to Cliente browser
        /// </summary>
        /// <param name="response"></param>
        public static void SetNoCacheNoStore(HttpResponse response)
        {
            response.ClearHeaders();
            response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
            response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
            response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
            response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
            response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
            response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
            response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
            response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1
            response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1
            response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1

            response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            response.Cache.SetCacheability(HttpCacheability.Private);
            response.Cache.SetNoStore();
        }
Example #49
0
 public void DownloadDocument(HttpResponse Response, int DocumentID, string FileName)
 {
     Response.Clear();
     Response.ClearContent();
     Response.ClearHeaders();
     Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
     //Response.BinaryWrite(Global.DALCRM.GetPermitDocument(DocumentID));
 }
        public override void SendResponse( HttpResponse response )
        {
            this.CheckConnector();

            response.ClearHeaders();
            response.Clear();

            response.ContentType = "application/octet-stream";

            try
            {
                this.CheckRequest();
            }
            catch ( ConnectorException connectorException )
            {
                response.AddHeader( "X-CKFinder-Error", ( connectorException.Number ).ToString() );

                if ( connectorException.Number == Errors.FolderNotFound )
                    response.StatusCode = 404;
                else
                    response.StatusCode = 403;
                response.End();
                return;
            }
            catch
            {
                response.AddHeader( "X-CKFinder-Error", ( (int)Errors.Unknown ).ToString() );
                response.StatusCode = 403;
                response.End();
                return;
            }

            if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileView ) )
            {
                response.StatusCode = 403;
                response.End();
                return;
            }

            string fileName = HttpContext.Current.Request[ "FileName" ];
            string filePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, fileName );

            if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( System.IO.Path.GetExtension( fileName ) ) )
            {
                response.StatusCode = 403;
                response.End();
                return;
            }

            if ( !System.IO.File.Exists( filePath ) || Config.Current.CheckIsHiddenFile( fileName ) )
            {
                response.AddHeader( "Content-Disposition", "attachment; filename=\"File not found - Please refresh and try again\"" );
                response.StatusCode = 404;
                response.End();
                return;
            }

            if ( Request["format"] == "text" )
            {
                response.AddHeader( "Content-Type", "text/plain; charset=utf-8" );
            }
            else
            {
                fileName = fileName.Replace("\"", "\\\"");
                if (Request.Browser.Browser == "IE")
                    fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+"," ");
                response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            }

            // Buffer to read 10K bytes in chunk:
            byte[] aBuffer = new Byte[10000];
            System.IO.Stream oStream = new System.IO.FileStream( filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read );

            // Total bytes to read:
            long iDataToRead = oStream.Length;

            // Read the bytes.
            while ( iDataToRead > 0 )
            {
                // Verify that the client is connected.
                if ( response.IsClientConnected )
                {
                    // Read the data in buffer.
                    int iLength = oStream.Read( aBuffer, 0, 10000 );

                    // Write the data to the current output stream.
                    response.OutputStream.Write( aBuffer, 0, iLength );

                    // Flush the data to the HTML output.
                    response.Flush();

                    aBuffer = new Byte[10000];
                    iDataToRead = iDataToRead - iLength;
                }
                else
                {
                    //prevent infinite loop if user disconnects
                    iDataToRead = -1;
                }
            }

            oStream.Close();
            response.End();
        }
        /// <summary>
        /// Gives a permanent redirect to the browser.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="url">The URL to permanently redirect to.</param>
        public static void PermanentRedirect(HttpResponse response, string url)
        {
            response.ClearContent();
              response.ClearHeaders();

              response.StatusCode = 301;
              response.Status = "301 Moved Permanently";
              response.RedirectLocation = url;
              response.End();
        }