WriteFile() private method

private WriteFile ( FileStream fs, long offset, long size ) : void
fs FileStream
offset long
size long
return void
Example #1
0
        public bool ReturnXls(System.Web.HttpResponse resp, string fileName)
        {
            System.IO.FileInfo f = new System.IO.FileInfo(fileName);
            resp.ClearHeaders();
            resp.ClearContent();

            DialogUtils.SetCookieResponse(resp);

            resp.HeaderEncoding = System.Text.Encoding.Default;
            resp.AddHeader("Content-Disposition", "attachment; filename=" + f.Name);
            resp.AddHeader("Content-Length", f.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.WriteFile(f.FullName);
            //resp.End();
            return(true);
        }
Example #2
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");
            }
        }
Example #3
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;
            }
        }
Example #4
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");
            }
        }
Example #5
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);
 }
Example #6
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();
        }
 private static void WriteFile(HttpResponse response, HttpRequest request, string virtualPath)
 {
     var filePath = GetRealLocation(request, virtualPath);
     if (filePath != null && File.Exists(filePath))
     {
         response.ContentType = "application/javascript";
         response.WriteFile(Path.GetFileName(filePath));
     }
     else
         Return404(response);
 }
    /// <summary>
    /// Sends the file to the response with content-length header. will check last-writetime for sending modified header
    /// </summary>
    /// <param name="Response"></param>
    /// <param name="file"></param>
    /// <param name="mimetype"></param>
    /// <remarks>Works with all types of files, not image specific</remarks>
    public void SendToResponse(HttpResponse Response, FileInfo file, string mimetype)
    {
      Response.ClearHeaders();
      setCacheHeaders(Response);   

      //Response.Cache.SetETag("\"999ed196eeb0cc1:9\"");
      Response.Cache.SetLastModified(file.LastWriteTime);
      Response.ContentType = mimetype;      
      Response.AppendHeader("Content-Length", file.Length.ToString());
      Response.WriteFile(file.FullName);
      Response.End();
    }
Example #9
0
        public void DownloadFile()
        {
            string filePath = Server.MapPath("~/Files_SelfEmployment/App/") + "Test" + ".pdf";

            //This is used to get the current response.
            System.Web.HttpResponse res = GetHttpResponse();
            res.Clear();
            res.AppendHeader("content-disposition", "attachment; filename=" + filePath);
            res.ContentType = "application/octet-stream";
            res.WriteFile(filePath);
            res.Flush();
            res.End();
        }
Example #10
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();
 }
Example #11
0
		/// <summary>
		/// 写入文件到http回应中
		/// </summary>
		/// <param name="response"></param>
		public void WriteResponse(HttpResponse response) {
			// 设置文件的最后修改时间
			var lastModified = File.GetLastWriteTimeUtc(FilePath).Truncate();
			response.Cache.SetLastModified(lastModified);
			// 文件没有修改时返回304
			if (IfModifiedSince != null && IfModifiedSince == lastModified) {
				response.StatusCode = 304;
				response.SuppressContent = true;
				return;
			}
			// 写入文件到http回应中
			response.ContentType = MimeMapping.GetMimeMapping(FilePath);
			response.WriteFile(FilePath);
		}
        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();
        }
Example #13
0
        public static void Exportar(string nombreArchivo, IList titulos, IList propiedades, IList elementos, HttpResponse response, string tituloPrincipal)
        {
            string pathArchivo = ConfigurationManager.AppSettings["PATH_TEMP"] + nombreArchivo;

            FileInfo archivo = new FileInfo(pathArchivo);
            StreamWriter handlerArchivo = archivo.CreateText();

            handlerArchivo.WriteLine(tituloPrincipal);

            // Escribir encabezado
            string linea = "";

            foreach (string titulo in titulos)
            {
                linea += "=CONCATENAR(\"\";\"" + titulo + "\";\"\")\t";
            }

            handlerArchivo.WriteLine(linea);

            // Escribir contenido
            foreach (object elemento in elementos)
            {
                linea = "";

                foreach (string propiedad in propiedades)
                {
                    linea += "=CONCATENAR(\"\";\"" + ReflectionUtils.GetProperty(elemento, propiedad) + "\";\"\")\t";
                }

                handlerArchivo.WriteLine(linea);
            }

            // Genero la salida
            handlerArchivo.Close();
            response.AppendHeader("content-disposition", "attachment; filename=" + nombreArchivo);
            response.ContentType = "application / msexcel";
            response.WriteFile(pathArchivo);
            response.End();
        }
Example #14
0
        private void Real(HttpResponse response, HttpRequest request)
        {

            string Files_Root = ConfigurationManager.AppSettings.Get("ContentRoot");
            string Files_PhysicalPath = request.FilePath;
            Files_PhysicalPath = string.Format("{0}{1}", Files_Root, request.FilePath.Replace("/", "\\"));

            //response.Write(Files_PhysicalPath);
            //response.End();

            if (File.Exists(Files_PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(Files_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 ".mp4":
                        response.ContentType = "video/mp4";
                        break;
                    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");
            }
        }
Example #15
0
		public void WriteFile_PermitOnly_UnmanagedCode ()
		{
			HttpResponse response = new HttpResponse (writer);
			response.WriteFile (handle, 0, 1);
		}
Example #16
0
		public void WriteFile_StringIntInt_Deny_FileIOPermission ()
		{
			HttpResponse response = new HttpResponse (writer);
			response.WriteFile (fname, 0, 1);
		}
 void transmitify(HttpResponse response, FileInfo fi)
 {
     response.StatusCode = 200;
     response.AddHeader("ETag", fi.LastWriteTimeUtc.Ticks.ToString("x"));
     response.AddHeader("Content-Type", _compiler.OutputMimeType);
     response.AddHeader("Content-Disposition", "inline");
     response.AddHeader("Last-Modified", fi.LastWriteTimeUtc.ToString("R"));
     response.WriteFile(fi.FullName);
 }
Example #18
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void Compress(HttpRequest request, HttpResponse response)
        {
            Encoding encoding = Encoding.GetEncoding("windows-1252");
            string enc, cacheFile = null, cacheKey = null, content = "";
            StringWriter writer = new StringWriter();
            byte[] buff = new byte[1024];
            GZipOutputStream gzipStream;
            bool supportsGzip;

            // Set response headers
            response.ContentType = "text/javascript";
            response.Charset = this.charset;
            response.Buffer = false;

            // Setup cache
            response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset));

            // Check if it supports gzip
            enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower();
            supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null;
            enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip";

            // Setup cache info
            if (this.diskCache) {
                cacheKey = "";

                foreach (JSCompressItem item in this.items) {
                    // Get last mod
                    if (item.Type == JSItemType.File) {
                        DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value));

                        if (fileMod > this.lastUpdate)
                            this.lastUpdate = fileMod;
                    }

                    cacheKey += item.Value;
                }

                cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey);

                if (this.gzipCompress)
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz");
                else
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".js");
            }

            // Use cached file disk cache
            if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                response.WriteFile(cacheFile);
                return;
            }

            foreach (JSCompressItem item in this.items) {
                if (item.Type == JSItemType.File) {
                    if (!File.Exists(request.MapPath(item.Value))) {
                        writer.WriteLine("alert('Could not load file: " + StringUtils.Escape(item.Value) + "');");
                        continue;
                    }

                    StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8);

                    if (item.RemoveWhiteSpace) {
                        JavaScriptMinifier jsMin = new JavaScriptMinifier(reader, writer);
                        jsMin.Compress();
                    } else {
                        writer.Write('\n');
                        writer.Write(reader.ReadToEnd());
                        writer.Write(";\n");
                    }

                    reader.Close();
                } else {
                    if (item.RemoveWhiteSpace) {
                        JavaScriptMinifier jsMin = new JavaScriptMinifier(new StringReader(item.Value), writer);
                        jsMin.Compress();
                    } else {
                        writer.Write('\n');
                        writer.Write(item.Value);
                        writer.Write('\n');
                    }
                }
            }

            content = writer.ToString();

            // Generate GZIP'd content
            if (supportsGzip) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                if (this.diskCache && cacheKey != null) {
                    try {
                        // Gzip compress
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(File.Create(cacheFile));
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        } else {
                            StreamWriter sw = File.CreateText(cacheFile);
                            sw.Write(content);
                            sw.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        }

                        // Write to stream
                        response.WriteFile(cacheFile);
                    } catch (Exception) {
                        content = "/* Not cached */" + content;
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(response.OutputStream);
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();
                        } else {
                            response.Write(content);
                        }
                    }
                } else {
                    content = "/* Not cached */" + content;
                    gzipStream = new GZipOutputStream(response.OutputStream);
                    buff = encoding.GetBytes(content.ToCharArray());
                    gzipStream.Write(buff, 0, buff.Length);
                    gzipStream.Close();
                }
            } else {
                content = "/* Not cached */" + content;
                response.Write(content);
            }
        }
Example #19
0
		/// <summary>
		/// 渡された HttpResponse にレスポンスを書き込みます。
		/// 一度書いたらファイルに保存します。
		/// </summary>
		public override void WriteResponse(HttpResponse response){
			if(Html != null){
				string resultStr = Html.OuterXml;
				response.Write(resultStr);
				// もう一度見る
				if(myCacheFile.Exists) Html = null;
			} else if(myCacheFile != null){
				myCacheFile.Refresh();
				if(myCacheFile.Exists){
					response.WriteFile(myCacheFile.FullName);
				} else {
					Util.Throw("???");
				}
			}
			WriteResponseHeader(response);
			SetLastModified(response);
		}
        private static void WriteFile(HttpResponse response, HttpServerUtility server, string requestPath)
        {
            var filePath = server.MapPath(requestPath);

            response.WriteFile(filePath);
        }
        void BuildFileItemResponse(HttpContext context,
                                   string fileName,
                                   long fileSize,
                                   DateTime lastModifiedTime,
                                   string strETag)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;
            bool         fCache   = false;
            string       strRange;
            int          cbCacheThreshold = DEFAULT_CACHE_THRESHOLD;
            bool         fIsRangeRequest  = false;

            //
            // Get the Range: header if it exists
            //

            strRange = request.Headers["Range"];
            if (strRange != null)
            {
                if (strRange.ToLower(CultureInfo.InvariantCulture).StartsWith("bytes"))
                {
                    fIsRangeRequest = true;
                }
            }

            //
            // Give the range code a first crack at sending the ranges.  If
            // the Range: header is syntactically invalid, then we will fall
            // thru as if the Range: header was not present.
            //

            if (fIsRangeRequest &&
                !SendEntireEntity(context,
                                  strETag,
                                  lastModifiedTime))
            {
                // At this point we know that based on "If-Range"
                // (if provided) we may not send the entire entity.

#if  SUPPORT_HTTP_RANGE_REQUESTS
                if (RangeSupport.ProcessRangeRequest(context,
                                                     strRange,
                                                     fileName,
                                                     fileSize))
                {
                    //
                    // If ProcessRangeRequest() returned true, then it
                    // handled the range somehow (either sending it back
                    // with a 206 or sent a 416
                    //

                    response.Cache.SetNoServerCaching();

                    return;
                }
#endif
                //
                // Fall thru.  The request is now cacheable again
                //
            }

            if (fileSize <= cbCacheThreshold &&
                !request.RequestType.Equals("(GETSOURCE)") &&
                !request.RequestType.Equals("(HEADSOURCE)"))
            {
                fCache = true;
            }

            //
            // Ask ASP to open the file contents and cache them
            // (hence the second parameter to WriteFile())
            //

            response.WriteFile(fileName, fCache);

            //
            // Specify content type. Use extension to do the mapping
            //

            response.ContentType = MimeMapping.GetMimeMapping(fileName);

            //
            // Static file handler supports byte ranges (duh)
            //

            response.AppendHeader("Accept-Ranges", "bytes");

            //
            // If we are caching, the instruct the ASP output cache to
            // to cache the result.
            //

            if (fCache)
            {
                //
                // Set a validation handler to check to avoid serving from
                // ASP.NET output cache when Range or Translate:f
                //


                response.Cache.AddValidationCallback(
                    new HttpCacheValidateHandler(this.CacheValidateHandler),
                    null);

                //
                //
                // We want to flush cache entry when static file has changed
                //

                response.AddFileDependency(fileName);

                //
                // Set an expires in the future.
                //

                response.Cache.SetExpires(DateTime.Now.AddDays(1));
            }
        }
Example #22
0
        public static bool DownloadFile(Page page, HttpResponse response, HttpSessionState userSession)
        {
            Regex RE = new Regex(@"[,]+");
            string[] tImagePathDef = RE.Split((string)userSession[IGSMRequest.IGSMREQUEST_PARAM_LISTPATH]);

            string sImageFileName = Path.GetFileName(tImagePathDef[0]);
            string sFilePath = page.MapPath(tImagePathDef[0]);
            response.ContentType = "application/octet-stream";
            response.AddHeader("Content-Disposition", "attachment; filename=" + sImageFileName);
            response.WriteFile(sFilePath);
            userSession.Remove(IGSMRequest.IGSMREQUEST_PARAM_LISTPATH);
            return true;
        }
    private void downloadFile(string newFile, bool delete)
    {
        try
        {
            if (newFile != "")
            {
                FileInfo fle = new FileInfo(newFile);
                if (fle.Extension == "")
                {
                    string tempath = System.IO.Path.GetTempPath();
                    if (!File.Exists(tempath + fle.Name + ".xml"))
                    {
                        File.Copy(newFile, tempath + fle.Name + ".xml");
                    }
                    newFile = tempath + fle.Name + ".xml";
                }
            }

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

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

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

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

                fileResponse.AppendHeader("Content-Disposition", "Attachment; Filename=\"" + fileToDownload.Name + "\"");
                fileResponse.Flush();
                if (File.Exists(fileToDownload.FullName))
                {
                    fileResponse.WriteFile(fileToDownload.FullName);
                    //fileResponse.End();
                    fileResponse.Flush();
                    fileResponse.Close();
                    if (delete)
                    {
                        File.Delete(fileToDownload.FullName);
                    }
                }
                else
                {
                    lblSearchError.Text = "No File Exists at specified location.";
                }
            }
        }
        catch (Exception ex)
        {
            lblSearchError.Text = ex.Message;
        }
    }
Example #24
0
        /// <summary>
        /// Returns the XML for the requested transaction and removes any state files associated with it.
        /// </summary>
        /// <param name="response"><see cref="T:System.Web.HttpResponse"/></param>
        /// <param name="transaction">Transaction TcmUri</param>
        private void HandleTransactionRequest(HttpResponse response, String transaction)
        {
            Logger.Info("FileTransaction - Requested '{0}'.", transaction);

            if (TcmUri.IsValid(transaction))
            {
                String mappedFile = Path.Combine(mIncomingFolder, transaction + ".xml");

                if (File.Exists(mappedFile))
                {
                    response.ContentType = "text/xml";
                    response.WriteFile(mappedFile);

                    try
                    {
                        String stateFile = Path.Combine(mIncomingFolder, transaction + ".state.xml");
                        Logger.Debug("Removing transaction state xml '{0}'.", stateFile);

                        if (File.Exists(stateFile))
                            File.Delete(stateFile);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("FileTransaction - Removing '{0}'.", ex, ex.Message);
                    }

                    return;
                }

                Logger.Warning("FileTransaction - Not found transaction file '{0}'.", mappedFile);
            }

            Logger.Warning("FileTransaction - Invalid transaction '{0}'.", transaction);

            response.StatusCode = (int)HttpStatusCode.NoContent;
            response.Write("No Content");
        }
Example #25
0
        /// <summary>
        /// Handles "fileName=" requests from the cd_transport service
        /// </summary>
        /// <param name="response"><see cref="T:System.Web.HttpResponse"/></param>
        /// <param name="fileName">fileName</param>
        /// <param name="action">action to take, either empty or "remove"</param>
        private void HandleFileRequest(HttpResponse response, String fileName, String action)
        {
            String mappedFile = TcmUri.IsValid(fileName) ? Path.Combine(mIncomingFolder, fileName + ".state.xml") : Path.Combine(mIncomingFolder, fileName);

            Logger.Info("FileRequest - fileName '{0}', action '{1}'.", fileName, action);

            if (File.Exists(mappedFile))
            {
                if (String.Equals(action, "remove", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        Logger.Info("FileRequest - removing file '{0}'.", fileName);
                        File.Delete(mappedFile);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("FileRequest - removing file", ex, ex.Message);
                    }

                    response.Write("File removed");

                    return;
                }
                else
                {
                    if (String.Equals(Path.GetExtension(mappedFile), ".xml", StringComparison.OrdinalIgnoreCase))
                    {
                        response.ContentType = "text/xml";

                        if (String.Equals(fileName, META_XML, StringComparison.OrdinalIgnoreCase))
                        {
                            CleanTransactions.Execute();

                            Logger.Debug("FileRequest - meta.xml requested");

                            String metaXml = HttpContext.Current.Cache[META_XML] as String;

                            if (String.IsNullOrEmpty(metaXml))
                            {
                                metaXml = File.ReadAllText(mappedFile, Encoding.UTF8);
                                HttpContext.Current.Cache.Insert(META_XML, metaXml, new CacheDependency(mappedFile));
                            }
                            else
                            {
                                Logger.Info("FileRequest - Sending cached meta.xml");
                            }

                            response.Write(metaXml);
                            return;
                        }
                    }

                    Logger.Info("FileRequest - sending file {0}", fileName);

                    response.WriteFile(mappedFile);
                    return;
                }
            }

            Logger.Warning("FileRequest - Not found or invalid '{0}'.", mappedFile);

            response.StatusCode = (int)HttpStatusCode.NoContent;
            response.Write("No Content");
        }
Example #26
0
        /// <summary>
        /// 将DataTable导出到Excel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">仅文件名(非路径)</param>
        /// <returns>返回Excel文件绝对路径</returns>
        public void ExportDataSetToExcel(DataTable dt, string fileName, System.Web.HttpResponse Response)
        {
            #region 表头
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet hssfSheet = hssfworkbook.CreateSheet(fileName);
            hssfSheet.DefaultColumnWidth = 10;
            hssfSheet.SetColumnWidth(0, 10 * 256);
            hssfSheet.SetColumnWidth(3, 10 * 256);

            // 表头
            NPOI.SS.UserModel.IRow tagRow0 = hssfSheet.CreateRow(0);
            tagRow0.Height = 40 * 40;
            ICell cell0 = tagRow0.CreateCell(0);
            //设置单元格内容
            cell0.SetCellValue("力诺瑞特制造工厂");
            hssfSheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 13));

            NPOI.SS.UserModel.IRow tagRow1 = hssfSheet.CreateRow(1);
            tagRow1.Height = 30 * 20;
            ICell cell1 = tagRow1.CreateCell(0);
            //设置单元格内容
            cell1.SetCellValue("反冲材料补料单");
            hssfSheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 13));


            NPOI.SS.UserModel.ICellStyle tagStyle = hssfworkbook.CreateCellStyle();
            tagStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            tagStyle.VerticalAlignment = VerticalAlignment.Center;
            //tagStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            //tagStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            IFont font = hssfworkbook.CreateFont();
            font.FontHeightInPoints = 16;
            font.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            font.FontName           = "宋体";
            tagStyle.SetFont(font);//HEAD 样式
            cell0.CellStyle = tagStyle;
            NPOI.SS.UserModel.ICellStyle tagStyle1 = hssfworkbook.CreateCellStyle();
            tagStyle1.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            tagStyle1.VerticalAlignment = VerticalAlignment.Center;
            cell1.CellStyle             = tagStyle1;

            // 标题样式
            NPOI.SS.UserModel.ICellStyle cellStyle1 = hssfworkbook.CreateCellStyle();
            cellStyle1.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle1.VerticalAlignment = VerticalAlignment.Center;
            cellStyle1.BorderBottom      = NPOI.SS.UserModel.BorderStyle.None;
            cellStyle1.BorderLeft        = NPOI.SS.UserModel.BorderStyle.None;
            cellStyle1.BorderRight       = NPOI.SS.UserModel.BorderStyle.None;
            cellStyle1.BorderTop         = NPOI.SS.UserModel.BorderStyle.None;
            #endregion

            //数据样式
            NPOI.SS.UserModel.ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.LeftBorderColor   = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.RightBorderColor  = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.TopBorderColor    = NPOI.HSSF.Util.HSSFColor.Black.Index;
            #region 表数据

            // 表数据
            for (int k = 0; k < 2; k++)
            {
                DataRow dr = dt.Rows[k];
                NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(k + 2);
                row.Height = 30 * 20;

                for (int i = 0; i < 2; i += 2)
                {
                    row.CreateCell(i).SetCellValue(dr[0].ToString());
                    row.GetCell(i).CellStyle = cellStyle1;
                }

                for (int i = 2; i < 5; i += 3)
                {
                    row.CreateCell(i).SetCellValue(dr[1].ToString());
                    row.GetCell(i).CellStyle = cellStyle1;
                }

                for (int i = 5; i < 7; i += 2)
                {
                    row.CreateCell(i).SetCellValue(dr[2].ToString());
                    row.GetCell(i).CellStyle = cellStyle1;
                }
                for (int i = 7; i < 9; i += 2)
                {
                    row.CreateCell(i).SetCellValue(dr[3].ToString());
                    row.GetCell(i).CellStyle = cellStyle1;
                }
                for (int i = 9; i < 11; i += 2)
                {
                    row.CreateCell(i).SetCellValue(dr[4].ToString());
                    row.GetCell(i).CellStyle = cellStyle1;
                }
                for (int i = 11; i < 14; i += 3)
                {
                    row.CreateCell(i).SetCellValue(dr[5].ToString());
                    row.GetCell(i).CellStyle = cellStyle1;
                }

                row.CreateCell(1).SetCellValue("");
                row.GetCell(1).CellStyle = cellStyle1;
                row.CreateCell(3).SetCellValue("");
                row.GetCell(3).CellStyle = cellStyle1;
                row.CreateCell(4).SetCellValue("");
                row.GetCell(4).CellStyle = cellStyle1;
                row.CreateCell(6).SetCellValue("");
                row.GetCell(6).CellStyle = cellStyle1;
                row.CreateCell(8).SetCellValue("");
                row.GetCell(8).CellStyle = cellStyle1;
                row.CreateCell(10).SetCellValue("");
                row.GetCell(10).CellStyle = cellStyle1;
                row.CreateCell(12).SetCellValue("");
                row.GetCell(12).CellStyle = cellStyle1;
                row.CreateCell(13).SetCellValue("");
                row.GetCell(13).CellStyle = cellStyle1;
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 0, 1));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 2, 4));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 5, 6));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 7, 8));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 9, 10));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 11, 13));
            }
            // 表数据
            for (int k = 2; k < dt.Rows.Count; k++)
            {
                if (k == dt.Rows.Count - 1)
                {
                    DataRow drlast = dt.Rows[k];
                    NPOI.SS.UserModel.IRow rowlast = hssfSheet.CreateRow(k + 2);
                    rowlast.Height = 30 * 20;

                    for (int i = 0; i < 2; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue(drlast[0].ToString());
                        rowlast.GetCell(i).CellStyle = cellStyle1;
                    }

                    for (int i = 2; i < 4; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue("");
                        rowlast.GetCell(i).CellStyle = cellStyle1;
                    }

                    for (int i = 4; i < 6; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue(drlast[2].ToString());
                        rowlast.GetCell(i).CellStyle = cellStyle1;
                    }

                    for (int i = 6; i < 8; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue("");
                        rowlast.GetCell(i).CellStyle = cellStyle1;
                    }

                    for (int i = 8; i < 10; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue(drlast[4].ToString());
                        rowlast.GetCell(i).CellStyle = cellStyle1;
                    }
                    for (int i = 10; i < 14; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue("");
                        rowlast.GetCell(i).CellStyle = cellStyle1;
                    }
                    //hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 1, 7));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 0, 1));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 2, 3));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 4, 5));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 6, 7));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 8, 9));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 10, 13));
                }
                else
                {
                    DataRow dr = dt.Rows[k];
                    NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(k + 2);
                    row.Height = 30 * 20;

                    for (int i = 0; i < 1; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[i].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }

                    for (int i = 1; i < 3; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[1].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                    for (int i = 3; i < 6; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[2].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                    for (int i = 6; i < 8; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[3].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                    for (int i = 8; i < 10; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[4].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                    for (int i = 10; i < 12; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[5].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                    for (int i = 12; i < 14; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[6].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }

                    row.CreateCell(2).SetCellValue("");
                    row.GetCell(2).CellStyle = cellStyle;
                    row.CreateCell(4).SetCellValue("");
                    row.GetCell(4).CellStyle = cellStyle;
                    row.CreateCell(5).SetCellValue("");
                    row.GetCell(5).CellStyle = cellStyle;
                    row.CreateCell(7).SetCellValue("");
                    row.GetCell(7).CellStyle = cellStyle;
                    row.CreateCell(9).SetCellValue("");
                    row.GetCell(9).CellStyle = cellStyle;
                    row.CreateCell(11).SetCellValue("");
                    row.GetCell(11).CellStyle = cellStyle;
                    row.CreateCell(13).SetCellValue("");
                    row.GetCell(13).CellStyle = cellStyle;

                    #region 合并单元格
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 1, 2));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 3, 5));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 6, 7));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 8, 9));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 10, 11));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 12, 13));
                    #endregion
                }
            }

            #endregion
            hssfSheet.PrintSetup.NoColor   = true;
            hssfSheet.PrintSetup.Landscape = true;
            hssfSheet.PrintSetup.PaperSize = (short)PaperSize.A4;
            //是否自适应界面
            hssfSheet.FitToPage = true;
            string uploadPath = HttpContext.Current.Request.PhysicalApplicationPath + "Mfg/Temp/";
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            try
            {
                FileStream file = new FileStream(uploadPath + fileName + ".xls", FileMode.Create);
                hssfworkbook.Write(file);
                file.Close();
                var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);
                //return (basePath + "Temp/" + fileName + ".xls");
                string fileURL = HttpContext.Current.Server.MapPath((basePath + "Mfg/Temp/" + fileName + ".xls"));//文件路径,可用相对路径

                FileInfo fileInfo = new FileInfo(fileURL);
                Response.Clear();

                using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ELCO_ConnectionString"].ToString()))
                {
                    SqlCommand     cmd         = new SqlCommand();
                    SqlTransaction transaction = null;
                    try
                    {
                        conn.Open();
                        transaction     = conn.BeginTransaction();
                        cmd.Transaction = transaction;
                        cmd.Connection  = conn;
                        cmd.CommandType = CommandType.Text;
                        string str1 = string.Empty;
                        for (int i = 0; i < materialid.Length; i++)
                        {
                            str1            = "update  MFG_WIP_BKF_MTL_Record set Status='3',ConfirmTime=GETDATE(),ConfirmUser='******',PrintTime=GETDATE() where ID=" + materialid[i];
                            cmd.CommandText = str1;
                            cmd.ExecuteNonQuery();
                        }

                        Response.AddHeader("content-disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileInfo.Name.ToString())); //文件名
                        Response.AppendHeader("content-type", "application/x-msexcel");
                        Response.AddHeader("content-length", fileInfo.Length.ToString());                                                                   //文件大小
                        Response.ContentType     = "application/octet-stream";
                        Response.ContentEncoding = System.Text.Encoding.Default;
                        Response.WriteFile(fileURL);
                        Response.Flush();
                        Response.Close();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
Example #27
0
        /// <summary>
        /// 将DataTable导出到Excel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">仅文件名(非路径)</param>
        /// <returns>返回Excel文件绝对路径</returns>
        public void ExportDataSetToExcel(DataTable dt, string fileName, System.Web.HttpResponse Response)
        {
            #region 表头
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet hssfSheet = hssfworkbook.CreateSheet(fileName);
            hssfSheet.DefaultColumnWidth = 13;
            hssfSheet.SetColumnWidth(0, 25 * 256);
            hssfSheet.SetColumnWidth(3, 20 * 256);

            // 表头
            NPOI.SS.UserModel.IRow tagRow0 = hssfSheet.CreateRow(0);
            tagRow0.Height = 40 * 40;
            ICell cell0 = tagRow0.CreateCell(0);
            //设置单元格内容
            cell0.SetCellValue("力诺瑞特制造工厂");
            hssfSheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 7));

            NPOI.SS.UserModel.IRow tagRow1 = hssfSheet.CreateRow(1);
            tagRow1.Height = 20 * 20;
            ICell cell1 = tagRow1.CreateCell(0);
            //设置单元格内容
            cell1.SetCellValue("计划外领料单");
            hssfSheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 7));


            NPOI.SS.UserModel.ICellStyle tagStyle = hssfworkbook.CreateCellStyle();
            tagStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            tagStyle.VerticalAlignment = VerticalAlignment.Center;
            //tagStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            //tagStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            IFont font = hssfworkbook.CreateFont();
            font.FontHeightInPoints = 16;
            font.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            font.FontName           = "宋体";
            tagStyle.SetFont(font);//HEAD 样式
            cell0.CellStyle = tagStyle;
            NPOI.SS.UserModel.ICellStyle tagStyle1 = hssfworkbook.CreateCellStyle();
            tagStyle1.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            tagStyle1.VerticalAlignment = VerticalAlignment.Center;
            cell1.CellStyle             = tagStyle1;

            // 标题样式
            NPOI.SS.UserModel.ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.LeftBorderColor   = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.RightBorderColor  = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.TopBorderColor    = NPOI.HSSF.Util.HSSFColor.Black.Index;

            #endregion

            #region 表数据

            // 表数据
            for (int k = 0; k < 2; k++)
            {
                DataRow dr = dt.Rows[k];
                NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(k + 2);
                row.Height = 30 * 20;
                for (int i = 0; i < dt.Columns.Count; i += 2)
                {
                    row.CreateCell(i).SetCellValue(dr[i / 2].ToString());
                    row.GetCell(i).CellStyle = cellStyle;
                }
                row.CreateCell(1).SetCellValue("");
                row.GetCell(1).CellStyle = cellStyle;
                row.CreateCell(3).SetCellValue("");
                row.GetCell(3).CellStyle = cellStyle;
                row.CreateCell(5).SetCellValue("");
                row.GetCell(5).CellStyle = cellStyle;
                row.CreateCell(7).SetCellValue("");
                row.GetCell(7).CellStyle = cellStyle;
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 0, 1));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 2, 3));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 4, 5));
                hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 6, 7));
            }
            // 表数据
            for (int k = 2; k < dt.Rows.Count; k++)
            {
                if (k == dt.Rows.Count - 1)
                {
                    DataRow drlast = dt.Rows[k];
                    NPOI.SS.UserModel.IRow rowlast = hssfSheet.CreateRow(k + 2);
                    rowlast.Height = 30 * 20;
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        rowlast.CreateCell(i).SetCellValue(drlast[i].ToString());
                        rowlast.GetCell(i).CellStyle = cellStyle;
                    }
                    //hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 1, 7));
                }
                else
                {
                    DataRow dr = dt.Rows[k];
                    NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(k + 2);
                    row.Height = 30 * 20;

                    for (int i = 0; i < 4; i += 2)
                    {
                        row.CreateCell(i).SetCellValue(dr[i / 2].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }

                    for (int i = 4; i < dt.Columns.Count; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[i - 2].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                    row.CreateCell(1).SetCellValue("");
                    row.GetCell(1).CellStyle = cellStyle;
                    row.CreateCell(3).SetCellValue("");
                    row.GetCell(3).CellStyle = cellStyle;

                    #region 合并单元格
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 0, 1));
                    hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 2, 3));

                    #endregion
                }
            }

            //NPOI.SS.UserModel.IRow tagRow5 = hssfSheet.CreateRow(dt.Rows.Count + 5);
            //tagRow5.Height = 20 * 20;
            //ICell cell12 = tagRow5.CreateCell(0);
            ////设置单元格内容报告
            //cell12.SetCellValue("Rev: 1.0");
            //hssfSheet.AddMergedRegion(new CellRangeAddress(dt.Rows.Count + 5, dt.Rows.Count + 5, 0, 7));
            //cell12.CellStyle = TelNoStyle;
            #endregion


            hssfSheet.PrintSetup.NoColor   = true;
            hssfSheet.PrintSetup.Landscape = true;
            hssfSheet.PrintSetup.PaperSize = (short)PaperSize.A4;
            //是否自适应界面
            hssfSheet.FitToPage = true;
            string uploadPath = HttpContext.Current.Request.PhysicalApplicationPath + "Mfg/Temp/";
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            FileStream file = new FileStream(uploadPath + fileName + ".xls", FileMode.Create);
            hssfworkbook.Write(file);
            file.Close();
            var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);
            //return (basePath + "Temp/" + fileName + ".xls");
            string   fileURL  = HttpContext.Current.Server.MapPath((basePath + "Mfg/Temp/" + fileName + ".xls"));//文件路径,可用相对路径
            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);
        }
        public override void SendResponse(HttpResponse response)
        {
            CheckConnector();

            try
            {
                CheckRequest();
            }
            catch (ConnectorException connectorException)
            {
                response.AddHeader("X-CKFinder-Error", (connectorException.Number).ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }
            catch
            {
                response.AddHeader("X-CKFinder-Error", Errors.Unknown.ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            if (!Config.Current.Thumbnails.Enabled)
            {
                response.AddHeader("X-CKFinder-Error", Errors.ThumbnailsDisabled.ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            if (!CurrentFolder.CheckAcl(AccessControlRules.FileView))
            {
                response.AddHeader("X-CKFinder-Error", Errors.Unauthorized.ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            bool is304 = false;

            string fileName = HttpContext.Current.Request["FileName"];

            string thumbFilePath = Path.Combine(CurrentFolder.ThumbsServerPath, fileName.Replace("/", "\\"));

            if (!Connector.CheckFileName(fileName))
            {
                response.AddHeader("X-CKFinder-Error", Errors.InvalidRequest.ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            if (Config.Current.CheckIsHiddenFile(fileName))
            {
                response.AddHeader("X-CKFinder-Error", string.Format("{0} - Hidden folder", Errors.FileNotFound));
                response.StatusCode = 404;
                response.End();
                return;
            }

            // If the thumbnail file doesn't exists, create it now.
            if (!File.Exists(thumbFilePath))
            {
                string sourceFilePath = Path.Combine(CurrentFolder.ServerPath, fileName);

                if (!File.Exists(sourceFilePath))
                {
                    response.AddHeader("X-CKFinder-Error", Errors.FileNotFound.ToString());
                    response.StatusCode = 404;
                    response.End();
                    return;
                }

                ImageTools.ResizeImage(sourceFilePath, thumbFilePath, Config.Current.Thumbnails.MaxWidth, Config.Current.Thumbnails.MaxHeight, true, Config.Current.Thumbnails.Quality);
            }

            var thumbfile = new FileInfo(thumbFilePath);

            string eTag = thumbfile.LastWriteTime.Ticks.ToString("X") + "-" + thumbfile.Length.ToString("X");

            string chachedETag = Request.ServerVariables["HTTP_IF_NONE_MATCH"];
            if (!string.IsNullOrEmpty(chachedETag) && eTag == chachedETag)
                is304 = true;

            if (!is304)
            {
                string cachedTimeStr = Request.ServerVariables["HTTP_IF_MODIFIED_SINCE"];
                if (!string.IsNullOrEmpty(cachedTimeStr))
                {
                    try
                    {
                        DateTime cachedTime = DateTime.Parse(cachedTimeStr);

                        if (cachedTime >= thumbfile.LastWriteTime)
                            is304 = true;
                    }
                    catch
                    {
                        is304 = false;
                    }
                }
            }

            if (is304)
            {
                response.StatusCode = 304;
                response.End();
                return;
            }

            string thumbFileExt = Path.GetExtension(thumbFilePath).TrimStart('.').ToLower();

            if (thumbFilePath == ".jpg")
                response.ContentType = "image/jpeg";
            else
                response.ContentType = "image/" + thumbFileExt;

            response.Cache.SetETag(eTag);
            response.Cache.SetLastModified(thumbfile.LastWriteTime);
            response.Cache.SetCacheability(HttpCacheability.Private);

            response.WriteFile(thumbFilePath);
        }
Example #29
0
        /// <summary>
        /// 将DataTable导出到Excel
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">仅文件名(非路径)</param>
        /// <returns>返回Excel文件绝对路径</returns>
        public void ExportDataSetToExcel(DataTable dt, string fileName, System.Web.HttpResponse Response)
        {
            int dtcolunmnum = dt.Columns.Count;

            #region 表头
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();

            NPOI.SS.UserModel.ISheet hssfSheet = hssfworkbook.CreateSheet(fileName);
            hssfSheet.DefaultColumnWidth = 13;
            //hssfSheet.SetColumnWidth(0, 20 * 256);
            //hssfSheet.SetColumnWidth(3, 20 * 256);

            // 表头
            NPOI.SS.UserModel.IRow tagRow0 = hssfSheet.CreateRow(0);
            tagRow0.Height = 40 * 40;
            ICell cell0 = tagRow0.CreateCell(0);
            //设置单元格内容
            cell0.SetCellValue("力诺瑞特制造工厂");
            hssfSheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtcolunmnum - 1));

            NPOI.SS.UserModel.IRow tagRow1 = hssfSheet.CreateRow(1);
            tagRow1.Height = 30 * 20;
            ICell cell1 = tagRow1.CreateCell(0);
            //设置单元格内容
            cell1.SetCellValue(fileName);
            hssfSheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, dtcolunmnum - 1));

            // 标题样式
            NPOI.SS.UserModel.ICellStyle tagStyle = hssfworkbook.CreateCellStyle();
            tagStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            tagStyle.VerticalAlignment = VerticalAlignment.Center;
            IFont font = hssfworkbook.CreateFont();
            font.FontHeightInPoints = 16;
            font.Boldweight         = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            font.FontName           = "宋体";
            tagStyle.SetFont(font);//HEAD 样式
            cell0.CellStyle = tagStyle;
            NPOI.SS.UserModel.ICellStyle tagStyle1 = hssfworkbook.CreateCellStyle();
            tagStyle1.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            tagStyle1.VerticalAlignment = VerticalAlignment.Center;
            cell1.CellStyle             = tagStyle1;

            NPOI.SS.UserModel.ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment         = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderBottom      = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderLeft        = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.LeftBorderColor   = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderRight       = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.RightBorderColor  = NPOI.HSSF.Util.HSSFColor.Black.Index;
            cellStyle.BorderTop         = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.TopBorderColor    = NPOI.HSSF.Util.HSSFColor.Black.Index;

            #endregion

            // 表数据
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                DataRow drlast = dt.Rows[k];
                NPOI.SS.UserModel.IRow rowlast = hssfSheet.CreateRow(k + 2);
                rowlast.Height = 30 * 20;

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    rowlast.CreateCell(i).SetCellValue(drlast[i].ToString());
                    rowlast.GetCell(i).CellStyle = cellStyle;
                }
            }

            // 表数据
            //for (int k = 0; k < dt.Rows.Count; k++)
            //{
            //    hssfSheet.AutoSizeColumn(k);
            //}

            //获取当前列的宽度,然后对比本列的长度,取最大值
            for (int columnNum = 0; columnNum <= dt.Columns.Count; columnNum++)
            {
                int columnWidth = hssfSheet.GetColumnWidth(columnNum) / 256;
                for (int rowNum = 1; rowNum <= hssfSheet.LastRowNum; rowNum++)
                {
                    IRow currentRow;
                    //当前行未被使用过
                    if (hssfSheet.GetRow(rowNum) == null)
                    {
                        currentRow = hssfSheet.CreateRow(rowNum);
                    }
                    else
                    {
                        currentRow = hssfSheet.GetRow(rowNum);
                    }

                    if (currentRow.GetCell(columnNum) != null)
                    {
                        ICell currentCell = currentRow.GetCell(columnNum);
                        int   length      = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                        if (columnWidth < length)
                        {
                            columnWidth = length;
                        }
                    }
                }
                hssfSheet.SetColumnWidth(columnNum, columnWidth * 256);
            }

            hssfSheet.PrintSetup.NoColor   = true;
            hssfSheet.PrintSetup.Landscape = true;
            hssfSheet.PrintSetup.PaperSize = (short)PaperSize.A4;

            //是否自适应界面
            hssfSheet.FitToPage = true;

            //保存excel文件
            string uploadPath = HttpContext.Current.Request.PhysicalApplicationPath + "Report/Temp/";
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }
            FileStream file = new FileStream(uploadPath + fileName + ".xls", FileMode.Create);
            hssfworkbook.Write(file);
            file.Close();
            var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);
            //return (basePath + "Temp/" + fileName + ".xls");
            string   fileURL  = HttpContext.Current.Server.MapPath((basePath + "Report/Temp/" + fileName + ".xls"));//文件路径,可用相对路径
            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);
        }
        /// <summary>
        /// Writes file to response.
        /// </summary>
        public void DownloadFile(String path, String localFileName, String originalFileName,
            String contentType, HttpResponse response)
        {
            if (!System.IO.File.Exists(path + localFileName))
            {
                return;
            }
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType = contentType;
            response.AddHeader("content-disposition",
                               "attachment; filename=" + originalFileName);

            response.WriteFile(path + localFileName);
            response.End();
        }
Example #31
0
        private void ExecuteInternal(IHttpHandler handler, TextWriter writer, bool preserveForm, bool setPreviousPage, VirtualPath path, VirtualPath filePath, string physPath, Exception error, string queryStringOverride)
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }
            HttpRequest         request             = this._context.Request;
            HttpResponse        response            = this._context.Response;
            HttpApplication     applicationInstance = this._context.ApplicationInstance;
            HttpValueCollection form   = null;
            VirtualPath         path2  = null;
            string     queryStringText = null;
            TextWriter writer2         = null;
            AspNetSynchronizationContext syncContext = null;

            this.VerifyTransactionFlow(handler);
            this._context.PushTraceContext();
            this._context.SetCurrentHandler(handler);
            bool enabled = this._context.SyncContext.Enabled;

            this._context.SyncContext.Disable();
            try
            {
                try
                {
                    this._context.ServerExecuteDepth++;
                    path2 = request.SwitchCurrentExecutionFilePath(filePath);
                    if (!preserveForm)
                    {
                        form = request.SwitchForm(new HttpValueCollection());
                        if (queryStringOverride == null)
                        {
                            queryStringOverride = string.Empty;
                        }
                    }
                    if (queryStringOverride != null)
                    {
                        queryStringText         = request.QueryStringText;
                        request.QueryStringText = queryStringOverride;
                    }
                    if (writer != null)
                    {
                        writer2 = response.SwitchWriter(writer);
                    }
                    Page page = handler as Page;
                    if (page != null)
                    {
                        if (setPreviousPage)
                        {
                            page.SetPreviousPage(this._context.PreviousHandler as Page);
                        }
                        Page page2 = this._context.Handler as Page;
                        if ((page2 != null) && page2.SmartNavigation)
                        {
                            page.SmartNavigation = true;
                        }
                        if (page is IHttpAsyncHandler)
                        {
                            syncContext = this._context.InstallNewAspNetSynchronizationContext();
                        }
                    }
                    if (((handler is StaticFileHandler) || (handler is DefaultHttpHandler)) && !DefaultHttpHandler.IsClassicAspRequest(filePath.VirtualPathString))
                    {
                        try
                        {
                            response.WriteFile(physPath);
                        }
                        catch
                        {
                            error = new HttpException(0x194, string.Empty);
                        }
                    }
                    else if (!(handler is Page))
                    {
                        error = new HttpException(0x194, string.Empty);
                    }
                    else
                    {
                        if (handler is IHttpAsyncHandler)
                        {
                            bool isInCancellablePeriod = this._context.IsInCancellablePeriod;
                            if (isInCancellablePeriod)
                            {
                                this._context.EndCancellablePeriod();
                            }
                            try
                            {
                                IHttpAsyncHandler handler2 = (IHttpAsyncHandler)handler;
                                IAsyncResult      result   = handler2.BeginProcessRequest(this._context, null, null);
                                if (!result.IsCompleted)
                                {
                                    bool flag3 = false;
                                    try
                                    {
                                        try
                                        {
                                        }
                                        finally
                                        {
                                            Monitor.Exit(applicationInstance);
                                            flag3 = true;
                                        }
                                        WaitHandle asyncWaitHandle = result.AsyncWaitHandle;
                                        if (asyncWaitHandle == null)
                                        {
                                            goto Label_0210;
                                        }
                                        asyncWaitHandle.WaitOne();
                                        goto Label_0226;
Label_020A:
                                        Thread.Sleep(1);
Label_0210:
                                        if (!result.IsCompleted)
                                        {
                                            goto Label_020A;
                                        }
                                    }
                                    finally
                                    {
                                        if (flag3)
                                        {
                                            Monitor.Enter(applicationInstance);
                                        }
                                    }
                                }
Label_0226:
                                try
                                {
                                    handler2.EndProcessRequest(result);
                                }
                                catch (Exception exception)
                                {
                                    error = exception;
                                }
                                goto Label_0306;
                            }
                            finally
                            {
                                if (isInCancellablePeriod)
                                {
                                    this._context.BeginCancellablePeriod();
                                }
                            }
                        }
                        using (new DisposableHttpContextWrapper(this._context))
                        {
                            try
                            {
                                handler.ProcessRequest(this._context);
                            }
                            catch (Exception exception2)
                            {
                                error = exception2;
                            }
                        }
                    }
                }
                finally
                {
                    this._context.ServerExecuteDepth--;
                    this._context.RestoreCurrentHandler();
                    if (writer2 != null)
                    {
                        response.SwitchWriter(writer2);
                    }
                    if ((queryStringOverride != null) && (queryStringText != null))
                    {
                        request.QueryStringText = queryStringText;
                    }
                    if (form != null)
                    {
                        request.SwitchForm(form);
                    }
                    request.SwitchCurrentExecutionFilePath(path2);
                    if (syncContext != null)
                    {
                        this._context.RestoreSavedAspNetSynchronizationContext(syncContext);
                    }
                    if (enabled)
                    {
                        this._context.SyncContext.Enable();
                    }
                    this._context.PopTraceContext();
                }
            }
            catch
            {
                throw;
            }
Label_0306:
            if (error == null)
            {
                return;
            }
            if ((error is HttpException) && (((HttpException)error).GetHttpCode() != 500))
            {
                error = null;
            }
            if (path != null)
            {
                throw new HttpException(System.Web.SR.GetString("Error_executing_child_request_for_path", new object[] { path }), error);
            }
            throw new HttpException(System.Web.SR.GetString("Error_executing_child_request_for_handler", new object[] { handler.GetType().ToString() }), error);
        }
Example #32
0
		///////////////////////////////////////////////////////////////////////
		public static void print_bug (HttpResponse Response, DataRow dr, IIdentity identity, bool include_style, bool images_inline, bool history_inline, bool internal_posts)
		{

			int bugid = Convert.ToInt32(dr["id"]);
			string string_bugid = Convert.ToString(bugid);

            if (include_style) // when sending emails
            {
                Response.Write("\n<style>\n");

                // If this file exists, use it.

                string css_for_email_file = Util.GetAbsolutePath("custom\\btnet_css_for_email.css");

                try
                {
                    if (System.IO.File.Exists(css_for_email_file))
                    {
                        Response.WriteFile(css_for_email_file);
					    Response.Write("\n");
                    }
                    else
                    {
                        css_for_email_file = Util.GetAbsolutePath("btnet_base.css");
                        Response.WriteFile(css_for_email_file);
					    Response.Write("\n");
                        css_for_email_file = Util.GetAbsolutePath("custom\\btnet_custom.css");
                        if (System.IO.File.Exists(css_for_email_file))
                        {
                            Response.WriteFile(css_for_email_file);
                            Response.Write("\n");
                        }
                    }
                }
                catch (Exception e)
                {
                    btnet.Util.write_to_log("Exception trying to read css file for email \"" 
                        + css_for_email_file
                        + "\":" 
                        + e.Message);
                }

                // underline links in the emails to make them more obvious
                Response.Write("\na {text-decoration: underline; }");
                Response.Write("\na:visited {text-decoration: underline; }");
                Response.Write("\na:hover {text-decoration: underline; }");
                Response.Write("\n</style>\n");
            }

			Response.Write ("<body style='background:white'>");
			Response.Write ("<b>"
				+ btnet.Util.capitalize_first_letter(btnet.Util.get_setting("SingularBugLabel","bug"))
				+ " ID:&nbsp;<a href="
				+ btnet.Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
				+ "edit_bug.aspx?id="
				+ string_bugid
				+ ">"
				+ string_bugid
				+ "</a>");

            if (btnet.Util.get_setting("EnableMobile", "0") == "1")
            {
                Response.Write(
                    "&nbsp;&nbsp;&nbsp;&nbsp;Mobile link:&nbsp;<a href="
                    + btnet.Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
                    + "mbug.aspx?id="
                    + string_bugid
                    + ">"
                    + btnet.Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
                    + "mbug.aspx?id="
                    + string_bugid
                    + "</a>");

            }

            Response.Write("<br>");

			Response.Write ("Short desc:&nbsp;<a href="
				+ btnet.Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
				+ "edit_bug.aspx?id="
				+ string_bugid
				+ ">"
				+ HttpUtility.HtmlEncode((string)dr["short_desc"])
				+ "</a></b><p>");

			// start of the table with the bug fields
			Response.Write ("\n<table border=1 cellpadding=3 cellspacing=0>");
            Response.Write("\n<tr><td>Last changed by<td>"
				+ format_username((string)dr["last_updated_user"],(string)dr["last_updated_fullname"])
				+ "&nbsp;");
            Response.Write("\n<tr><td>Reported By<td>"
				+ format_username((string)dr["reporter"],(string)dr["reporter_fullname"])
				+ "&nbsp;");
            Response.Write("\n<tr><td>Reported On<td>" + btnet.Util.format_db_date_and_time(dr["reported_date"]) + "&nbsp;");

            if (identity.GetTagsFieldPermissionLevel() > 0)
	            Response.Write("\n<tr><td>Tags<td>" + dr["bg_tags"] + "&nbsp;");

            if (identity.GetProjectFieldPermissionLevel() > 0)
	            Response.Write("\n<tr><td>Project<td>" + dr["current_project"] + "&nbsp;");

            if (identity.GetOrgFieldPermissionLevel() > 0)
	            Response.Write("\n<tr><td>Organization<td>" + dr["og_name"] + "&nbsp;");

            if (identity.GetCategoryFieldPermissionLevel()> 0)
	            Response.Write("\n<tr><td>Category<td>" + dr["category_name"] + "&nbsp;");

            if (identity.GetPriorityFieldPermissionLevel() > 0)
	            Response.Write("\n<tr><td>Priority<td>" + dr["priority_name"] + "&nbsp;");

            if (identity.GetAssignedToFieldPermissionLevel() > 0)
	            Response.Write("\n<tr><td>Assigned<td>"
					+ format_username((string)dr["assigned_to_username"],(string)dr["assigned_to_fullname"])
					+ "&nbsp;");

            if (identity.GetStatusFieldPermissionLevel() > 0)
            	Response.Write("\n<tr><td>Status<td>" + dr["status_name"] + "&nbsp;");

			if (identity.GetUdfFieldPermissionLevel() > 0)
				if (btnet.Util.get_setting("ShowUserDefinedBugAttribute","1") == "1")
				{
					Response.Write("\n<tr><td>"
						+ btnet.Util.get_setting("UserDefinedBugAttributeName","YOUR ATTRIBUTE")
						+ "<td>"
						+ dr["udf_name"] + "&nbsp;");
				}

			// Get custom column info  (There's an inefficiency here - we just did this
			// same call in get_bug_datarow...)				

			// create project custom dropdowns
			if ((int)dr["project"] != 0)
			{

				var sql = new SQLString(@"select
					isnull(pj_enable_custom_dropdown1,0) [pj_enable_custom_dropdown1],
					isnull(pj_enable_custom_dropdown2,0) [pj_enable_custom_dropdown2],
					isnull(pj_enable_custom_dropdown3,0) [pj_enable_custom_dropdown3],
					isnull(pj_custom_dropdown_label1,'') [pj_custom_dropdown_label1],
					isnull(pj_custom_dropdown_label2,'') [pj_custom_dropdown_label2],
					isnull(pj_custom_dropdown_label3,'') [pj_custom_dropdown_label3]
					from projects where pj_id = @pj");

				sql = sql.AddParameterWithValue("pj", Convert.ToString((int)dr["project"]));

				DataRow project_dr = btnet.DbUtil.get_datarow(sql);


				if (project_dr != null)
				{
					for (int i = 1; i < 4; i++)
					{
						if ((int)project_dr["pj_enable_custom_dropdown" + Convert.ToString(i)] == 1)
						{
                            Response.Write("\n<tr><td>");
							Response.Write (project_dr["pj_custom_dropdown_label" + Convert.ToString(i)]);
							Response.Write ("<td>");
							Response.Write (dr["bg_project_custom_dropdown_value"  + Convert.ToString(i)]);
							Response.Write ("&nbsp;");
						}
					}
				}
			}



			Response.Write("\n</table><p>"); // end of the table with the bug fields

			// Relationships
			if (btnet.Util.get_setting("EnableRelationships", "0") == "1")
			{
				write_relationships(Response, bugid);
			}

			// Tasks
			if (btnet.Util.get_setting("EnableTasks", "0") == "1")
			{
				write_tasks(Response, bugid);
			}


            DataSet ds_posts = get_bug_posts(bugid, identity.GetIsExternalUser(), history_inline);
			write_posts (
                ds_posts,
                Response, 
                bugid, 
                0, 
                false, /* don't write links */
                images_inline, 
                history_inline, 
                internal_posts, identity);

			Response.Write ("</body>");

		}
Example #33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string projectID = (Page.RouteData.Values["project_id"] as string);

        string repsIdsToCreate = (Page.RouteData.Values["reports"] as string);

        // Validar 1 o más arboles
        List <Project_Organisms> project_Organisms = new List <Project_Organisms>();

        if (repsIdsToCreate == "a")
        {
            project_Organisms = new Project_OrganismsBLL().GetProject_OrganismsByProjectID(Convert.ToInt32(projectID));
        }
        else if (repsIdsToCreate == "b")
        {
            project_Organisms = new Project_OrganismsBLL().GetProject_OrganismsByProjectID(Convert.ToInt32(projectID)).Where(i => i.TreeDetails.First().ActionProposedID == 2 || i.TreeDetails.First().ActionProposedID == 2).ToList();
        }
        else
        {
            return;
        }

        Eisk.BusinessEntities.Project project = new ProjectBLL().GetProjectByProjectID(Convert.ToInt32(projectID));

        string name = Reports.Translate(project.ProjectInfoes.First().ProjectName).Replace(" ", "_");

        if (repsIdsToCreate == "b")
        {
            name += "(Proteccion_Poda)";
        }

        string path = System.Web.HttpContext.Current.Server.MapPath(@System.Configuration.ConfigurationManager.AppSettings["ProjectsRoot"]) + projectID.ToString();

        // check folder exists
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            System.IO.File.WriteAllText(path + "/" + name + ".csv", "");
        }

        FileInfo newFile = new FileInfo(path + @"\" + name + ".csv");

        File.Delete(path + @"\" + name + ".csv");

        foreach (Project_Organisms project_Organism in project_Organisms)
        {
            AddTreeToAutoCADImportFile(project_Organism, path + @"\" + name + ".csv");
        }

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "application/ms-excel";
        response.AddHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
        response.WriteFile(path + @"/" + name + ".csv");

        response.End();
    }
Example #34
0
        /// <summary>
        /// Downloads the given file on the client's machine
        /// </summary>
        /// <param name="currentResponse">the response object of the current request (always use this.Response)</param>
        /// <param name="FileName">File name</param>
        /// <param name="FilePath">File physical path</param>
        /// <param name="forceDownload">if to force the download dialog box to show</param>
        /// <param name="IsVideo">if the file to be downloaded is a video strem</param>
        public static void DownloadFile(HttpResponse currentResponse, string FileName, string FilePath, bool forceDownload, bool IsVideo)
        {
            string name = Path.GetFileName(FileName);
            string ext = Path.GetExtension(FileName);
            string type = string.Empty;

            // set known types based on file extension
            if (!string.IsNullOrEmpty(ext))
            {
                if (IsVideo)
                {
                    switch (ext.ToLower())
                    {
                        case CommonStrings.Ext_rm:
                            type = CommonStrings.Mime_ramAudio;
                            break;

                        case CommonStrings.Ext_ram:
                            type = CommonStrings.Mime_ramVideo;
                            break;

                        default:
                            type = CommonStrings.Mime_ramAudio;
                            break;
                    }
                }
                else
                {
                    switch (ext.ToLower())
                    {
                        case CommonStrings.Ext_htm:
                        case CommonStrings.Ext_html:
                            type = CommonStrings.Mime_HTML;
                            break;

                        case CommonStrings.Ext_txt:
                            type = CommonStrings.Mime_Text;
                            break;

                        case CommonStrings.Ext_doc:
                        case CommonStrings.Ext_rtf:
                            type = CommonStrings.Mime_MSWord;
                            break;

                        case CommonStrings.Ext_rm:
                            type = CommonStrings.Mime_rmAudio;
                            break;

                        case CommonStrings.Ext_ram:
                            type = CommonStrings.Mime_ramAudio;
                            break;

                        default:
                            type = CommonStrings.Mime_Text;
                            break;
                    }
                }
            }

            if (forceDownload)
            {
                currentResponse.AppendHeader(CommonStrings.ContentDisposition, string.Concat(CommonStrings.Attachment,
                                                                                             CommonStrings.SemiColon,
                                                                                             CommonStrings.Space,
                                                                                             CommonStrings.FileName,
                                                                                             CommonStrings.EqualSymbol,
                                                                                             name));
            }

            if (!string.IsNullOrEmpty(type))
            {
                currentResponse.ContentType = type;
            }

            currentResponse.WriteFile(FilePath);
        }
Example #35
0
		/// <summary>
		/// 渡された HttpResponse にレスポンスを書き込みます。
		/// </summary>
		public override void WriteResponse(HttpResponse response){
			WriteResponseHeader(response);
			WriteAdditionalHeader(response);
			SetLastModified(response);
			response.WriteFile(FileSource.FullName);
		}
Example #36
0
 public override void WriteFile(string filename)
 {
     w.WriteFile(filename);
 }
Example #37
0
        public void ProcessRequest(HttpContext context)
        {
            string picPath          = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter", "chartExport");
            string fileName         = Path.ChangeExtension(picPath, "svg");
            string downloadFileName = context.Request.Params["type"].ToString() + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + context.Request.Params["output_format"].ToString();
            string svg = (context.Request.Params["data"].ToString());

            try
            {
                string           newSvg = Uri.UnescapeDataString(svg);
                Process          p      = new Process();
                ProcessStartInfo info   = new ProcessStartInfo();
                info.FileName = "cmd.exe";
                info.RedirectStandardInput = true;
                info.UseShellExecute       = false;
                p.StartInfo = info;
                p.Start();

                /*var stream = newSvg.ToString();
                 *
                 * using (StreamWriter sw = new StreamWriter(fileName))
                 * {
                 *  sw.WriteLine(stream);
                 * }*/
                File.WriteAllText(fileName, newSvg);
                fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);

                using (StreamWriter sw = p.StandardInput)
                {
                    if (sw.BaseStream.CanWrite)
                    {
                        sw.WriteLine(context.Request.PhysicalApplicationPath.Split(':')[0] + ":");
                        sw.WriteLine("cd " + Path.Combine(context.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter"));
                        if (context.Request.Params["output_format"].ToString() == "pdf")
                        {
                            sw.WriteLine("rsvg-convert -o " + downloadFileName + " -b white  -f pdf chartExport.svg");
                        }
                        else if (context.Request.Params["output_format"].ToString() == "jpg")
                        {
                            sw.WriteLine("rsvg-convert -o " + downloadFileName + " -b white   -f jpg chartExport.svg");
                        }

                        else
                        {
                            sw.WriteLine("rsvg-convert -o " + downloadFileName + " -b white -f png chartExport.svg");
                        }
                    }
                    sw.Close();
                    sw.Dispose();
                }

                Thread.Sleep(900);

                System.Web.HttpResponse response = context.Response;
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", "attachment; filename=" + downloadFileName + ";");
                response.WriteFile(Path.Combine(context.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter", downloadFileName));
                response.Flush();
                response.Close();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                File.Delete(Path.Combine(context.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter", downloadFileName));
            }
        }
Example #38
0
		public void WriteFile_StringBool_Deny_FileIOPermission ()
		{
			HttpResponse response = new HttpResponse (writer);
			response.WriteFile (fname, false);
		}
Example #39
0
		///////////////////////////////////////////////////////////////////////
		public static void print_bug (HttpResponse Response, DataRow dr, Security security, 
            bool include_style, 
            bool images_inline, 
            bool history_inline,
            bool internal_posts)
		{

			int bugid = Convert.ToInt32(dr["id"]);
			string string_bugid = Convert.ToString(bugid);

            if (include_style) // when sending emails
            {
                Response.Write("\n<style>\n");

                // If this file exists, use it.

                string map_path = (string) HttpRuntime.Cache["MapPath"];

                string css_for_email_file = map_path + "\\custom\\btnet_css_for_email.css";

                try
                {
                    if (System.IO.File.Exists(css_for_email_file))
                    {
                        Response.WriteFile(css_for_email_file);
					    Response.Write("\n");
                    }
                    else
                    {
                        css_for_email_file = map_path + "\\btnet_base.css";
                        Response.WriteFile(css_for_email_file);
					    Response.Write("\n");
                        css_for_email_file = map_path + "\\custom\\" + "btnet_custom.css";
                        if (System.IO.File.Exists(css_for_email_file))
                        {
                            Response.WriteFile(css_for_email_file);
                            Response.Write("\n");
                        }
                    }
                }
                catch (Exception e)
                {
                    btnet.Util.write_to_log("Exception trying to read css file for email \"" 
                        + css_for_email_file
                        + "\":" 
                        + e.Message);
                }

                // underline links in the emails to make them more obvious
                Response.Write("\na {text-decoration: underline; }");
                Response.Write("\na:visited {text-decoration: underline; }");
                Response.Write("\na:hover {text-decoration: underline; }");
                Response.Write("\n</style>\n");
            }

			Response.Write ("<body style='background:white'>");
			Response.Write ("<b>"
				+ btnet.Util.capitalize_first_letter(btnet.Util.get_setting("SingularBugLabel","bug"))
				+ " ID:&nbsp;<a href="
				+ btnet.Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
				+ "edit_bug.aspx?id="
				+ string_bugid
				+ ">"
				+ string_bugid
				+ "</a><br>");

			Response.Write ("Short desc:&nbsp;<a href="
				+ btnet.Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
				+ "edit_bug.aspx?id="
				+ string_bugid
				+ ">"
				+ HttpUtility.HtmlEncode((string)dr["short_desc"])
				+ "</a></b><p>");

			// start of the table with the bug fields
			Response.Write ("\n<table border=1 cellpadding=3 cellspacing=0>");
            Response.Write("\n<tr><td>Last changed by<td>"
				+ format_username((string)dr["last_updated_user"],(string)dr["last_updated_fullname"])
				+ "&nbsp;");
            Response.Write("\n<tr><td>Reported By<td>"
				+ format_username((string)dr["reporter"],(string)dr["reporter_fullname"])
				+ "&nbsp;");
            Response.Write("\n<tr><td>Reported On<td>" + btnet.Util.format_db_date_and_time(dr["reported_date"]) + "&nbsp;");

            if (security.user.tags_field_permission_level > 0)
	            Response.Write("\n<tr><td>Tags<td>" + dr["bg_tags"] + "&nbsp;");

            if (security.user.project_field_permission_level > 0)
	            Response.Write("\n<tr><td>Project<td>" + dr["current_project"] + "&nbsp;");

            if (security.user.org_field_permission_level > 0)
	            Response.Write("\n<tr><td>Organization<td>" + dr["og_name"] + "&nbsp;");

            if (security.user.category_field_permission_level > 0)
	            Response.Write("\n<tr><td>Category<td>" + dr["category_name"] + "&nbsp;");

            if (security.user.priority_field_permission_level > 0)
	            Response.Write("\n<tr><td>Priority<td>" + dr["priority_name"] + "&nbsp;");

            if (security.user.assigned_to_field_permission_level > 0)
	            Response.Write("\n<tr><td>Assigned<td>"
					+ format_username((string)dr["assigned_to_username"],(string)dr["assigned_to_fullname"])
					+ "&nbsp;");

            if (security.user.status_field_permission_level > 0)
            	Response.Write("\n<tr><td>Status<td>" + dr["status_name"] + "&nbsp;");

			if (security.user.udf_field_permission_level > 0)
				if (btnet.Util.get_setting("ShowUserDefinedBugAttribute","1") == "1")
				{
					Response.Write("\n<tr><td>"
						+ btnet.Util.get_setting("UserDefinedBugAttributeName","YOUR ATTRIBUTE")
						+ "<td>"
						+ dr["udf_name"] + "&nbsp;");
				}

			// Get custom column info  (There's an inefficiency here - we just did this
			// same call in get_bug_datarow...)

			
			DataSet ds_custom_cols = btnet.Util.get_custom_columns();


			// Show custom columns

			foreach (DataRow drcc in ds_custom_cols.Tables[0].Rows)
			{
                string column_name = (string) drcc["name"];

                if (security.user.dict_custom_field_permission_level[column_name] == Security.PERMISSION_NONE)
                {
                    continue;
                }

                Response.Write("\n<tr><td>");
				Response.Write (column_name);
				Response.Write ("<td>");

				if ((string)drcc["datatype"] == "datetime")
				{
					object dt = dr[(string)drcc["name"]];

					Response.Write (btnet.Util.format_db_date_and_time(dt));
				}
				else
				{
					string s = "";

					if ((string)drcc["dropdown type"] == "users")
					{
						object obj = dr[(string)drcc["name"]];
						if (obj.GetType().ToString() != "System.DBNull")
						{
							int userid = Convert.ToInt32(obj);
							if (userid != 0)
							{
								string sql_get_username = "******";
								s = (string) btnet.DbUtil.execute_scalar(sql_get_username.Replace("$1", Convert.ToString(userid)));
							}
						}
					}
					else
					{
						s = Convert.ToString(dr[(string)drcc["name"]]);
					}

					s = HttpUtility.HtmlEncode(s);
					s = s.Replace("\n","<br>");
					s = s.Replace("  ","&nbsp; ");
					s = s.Replace("\t","&nbsp;&nbsp;&nbsp;&nbsp;");
					Response.Write (s);
				}
				Response.Write ("&nbsp;");
			}


			// create project custom dropdowns
			if ((int)dr["project"] != 0)
			{

				string sql = @"select
					isnull(pj_enable_custom_dropdown1,0) [pj_enable_custom_dropdown1],
					isnull(pj_enable_custom_dropdown2,0) [pj_enable_custom_dropdown2],
					isnull(pj_enable_custom_dropdown3,0) [pj_enable_custom_dropdown3],
					isnull(pj_custom_dropdown_label1,'') [pj_custom_dropdown_label1],
					isnull(pj_custom_dropdown_label2,'') [pj_custom_dropdown_label2],
					isnull(pj_custom_dropdown_label3,'') [pj_custom_dropdown_label3]
					from projects where pj_id = $pj";

				sql = sql.Replace("$pj", Convert.ToString((int)dr["project"]));

				DataRow project_dr = btnet.DbUtil.get_datarow(sql);


				if (project_dr != null)
				{
					for (int i = 1; i < 4; i++)
					{
						if ((int)project_dr["pj_enable_custom_dropdown" + Convert.ToString(i)] == 1)
						{
                            Response.Write("\n<tr><td>");
							Response.Write (project_dr["pj_custom_dropdown_label" + Convert.ToString(i)]);
							Response.Write ("<td>");
							Response.Write (dr["bg_project_custom_dropdown_value"  + Convert.ToString(i)]);
							Response.Write ("&nbsp;");
						}
					}
				}
			}



			Response.Write("\n</table><p>"); // end of the table with the bug fields

			// Relationships
			if (btnet.Util.get_setting("EnableRelationships", "0") == "1")
			{
				write_relationships(Response, bugid);
			}

			// Tasks
			if (btnet.Util.get_setting("EnableTasks", "0") == "1")
			{
				write_tasks(Response, bugid);
			}


            DataSet ds_posts = get_bug_posts(bugid, security.user.external_user, history_inline);
			write_posts (
                ds_posts,
                Response, 
                bugid, 
                0, 
                false, /* don't write links */
                images_inline, 
                history_inline, 
                internal_posts,
                security.user);

			Response.Write ("</body>");

		}
Example #40
0
		public void WriteFile_PermitOnly_FileIOPermission ()
		{
			HttpResponse response = new HttpResponse (writer);
			response.WriteFile (fname);
			response.WriteFile (fname, false);
			response.WriteFile (fname, 0, 0);
		}
        public override void SendResponse(System.Web.HttpResponse response)
        {
            this.CheckConnector();

            try
            {
                this.CheckRequest();
            }
            catch (ConnectorException connectorException)
            {
                response.AddHeader("X-CKFinder-Error", (connectorException.Number).ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }
            catch
            {
                response.AddHeader("X-CKFinder-Error", ((int)Errors.Unknown).ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            if (!Config.Current.Thumbnails.Enabled)
            {
                response.AddHeader("X-CKFinder-Error", ((int)Errors.ThumbnailsDisabled).ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileView))
            {
                response.AddHeader("X-CKFinder-Error", ((int)Errors.Unauthorized).ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            bool is304 = false;

            string fileName = HttpContext.Current.Request["FileName"];

            string thumbFilePath = System.IO.Path.Combine(this.CurrentFolder.ThumbsServerPath, fileName);

            if (!Connector.CheckFileName(fileName))
            {
                response.AddHeader("X-CKFinder-Error", ((int)Errors.InvalidRequest).ToString());
                response.StatusCode = 403;
                response.End();
                return;
            }

            if (Config.Current.CheckIsHiddenFile(fileName))
            {
                response.AddHeader("X-CKFinder-Error", ((int)Errors.FileNotFound).ToString() + " - Hidden folder");
                response.StatusCode = 404;
                response.End();
                return;
            }

            // If the thumbnail file doesn't exists, create it now.
            if (!System.IO.File.Exists(thumbFilePath))
            {
                string sourceFilePath = System.IO.Path.Combine(this.CurrentFolder.ServerPath, fileName);

                if (!System.IO.File.Exists(sourceFilePath))
                {
                    response.AddHeader("X-CKFinder-Error", ((int)Errors.FileNotFound).ToString());
                    response.StatusCode = 404;
                    response.End();
                    return;
                }

                ImageTools.ResizeImage(sourceFilePath, thumbFilePath, Config.Current.Thumbnails.MaxWidth, Config.Current.Thumbnails.MaxHeight, true, Config.Current.Thumbnails.Quality);
            }

            System.IO.FileInfo thumbfile = new System.IO.FileInfo(thumbFilePath);

            string eTag = thumbfile.LastWriteTime.Ticks.ToString("X") + "-" + thumbfile.Length.ToString("X");

            string chachedETag = Request.ServerVariables["HTTP_IF_NONE_MATCH"];

            if (chachedETag != null && chachedETag.Length > 0 && eTag == chachedETag)
            {
                is304 = true;
            }

            if (!is304)
            {
                string cachedTimeStr = Request.ServerVariables["HTTP_IF_MODIFIED_SINCE"];
                if (cachedTimeStr != null && cachedTimeStr.Length > 0)
                {
                    try
                    {
                        DateTime cachedTime = DateTime.Parse(cachedTimeStr);

                        if (cachedTime >= thumbfile.LastWriteTime)
                        {
                            is304 = true;
                        }
                    }
                    catch
                    {
                        is304 = false;
                    }
                }
            }

            if (is304)
            {
                response.StatusCode = 304;
                response.End();
                return;
            }

            string thumbFileExt = System.IO.Path.GetExtension(thumbFilePath).TrimStart('.').ToLower();

            if (thumbFilePath == ".jpg")
            {
                response.ContentType = "image/jpeg";
            }
            else
            {
                response.ContentType = "image/" + thumbFileExt;
            }

            response.Cache.SetETag(eTag);
            response.Cache.SetLastModified(thumbfile.LastWriteTime);
            response.Cache.SetCacheability(HttpCacheability.Private);

            response.WriteFile(thumbFilePath);
        }
 public override void WriteFile(string filename)
 {
     _httpResponse.WriteFile(filename);
 }
Example #43
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void Compress(HttpRequest request, HttpResponse response)
        {
            Encoding encoding = Encoding.GetEncoding("windows-1252");
            string enc, cacheFile = null, cacheKey = null, content = "";
            StringWriter writer = new StringWriter();
            byte[] buff = new byte[1024];
            GZipOutputStream gzipStream;
            bool supportsGzip;

            // Set response headers
            response.ContentType = "text/css";
            response.Charset = this.charset;
            response.Buffer = false;

            // Setup cache
            response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset));

            // Check if it supports gzip
            enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower();
            supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null;
            enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip";

            // Setup cache info
            if (this.diskCache) {
                cacheKey = "";

                foreach (CSSCompressItem item in this.items) {
                    // Get last mod
                    if (item.Type == CSSItemType.File) {
                        DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value));

                        if (fileMod > this.lastUpdate)
                            this.lastUpdate = fileMod;
                    }

                    cacheKey += item.Value;
                }

                cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey);

                if (this.gzipCompress)
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz");
                else
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".css");
            }

            // Use cached file disk cache
            if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                response.WriteFile(cacheFile);
                return;
            }

            foreach (CSSCompressItem item in this.items) {
                if (item.Type == CSSItemType.File) {
                    StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8);
                    string data;

                    if (item.RemoveWhiteSpace)
                        data = this.TrimWhiteSpace(reader.ReadToEnd());
                    else
                        data = reader.ReadToEnd();

                    if (this.convertUrls)
                        data = Regex.Replace(data, "url\\(['\"]?(?!\\/|http)", "$0" + PathUtils.ToUnixPath(Path.GetDirectoryName(item.Value)) + "/");

                    writer.Write(data);

                    reader.Close();
                } else {
                    if (item.RemoveWhiteSpace)
                        writer.Write(this.TrimWhiteSpace(item.Value));
                    else
                        writer.Write(item.Value);
                }
            }

            content = writer.ToString();

            // Generate GZIP'd content
            if (supportsGzip) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                if (this.diskCache && cacheKey != null) {
                    try {
                        // Gzip compress
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(File.Create(cacheFile));
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        } else {
                            StreamWriter sw = File.CreateText(cacheFile);
                            sw.Write(content);
                            sw.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        }

                        // Write to stream
                        response.WriteFile(cacheFile);
                    } catch (Exception) {
                        content = "/* Not cached */" + content;
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(response.OutputStream);
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();
                        } else {
                            response.Write(content);
                        }
                    }
                } else {
                    content = "/* Not cached */" + content;
                    gzipStream = new GZipOutputStream(response.OutputStream);
                    buff = encoding.GetBytes(content.ToCharArray());
                    gzipStream.Write(buff, 0, buff.Length);
                    gzipStream.Close();
                }
            } else {
                content = "/* Not cached */" + content;
                response.Write(content);
            }
        }
Example #44
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string projectID = (Page.RouteData.Values["project_id"] as string);

        List <string> repsIdsToCreate = (Page.RouteData.Values["reports"] as string).Split(',').ToList();

        List <Rep> repsToCreate = new List <Rep>();

        foreach (string repID in repsIdsToCreate)
        {
            repsToCreate.Add(new RepBLL().GetRepByRepID(Convert.ToInt32(repID)));
        }

        bool isFullHeader = Convert.ToBoolean(Page.RouteData.Values["headeroneachreport"] as string);// cbHeaderOnEachReport.Checked;

        Eisk.BusinessEntities.Project  project  = new ProjectBLL().GetProjectByProjectID(Convert.ToInt32(projectID));
        Eisk.BusinessEntities.User     user     = new UserBLL().GetUserByUserName((HttpContext.Current.User.Identity).Name);
        Eisk.BusinessEntities.UserInfo userInfo = user.UserInfoes.First(instance => instance.UserID == user.UserID);

        DateTime time = DateTime.Now;

        string name = Reports.Translate(project.ProjectInfoes.First().ProjectName);

        string path = System.Web.HttpContext.Current.Server.MapPath(@System.Configuration.ConfigurationManager.AppSettings["ProjectsRoot"]) + projectID.ToString();

        // check folder exists
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
            System.IO.File.WriteAllText(path + "/" + name + ".xlsx", "");
        }

        FileInfo newFile = new FileInfo(path + @"\" + name + ".xlsx");

        File.Delete(path + @"\" + name + ".xlsx");
        using (ExcelPackage pck = new ExcelPackage(newFile))
        {
            ProjectInfo projectInfo = new ProjectInfoBLL().GetProjectInfoesByProjectID(Convert.ToInt32(projectID)).First();
            List <Project_Organisms> project_Organisms = new Project_OrganismsBLL().GetProject_OrganismsByProjectID(Convert.ToInt32(projectID));

            int totalPages        = 0;
            int currentPageNumber = 0;
            int maxLines          = Convert.ToInt32(@System.Configuration.ConfigurationManager.AppSettings["reportsMaxLines"]);

            List <TreeDetail>   treeDetails            = new List <TreeDetail>();
            List <TreeDetail>   treeComentaries        = new List <TreeDetail>();
            List <TreesSummary> actionProposedID0Items = new List <TreesSummary>();
            List <TreesSummary> actionProposedID1Items = new List <TreesSummary>();
            List <TreesSummary> actionProposedID2Items = new List <TreesSummary>();
            List <TreesSummary> actionProposedID3Items = new List <TreesSummary>();
            List <TreesSummary> actionProposedID4Items = new List <TreesSummary>();

            int treeDetailsCount            = 0;
            int actionProposedID0ItemsCount = 0;
            int actionProposedID1ItemsCount = 0;
            int actionProposedID2ItemsCount = 0;
            int actionProposedID3ItemsCount = 0;
            int actionProposedID4ItemsCount = 0;

            List <Index> idexes = new List <Index>();

            if (repsToCreate.Select(instance => instance.RepID).Contains(1))
            {
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 1).Select(instance => instance.RepName).First(),
                        1,
                        totalPages + 1,
                        totalPages + 1
                        ));
                totalPages += 1;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(2))
            {
                treeDetails       = new TreeDetailBLL().GetTreeDetailsByProjectID(Convert.ToInt32(projectID));
                treeDetailsCount += Reports.GetPageCountOrDefault(maxLines, treeDetails.Count);
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 2).Select(instance => instance.RepName).First(),
                        2,
                        totalPages + 1,
                        totalPages + treeDetailsCount
                        ));
                totalPages += treeDetailsCount;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(3))
            {
                actionProposedID0Items      = new TreesSummaryBLL().GetItems(project_Organisms, 0, true);
                actionProposedID0ItemsCount = Reports.GetPageCountOrDefault(maxLines, actionProposedID0Items.Count);
                ;
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 3).Select(instance => instance.RepName).First(),
                        3,
                        totalPages + 1,
                        totalPages + actionProposedID0ItemsCount
                        ));
                totalPages += actionProposedID0ItemsCount;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(4))
            {
                actionProposedID1Items       = new TreesSummaryBLL().GetItems(project_Organisms, 1, true);
                actionProposedID1ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID1Items.Count);
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 4).Select(instance => instance.RepName).First(),
                        4,
                        totalPages + 1,
                        totalPages + actionProposedID1ItemsCount
                        ));
                totalPages += actionProposedID1ItemsCount;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(5))
            {
                actionProposedID2Items       = new TreesSummaryBLL().GetItems(project_Organisms, 2, true);
                actionProposedID2ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID2Items.Count);
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 5).Select(instance => instance.RepName).First(),
                        5,
                        totalPages + 1,
                        totalPages + actionProposedID2ItemsCount
                        ));
                totalPages += actionProposedID2ItemsCount;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(6))
            {
                actionProposedID3Items       = new TreesSummaryBLL().GetItems(project_Organisms, 3, true);
                actionProposedID3ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID3Items.Count);
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 6).Select(instance => instance.RepName).First(),
                        6,
                        totalPages + 1,
                        totalPages + actionProposedID3ItemsCount
                        ));
                totalPages += actionProposedID3ItemsCount;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(7))
            {
                actionProposedID4Items       = new TreesSummaryBLL().GetItems(project_Organisms, 4, true);
                actionProposedID4ItemsCount += Reports.GetPageCountOrDefault(maxLines, actionProposedID4Items.Count);
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 7).Select(instance => instance.RepName).First(),
                        7,
                        totalPages + 1,
                        totalPages + actionProposedID4ItemsCount
                        ));
                totalPages += actionProposedID4ItemsCount;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(8))
            {
                idexes.Add(
                    new Index(
                        repsToCreate.Where(instance => instance.RepID == 8).Select(instance => instance.RepName).First(),
                        1,
                        totalPages + 1,
                        totalPages + 1
                        ));
                totalPages += 1;
            }
            if (repsToCreate.Select(instance => instance.RepID).Contains(2)) // Se repite el ID de inventario de arboles para anejar comentarios muy largos
            {
                treeComentaries = treeDetails.AsQueryable().DynamicOrderBy("Number").Where(instance => instance.Commentary.Trim().Length > 100).ToList();

                int totalTreeDetailsLines = 0;
                int pageCount             = 0;
                foreach (var treeDetail in treeComentaries)
                {
                    int lines = (int)Math.Ceiling((double)treeDetail.Commentary.Length / 200D);
                    if (totalTreeDetailsLines + lines > maxLines * pageCount)
                    {
                        pageCount++;
                    }

                    totalTreeDetailsLines += lines;
                }

                if (treeComentaries.Count > 0)
                {
                    idexes.Add(
                        new Index(
                            "Comentarios (Continuación)",
                            0,
                            totalPages + 1,
                            totalPages + pageCount
                            ));
                }
                //int pageCount = (int)Math.Ceiling((double)totalTreeDetailsLines / (double)maxLines);
                totalPages += pageCount;
            }

            bool hasIndex = Convert.ToBoolean(Page.RouteData.Values["createindex"] as string);
            if (hasIndex)//cbCreateIndex.Checked)
            {
                Reports.Index(isFullHeader, currentPageNumber, totalPages, "Tabla de Contenido", project, userInfo, idexes, time, pck);
            }

            foreach (Int32 reportID in repsToCreate.Select(instance => instance.RepID))
            {
                switch (reportID)
                {
                case 1:
                {
                    Reports.ProjectInfo(isFullHeader, hasIndex, currentPageNumber, totalPages, project, userInfo, time, pck);
                    currentPageNumber += 1;
                }
                break;

                case 2:
                {
                    Reports.TreeInventory(isFullHeader, hasIndex, currentPageNumber, totalPages, project, userInfo, treeDetails.AsQueryable().DynamicOrderBy("Number").ToList(), time, pck, maxLines);
                    currentPageNumber += treeDetailsCount;
                }
                break;

                case 3:
                {        // actionProposedID = 0; ALL
                    Reports.TreesSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, project, userInfo, actionProposedID0Items, time, pck, maxLines);
                    currentPageNumber += actionProposedID0ItemsCount;
                }
                break;

                case 4:
                {        // actionProposedID = 1; Corte y Remoción
                    Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Corte y Remoción", project, userInfo, actionProposedID1Items, time, pck, maxLines);
                    currentPageNumber += actionProposedID1ItemsCount;
                }
                break;

                case 5:
                {        // actionProposedID = 2; Protección
                    Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Protección", project, userInfo, actionProposedID2Items, time, pck, maxLines);
                    currentPageNumber += actionProposedID2ItemsCount;
                }
                break;

                case 6:
                {        // actionProposedID = 3; Poda
                    Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Poda", project, userInfo, actionProposedID3Items, time, pck, maxLines);
                    currentPageNumber += actionProposedID3ItemsCount;
                }
                break;

                case 7:
                {        // actionProposedID = 4; Transplante
                    Reports.ActionProposedSummary(isFullHeader, hasIndex, currentPageNumber, totalPages, "Resumen de Transplante", project, userInfo, actionProposedID4Items, time, pck, maxLines);
                    currentPageNumber += actionProposedID4ItemsCount;
                }
                break;

                case 8:
                {
                    using (ExcelPackage pck2 = new OfficeOpenXml.ExcelPackage())
                    {
                        ExcelWorksheet wsTemplate = null;
                        pck2.Load(File.OpenRead(System.Web.HttpContext.Current.Server.MapPath(@"~\App_Resources\Excel\Totales.xlsx")));
                        wsTemplate = pck2.Workbook.Worksheets.First();
                        Reports.ProjectResults(isFullHeader, hasIndex, currentPageNumber, totalPages, project_Organisms, project, userInfo, time, pck, wsTemplate);
                        currentPageNumber += 1;
                    }
                }
                break;

                default:
                    break;
                }
            }

            if (treeComentaries.Count > 0 && treeDetailsCount > 0)
            {
                Reports.Comentaries(isFullHeader, hasIndex, currentPageNumber, totalPages, "Comentarios (Continuación)", project, userInfo, treeComentaries, time, pck, maxLines);
            }

            pck.Save();
            pck.Dispose();
        }

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "application/ms-excel";
        response.AddHeader("Content-Disposition", "attachment; filename=" + name + ".xlsx");
        response.WriteFile(path + @"/" + name + ".xlsx");

        response.End();
    }
Example #45
0
 public override void WriteResponse(HttpResponse response)
 {
     response.ContentType = this.ContentType;
     if(myFile.Exists) response.WriteFile(myFile.FullName);
 }