Exemplo n.º 1
0
        public async Task <Response> Generate(Request request, ILogger logger)
        {
            var path     = string.Join(Path.DirectorySeparatorChar, request.Path.Split("/").Skip(2));
            var fullPath = Path.Combine(FolderPath, path);

            if (!File.Exists(fullPath))
            {
                var    defaultHtml  = $@"<div>
 <h2>Default Page</h2>
<div>Your file is not found in the folder - ""{FolderName}""</div>
</div>";
                byte[] defaultBytes = Encoding.ASCII.GetBytes(defaultHtml);
                return(new Response
                {
                    Bytes = defaultBytes,
                    Type = ResponseType.Binary,
                    ContentType = ContentTypes.GetContentType(fullPath)
                });
            }
            else
            {
                var bytes = await File.ReadAllBytesAsync(fullPath);

                var    footer        = $"<div style='bottom: 0;position: absolute;'>Total size of the file is: {bytes.Count()} bytes.</div>";
                byte[] footerBytes   = Encoding.ASCII.GetBytes(footer);
                var    completeBytes = Combine(bytes, footerBytes);

                return(new Response
                {
                    Bytes = completeBytes,
                    Type = ResponseType.Binary,
                    ContentType = ContentTypes.GetContentType(fullPath)
                });
            }
        }
Exemplo n.º 2
0
        private ActionResult Foo()
        {
            System.Threading.Thread.Sleep(3000);

            DataTable salaryTable = new DataTable();

            //1.创建表头
            DataColumn BankCardNumber = new DataColumn("BankCardNumber", typeof(String));

            salaryTable.Columns.Add(BankCardNumber);
            DataColumn columnUserNameCN = new DataColumn("UserNameCN", typeof(String));

            salaryTable.Columns.Add(columnUserNameCN);
            DataColumn SalaryValue = new DataColumn("SalaryValue", typeof(decimal));

            salaryTable.Columns.Add(SalaryValue);
            DataColumn SalaryMemo = new DataColumn("SalaryMemo", typeof(String));

            salaryTable.Columns.Add(SalaryMemo);

            //2. 创建数据
            DataRow row = salaryTable.NewRow();

            row[BankCardNumber]   = "bbbbbbbbbbbbbbbb";
            row[columnUserNameCN] = "nnnnnnnnnnnnnnnn";
            row[SalaryValue]      = 12.5M;
            row[SalaryMemo]       = "ccccccccccccccc";
            salaryTable.Rows.Add(row);

            Stream salaryStream     = ExcelHelper.WriteExcel(salaryTable, false);
            string fileDownloadName = string.Format("{0}-{1}", "测试文件", DateTime.Now.ToString("yyyyMM"));

            return(File(salaryStream, ContentTypes.GetContentType("xls"), fileDownloadName));
            //DownloadHelper.Down(salaryStream,"xls", fileDownloadName);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Ответ на основе бинарного файла. Код ответа и типа контекста берётся на основе доступности и типа файла
        /// </summary>
        /// <param name="strPath">Путь к файлу</param>
        public Response(string strPath)
        {
            MakeDefaultSettings();
            if (String.IsNullOrEmpty(strPath))
            {
                throw new ArgumentNullException();
            }

            if (Files.Exists(strPath))
            {
                var FileInfo = new FileInfo(strPath);

                Add(HeaderItem.Type.ContentType, ContentTypes.GetContentType(Files.GetOnlyExtension(strPath)));
                Add(HeaderItem.Type.ContentLength, FileInfo.Length.ToString());
                Add(HeaderItem.Type.LastModified, FileInfo.LastWriteTime.ToUniversalTime().ToString("s"));
                Add(HeaderItem.Type.ETag, Files.CalcMD5fast(strPath));
                AddDefaultHeaderItems();

                MakeResponseHeader(HttpStatusCode.OK);
                strSourceFile = strPath;
                MakeHeaderString();
            }
            else
            {
                MakeSimpleResponse("404", HttpStatusCode.NotFound);
            }
        }
Exemplo n.º 4
0
        public MarkdownMenu(DTE2 dte, OleMenuCommandService mcs)
        {
            Mef.SatisfyImportsOnce(this);
            _contentType = ContentTypes.GetContentType("Markdown");
            _extensions  = FileExtensionRegistry.GetFileExtensionSet(_contentType);

            _dte = dte;
            _mcs = mcs;
        }
        public void ContentTypes_GetContentType_ReturnsEnumeratedValue()
        {
            // 1. Arrange
            string fullPath = @"C:\Folder\image.jpg";
            string expected = "image/jpeg";
            // 2. Act
            string actual = ContentTypes.GetContentType(fullPath);

            // 3. Assert
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 6
0
        public HandlebarsMenu(DTE2 dte, OleMenuCommandService mcs)
        {
            Mef.SatisfyImportsOnce(this);
            _contentType = ContentTypes.GetContentType("Handlebars");

            if (_contentType != null)
            {
                _extensions = FileExtensionRegistry.GetFileExtensionSet(_contentType);
            }

            _dte = dte;
            _mcs = mcs;
        }
        private static async Task WriteAsJsonAsync(HttpContext context, HttpStatusCode httpStatusCode, object payload, bool clearResponseBeforeWrite = true)
        {
            if (clearResponseBeforeWrite)
            {
                context.Response.Clear();
            }

            context.Response.StatusCode  = (int)httpStatusCode;
            context.Response.ContentType = ContentTypes.GetContentType(ContentType.Json);

            string jsonText = JsonConvert.SerializeObject(payload);

            await context.Response.WriteAsync(jsonText);
        }
Exemplo n.º 8
0
        private void MakeSimpleResponse(string strResponce, HttpStatusCode httpStatusCode)
        {
            if (strResponce == null)
            {
                strResponce = "";
            }

            Add(HeaderItem.Type.ContentType, ContentTypes.GetContentType("html"));
            Add(HeaderItem.Type.ContentLength, strResponce.Length.ToString());
            Add(HeaderItem.Type.ETag, Strings.CalcMD5(ref strResponce));
            AddDefaultHeaderItems();
            MakeResponseHeader(httpStatusCode);
            strResponseData = strResponce;
            MakeHeaderString();
        }
Exemplo n.º 9
0
        public void SetupCommands()
        {
            AddCommand(CommandId.BuildLess, ContentTypes.GetContentType(LessContentTypeDefinition.LessContentType));
            AddCommand(CommandId.BuildSass, ContentTypes.GetContentType(ScssContentTypeDefinition.ScssContentType));
            AddCommand(CommandId.BuildCoffeeScript, ContentTypes.GetContentType(CoffeeContentTypeDefinition.CoffeeContentType));
            AddCommand(CommandId.BuildSweetJs, ContentTypes.GetContentType(SweetJsContentTypeDefinition.SweetJsContentType));
            //TODO: Iced CoffeeScript?

            CommandID      cmdBundles  = new CommandID(CommandGuids.guidBuildCmdSet, (int)CommandId.BuildBundles);
            OleMenuCommand menuBundles = new OleMenuCommand(async(s, e) => await UpdateBundleFiles(), cmdBundles);

            _mcs.AddCommand(menuBundles);

            CommandID      cmdMinify  = new CommandID(CommandGuids.guidBuildCmdSet, (int)CommandId.BuildMinify);
            OleMenuCommand menuMinify = new OleMenuCommand((s, e) => Task.Run(new Action(Minify)), cmdMinify);

            _mcs.AddCommand(menuMinify);
        }
Exemplo n.º 10
0
        public virtual async Task <Response> Generate(Request request, ILogger logger)
        {
            var path     = string.Join(Path.DirectorySeparatorChar, request.Path.Split("/").Skip(2));
            var fullPath = Path.Combine(FolderPath, path);

            if (!File.Exists(fullPath))
            {
                return(new NotFoundResponse());
            }

            var bytes = await File.ReadAllBytesAsync(fullPath);

            return(new Response
            {
                Bytes = bytes,
                Type = ResponseType.Binary,
                ContentType = ContentTypes.GetContentType(fullPath)
            });
        }
        public virtual async Task <Response> Generate(Request request, ILogger logger)
        {
            var path     = string.Join(Path.DirectorySeparatorChar, request.Path.Split("/").Skip(2));
            var fullPath = Path.Combine(FolderPath, path);

            if (!File.Exists(fullPath))
            {
                var indexPath = Path.Combine(fullPath, "index.html");
                if (Directory.Exists(fullPath))
                {
                    var imageFiles = Directory.GetFiles(fullPath, "*.jpg");
                    if (imageFiles.Length > 1)
                    {
                        return(GalleryFolderPlugin.Generate(imageFiles));
                    }
                }
                if (!File.Exists(indexPath))
                {
                    return(new NotFoundResponse());
                }

                return(await GenerateHtml(indexPath));
            }


            var contentType = ContentTypes.GetContentType(fullPath);

            if (contentType == ContentTypes.HtmlText)
            {
                return(await GenerateHtml(fullPath));
            }

            var bytes = await File.ReadAllBytesAsync(fullPath);

            var response = new Response
            {
                Bytes       = bytes,
                Type        = ResponseType.Binary,
                ContentType = contentType
            };

            return(response);
        }
Exemplo n.º 12
0
        public override void Handle(IHttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;
            var rawUrl   = context.RawUrl;
            var fileInfo = HttpUtility.GetFileInfo(context.Site, rawUrl);

            if (fileInfo == null)
            {
                throw new FileNotFoundException(rawUrl);
            }

            var extension = Path.GetExtension(fileInfo.Name);

            response.ContentType = ContentTypes.GetContentType(extension);
            response.StatusCode  = (int)HttpStatusCode.OK;

            try
            {
                var obj    = scriptEngines.CreateInstance(fileInfo.FullName, null);
                var script = (CSharpScript)obj;

                try
                {
                    script.Initialize(scriptEngines, context, fileInfo);
                    script.Invoke();
                }
                finally
                {
                    script.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.Warn("{0} file:{1} error: {2}", nameof(ScriptProcessor), fileInfo.FullName, ex);
                if (scriptEngines.IsDebug)
                {
                    throw;
                }

                throw new InvalidOperationException("Internal Server Error");
            }
        }
Exemplo n.º 13
0
        public ActionResult OperationResults(bool isOnlyPlaceHolder = true)
        {
            int inputDisplayCount = RequestHelper.GetValue("inputDisplayCount", 0);

            if (inputDisplayCount > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < inputDisplayCount; i++)
                {
                    string inputDisplayContent = RequestHelper.GetValue("inputDisplayContent+" + i);
                    sb.AppendLine(inputDisplayContent);
                }

                Stream stream = new MemoryStream(StringHelper.GetByteArray(sb.ToString()));
                stream.Flush();

                return(File(stream, ContentTypes.GetContentType(".txt"), "操作信息.txt"));
            }

            return(new EmptyResult());
        }
Exemplo n.º 14
0
        public override void Handle(IHttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;
            var rawUrl   = context.RawUrl;
            var fileInfo = HttpUtility.GetFileInfo(context.Site, rawUrl);

            if (fileInfo == null)
            {
                throw new FileNotFoundException(rawUrl);
            }

            var extension = Path.GetExtension(fileInfo.Name);

            response.ContentType     = ContentTypes.GetContentType(extension);
            response.ContentLength64 = fileInfo.Length;
            response.StatusCode      = (int)HttpStatusCode.OK;
            using (var fStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                fStream.CopyTo(response.OutputStream);
            }
        }
Exemplo n.º 15
0
        public void SetupCommands()
        {
            AddCommand(CommandId.BuildLess, ContentTypes.GetContentType(LessContentTypeDefinition.LessContentType));
            AddCommand(CommandId.BuildSass, ContentTypes.GetContentType(ScssContentTypeDefinition.ScssContentType));
            AddCommand(CommandId.BuildCoffeeScript, ContentTypes.GetContentType(CoffeeContentTypeDefinition.CoffeeContentType));
            AddCommand(CommandId.BuildSweetJs, ContentTypes.GetContentType(SweetJsContentTypeDefinition.SweetJsContentType));
            //TODO: Iced CoffeeScript?

            CommandID      cmdBundles  = new CommandID(CommandGuids.guidBuildCmdSet, (int)CommandId.BuildBundles);
            OleMenuCommand menuBundles = new OleMenuCommand((s, e) => UpdateBundleFiles().DoNotWait("Web Essentials: Updating Bundles..."), cmdBundles);

            _mcs.AddCommand(menuBundles);

            CommandID      cmdSprites  = new CommandID(CommandGuids.guidBuildCmdSet, (int)CommandId.BuildSprites);
            OleMenuCommand menuSprites = new OleMenuCommand((s, e) => UpdateSpriteFiles().DoNotWait("Web Essentials: Updating Sprites..."), cmdSprites);

            _mcs.AddCommand(menuSprites);

            CommandID      cmdMinify  = new CommandID(CommandGuids.guidBuildCmdSet, (int)CommandId.BuildMinify);
            OleMenuCommand menuMinify = new OleMenuCommand((s, e) => Minify().DoNotWait("Web Essentials: Minifying files..."), cmdMinify);

            _mcs.AddCommand(menuMinify);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Returns the content type of the given HttpPostedFile.
        /// </summary>
        /// There is no such thing as an official mapping of file extentions to content types or vice versa.
        /// Windows has a one-one mapping in the registry, which is how the client's (Windows) computer determines the file type.
        /// Windows determines the content type through no other means than the file extension. This also means that
        /// different clients can have different content types and are even able to spoof the content-type. HttpPostedFile does nothing more
        /// than determine the content-type given by the client headers. Because of this, I think that would should
        /// first be consulting our official mappings of file extensions to content types, and then fall back on the .NET provided method.
        /// Maybe we should never be trusting the client's content-type, since it's conceivable it could lead to a buffer-overflow attack.
        /// We could fall back to consulting the server's content-type mappings instead of trusting the client at all, but this is flawed too
        /// since all it takes to make us determine the file to be another content-type is to change the extension.
        internal static string GetContentTypeForPostedFile(RsFile file)
        {
            var type = ContentTypes.GetContentType(file.FileName);

            return(type != String.Empty ? type : file.ContentType);
        }
Exemplo n.º 17
0
        public override void Handle(IHttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;
            var rawUrl   = context.RawUrl;
            var fileInfo = HttpUtility.GetFileInfo(context.Site, rawUrl);

            if (fileInfo == null)
            {
                //文件未找到
                throw new FileNotFoundException(rawUrl);
            }
            var extension = Path.GetExtension(fileInfo.Name);

            response.ContentType = ContentTypes.GetContentType(extension);
            using (var outputStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                //先锁定文件,再从新获取
                fileInfo.Refresh();
                response.AddHeader(HttpResponseHeader.ETag.ToString(), GetETag(fileInfo));
                response.AddHeader(HttpResponseHeader.LastModified.ToString(), fileInfo.LastWriteTime.ToUniversalTime().ToString("r"));
                var rangeText = request.Headers[HttpRequestHeader.Range.ToString()];
                if (rangeText != null)
                {
                    var pattern = @"^bytes=(?<begin>\d*?)-(?<end>\d*?)$";
                    var match   = Regex.Match(rangeText, pattern);
                    if (match.Success)
                    {
                        //分段下载
                        response.AddHeader(HttpResponseHeader.AcceptRanges.ToString(), "bytes");
                        var lengthSentinel  = fileInfo.Length - 1;
                        var rangeEndText    = match.Groups["end"].Value;
                        var rangeBeginText  = match.Groups["begin"].Value;
                        var rangeEndIndex   = !string.IsNullOrEmpty(rangeEndText) ? long.Parse(rangeEndText) : lengthSentinel;
                        var rangeBeginIndex = !string.IsNullOrEmpty(rangeBeginText) ? long.Parse(rangeBeginText) : 0;
                        if (rangeBeginIndex < 0 || rangeEndIndex < 0 || rangeBeginIndex > rangeEndIndex)
                        {
                            response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
                            return;
                        }
                        if (rangeBeginIndex > lengthSentinel)
                        {
                            rangeBeginIndex = lengthSentinel;
                        }
                        if (rangeEndIndex > lengthSentinel)
                        {
                            rangeEndIndex = lengthSentinel;
                        }

                        //Content-Range: bytes 0-10/3103
                        var remainderLength = rangeEndIndex - rangeBeginIndex + 1;
                        response.ContentLength64 = remainderLength;
                        response.StatusCode      = (int)HttpStatusCode.PartialContent;
                        response.AddHeader(HttpResponseHeader.ContentRange.ToString(), string.Format("bytes {0}-{1}/{2}", rangeBeginIndex, rangeEndIndex, fileInfo.Length));
                        if (remainderLength > 0)
                        {
                            int length;
                            int affectedLength;
                            var buffer = new byte[Math.Min(10240, remainderLength)];
                            outputStream.Seek(rangeBeginIndex, SeekOrigin.Begin);
                            while (remainderLength > 0)
                            {
                                affectedLength = Math.Min(checked ((int)remainderLength), buffer.Length);
                                if ((length = outputStream.Read(buffer, 0, affectedLength)) <= 0)
                                {
                                    break;
                                }

                                remainderLength -= length;
                                response.OutputStream.Write(buffer, 0, length);
                            }
                        }
                        return;
                    }
                }

                response.ContentLength64 = fileInfo.Length;
                response.StatusCode      = (int)HttpStatusCode.OK;
                outputStream.CopyTo(response.OutputStream);
            }
        }
Exemplo n.º 18
0
 public FileContentType(string filetype)
 {
     Ext         = filetype;
     ContentType = ContentTypes.GetContentType(Ext);
 }