[HttpGet("{type}/{code}/{width}/{height}/{scale}")] //Get /api/design/barcode/BarCode128/123456/200/100/1
        public async Task Barcode(string type, string code, int width, int height, float scale)
        {
            //设置当前用户会话
            RuntimeContext.Current.CurrentSession = HttpContext.Session.LoadWebSession();
            //判断权限
            if (!(RuntimeContext.Current.CurrentSession is IDeveloperSession))
            {
                throw new Exception("Must login as a Developer");
            }

            var bw = new ZXing.SkiaSharp.BarcodeWriter(); //TODO:优化单例ZXing.BarCodeRender

            bw.Format         = (ZXing.BarcodeFormat)Enum.Parse(typeof(ZXing.BarcodeFormat), type);
            bw.Options.Height = (int)(height * scale);
            bw.Options.Width  = (int)(width * scale);
            var skbmp = bw.Write(code);

            using var bmp = new Drawing.Bitmap(skbmp);
            using var ms  = new System.IO.MemoryStream(1024);
            bmp.Save(ms, Drawing.ImageFormat.Jpeg, 90);
            ms.Position = 0;

            HttpContext.Response.ContentType = "image/jpg";
            await ms.CopyToAsync(HttpContext.Response.Body);

            //bmp.Save(HttpContext.Response.Body, Drawing.ImageFormat.Png); //不支持同步直接写
        }
Exemple #2
0
        static StackObject *CopyToAsync_15(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 4);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Threading.CancellationToken @cancellationToken = (System.Threading.CancellationToken) typeof(System.Threading.CancellationToken).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Int32 @bufferSize = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.IO.Stream @destination = (System.IO.Stream) typeof(System.IO.Stream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
            System.IO.MemoryStream instance_of_this_method = (System.IO.MemoryStream) typeof(System.IO.MemoryStream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.CopyToAsync(@destination, @bufferSize, @cancellationToken);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemple #3
0
        static int _m_CopyToAsync(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.MemoryStream gen_to_be_invoked = (System.IO.MemoryStream)translator.FastGetCSObj(L, 1);



                {
                    System.IO.Stream _destination = (System.IO.Stream)translator.GetObject(L, 2, typeof(System.IO.Stream));
                    int _bufferSize = LuaAPI.xlua_tointeger(L, 3);
                    System.Threading.CancellationToken _cancellationToken; translator.Get(L, 4, out _cancellationToken);

                    System.Threading.Tasks.Task gen_ret = gen_to_be_invoked.CopyToAsync(_destination, _bufferSize, _cancellationToken);
                    translator.Push(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Exemple #4
0
        public async void Returns_ParentDirectoryAndStatus200OK_whenSuccessDeletedFile()
        {
            IDatabaseContext    databaseContext     = DatabaseTestHelper.GetContext();
            MapperConfiguration mapperConfiguration = new MapperConfiguration(conf =>
            {
                conf.AddProfile(new Directory_to_DirectoryOut());
            });

            IMapper mapper = mapperConfiguration.CreateMapper();

            IFileService fileService = new FileService(databaseContext, mapper);

            string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id;

            Directory baseDirectory = new Directory
            {
                ResourceType = ResourceType.DIRECTORY,
                Name         = "TestDirectory",
                OwnerID      = userId
            };

            await databaseContext.Directories.AddAsync(baseDirectory);

            await databaseContext.SaveChangesAsync();

            string pathToFile = System.IO.Path.Combine(_pathToUpload, Guid.NewGuid().ToString());

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Test file"));
            System.IO.FileStream   fileStream   = new System.IO.FileStream(pathToFile, System.IO.FileMode.Create);
            await memoryStream.CopyToAsync(fileStream);

            fileStream.Close();

            Assert.True(System.IO.File.Exists(pathToFile));

            File fileToDelete = new File
            {
                ResourceType      = ResourceType.FILE,
                Name              = "ToDelete.txt",
                OwnerID           = userId,
                ParentDirectoryID = baseDirectory.ID,
                Path              = pathToFile,
                CreatedDateTime   = DateTime.Now
            };

            await databaseContext.Files.AddAsync(fileToDelete);

            await databaseContext.SaveChangesAsync();

            Assert.True(databaseContext.Files.Any(_ => _.ID == fileToDelete.ID));

            StatusCode <DirectoryOut> status = await fileService.DeleteByIdAndUser(fileToDelete.ID, "*****@*****.**");

            Assert.NotNull(status);
            Assert.True(status.Code == StatusCodes.Status200OK);
            Assert.True(status.Body.ID == baseDirectory.ID);
            Assert.False(databaseContext.Files.Any(_ => _.ID == fileToDelete.ID));
            Assert.False(System.IO.File.Exists(pathToFile));
        }
        public async void ProcessRequest(Microsoft.AspNetCore.Http.HttpContext context)
#endif
        {
            var request  = context.Request;
            var response = context.Response;

            string result;

            try
            {
                result = this.DoCommand(context);
            }
            catch (System.Exception ex)
            {
                result = System.Text.Json.JsonSerializer.Serialize(new Thinksea.Net.FileUploader.Result()
                {
                    ErrorCode = 1,
                    Message   = ex.Message
                });
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex.ToString());
#endif
            }

#if NETFRAMEWORK
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.ContentType     = "application/json";
            response.AddHeader("Pragma", "no-cache");
            response.CacheControl = "no-cache";
            response.Write(result);
#elif NETCOREAPP
            {
                if (!response.Headers.ContainsKey(Microsoft.Net.Http.Headers.HeaderNames.Pragma))
                {
                    response.Headers.Add(Microsoft.Net.Http.Headers.HeaderNames.Pragma, "no-cache");
                }
                //response.CacheControl = "no-store";
                if (!response.Headers.ContainsKey(Microsoft.Net.Http.Headers.HeaderNames.CacheControl))
                {
                    response.Headers.Add(Microsoft.Net.Http.Headers.HeaderNames.CacheControl, "no-cache");
                }

                System.Net.Http.Headers.MediaTypeHeaderValue mediaType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                mediaType.CharSet    = "utf-8";
                response.ContentType = mediaType.ToString();
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ms, System.Text.Encoding.UTF8))
                    {
                        sw.Write(result);
                        sw.Flush();
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        await ms.CopyToAsync(response.Body);
                    }
                }
                return;
            }
#endif
        }
        public async Task InvokeAsync(HttpContext context
                                      , ILogObj logObj
                                      )
        {
            var log = new LogModels.HttpRequest
            {
                RequestDate = DateTime.UtcNow,
                Url         = context.Request.Path,
                TraceId     = context.TraceIdentifier,
                RemoteIp    = context.Connection.RemoteIpAddress.ToString(),
            };

            logObj.AddChild(log);


            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();

            var responseBodyOrg = context.Response.Body;
            var responseBody    = new System.IO.MemoryStream();

            context.Response.Body = responseBody;

            ////////////////////////////
            //
            await _next(context);

            //
            ////////////////////////////

            var bytes = new byte[responseBody.Length];

            responseBody.Position = 0;
            await responseBody.ReadAsync(bytes, 0, (int)responseBody.Length);

            //var response = System.Text.Encoding.UTF8.GetString(bytes);
            var response = (1000000 < responseBody.Length)
                                ?"Interim measure for error."
                                :System.Text.Encoding.UTF8.GetString(bytes);

            responseBody.Position = 0;
            await responseBody.CopyToAsync(responseBodyOrg);

            sw.Stop();

            log.Response     = response;
            log.StatusCode   = context.Response.StatusCode;
            log.ElapsedTime  = sw.ElapsedMilliseconds;
            log.ResponseDate = DateTime.UtcNow;
        }
Exemple #7
0
        public async void Returns_DownloadFileInfoAndStatus200OK_when_SuccessDownload()
        {
            IDatabaseContext databaseContext = DatabaseTestHelper.GetContext();
            IFileService     fileService     = new FileService(databaseContext, null);

            string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id;

            string pathToFile = System.IO.Path.Combine(_pathToUpload, Guid.NewGuid().ToString());

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Test file"));
            System.IO.FileStream   fileStream   = new System.IO.FileStream(pathToFile, System.IO.FileMode.Create);
            await memoryStream.CopyToAsync(fileStream);

            fileStream.Close();

            Assert.True(System.IO.File.Exists(pathToFile));

            File fileToDownload = new File
            {
                ResourceType      = ResourceType.FILE,
                Name              = "ToDownload.txt",
                OwnerID           = userId,
                ParentDirectoryID = null,
                Path              = pathToFile,
                CreatedDateTime   = DateTime.Now
            };

            await databaseContext.Files.AddAsync(fileToDownload);

            await databaseContext.SaveChangesAsync();

            Assert.True(databaseContext.Files.Any(_ => _.ID == fileToDownload.ID));

            //Get MIME type
            FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();

            if (!provider.TryGetContentType(fileToDownload.Name, out string contentType))
            {
                contentType = "application/octet-stream";
            }

            byte[] fileContent = System.IO.File.ReadAllBytes(pathToFile);

            StatusCode <DownloadFileInfo> status = await fileService.DownloadByIdAndUser(fileToDownload.ID, "*****@*****.**");

            Assert.NotNull(status);
            Assert.True(status.Code == StatusCodes.Status200OK);
            Assert.Equal(fileToDownload.Name, status.Body.FileName);
            Assert.Equal(fileContent, status.Body.FileContent);
            Assert.Equal(contentType, status.Body.ContentType);
        }
        public void Configure(IApplicationBuilder app)
        {
            app.Map("/getLarge", next =>
            {
                next.Run(async context =>
                {
                    using var client = new WebClient();
                    var html         = await client.DownloadStringTaskAsync("https://kingdavidconsulting.com");

                    var pdfGenerator = next.ApplicationServices.GetRequiredService <IPdfGenerator>();
                    var pdf          = await pdfGenerator.GetAsync(html, CancellationToken.None);

                    context.Response.ContentType = "application/pdf";

                    var pdfStream = new System.IO.MemoryStream();
                    pdfStream.Write(pdf, 0, pdf.Length);
                    pdfStream.Position = 0;
                    await pdfStream.CopyToAsync(context.Response.Body);
                });
            });

            app.Map("/getSmall", next =>
            {
                next.Run(async context =>
                {
                    using var client = new WebClient();
                    var html         = @"<!DOCTYPE html>
                        <html>
                        <head>
                        </head>
                        <body>
                            <header>
                                <h1>This is a hardcoded test</h1>
                            </header>
                            <div>
                                <h2>456789</h2>
                            </div>
                        </body>";

                    var pdfGenerator = next.ApplicationServices.GetRequiredService <IPdfGenerator>();
                    var pdf          = await pdfGenerator.GetAsync(html, CancellationToken.None);

                    context.Response.ContentType = "application/pdf";

                    var pdfStream = new System.IO.MemoryStream();
                    pdfStream.Write(pdf, 0, pdf.Length);
                    pdfStream.Position = 0;
                    await pdfStream.CopyToAsync(context.Response.Body);
                });
            });
        }
Exemple #9
0
        public async Task <string> CacheImage(byte[] bytes)
        {
            var outputFile = CreateTempFile();

            System.IO.MemoryStream s = new System.IO.MemoryStream(bytes);
            using (System.IO.FileStream fileStream = System.IO.File.OpenWrite(outputFile.AbsolutePath))
            {
                await s.CopyToAsync(fileStream);

                await s.FlushAsync();

                await fileStream.FlushAsync();
            }
            return(outputFile.AbsolutePath);
        }
Exemple #10
0
            public override async Task Invoke(OperationContext context)
            {
                var original = context.HttpContext.Response.Body;

                using (var buffer = new System.IO.MemoryStream())
                {
                    Console.WriteLine("test");
                    context.HttpContext.Response.Body = buffer;
                    await Next(context).ConfigureAwait(false);

                    context.HttpContext.Response.Body          = original;
                    context.HttpContext.Response.ContentLength = buffer.Length;
                    buffer.Position = 0;
                    await buffer.CopyToAsync(original);
                };
            }
        /// <summary>
        /// 通过实现 System.Web.IHttpHandler 接口的自定义 HttpHandler 启用 HTTP Web 请求的处理。
        /// </summary>
        /// <param name="context">Microsoft.AspNetCore.Http.HttpContext 对象,它提供对用于为 HTTP 请求提供服务的内部服务器对象(如 Request、Response、Session 和 Server)的引用。</param>
        public async void ProcessRequest(Microsoft.AspNetCore.Http.HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            //在此写入您的处理程序实现。
            string VerifyCodeID = request.Query["VerifyCodeID"];
            //            if (string.IsNullOrEmpty(VerifyCodeID))
            //            {
            //                //response.ContentType = "text/plain";
            //                response.ContentType = "text/html";
            //                response.Write(@"<html><head><meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" /></head><body>
            //" + Thinksea.Web.TextToHtml(@"功能:生成一个验证码图片。
            //参数列表:
            //VerifyCodeID:验证码对应的唯一 ID。(*必选参数)
            //") + @"
            //</body></html>");
            //                return;
            //            }

            //string generateVerifyCode = VerifyCode.GenerateVerifyCodeString();
            string generateVerifyCodeQuestion, generateVerifyCodeAnswer;

            VerifyCode.GenerateVerifyCode(out generateVerifyCodeQuestion, out generateVerifyCodeAnswer);
            string _VerifyCode = generateVerifyCodeAnswer.ToLower(); //用于存储验证码的密码字符串。

            //if (this.IsTrackingViewState)
            {
                SaveVerifyCode(context, VerifyCodeID, _VerifyCode);
            }

            //response.ContentType = "text/plain";
            response.ContentType = "image/png";
            //response.ContentType = "application/octet-stream";

            //response.Write("Hello World");
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.Drawing.Bitmap image = Thinksea.VerifyCode.GenerateVerifyCodeImage(generateVerifyCodeQuestion))
                {
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    //image.Dispose();
                }
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                await ms.CopyToAsync(response.Body);
            }
        }
Exemple #12
0
        public async void Returns_Status404NotFound_when_FileNotBelongsToUser()
        {
            IDatabaseContext databaseContext = DatabaseTestHelper.GetContext();
            IFileService     fileService     = new FileService(databaseContext, null);

            string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id;

            string pathToFile = System.IO.Path.Combine(_pathToUpload, Guid.NewGuid().ToString());

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Test file"));
            System.IO.FileStream   fileStream   = new System.IO.FileStream(pathToFile, System.IO.FileMode.Create);
            await memoryStream.CopyToAsync(fileStream);

            fileStream.Close();

            Assert.True(System.IO.File.Exists(pathToFile));

            File fileToDownload = new File
            {
                ResourceType      = ResourceType.FILE,
                Name              = "ToDownload.txt",
                OwnerID           = userId,
                ParentDirectoryID = null,
                Path              = pathToFile,
                CreatedDateTime   = DateTime.Now
            };

            await databaseContext.Files.AddAsync(fileToDownload);

            await databaseContext.SaveChangesAsync();

            Assert.True(databaseContext.Files.Any(_ => _.ID == fileToDownload.ID));

            StatusCode <DownloadFileInfo> status = await fileService.DownloadByIdAndUser(fileToDownload.ID, "*****@*****.**");

            Assert.NotNull(status);
            Assert.True(status.Code == StatusCodes.Status404NotFound);
        }