Пример #1
0
 /// <summary>
 /// 输出纯文本到客户端
 /// </summary>
 /// <param name="Response"></param>
 /// <param name="text"></param>
 public static void WriteText(this HttpResponseBase Response, string text)
 {
     Response.ContentType = "text/plain";
     Response.ClearContent();
     Response.BinaryWrite(Encoding.UTF8.GetBytes(text));
     Response.Flush();
 }
Пример #2
0
 /// <summary>
 /// 输出Jsonp文本到客户端
 /// </summary>
 /// <param name="Response"></param>
 /// <param name="callBack">客户端的js回调方法</param>
 /// <param name="json">json参数</param>
 public static void WriteJsonp(this HttpResponseBase Response, string callBack, IJson json)
 {
     Response.ContentType = "application/x-javascript";
     Response.ClearContent();
     Response.BinaryWrite(Encoding.UTF8.GetBytes(string.Format("{0}({1});", callBack, json.ToString())));
     Response.Flush();
 }
Пример #3
0
 /// <summary>
 /// 输出Json文本到客户端
 /// </summary>
 /// <param name="Response"></param>
 /// <param name="json"></param>
 public static void WriteJson(this HttpResponseBase Response, IJson json)
 {
     Response.ContentType = "application/json";
     Response.ClearContent();
     Response.BinaryWrite(Encoding.UTF8.GetBytes(json.ToString()));
     Response.Flush();
 }
Пример #4
0
        /// <summary>
        /// Copies the full binary contents of the given blob to the given HTTP response.
        /// </summary>
        private static void CopyContents(CloudBlob blob, HttpResponseBase response, long offset = 0)
        {
            blob.FetchAttributes();

            response.BufferOutput = false;
            response.AddHeader("Content-Length", blob.Attributes.Properties.Length.ToString());
            response.Flush();

            using (var reader = blob.OpenRead())
            {
                reader.Seek(offset, System.IO.SeekOrigin.Begin);

                byte[] buffer = new byte[1024 * 4]; // 4KB buffer
                while (reader.CanRead)
                {
                    int numBytes = reader.Read(buffer, 0, buffer.Length);

                    if (numBytes <= 0)
                        break;

                    response.BinaryWrite(buffer);
                    response.Flush();
                }
            }
        }
Пример #5
0
        public static ActionResult GetFile(HttpResponseBase Response, HttpRequestBase Request, HttpServerUtilityBase Server,
            string filePath, string fileName, string contentType, string userFileName)
        {
            byte[] value;
            using (FileStream stream = System.IO.File.Open(filePath, FileMode.Open))
            {
                value = new byte[stream.Length];
                stream.Read(value, 0, (int)stream.Length);
            }
            //const string userFileName = "MissionOrder.pdf";
            //const string contentType = "application/pdf";
            Response.Clear();
            if (Request.Browser.Browser == "IE")
            {
                string attachment = String.Format("attachment; filename=\"{0}\"", Server.UrlPathEncode(userFileName));
                Response.AddHeader("Content-Disposition", attachment);
            }
            else
                Response.AddHeader("Content-Disposition", "attachment; filename=\"" + userFileName + "\"");

            Response.ContentType = contentType;
            Response.Charset = "utf-8";
            Response.HeaderEncoding = Encoding.UTF8;
            Response.ContentEncoding = Encoding.UTF8;
            Response.BinaryWrite(value);
            Response.End();
            return null;
        }
Пример #6
0
        protected override void WriteFile(HttpResponseBase response)
        {
            response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", FileDownloadName));
            byte[] fileContents = Convert.FromBase64String(_base64);

            response.BinaryWrite(fileContents);
            response.End();
        }
Пример #7
0
 private void CreateFileResponse(HttpResponseBase response, AttachmentDO attachment)
 {
     var fileData = attachment.Bytes;
     
     response.ContentType = "application/octet-stream";
     response.AddHeader("Content-Disposition", "filename=\"" + attachment.OriginalName + "\"");
     response.AddHeader("Content-Length", fileData.LongLength.ToString());
     response.AddHeader("Content-Type", attachment.Type + "; name=\"" + attachment.OriginalName + "\";");
     //Write the data
     response.BinaryWrite(fileData);
 }
Пример #8
0
        private void SetHttpResponse(HttpResponseBase httpResponse, string fileNameWithoutExtension, ExcelPackage package)
        {
            httpResponse.ClearContent();
            httpResponse.Buffer = true;

            //Write it back to the client
            httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            httpResponse.AddHeader("content-disposition", string.Format("attachment;  filename={0}.xlsx", fileNameWithoutExtension));
            httpResponse.BinaryWrite(package.GetAsByteArray());

            httpResponse.Flush();
            httpResponse.End();
        }
Пример #9
0
 protected override void WriteFile(HttpResponseBase response)
 {
     // 
     string filePath = HostingEnvironment.MapPath("~/Videos/" + FileName);
     FileInfo file = new FileInfo(filePath);
     if (file.Exists)
     {
         FileStream stream = file.OpenRead();
         byte[] videostream = new byte[stream.Length];
         stream.Read(videostream, 0, (int)file.Length);
         response.BinaryWrite(videostream);
     }
     else
     {
         throw new ArgumentException("檔案不存在。", "fileName");
     }
 }
Пример #10
0
        public bool SendContent(string url, HttpResponseBase response)
        {
            if (FileStore.SendContent(url, response))
                return true;

            var key = uriBuilder.ParseKey(url);
            var id = Hasher.Hash(uriBuilder.ParseFileName(url));
            var file = repository.SingleOrDefault<RequestReduceFile>(id);

            if(file != null)
            {
                response.BinaryWrite(file.Content);
                try
                {
                    FileStore.Save(file.Content, url, null);
                }
                catch(Exception ex)
                {
                    var message = string.Format("could not save {0}", url);
                    var wrappedException =
                        new ApplicationException(message, ex);
                    RRTracer.Trace(message);
                    RRTracer.Trace(ex.ToString());
                    if (Registry.CaptureErrorAction != null)
                        Registry.CaptureErrorAction(wrappedException);
                }
                RRTracer.Trace("{0} transmitted from db.", url);
                if (file.IsExpired)
                    reductionRepository.RemoveReduction(key);
                return true;
            }

            RRTracer.Trace("{0} not found on file or db.", url);
            reductionRepository.RemoveReduction(key);
            return false;
        }
Пример #11
0
 protected override void WriteFile(HttpResponseBase response)
 {
     response.BinaryWrite(CreateCalendarBytes());
 }
Пример #12
0
        public void WriteResponse(HttpResponseBase response)
        {
            response.ThrowIfNull("response");

            response.StatusCode = _statusCode.StatusCode;
            response.SubStatusCode = _statusCode.SubStatusCode;
            response.ContentType = ContentType;
            response.Charset = Charset;
            response.ContentEncoding = ContentEncoding;
            foreach (Header header in Headers)
            {
                response.Headers.Add(header.Field, header.Value);
            }
            response.HeaderEncoding = HeaderEncoding;
            foreach (Cookie cookie in Cookies)
            {
                response.Cookies.Add(cookie.GetHttpCookie());
            }
            _cachePolicy.Apply(response.Cache);

            response.BinaryWrite(_content);
        }
Пример #13
0
        private void ReceivePack(ControllerContext context, Stream input, HttpResponseBase response)
        {
            var capabilities = new HashSet<string>(Capabilities.Split(' '));
            var requests = ProtocolUtils.ParseUpdateRequests(input, capabilities).ToList();
            if (requests.Count == 0)
            {
                response.BinaryWrite(ProtocolUtils.EndMarker);
                return;
            }

            var reportStatus = capabilities.Contains("report-status");
            var useSideBand = capabilities.Contains("side-band-64k");
            var reportBand = useSideBand ? ProtocolUtils.PrimaryBand : (int?)null;
            var failureBand = reportStatus ? reportBand : ProtocolUtils.ErrorBand;

            try
            {
                ProtocolUtils.UpdateRequest source;
                ProtocolUtils.UpdateRequest destination;
                var errors = ReadRequests(requests, out source, out destination);
                if (errors.Any(e => e.Value != null) || source == null || destination == null)
                {
                    if (reportStatus || useSideBand)
                    {
                        ReportFailure(response, failureBand, errors, "expected source and destination branches to be pushed");
                    }

                    return;
                }

                var refPrefix = Guid.NewGuid().ToString();
                source = new ProtocolUtils.UpdateRequest(
                    source.SourceIdentifier,
                    source.TargetIdentifier,
                    RepoFormat.FormatSourceRef(refPrefix, 1));
                destination = new ProtocolUtils.UpdateRequest(
                    destination.SourceIdentifier,
                    destination.TargetIdentifier,
                    RepoFormat.FormatDestinationRef(refPrefix, 1));

                var output = this.ReadPack(new[] { source, destination }, capabilities, input);
                var line = ProtocolUtils.ReadPacketLine(output).TrimEnd('\n');
                if (line != "unpack ok")
                {
                    line = line.Substring("unpack ".Length);

                    if (reportStatus || useSideBand)
                    {
                        ReportFailure(response, failureBand, errors, line);
                    }

                    return;
                }

                string id;
                try
                {
                    using (var ctx = new ReviewContext())
                    {
                        using (new NoSyncScope())
                        {
                            id = ctx.GetNextReviewId().Result;
                        }

                        ctx.Reviews.Add(new Review
                        {
                            Id = id,
                            RefPrefix = refPrefix,
                        });
                        ctx.SaveChanges();
                    }
                }
                catch (DbUpdateException ex)
                {
                    ReportFailure(response, failureBand, errors, ex.GetBaseException().Message);
                    throw;
                }

                if (useSideBand)
                {
                    var url = new UrlHelper(context.RequestContext).Action("Index", "Home", null, context.HttpContext.Request.Url.Scheme) + "#/" + id;
                    var message = string.Format("code review created:\n\n\t{0}\n\n", url);
                    response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.MessageBand, Encoding.UTF8.GetBytes(message)));
                }

                if (reportStatus)
                {
                    ReportSuccess(response, reportBand);
                }
            }
            finally
            {
                if (useSideBand)
                {
                    response.BinaryWrite(ProtocolUtils.EndMarker);
                }
            }
        }
Пример #14
0
 private static void ReportSuccess(HttpResponseBase response, int? reportBand)
 {
     response.BinaryWrite(ProtocolUtils.Band(reportBand,
         ProtocolUtils.PacketLine("unpack ok\n"),
         ProtocolUtils.PacketLine("ok " + DestinationRefName + "\n"),
         ProtocolUtils.PacketLine("ok " + SourceRefName + "\n"),
         ProtocolUtils.EndMarker));
 }
Пример #15
0
        private static void ReportFailure(HttpResponseBase response, int? reportBand, Dictionary<ProtocolUtils.UpdateRequest, string> errors, string message)
        {
            if (reportBand == ProtocolUtils.ErrorBand)
            {
                response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.MessageBand,
                    ProtocolUtils.DefaultEncoding.GetBytes(string.Format("{0}\n", message))));

                foreach (var e in errors)
                {
                    response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.MessageBand,
                        ProtocolUtils.DefaultEncoding.GetBytes(string.Format("{0} ({1})\n", e.Key.CanonicalName, e.Value ?? "not created, see other errors"))));
                }

                response.BinaryWrite(ProtocolUtils.Band(ProtocolUtils.ErrorBand, ProtocolUtils.DefaultEncoding.GetBytes("code review creation aborted\n")));
            }
            else
            {
                var status = new List<byte[]>();

                status.Add(ProtocolUtils.PacketLine(string.Format("unpack {0}\n", message)));

                foreach (var e in errors)
                {
                    status.Add(ProtocolUtils.PacketLine(string.Format("ng {0} {1}\n", e.Key.CanonicalName, e.Value ?? "not created, see other errors")));
                }

                status.Add(ProtocolUtils.EndMarker);

                response.BinaryWrite(ProtocolUtils.Band(reportBand, status));
            }
        }
Пример #16
0
		public async Task WriteResponseAsync(HttpResponseBase response)
		{
			response.ThrowIfNull("response");

			response.StatusCode = _statusCode.StatusCode;
			response.SubStatusCode = _statusCode.SubStatusCode;
			response.ContentType = ContentType;
			response.Charset = Charset;
			response.ContentEncoding = ContentEncoding;
			foreach (Header header in Headers)
			{
				response.Headers.Add(header.Field, header.Value);
			}
			response.HeaderEncoding = HeaderEncoding;
			foreach (Cookie cookie in Cookies)
			{
				response.Cookies.Add(cookie.GetHttpCookie());
			}
			_cachePolicy.Apply(response.Cache);
			response.TrySkipIisCustomErrors = _skipIisCustomErrors;

			response.BinaryWrite(await _content.Value);
		}
 public static void ExportPdf(ExportEventArgs options, HttpResponseBase response)
 {
     response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.pdf", options.Title));
     response.ContentType = "application/pdf";
     response.BinaryWrite(ExportPdfHelper.ToPdfBytes(options));
 }
Пример #18
0
        private void CreateCheckCodeImage(string checkCode, HttpResponseBase response)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 16.5)), 35);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);
               // Pen drawPen = new Pen(Color.Blue);

               // 添加多种颜色 hooyes
                Color[] colors = { Color.Blue,Color.Silver,Color.SlateGray,Color.Turquoise,Color.Violet,Color.Turquoise,Color.Tomato,Color.Thistle,Color.Teal,Color.SteelBlue };

                //画图片的背景噪音线
                for (int i = 0; i < 9; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    Pen drawPen2 = new Pen(colors[i]);
                    g.DrawLine(drawPen2, x1, y1, x2, y2);

                }
                // drawPen.Dispose(); Tahoma
                Font font = new System.Drawing.Font("Arial", 13, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Gray, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 1);
               // g.DrawString("J", font, brush, 1, 115);
                font.Dispose();
                brush.Dispose();

                //画图片的前景噪音点
                for (int i = 0; i < 20; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(0x8b, 0x8b, 0x8b));
                }

                //画图片的边框线
                Pen borderPen = new Pen(Color.Transparent);
                g.DrawRectangle(borderPen, 0, 0, image.Width - 1, image.Height - 1);
                borderPen.Dispose();

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                byte[] buffer = ms.ToArray();
                ms.Dispose();
                response.ClearContent();
                response.ContentType = "image/bmp";
                response.BinaryWrite(buffer);
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
Пример #19
0
 /// <summary>
 /// 创建验证码的图片
 /// </summary>
 /// <param name="containsPage">要输出到的page对象</param>
 /// <param name="validateNum">验证码</param>
 public void CreateValidateGraphic(string validateCode,HttpResponseBase Response)
 {
     Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
     Graphics g = Graphics.FromImage(image);
     try
     {
         //生成随机生成器
         Random random = new Random();
         //清空图片背景色
         g.Clear(Color.White);
         //画图片的干扰线
         for (int i = 0; i < 25; i++)
         {
             int x1 = random.Next(image.Width);
             int x2 = random.Next(image.Width);
             int y1 = random.Next(image.Height);
             int y2 = random.Next(image.Height);
             g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
         }
         Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
         LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
          Color.Blue, Color.DarkRed, 1.2f, true);
         g.DrawString(validateCode, font, brush, 3, 2);
         //画图片的前景干扰点
         for (int i = 0; i < 100; i++)
         {
             int x = random.Next(image.Width);
             int y = random.Next(image.Height);
             image.SetPixel(x, y, Color.FromArgb(random.Next()));
         }
         //画图片的边框线
         g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
         //保存图片数据
         MemoryStream stream = new MemoryStream();
         image.Save(stream, ImageFormat.Jpeg);
         //输出图片流
         Response.Clear();
         Response.ContentType = "image/jpeg";
         Response.BinaryWrite(stream.ToArray());
     }
     finally
     {
         g.Dispose();
         image.Dispose();
     }
 }
Пример #20
0
        private static void SaveToResponse(string fileName, HttpResponseBase stream)
        {
            using (var reader = File.OpenRead(fileName))
            {
                var bt = new byte[1024];
                var count = 0;
                while ((count = reader.Read(bt, 0, 1024)) == 1024)
                {
                    stream.BinaryWrite(bt);
                }

                if (count > 0)
                {
                    var bt2 = new byte[count];
                    Array.Copy(bt, bt2, count);
                    stream.BinaryWrite(bt2);
                }
            }
        }
        /// <summary>
        /// 创建Excel
        /// </summary>
        public static void CreateExcel(HttpResponseBase response, HttpRequestBase request, int[] idArr)
        {
            // 文件名
            //string fileName = DateTime.Now.ToString("yyyyMMdd") + "测试.xls";、
            string fileName = "面试者信息表.xls";
            string UserAgent = request.ServerVariables["http_user_agent"].ToLower();

            // Firfox和IE下输出中文名显示正常
            if (UserAgent.IndexOf("firefox") == -1)
            {
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            }
            response.ContentType = "application/vnd.ms-excel;charset=UTF-8";
            response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
            response.Clear();

            // 新建Excel文档
            HSSFWorkbook excel = new HSSFWorkbook();

            // 新建一个Excel页签
            ISheet sheet = excel.CreateSheet("面试者信息表");

            //设置居中
            ICellStyle cellStyle = excel.CreateCellStyle();
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;

            // 创建新增行
            IRow row = sheet.CreateRow(0);

            // 设计表头
            ICell cell = row.CreateCell(0);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("ID");

            cell = row.CreateCell(1);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("学号");

            cell = row.CreateCell(2);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("姓名");

            cell = row.CreateCell(3);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("性别");

            cell = row.CreateCell(4);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("学院");

            cell = row.CreateCell(5);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("专业");

            cell = row.CreateCell(6);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("班级");

            cell = row.CreateCell(7);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("QQ");

            cell = row.CreateCell(8);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("E-mail");

            cell = row.CreateCell(9);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("联系方式");

            cell = row.CreateCell(10);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("学习经验");

            cell = row.CreateCell(11);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("自我介绍");

            cell = row.CreateCell(12);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("是否应聘技术方向");

            cell = row.CreateCell(13);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("选择题得分");

            cell = row.CreateCell(14);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("简答题得分");

            cell = row.CreateCell(15);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("总分");

            cell = row.CreateCell(16);
            cell.CellStyle = cellStyle;
            cell.SetCellValue("评语");

            //根据答卷
            //表格添加内容
            List<MODEL.T_InterviewerInfo> list
                = OperateContext.Current.BLLSession
                .IInterviewerInfoBLL.GetListBy(i => idArr.Contains(i.ID)).ToList();
            for (int i = 0; i < list.Count; i++)
            {
                row = sheet.CreateRow(i + 1);

                cell = row.CreateCell(0);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].ID);

                cell = row.CreateCell(1);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Num);

                cell = row.CreateCell(2);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Name);

                cell = row.CreateCell(3);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Gender);

                cell = row.CreateCell(4);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Academy);

                cell = row.CreateCell(5);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Major);

                cell = row.CreateCell(6);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Class);

                cell = row.CreateCell(7);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].QQ);

                cell = row.CreateCell(8);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].Email);

                cell = row.CreateCell(9);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].TelNum);

                cell = row.CreateCell(10);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].LearningExperience);

                cell = row.CreateCell(11);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].SelfEvaluation);

                cell = row.CreateCell(12);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(list[i].IsRequestTech == true ? "是" : "否");

                cell = row.CreateCell(13);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(GetChoiceScore(list[i].ID));

                cell = row.CreateCell(14);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(GetBriefScore(list[i].ID));

                cell = row.CreateCell(15);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(GetTotalScore(list[i].ID));

                cell = row.CreateCell(16);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(GetComment(list[i].ID));
            }

            // 设置行宽度
            sheet.SetColumnWidth(1, 18 * 256);
            sheet.SetColumnWidth(4, 22 * 256);
            sheet.SetColumnWidth(5, 22 * 256);
            sheet.SetColumnWidth(7, 15 * 256);
            sheet.SetColumnWidth(8, 21 * 256);
            sheet.SetColumnWidth(9, 16 * 256);
            sheet.SetColumnWidth(12, 18 * 256);
            sheet.SetColumnWidth(16, 30 * 256);

            //将Excel内容写入到流中
            MemoryStream file = new MemoryStream();
            excel.Write(file);

            //输出
            response.BinaryWrite(file.GetBuffer());
            response.End();
        }
Пример #22
0
        public bool SendContent(string url, HttpResponseBase response)
        {
            if (fileStore.SendContent(url, response))
                return true;

            var key = uriBuilder.ParseKey(url);
            var id = Guid.Parse(uriBuilder.ParseSignature(url));
            var file = repository[id];

            if(file != null)
            {
                response.BinaryWrite(file.Content);
                fileStore.Save(file.Content, url, null);
                RRTracer.Trace("{0} transmitted from db.", url);
                if (file.IsExpired)
                    reductionRepository.RemoveReduction(key);
                return true;
            }

            RRTracer.Trace("{0} not found on file or db.", url);
            reductionRepository.RemoveReduction(key);
            return false;
        }
Пример #23
0
        public static void DumpXlsx(HttpResponseBase response, DataTable table, string fileName, string title = "")
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();
            using (ExcelPackage pck = new ExcelPackage())
            {
                //Create the worksheet
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Report");

                int headerRowNo = 1;
                //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
                if (title.IsNullOrEmpty())
                {
                    headerRowNo = 2;
                }
                else
                {
                    headerRowNo = 3;
                }

                //var t = sw.Elapsed;
                //System.Diagnostics.Debug.WriteLine(string.Format("1. {0}M {1}S, {2}MS", t.Minutes, t.Seconds, t.Milliseconds));
                //sw.Restart();

                ws.Cells[string.Format("A{0}", headerRowNo)].LoadFromDataTable(table, true);

                //t = sw.Elapsed;
                //System.Diagnostics.Debug.WriteLine(string.Format("2. {0}M {1}S, {2}MS", t.Minutes, t.Seconds, t.Milliseconds));
                //sw.Restart();

                int colCount = table.Columns.Count;
                string lastColName = GetExcelColumnName(colCount);
                ExcelRange cols = ws.Cells[string.Format("A:{0}", lastColName)];
                cols.Style.Font.Name = "Tahoma";
                cols.Style.Font.Size = 10;

                //Format the header for column 1-3
                using (ExcelRange rng = ws.Cells[string.Format("A{0}:{1}{0}", headerRowNo, lastColName)]) // "A1:{0}1"
                {
                    rng.Style.Font.Bold = true;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
                    rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                    rng.Style.Font.Color.SetColor(Color.White);
                }

                //t = sw.Elapsed;
                //System.Diagnostics.Debug.WriteLine(string.Format("3. {0}M {1}S, {2}MS", t.Minutes, t.Seconds, t.Milliseconds));
                //sw.Restart();

                ws.Cells[headerRowNo, 1, headerRowNo + 10, colCount].AutoFitColumns();

                //t = sw.Elapsed;
                //System.Diagnostics.Debug.WriteLine(string.Format("4. {0}M {1}S, {2}MS", t.Minutes, t.Seconds, t.Milliseconds));
                //sw.Restart();

                string createDate = string.Format("{0}: {1}", "สร้างเมื่อ", DateTime.Now.ToString("d MMMM yyyy เวลา H:mm น.", AppUtils.ThaiCulture));
                if (!title.IsNullOrEmpty())
                {
                    ws.Cells[1, 1].Value = title;
                    // ws.SetValue(1, 1, title);

                    using (ExcelRange rng = ws.Cells["A1:A1"])
                    {
                        rng.Style.Font.Bold = true;
                    }
                    ws.Cells[2, 1].Value = createDate;
                }
                else
                {
                    ws.Cells[1, 1].Value = createDate;
                }
                //Example how to Format Column 1 as numeric
                //using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
                //{
                //    col.Style.Numberformat.Format = "#,##0.00";
                //    col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                //}

                //t = sw.Elapsed;
                //System.Diagnostics.Debug.WriteLine(string.Format("5. {0}M {1}S, {2}MS", t.Minutes, t.Seconds, t.Milliseconds));
                //sw.Restart();

                //Write it back to the client
                response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                response.AddHeader("content-disposition", string.Format("attachment;  filename={0}.xlsx", AppUtils.CleanFileName(fileName)));
                response.BinaryWrite(pck.GetAsByteArray());

                //t = sw.Elapsed;
                //System.Diagnostics.Debug.WriteLine(string.Format("6. {0}M {1}S, {2}MS", t.Minutes, t.Seconds, t.Milliseconds));
                //sw.Restart();
            }
        }