AddHeader() public method

public AddHeader ( string name, string value ) : void
name string
value string
return void
Beispiel #1
0
 public static bool DownFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
 {
     try
     {
         FileStream input = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         BinaryReader reader = new BinaryReader(input);
         try
         {
             _Response.AddHeader("Accept-Ranges", "bytes");
             _Response.Buffer = false;
             long length = input.Length;
             long num2 = 0L;
             int count = 0x2800;
             double d = ((long) (0x3e8 * count)) / _speed;
             int millisecondsTimeout = ((int) Math.Floor(d)) + 1;
             if (_Request.Headers["Range"] != null)
             {
                 _Response.StatusCode = 0xce;
                 num2 = Convert.ToInt64(_Request.Headers["Range"].Split(new char[] { '=', '-' })[1]);
             }
             _Response.AddHeader("Content-Length", (length - num2).ToString());
             if (num2 != 0L)
             {
                 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", num2, length - 1L, length));
             }
             _Response.AddHeader("Connection", "Keep-Alive");
             _Response.ContentType = "application/octet-stream";
             _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, Encoding.UTF8));
             reader.BaseStream.Seek(num2, SeekOrigin.Begin);
             double num6 = (length - num2) / ((long) count);
             int num7 = ((int) Math.Floor(num6)) + 1;
             for (int i = 0; i < num7; i++)
             {
                 if (_Response.IsClientConnected)
                 {
                     _Response.BinaryWrite(reader.ReadBytes(count));
                     Thread.Sleep(millisecondsTimeout);
                 }
                 else
                 {
                     i = num7;
                 }
             }
         }
         catch
         {
             return false;
         }
         finally
         {
             reader.Close();
             input.Close();
         }
     }
     catch
     {
         return false;
     }
     return true;
 }
Beispiel #2
0
        public void DownLoadFlash(FlashInfo flashInfo, System.Web.HttpResponse Response)
        {
            var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);

            string fileURL = "";

            if (flashInfo.FlashVersion == "Chrome")
            {
                fileURL = HttpContext.Current.Server.MapPath((basePath + "Login/Temp/flashplayerPPAPI_25.0.0.127.exe"));//文件路径,可用相对路径
            }
            else
            {
                fileURL = HttpContext.Current.Server.MapPath((basePath + "Login/Temp/flashplayerNPAPI_26.0.0.131.exe"));//文件路径,可用相对路径
            }

            try
            {
                FileInfo fileInfo = new FileInfo(fileURL);
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileInfo.Name.ToString())); //文件名
                Response.AddHeader("content-length", fileInfo.Length.ToString());                                                                   //文件大小
                Response.ContentType     = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.Default;
                Response.WriteFile(fileURL);
            }
            catch (Exception ex)
            {
                flashInfo.result = "failed";
                flashInfo.msg    = "下载失败! \n" + ex.Message;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Create the confirmation received response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <param name="memberResult">The member result; true if success; else false.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="statusCode">The status code.</param>
        /// <param name="statusDescription">The status description.</param>
        /// <param name="contentLength">The content length.</param>
        private void CreateResponse(System.Web.HttpResponse response, bool memberResult, int errorCode,
                                    int statusCode = 200, string statusDescription = "OK", long contentLength = 0)
        {
            // Get the error code.
            switch (errorCode)
            {
            case 500:
                // Internal error.
                response.StatusCode        = 500;
                response.StatusDescription = statusDescription;
                response.AddHeader("MemberResult", false.ToString());
                break;

            case 400:
                // Bad request.
                response.StatusCode        = 400;
                response.StatusDescription = statusDescription;
                response.AddHeader("MemberResult", false.ToString());
                break;

            default:
                // Default response.
                response.StatusCode        = statusCode;
                response.StatusDescription = statusDescription;
                response.AddHeader("MemberResult", memberResult.ToString());
                break;
            }

            // Send the response.
            response.AddHeader("Content-Length", contentLength.ToString());
            response.Flush();
        }
        protected void btnPDF_Click222(object sender, EventArgs e)
        {
            string downloadName = "Report";

            byte[] downloadBytes = null;
            downloadName += ".pdf";
            PdfConverter pdfConverter = new PdfConverter();

            pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
            pdfConverter.PdfStandardSubset = PdfStandardSubset.Full;
            pdfConverter.PdfDocumentOptions.AutoSizePdfPage = true;
            pdfConverter.PdfDocumentOptions.EmbedFonts      = true;
            pdfConverter.PdfDocumentOptions.BottomMargin    = 80;
            pdfConverter.PdfDocumentOptions.TopMargin       = 50;

            string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid=39&isPdf=1", Request.Url.Host);

            downloadBytes = pdfConverter.GetPdfBytesFromUrl(url);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "binary/octet-stream");
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString());
            response.Flush();
            response.BinaryWrite(downloadBytes);
            response.Flush();
            response.End();
        }
Beispiel #5
0
 /// <summary>
 /// 发送PDF文件回浏览器端
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="ms"></param>
 /// <param name="encoding"></param>
 public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null)
 {
     fileName = (fileName + "").Replace(" ", "");
     encoding = encoding ?? Encoding.UTF8;
     if (ms != null && !string.IsNullOrEmpty(fileName))
     {
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.Clear();
         response.Charset = encoding.BodyName;// "utf-8";
         if (!HttpContext.Current.Request.UserAgent.Contains("Firefox") && !HttpContext.Current.Request.UserAgent.Contains("Chrome"))
         {
             fileName = HttpUtility.UrlEncode(fileName, encoding);
         }
         response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
         //为了解决打开,导出NPOI生成的xlsx文件时,提示发现不可读取内容。
         if (!(fileName + "").ToLower().EndsWith(".xlsx"))
         {
             response.AddHeader("Content-Type", "application/octet-stream");
             response.BinaryWrite(ms.GetBuffer());
         }
         else
         {
             response.BinaryWrite(ms.ToArray());
         }
         ms.Close();
         ms = null;
         response.Flush();
         response.End();
     }
 }
    /// <summary>
    /// Bietet die geforderte Datei zum Download an.
    /// </summary>
    /// <param name="file"></param>
    private void DownloadFile(HttpRequest request, HttpResponse response, ModuleConfig cfg, string file, bool asAttachment)
    {
      // Ermitteln des Filewappers der entsprechenden Datei.
      ConfigAgent cfgAgent = new ConfigAgent(cfg);
      FileWrapper dwnFile = cfgAgent.RootDirectory.GetFile(file);

      if (dwnFile != null)
      {
        response.CacheControl = "public";
        response.Cache.SetCacheability(HttpCacheability.Private);
        if (asAttachment)
          response.AddHeader("Content-Disposition", "attachment; filename=" + dwnFile.FileName);
        response.AddHeader("Content-Length", dwnFile.FileSize.ToString());
        String mimeType = dwnFile.MimeType;
        if (mimeType != null)
          response.ContentType = mimeType;
        response.TransmitFile(dwnFile.PhysicalPath);

        if(!Portal.API.Statistics.StatisticHelper.IsBot(request))
        {
          // In der Statistik zwischenspeichern.
          Statistic FbStatistic = new Statistic(cfgAgent.PhysicalRoot);
          FbStatistic.DownloadFile(file);
        }
      }
      else
        throw new FileNotFoundException();
    }
Beispiel #7
0
        private void Real(HttpResponse response, HttpRequest request)
        {
            if (File.Exists(request.PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
                response.Clear();
                response.AddHeader("Content-Disposition", "filename=" + file.Name);
                response.AddHeader("Content-Length", file.Length.ToString());
                string fileExtension = file.Extension.ToLower();
                switch (fileExtension)
                {
                   
                    case ".jpg":
                        response.ContentType = "image/jpeg";
                        break;
                    case ".gif":
                        response.ContentType = "image/gif";
                        break;
                    case ".png":
                        response.ContentType = "image/png";
                        break;
                    default:
                        response.ContentType = "application/octet-stream";
                        break;
                }

                response.WriteFile(file.FullName);
                response.End();
            }
            else
            {
                response.Write("File Not Exists");
            }
        }
Beispiel #8
0
        /// <summary>
        /// Pushes the attachment to web response.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="EMailMessageId">The E mail message id.</param>
        /// <param name="AttachementIndex">The attachement id.</param>
        public static void PushAttachmentToWebResponse(System.Web.HttpResponse response, int EMailMessageId, int AttachementIndex)
        {
            EMailMessageRow row = new EMailMessageRow(EMailMessageId);

            MemoryStream memStream = new MemoryStream(row.EmlMessage.Length);

            memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length);
            memStream.Position = 0;

            Pop3Message message = new Pop3Message(memStream);

            AttachmentData entry = GetAttachment(message.MimeEntries, ref AttachementIndex);

            response.ContentType = entry.ContentType;
            //response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", GetFileName(entry)));
            if (Common.OpenInNewWindow(entry.ContentType))
            {
                response.AddHeader("content-disposition", String.Format("inline; filename=\"{0}\"", entry.FileName));
            }
            else
            {
                response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", entry.FileName));
            }


            response.OutputStream.Write(entry.Data, 0, entry.Data.Length);
            response.OutputStream.Flush();

            response.End();
        }
Beispiel #9
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);
        }
Beispiel #10
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();
        }
Beispiel #11
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;
        }
Beispiel #12
0
        private void Real(HttpResponse response, HttpRequest request)
        {
            if (File.Exists(request.PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
                response.Clear();
                response.AddHeader("Content-Disposition", "filename=" + file.Name);
                response.AddHeader("Content-Length", file.Length.ToString());
                string fileExtension = file.Extension.ToLower();
                switch (fileExtension)
                {
                    case ".mp3":
                        response.ContentType = "audio/mpeg3";
                        break;
                    case ".mpeg":
                        response.ContentType = "video/mpeg";
                        break;
                    case ".jpg":
                        response.ContentType = "image/jpeg";
                        break;
                    case ".bmp":
                        response.ContentType = "image/bmp";
                        break;
                    case ".gif":
                        response.ContentType = "image/gif";
                        break;
                    case ".doc":
                        response.ContentType = "application/msword";
                        break;
                    case ".css":
                        response.ContentType = "text/css";
                        break;
                    case ".html":
                        response.ContentType = "text/html";
                        break;
                    case ".htm":
                        response.ContentType = "text/html";
                        break;
                    case ".swf":
                        response.ContentType = "application/x-shockwave-flash";
                        break;
                    case ".exe":
                        response.ContentType = "application/octet-stream";
                        break;
                    case ".inf":
                        response.ContentType = "application/x-texinfo";
                        break;
                    default:
                        response.ContentType = "application/octet-stream";
                        break;
                }

                response.WriteFile(file.FullName);
                response.End();
            }
            else
            {
                response.Write("File Not Exists");
            }
        }
        public void Genratepdf1(string str_Url, string filename)
        {
            try
            {
                string temp_path = "";

                PdfConverter pdfConverter_Transcrpit = new PdfConverter();
                string       temp1 = "";
                pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA=";

                PdfDocumentOptions docopt = new PdfDocumentOptions();
                pdfConverter_Transcrpit.PageWidth  = 1100;
                pdfConverter_Transcrpit.PageHeight = 500;
                byte[] downloadBytes = pdfConverter_Transcrpit.GetPdfFromUrlBytes(str_Url);
                pdfConverter_Transcrpit.SavePdfFromUrlToFile(str_Url, "D:\\LMS2.0Final\\LMS\\ABN\\pdfs\\test1.pdf");
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf" + "; size=" + downloadBytes.Length.ToString());
                response.Flush();
                response.BinaryWrite(downloadBytes);
                response.Flush();
                response.End();
            }
            catch (Exception EX)
            {
                //return "";
                throw EX;
            }
        }
Beispiel #14
0
        private void ExportDivContentToPDF()
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            try
            {
                // create an API client instance
                string          userName = ConfigurationManager.AppSettings["pdfcrowdUsername"].ToString();
                string          APIKey   = ConfigurationManager.AppSettings["pdfcrowdAPIKey"].ToString();
                pdfcrowd.Client client   = new pdfcrowd.Client(userName, APIKey);

                // convert a web page and write the generated PDF to a memory stream
                MemoryStream Stream = new MemoryStream();
                //client.convertURI("http://www.google.com", Stream);

                // set HTTP response headers
                Response.Clear();
                Response.AddHeader("Content-Type", "application/pdf");
                Response.AddHeader("Cache-Control", "max-age=0");
                Response.AddHeader("Accept-Ranges", "none");
                Response.AddHeader("Content-Disposition", "attachment; filename=TigerReservePdfExport.pdf");
                System.IO.StringWriter       stringWrite1 = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite1   = new HtmlTextWriter(stringWrite1);
                MainContent.RenderControl(htmlWrite1);
                client.convertHtml(stringWrite1.ToString(), Stream);
                // send the generated PDF
                Stream.WriteTo(Response.OutputStream);
                Stream.Close();
                Response.Flush();
                Response.End();
            }
            catch (pdfcrowd.Error why)
            {
                Response.Write(why.ToString());
            }
        }
        public void Genratepdftext(string text, string fname)
        {
            try
            {
                string temp_path = "";

                PdfConverter pdfConverter_Transcrpit = new PdfConverter();
                string       temp1 = "";
                pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA=";
                byte[] downloadBytes             = pdfConverter_Transcrpit.GetPdfBytesFromHtmlString(text);
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition", "attachment; filename=" + fname + ".pdf" + "; size=" + downloadBytes.Length.ToString());
                response.Flush();
                response.BinaryWrite(downloadBytes);
                response.Flush();
                response.End();
            }
            catch (Exception EX)
            {
                //return "";
                throw EX;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlToPdf.Options.PageSize   = PdfPageSizes.A4;// new SizeF(PdfPageSizes.A4.Height, PdfPageSizes.A4.Width);
            HtmlToPdf.Options.OutputArea = new RectangleF(0.05f, 0.07f, 8.17f, 12f);



            MemoryStream ms       = new MemoryStream();
            string       fileName = "ANGLO-EASTERN SHIP MANAGEMENT";
            var          watch    = System.Diagnostics.Stopwatch.StartNew();

            HtmlToPdf.ConvertUrl("D:\\" + fileName + ".html", ms);
            watch.Stop();
            //HtmlToPdf.ConvertUrl("D:\\HtmlContentForPdf.html", "D:\\result.pdf");
            byte[] bPDFBytes          = ms.ToArray();
            var    timeTakenToConvert = watch.ElapsedMilliseconds;

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "application/pdf");
            response.AddHeader("Content-Disposition", "attachment; filename=Eo_" + fileName + "_" + timeTakenToConvert + ".pdf; size=" + bPDFBytes.Length.ToString());
            response.Flush();
            response.BinaryWrite(bPDFBytes);
            response.Flush();
            response.End();
        }
Beispiel #17
0
 public void Process(System.Web.HttpResponse response)
 {
     response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(_filePath));
     response.AddHeader("Content-Transfer-Encoding", "binary");
     response.ContentType = "application/octet-stream";
     response.Cache.SetCacheability(HttpCacheability.NoCache);
     response.WriteFile(_filePath);
 }
Beispiel #18
0
        public void ProcessRequest(HttpContext context)
        {
            System.Web.HttpRequest       Request  = context.Request;
            System.Web.HttpServerUtility Server   = context.Server;
            System.Web.HttpResponse      Response = context.Response;

            _file = Request.QueryString["file"];

            try
            {
                Type = (DownloadType)Enum.Parse(typeof(DownloadType), Request.QueryString["Type"]);
            }
            catch (Exception Ex)
            {
                Response.Redirect("~/");
            }


            string path = "";

            switch (_Type)
            {
            case DownloadType.News:
                path  = Folders.NewsFile + "/";
                _file = string.Format("{0}/{1}{2}", WebContext.StartDir, path, _file);
                break;

            case DownloadType.Downloads:
                //_file = Server.MapPath(_file);
                break;

            default:
                _file = string.Format("{0}/{1}{2}", WebContext.StartDir, path, _file);
                break;
            }



            FileInfo fi = new FileInfo(Server.MapPath(_file));

            string mimeType = IO.GetMimeType(_file);

            if (mimeType == "")
            {
                mimeType = "application/force-download";
            }

            //Response.AddHeader("Content-Transfer-Encoding", "binary");


            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
            Response.AddHeader("Content-Type", mimeType);
            Response.AddHeader("Content-Length", fi.Length.ToString());
            Response.WriteFile(fi.FullName);
            Response.Flush();
            Response.End();
        }
        protected void UpdateNoCacheForResponse(HttpResponse response)
        {
            response.Buffer = false;
            response.BufferOutput = false;

            response.AddHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
            response.AddHeader("Pragma", "no-cache");
            response.AddHeader("Cache-Control", "no-cache, max-age=0, must-revalidate");
        }
Beispiel #20
0
        public void Genratepdftext(string url)
        {
            try
            {
                string temp_path = "";

                PdfConverter pdfobj = new PdfConverter();
                string       temp1  = "";
                pdfobj.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA=";
                pdfobj.PdfDocumentOptions.ShowHeader = false;
                pdfobj.PdfDocumentOptions.ShowFooter = false;
                pdfobj.PdfDocumentInfo.AuthorName    = "Cyber Best Technologies";
                pdfobj.PdfDocumentInfo.Title         = "Pharmacy Board";
                pdfobj.PdfDocumentInfo.Subject       = "Certificate";
                if (Convert.ToInt32(Request.QueryString[0].ToString().Substring(1)) < 11 || Convert.ToInt32(Request.QueryString[0].ToString().Substring(1)) > 19)
                {
                    float width  = (8.50f / 1.0f) * 72f;
                    float height = (11 / 1.0f) * 72f;
                    pdfobj.PdfDocumentOptions.AutoSizePdfPage    = false;
                    pdfobj.PdfDocumentOptions.PdfPageSize        = PdfPageSize.Custom;
                    pdfobj.PdfDocumentOptions.CustomPdfPageSize  = new SizeF(width, height);
                    pdfobj.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
                }
                else
                {
                    float width  = (11f / 1.0f) * 72f;
                    float height = (8.50f / 1.0f) * 72f;
                    pdfobj.PdfDocumentOptions.AutoSizePdfPage   = false;
                    pdfobj.PdfDocumentOptions.PdfPageSize       = PdfPageSize.Custom;
                    pdfobj.PdfDocumentOptions.CustomPdfPageSize = new SizeF(width, height);

                    pdfobj.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Landscape;
                }
                //pdfobj.PdfDocumentInfo.Keywords = "HTML, PDF,Converter";
                pdfobj.PdfDocumentInfo.CreatedDate = DateTime.Now;

                byte[] downloadBytes             = pdfobj.GetPdfBytesFromUrl(url);
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

                response.Clear();
                // response.Flush();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition", "attachment; filename=" + pname() + ".pdf; size=" + downloadBytes.Length.ToString());

                response.BinaryWrite(downloadBytes);
                PersonLicensing.Utilities_Licensing.GetCertficateJournal(Request.QueryString["refid"], pname().Replace("_", " "), Session["UID"].ToString());
                //   response.Flush();
                // response.End();
            }
            catch (Exception EX)
            {
                //return "";
                throw EX;
            }
        }
 static void BuildHeaders(HttpResponse response, string mimeType, DateTime lastModified)
 {
     response.StatusCode = 200;
     response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
     response.AddHeader("content-encoding", "gzip");
     response.Cache.VaryByHeaders["Accept-encoding"] = true;
     response.AddHeader("ETag", lastModified.Ticks.ToString("x"));
     response.AddHeader("Content-Type", mimeType);
     response.AddHeader("Content-Disposition", "inline");
     response.AddHeader("Last-Modified", lastModified.ToString("R"));
 }
        protected void Button2_Click(object sender, EventArgs e)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "application/pdf");
            response.AddHeader("Content-Disposition", "inline; filename=" + Label1.Text + "; size=" + "4");

            response.Flush();
            response.Flush();
            response.End();
        }
Beispiel #23
0
        public void Genratepdftext1(string murl, string fname)
        {
            try
            {
                string temp_path = "";

                PdfConverter pdfobj = new PdfConverter();
                string temp1 = "";
                pdfobj.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA=";
                pdfobj.PdfDocumentOptions.ShowHeader = false;
                pdfobj.PdfDocumentOptions.ShowFooter = false;
                string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
                thisPageURL = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/'));
                string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/') + 1) + "Prints/header.htm";
                pdfobj.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(headerAndFooterHtmlUrl);

                //enable header
                AddFooter(pdfobj);
                // set the header height in points
                pdfobj.PdfHeaderOptions.DrawHeaderLine = true;
                pdfobj.PdfHeaderOptions.HeaderHeight = 150;
                pdfobj.PdfHeaderOptions.HeaderText = "";
                pdfobj.PdfHeaderOptions.HeaderSubtitleText = "";
                pdfobj.PdfDocumentOptions.EmbedFonts = true;
                pdfobj.PdfDocumentInfo.AuthorName = "Cyber Best Technologies";
                pdfobj.PdfDocumentInfo.Title = "Pharmacy Board";
                pdfobj.PdfDocumentInfo.Subject = "Print LMS Forms";
                //pdfobj.PdfDocumentInfo.Keywords = "HTML, PDF,Converter";
                pdfobj.PdfDocumentInfo.CreatedDate = DateTime.Now;
                float width = (8.50f / 1.0f) * 72f;
                float height = (11 / 1.0f) * 72f;
                pdfobj.PdfDocumentOptions.AutoSizePdfPage = false;
                pdfobj.PdfDocumentOptions.PdfPageSize = PdfPageSize.Custom;
                pdfobj.PdfDocumentOptions.CustomPdfPageSize = new SizeF(width, height);
                pdfobj.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
                pdfobj.PdfDocumentOptions.LeftMargin = 10;
                pdfobj.PdfDocumentOptions.RightMargin = 10;
                byte[] downloadBytes = pdfobj.GetPdfBytesFromHtmlStream(GenerateStreamFromString(txtcomplaint.Text), System.Text.Encoding.Default);
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition", "attachment; filename=" + fname + ".pdf; size=" + downloadBytes.Length.ToString());

                response.BinaryWrite(downloadBytes);

            }
            catch (Exception EX)
            {
                //return "";
                throw EX;
            }
        }
        public static bool ResponseFile(HttpRequest request, HttpResponse response, string fileName, string fullPath, long speed, string pageUrl)
        {
            FileStream myFile = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                response.AddHeader("Accept-Ranges", "bytes");
                response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                const int pack = 10240;
                int sleep = (int)Math.Floor((double)(1000 * pack / speed)) + 1;
                if (request.Headers["Range"] != null)
                {
                    response.StatusCode = 206;
                    string[] range = request.Headers["Range"].Split(new[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                response.AddHeader("Connection", "Keep-Alive");
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (response.IsClientConnected)
                    {
                        response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            finally
            {
                br.Close();
                myFile.Close();
            }

            return true;
        }
Beispiel #25
0
 public static void DownloadFile(string nombreArchivo)
 {
     nombreArchivo = nombreArchivo + ".xlsx";
     System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
     Response.Clear();
     Response.ContentType = @"application\octet-stream";
     System.IO.FileInfo file = new System.IO.FileInfo(nombreArchivo);
     Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
     Response.AddHeader("Content-Length", file.Length.ToString());
     Response.ContentType = "application/octet-stream";
     Response.WriteFile(file.FullName);
     Response.Flush();
 }
Beispiel #26
0
        /// <summary>
        /// Exports in csv format.
        /// </summary>
        /// <param name="txtString"></param>
        /// <param name="filename"></param>
        public static void ExportCSV(string txtString, string filename)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.Charset = "utf-16";
            response.AddHeader("Content-Type", "text/csv");
            response.AddHeader("content-disposition", String.Format("attachment; filename={0}", filename));

            System.IO.StringWriter s = new System.IO.StringWriter();
            response.BinaryWrite(new byte[] { 0xff, 0xfe });
            response.BinaryWrite(Encoding.Unicode.GetBytes(txtString));
            response.End();
        }
Beispiel #27
0
        /// <summary>
        /// Generates a PDF document from the URL passed in, and returns to user in the HttpResponse (as a download)
        /// </summary>
        /// <param name="inUrl"></param>
        /// <param name="inPasswordProtectRandomly"></param>
        /// <param name="inOrientation"></param>
        /// <param name="inPageSize"></param>
        /// <param name="inServer">The requesting server (Page.Server when requested by an aspx or ascx page)</param>
        /// <param name="inFileName"></param>
        public static void GeneratePDFfromURL(string inUrl, bool inPasswordProtectRandomly, PDFPageOrientation inOrientation, PdfPageSize inPageSize, HttpServerUtility inServer, string inFileName)
        {
            // get the pdf bytes from html string
            byte[] downloadBytes = GetPDFfromURL(inUrl, inPasswordProtectRandomly, inOrientation, inPageSize, inServer);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "binary/octet-stream");
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + ((inFileName.Length > 0) ? inFileName : "Report") + ".pdf; size=" + downloadBytes.Length.ToString());

            response.BinaryWrite(downloadBytes);
        }
Beispiel #28
0
        /// <summary>
        /// 禁用客户端缓存
        /// </summary>
        public static void SetNoCache(HttpResponse response)
        {
            response.Buffer = true;
            response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            response.Expires = 0;
            response.CacheControl = "no-cache";
            response.AddHeader("Cache-Control", "no-cache");
            response.AddHeader("Pragma", "no-cache");

            response.Cache.SetNoStore();
            response.Cache.SetExpires(DateTime.MinValue);
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.SetValidUntilExpires(false);
        }
        public static void OutputExcel(System.Web.HttpServerUtility server, System.Web.HttpResponse response, string filename)
        {
            string path = server.MapPath(filename + ".xls");

            FileInfo file = new FileInfo(path);

            response.Clear();
            response.Charset         = "GB2312";
            response.ContentEncoding = Encoding.UTF8;
            response.AddHeader("Content-Disposition", "attachment; filename=" + server.UrlEncode(file.Name));
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = "application/ms-excel";
            response.WriteFile(file.FullName);
            response.End();
        }
Beispiel #30
0
        public static void SendPosterToBrowser( PosterBuilder.Builder pb, HttpResponse resp, string posterFilename, PosterBuilder.ImgFormat.SupportedTypes outputFormat)
        {
            string filename = BuildFilename(posterFilename, outputFormat);

            resp.Clear();
            // Ensure caching is off naturally
            resp.CacheControl = "no-cache";

            resp.ContentType = PosterBuilder.ImgFormat.ToMimeType(outputFormat);
            resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);

            // Call our image with our amendments and have it save to the response so we can send it back
            Bitmap bmp = pb.Render();

            // Have the Poster build our new image and save the result to the outgoing response
            // ... have to do all this with MemoryStreams as PNG doesn't like being saved directly to HttpResponse.OutputStream
            // ... may as well do the same for all image types and be consistent
            using (Bitmap bitmap = pb.Render()) {

                using (MemoryStream ms = new MemoryStream()) {
                    ImageFormat outFmt = PosterBuilder.ImgFormat.ToImageFormat(outputFormat);

                    bmp.Save(ms, outFmt);

                    ms.WriteTo(resp.OutputStream);
                } // using ms

            } // using pb

            // And of course, clear up after ourselves
            pb.Dispose();
            resp.End();
        }
 public void PrepareResponse(HttpResponse httpResponse)
 {
     httpResponse.Clear();
     httpResponse.ContentType = "text/tab-separated-values";
     httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".tsv\"");
     httpResponse.BufferOutput = false;
 }
Beispiel #32
0
        /// <summary>
        /// Exporta la información a Excel.
        /// </summary>
        /// <param name="response">HttpResponse actual.</param>
        /// <param name="data">Datos a exportar.</param>
        /// <param name="nombreArchivo">Nombre del archivo Excel</param>
        public static void ExportToExcelFile(HttpResponse response, DataView data, string nombreArchivo)
        {
            var dg = new DataGrid { DataSource = data };
            dg.DataBind();

            response.Clear();
            response.Buffer = true;

            //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            response.AddHeader("Content-Disposition", "filename=" + nombreArchivo);
            response.ContentType = "application/vnd.ms-excel";
            response.Charset = "UTF-8";
            response.ContentEncoding = System.Text.Encoding.Default;

            var stringWriter = new StringWriter();
            var htmlWriter = new HtmlTextWriter(stringWriter);
            dg.RenderControl(htmlWriter);

            response.Write(stringWriter.ToString());
            //resp.Flush();
            try
            {
                response.End();
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                throw ex;
            }
        }
Beispiel #33
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();
        }
Beispiel #34
0
        public void ExportPdf(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response, System.Web.UI.HtmlControls.HtmlForm htmlForm)
        {
            string strFileName = "PDFReport-" + System.DateTime.Now.Date.ToString("dd") + System.DateTime.Now.AddMonths(0).ToString("MM") + System.DateTime.Now.AddYears(0).ToString("yyyy");

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter hw  = new HtmlTextWriter(sw);
            HtmlForm       frm = new HtmlForm();

            exportGV.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(exportGV);
            frm.RenderControl(hw);

            StringReader sr         = new StringReader(Regex.Replace(sw.ToString(), "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase));
            Document     pdfDoc     = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker   htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
        public ActionResult ExportCSV(string emailList)
        {
            string FilePath = Server.MapPath("/App_Data/");
            string FileName = "EmailList.csv";

            System.IO.File.WriteAllText(FilePath + FileName, emailList);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/csv";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(FilePath + FileName);
            response.Flush();
            System.IO.File.Delete(FilePath + FileName); // Deletes the file on server

            response.End();
            List <string> listOfEmails = emailList.Split(',').ToList();

            foreach (var emailName in listOfEmails)
            {
                //Takes each email in list and searches for it on the JPStudents table and finds the associated ApplicationUserID.
                //Then calls the UpdateLatestContact method on each ApplicationUserID.
                var userId = db.JPStudents.Where(x => x.JPEmail == emailName).First().ApplicationUserId.ToString();
                UpdateLatestContact(userId);
            }
            return(RedirectToAction("Index"));
        }
Beispiel #36
0
        public void ExportToExcel(DataTable dataTable, HttpResponse response)
        {
            // Create a dummy GridView
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = dataTable;
            GridView1.DataBind();
            response.Clear();
            response.Buffer = true;
            response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int i = 0; (i
                        <= (GridView1.Rows.Count - 1)); i++)
            {
                // Apply text style to each Row
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }

            GridView1.RenderControl(hw);
            // style to format numbers to string
            string style = "<style> .textmode{mso-number-format:\\@;}</style>";
            response.Write(style);
            response.Output.Write(sw.ToString());
            response.Flush();
            response.End();
        }
Beispiel #37
0
        /// <summary>
        /// The purpose of this page is to service JSON Files. The files are already generated 
        /// elsewhere and are loaded from file system.
        /// 
        /// A query string parameter is sent to this page. Given name of 'm' and has values of '1:Get movies' file,
        /// '2:Get Movies Catalog' and so on.
        /// </summary>
        public static void Read(HttpRequest Request, HttpResponse Response)
        {
            string fileNameMovies = @"D:\SitiosWeb\Sitio\EC100A_Servicios\EC100A_PlanepolyWidget\planepoly-movies.json";
            string fileNameMoviesCatalog = @"D:\SitiosWeb\Sitio\EC100A_Servicios\EC100A_PlanepolyWidget\planepoly-movies-catalog.json";
            string fileName = "";
            string m = Request.QueryString["m"];

            if (m == null || (m != "1" && m != "2"))
            {
                Response.Write("Invalid");
                return;
            }
            switch (m)
            {
                case "1":
                    fileName = fileNameMovies;
                    break;
                case "2":
                    fileName = fileNameMoviesCatalog;
                    break;
                default:
                    break;
            }
            string s;
            using (StreamReader reader = new StreamReader(fileName))
            {
                s = reader.ReadToEnd();
            }
            Response.Write(s);
            Response.AddHeader("Access-Control-Allow-Origin", "*");
        }
Beispiel #38
0
        public void ExportToCSV(DataTable dataTable, HttpResponse response)
        {
            response.Clear();
            response.Buffer = true;
            response.AddHeader("content-disposition",
                "attachment;filename=DataTable.csv");
            response.Charset = "";
            response.ContentType = "application/text";

            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < dataTable.Columns.Count; k++)
            {
                //add separator
                sb.Append(dataTable.Columns[k].ColumnName + ',');
            }
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                for (int k = 0; k < dataTable.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(dataTable.Rows[i][k].ToString().Replace(",", ";") + ',');
                }
                //append new line
                sb.Append("\r\n");
            }
            response.Output.Write(sb.ToString());
            response.Flush();
            response.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            String FileName = null;

            switch ((string)Session["filetype"])
            {
            case ".txt":
                FileName = "CompressedText.cmx";
                break;

            case ".JPG":
            case ".jpg":
                FileName = "CompressedImage.cmi";
                break;

            case ".cmi":
                FileName = "ExtractedImage.jpg";
                break;

            case ".cmx":
                FileName = "ExtractedText.txt";
                break;
            }

            string fn = Server.MapPath("resources/" + FileName);

            System.Web.HttpResponse responses = System.Web.HttpContext.Current.Response;
            responses.ClearContent();
            responses.Clear();
            responses.ContentType = "text/plain";
            responses.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            responses.TransmitFile(fn);
            responses.Flush();
            responses.End();
        }
Beispiel #40
0
        public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head)
        {
            System.IO.StringWriter       sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);

            FrontDecorator(hw);
            if (Title != "")
            {
                hw.Write(Title + "<br>");
            }
            if (Head != "")
            {
                hw.Write(Head + "<br>");
            }

            DataGrid2Excel.EnableViewState = false;
            DataGrid2Excel.RenderControl(hw);

            RearDecorator(hw);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.Buffer          = true;
            response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
            response.ContentType     = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            response.Charset = "gb2312";
            response.Write(sw.ToString());
            response.End();
        }
Beispiel #41
0
        public void ProcessRequest(HttpContext context)
        {
            Int32  userid        = SessionData.UserID;
            String uploadFileDir = ConfigurationManager.AppSettings["UploadFolderPath"];

            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            string startDate      = request.QueryString["startDate"];
            string endDate        = request.QueryString["endDate"];
            string uploadfilepath = MppUtility.GetFilelocation(userid, uploadFileDir, "bulk");
            string fileName       = ConfigurationManager.AppSettings["filename"];
            string fileName1      = fileName.PadRight(29) + MppUtility.DateFormat(Convert.ToDateTime(startDate), 2) + "-" + MppUtility.DateFormat(Convert.ToDateTime(endDate), 2) + ".csv";
            string filePath       = Path.Combine(uploadfilepath, fileName1);
            bool   test           = System.IO.File.Exists(filePath);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            if (System.IO.File.Exists(filePath))
            {
                response.ClearContent();
                response.Clear();
                byte[] Content = System.IO.File.ReadAllBytes(filePath);
                response.ContentType = "text/csv";
                response.AddHeader("content-disposition", "attachment; filename=" + fileName1 + ".csv");
                response.BufferOutput = true;
                response.Cache.SetCacheability(HttpCacheability.NoCache);
                response.OutputStream.Write(Content, 0, Content.Length);
                response.Flush();
                response.End();
            }
            else
            {
                response.Redirect("ShowStatus.html");
            }
        }
Beispiel #42
0
 private void DoExportForHishop(string csvFilename, string imagePath, System.Collections.Generic.List <ExportToLocal.ProductDetail> list)
 {
     using (System.IO.FileStream fileStream = new System.IO.FileStream(csvFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
     {
         string productCSVForEcdev = this.GetProductCSVForHishop(imagePath, list);
         System.Text.UnicodeEncoding unicodeEncoding = new System.Text.UnicodeEncoding();
         //UTF8Encoding unicodeEncoding = new UTF8Encoding();
         int    byteCount = unicodeEncoding.GetByteCount(productCSVForEcdev);
         byte[] preamble  = unicodeEncoding.GetPreamble();
         byte[] array     = new byte[preamble.Length + byteCount];
         System.Buffer.BlockCopy(preamble, 0, array, 0, preamble.Length);
         unicodeEncoding.GetBytes(productCSVForEcdev.ToCharArray(), 0, productCSVForEcdev.Length, array, preamble.Length);
         fileStream.Write(array, 0, array.Length);
     }
     using (ZipFile zipFile = new ZipFile(System.Text.Encoding.Default))
     {
         System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(imagePath);
         zipFile.CompressionLevel = CompressionLevel.Default;
         zipFile.AddFile(csvFilename, "");
         zipFile.AddDirectory(directoryInfo.FullName, directoryInfo.Name);
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.ContentType     = "application/x-zip-compressed";
         response.ContentEncoding = this._encoding;
         response.AddHeader("Content-Disposition", "attachment; filename=" + directoryInfo.Name + ".zip");
         response.Clear();
         zipFile.Save(response.OutputStream);
         this._workDir.Delete(true);
         response.Flush();
         response.Close();
     }
 }
 void Download(HttpResponse resp, GUIDEx fileID)
 {
     lock (this)
     {
         if (resp != null)
         {
             string fullFileName = null, contentType = null;
             byte[] data = this.workDownloadService.Download(fileID, out fullFileName, out contentType);
             if (data != null && data.Length > 0)
             {
                 resp.Buffer = true;
                 resp.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fullFileName, System.Text.Encoding.UTF8));
                 resp.ContentEncoding = Encoding.GetEncoding("gb2312");//设置输出流为简体中文
                 resp.ContentType = contentType;//"application/OCTET-STREAM";
                 // resp.BufferOutput = true;
                 resp.BinaryWrite(data);
                 resp.Flush();
                 resp.End();
             }
             else
             {
                 resp.Write("文件不存在!" + fileID);
             }
         }
     }
 }
Beispiel #44
0
        public Document GetErrorDocument(
            Boolean openCloseConnection, Boolean addContentDisposition,
            String fileName,
            System.Web.HttpResponse webResponse, System.Web.HttpCookie cookie,
            DocTemplateVers.Domain.DTO.ServiceExport.DTO_Settings settings,
            IList <DocTemplateVers.Domain.DTO.ServiceExport.DTO_Signature> Signatures)
        {
            if (openCloseConnection)
            {
                webResponse.Clear();
            }
            if (cookie != null)
            {
                webResponse.AppendCookie(cookie);
            }
            if (addContentDisposition || openCloseConnection)
            {
                webResponse.AddHeader("Content-Disposition", "attachment; filename=" + HtmlCheckFileName(fileName) + "." + ExportFileType.pdf.ToString());
                webResponse.ContentType = "application/pdf";
            }

            Document doc = ExportTo(settings, webResponse.OutputStream, true, Signatures, "");

            if (doc != null && openCloseConnection)
            {
                webResponse.End();
            }
            return(doc);
        }
Beispiel #45
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();
            }
        }
Beispiel #46
0
    public static void exportarExcel(string htmlString, System.Web.HttpResponse response)
    {
        StringBuilder sb = new StringBuilder();

        System.IO.StringWriter sw  = new System.IO.StringWriter(sb);
        HtmlTextWriter         htw = new HtmlTextWriter(sw);
        Page     page = new Page();
        HtmlForm form = new HtmlForm();

        try
        {
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            page.Controls.Add(form);
            page.RenderControl(htw);
            response.Clear();
            response.Buffer      = true;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "inline;filename=Reporte.xls");
            string style = @"<style> .textmode { mso-number-format:\@; } .ancho{width:50%} .fechaformat{mso-number-format:\dd/mm/yyyy;} </style>";
            response.Write(style);
            response.Charset         = "utf-8";
            response.ContentEncoding = Encoding.UTF8;
            response.Write(htmlString);
            //'Response.End()
            response.Flush();
            response.SuppressContent = true;
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch (Exception)
        {
            throw;
        }
    }
Beispiel #47
0
        public void SavePdf( HttpResponse response, string downloadfilename )
        {
            response.Clear();
            response.ContentType = "application/x-pdf";
            response.AddHeader("content-disposition", string.Format("attachment; filename={0}",downloadfilename));

            SavePdf(response.OutputStream);
        }
		static void RedirectPermanent(HttpResponse response, string destination)
		{
			response.Clear();
			response.Status = "301 Moved Permanently";
			response.AddHeader("Location", destination);
			response.Flush();
			response.End();
		}
Beispiel #49
0
 internal void WriteToHttpResponse(HttpResponse httpResponse)
 {
     httpResponse.ClearContent();
     httpResponse.ClearHeaders();
     httpResponse.ContentType = model.ContentType;
     httpResponse.AddHeader("Content-Disposition", ContentDisposition);
     WriteToStream(httpResponse.OutputStream);
 }
Beispiel #50
0
 private static void PermanentRedirect(HttpResponse response, string location)
 {
     response.Clear();
     response.StatusCode = (int)HttpStatusCode.MovedPermanently;
     response.StatusDescription = "Moved Permanently";
     response.AddHeader("Location", location);
     response.End();
 }
Beispiel #51
0
        private void ToHttpResponse(LogResponse logResponse, HttpResponse httpResponse)
        {
            httpResponse.StatusCode = logResponse.StatusCode;

            foreach (KeyValuePair<string, string> kvp in logResponse.Headers)
            {
                httpResponse.AddHeader(kvp.Key, kvp.Value);
            }
        }
 private static void AddCORSHeaders(HttpRequest request, HttpResponse response)
 {
     var origin = request.Url.GetLeftPart(UriPartial.Authority);
     var requestedOrigin = request.Headers["Origin"];
     if (requestedOrigin != null && requestedOrigin.Trim().Length > 0)
     {
         origin = requestedOrigin;
     }
     response.AddHeader("Access-Control-Allow-Origin", origin);
 }
Beispiel #53
0
 private static void TransferHeader(HttpResponse to, IDictionary<string, string> from)
 {
     foreach (string k in from.Keys)
     {
         if (from.ContainsKey(k))
         {
             to.AddHeader(k, from[k]);
         }
     }
 }
Beispiel #54
0
        public static bool ShowDownloadToolFile(HttpResponse httpResponse, NameValueCollection queryString, CommonUtils.AppSettingKey settingKey, out Exception message)
        {
            try
            {
                string fileName = queryString["DownloadToolFile"];

                if (string.IsNullOrEmpty(fileName))
                {
                    message = new Exception("Query string 'DownloadToolFile' missing from url.");
                    return false;
                }

                if (!File.Exists(fileName))
                {
                    message = new FileNotFoundException(string.Format(@"Failed to find file '{0}'.
                                                    Please ask your administrator to check whether the folder exists.", fileName));
                    return false;
                }

                httpResponse.Clear();
                httpResponse.ClearContent();

                //Response.OutputStream.f
                httpResponse.BufferOutput = true;
                httpResponse.ContentType = "application/unknown";
                httpResponse.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(fileName)));
                byte[] fileContent = File.ReadAllBytes(fileName);

                BinaryWriter binaryWriter = new BinaryWriter(httpResponse.OutputStream);
                binaryWriter.Write(fileContent, 0, fileContent.Length);
                binaryWriter.Flush();
                binaryWriter.Close();

                var dirName = Path.GetDirectoryName(fileName);

                if (dirName != null)
                {
                    //Delete any files that are older than 1 hour
                    Directory.GetFiles(dirName)
                        .Select(f => new FileInfo(f))
                        .Where(f => f.CreationTime < DateTime.Now.AddHours(-1))
                        .ToList()
                        .ForEach(f => f.Delete());
                }
            }
            catch (Exception ex)
            {
                message = ex;
                return false;
            }

            message = null;
            return true;
        }
Beispiel #55
0
 /// <summary>
 /// Copy headers from the response that we received from the real server to the response that we are sending for the ajax request.
 /// </summary>
 /// <param name="source">HTTP response from the proxied server</param>
 /// <param name="destination">HTTP response being sent as a reply to the Ajax request.</param>
 public static void CopyHeadersTo(this HttpWebResponse source, HttpResponse destination)
 {
     foreach (string name in source.Headers)
     {
         if (IgnoredResponseHeaders.Contains(name))
             continue;
         var value = source.Headers[name];
         if (string.IsNullOrEmpty(value))
             continue;
         destination.AddHeader(name, value);
     }
 }
Beispiel #56
0
        public static void ToExcel(HttpResponse Response,DataTable dt , string fileName)
        {
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();

                //Add Header
                for (int count = 0; count < dt.Columns.Count - 1; count++)
                {
                    if (dt.Columns[count].ColumnName != null)
                        sb.Append(dt.Columns[count].ColumnName);
                    sb.Append("\t");
                }
                Response.Write(sb.ToString() + "\n");
                Response.Flush();

                //Append Data
                int index = 0;
                while (dt.Rows.Count >= index + 1)
                {
                    sb = new StringBuilder();

                    for (int col = 0; col < dt.Columns.Count -1; col++)
                    {
                        if (dt.Rows[index][col] != null)
                            //sb.Append(dt.Rows[index][col].ToString().Replace(",", " "));
                            sb.Append(dt.Rows[index][col].ToString());
                        sb.Append("\t");
                    }

                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    index = index + 1;
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

            dt.Dispose();
            Response.End();
        }
Beispiel #57
0
 /// <summary>
 /// Downloads the latex from estimate.
 /// </summary>
 /// <param name="projectId">The project id.</param>
 /// <param name="maxPriority">The max priority.</param>
 /// <param name="response">The response.</param>
 public void DownloadLatexFromEstimate(int? projectId
     , int? maxPriority
     , HttpResponse response)
 {
     response.Clear();
     response.AddHeader
         ("Content-Disposition"
         , "attachment;filename=estimate.tex");
     response.ContentType = "application/x-latex";
     response.Write(GetLatexFromEstimate
         (projectId, maxPriority));
     response.Flush();
     response.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           
        }
Beispiel #59
0
 public static void DataGridToExcel(HttpResponse myResponse, DataGrid dg, string fileName, int numRowLock)
 {
     myResponse.Clear();
     myResponse.Buffer = true;
     myResponse.ContentType = "application/vnd.ms-excel";
     myResponse.Charset = "";
     myResponse.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
     StringWriter writer = new StringWriter();
     HtmlTextWriter writer2 = new HtmlTextWriter(writer);
     dg.HeaderStyle.Height = 30;
     dg.HeaderStyle.BackColor = Color.LightSlateGray;
     MassageData(dg);
     dg.RenderControl(writer2);
     myResponse.End();
 }
        public static Stream GetCompressedResponseStreamIfSupported(HttpRequest request, HttpResponse response)
        {
            string AcceptEncoding = request.Headers["Accept-Encoding"];
            if (AcceptEncoding != null && AcceptEncoding.Contains("gzip"))
            {
                logger.Info(request.UserAgent + "contain : " + "gzip");
                //response.Headers.Remove("Content-Encoding");
                response.AddHeader("Content-Encoding", "gzip");

                return new GZipStream(response.OutputStream, CompressionMode.Compress);
            }
            else
            {
                return response.OutputStream;
            }
        }