Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            Authentication.Configure(app, env);

            Cors.Configure(app, env);

            //app.UseSignalR(routes =>
            //{
            //    routes.MapHub<ChatHub>("/chathub");
            //});

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHttpsRedirection();
                app.UseDeveloperExceptionPage();
                app.UseHsts();
            }

            MVC.Configure(app, env);

            SPA.Configure(app, env);

            StaticFiles.Configure(app, env);
        }
Exemplo n.º 2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // ReSharper disable once UnusedMember.Global
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime life)
        {
            AppLog.ShowLogOnError(app);

            BaseModel.IsDev = env.IsDevelopment();
            TZ.Init(env.IsDevelopment());

            Config.Initialize(env);

            Security.DenyFrame(app);

            StaticFiles.Configure(app);

            Route.CreateRoutes();

            Rewrite.TestThemAll(app);

            Context.Set(app);

            Error.AddHandlers(app, env);

            Orm.Config(app, life);

            Context.SetLanguage(app, env);

            Access.Run(app);

            Route.Execute(app);
        }
Exemplo n.º 3
0
            public string GetFile()
            {
                var path = Request.Url.AbsolutePath;

                if (BaseOptions.ResourcesDir != null)
                {
                    var filePath = Path.Combine(BaseOptions.ResourcesDir, path.Substring(1));

                    if (File.Exists(filePath))
                    {
                        Response.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(path));
                        return(File.ReadAllText(filePath));
                    }
                }

                string value;

                if (StaticFiles.TryGetValue(path, out value))
                {
                    Response.ContentType = MimeTypeMap.GetMimeType(Path.GetExtension(path));
                    return(value);
                }

                Response.StatusCode = 404;
                return("File not found.");
            }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //per https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#routing-startup-code
            // static files should be called before UseRouting
            StaticFiles.Configure(app, env);

            app.UseRouting();
            Cors.Configure(app, env);
            Authentication.Configure(app, env);


            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
                endpoints.MapHub <ChatHub>("/chathub");
                endpoints.MapHub <NotificationHub>("/notificationhub");
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHttpsRedirection();
                app.UseDeveloperExceptionPage();
                app.UseHsts();
            }

            MVC.Configure(app, env);

            SPA.Configure(app, env);
        }
Exemplo n.º 5
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/manifest.json")] HttpRequest req,
            ILogger log)
        {
            var stream = File.OpenRead(StaticFiles.Path($"wwwroot/manifest.json"));

            return(new FileStreamResult(stream, "application/json"));
        }
Exemplo n.º 6
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/robots.txt")] HttpRequest req,
            ILogger log)
        {
            var stream = File.OpenRead(StaticFiles.Path($"wwwroot/robots.txt"));

            return(new FileStreamResult(stream, "text/plain"));
        }
Exemplo n.º 7
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/service-worker.js")] HttpRequest req,
            ILogger log)
        {
            var stream = File.OpenRead(StaticFiles.Path($"wwwroot/service-worker.js"));

            return(new FileStreamResult(stream, "text/javascript"));
        }
Exemplo n.º 8
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/favicon.ico")] HttpRequest req,
            ILogger log)
        {
            var stream = File.OpenRead(StaticFiles.Path("wwwroot/favicon.ico"));

            return(new FileStreamResult(stream, "image/vnd.microsoft.icon"));
        }
Exemplo n.º 9
0
        internal static void Terminate()
        {
            for (int loop = 0; loop < 3; loop++)
            {
                SoundSources.DestroyAll();

                Cursors.DestroyAll();

                Texture2Ds.DestroyAll();
                CubemapTextures.DestroyAll();
                Fonts.DestroyAll();
                Chip2Ds.DestroyAll();

                Shader2Ds.DestroyAll();
                Shader3Ds.DestroyAll();
                Material2Ds.DestroyAll();
                Material3Ds.DestroyAll();
                MaterialPropertyBlocks.DestroyAll();

                ImagePackages.DestroyAll();

                Effects.DestroyAll();

                Meshs.DestroyAll();
                Deformers.DestroyAll();
                Models.DestroyAll();
                MassModels.DestroyAll();
                Terrain3Ds.DestroyAll();

                KeyframeAnimations.DestroyAll();
                AnimationSources.DestroyAll();

                Scenes.DestroyAll();

                Layer2Ds.DestroyAll();
                Object2Ds.DestroyAll();

                Layer3Ds.DestroyAll();
                Object3Ds.DestroyAll();

                PostEffects.DestroyAll();
                Transitions.DestroyAll();

                StaticFiles.DestroyAll();
                StreamFiles.DestroyAll();

                Shapes.DestroyAll();

                //Profilers.DestroyAll();

                Collector.Collect();
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
                System.GC.Collect();
                Collector.Collect();
            }
        }
Exemplo n.º 10
0
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "fonts/{file}")] HttpRequest req,
            string file,
            ILogger log)
        {
            var stream = File.OpenRead(StaticFiles.Path($"wwwroot/fonts/{file}"));

            return(new FileStreamResult(stream, "application/octet-stream"));
        }
Exemplo n.º 11
0
 public void Configure(IApplicationBuilder app)
 {
     app.UseHsts();
     app.UseHttpsRedirection();
     app.UseStaticFiles(StaticFiles.Configure());
     app.UseRouting();
     app.UseAuthentication();
     app.UseAuthorization();
     app.UseEndpoints(Endpoints.Configure);
 }
Exemplo n.º 12
0
        internal static void Update()
        {
            if (Collector.Collect())
            {
                SoundSources.Collect();

                Cursors.Collect();

                Texture2Ds.Collect();
                CubemapTextures.Collect();
                Fonts.Collect();
                Chip2Ds.Collect();

                Shader2Ds.Collect();
                Shader3Ds.Collect();
                Material2Ds.Collect();
                Material3Ds.Collect();
                MaterialPropertyBlocks.Collect();

                ImagePackages.Collect();
                MediaPlayers.Collect();

                Effects.Collect();

                Meshs.Collect();
                Deformers.Collect();
                Models.Collect();
                MassModels.Collect();
                Terrain3Ds.Collect();

                KeyframeAnimations.Collect();
                AnimationSources.Collect();
                AnimationClips.Collect();

                Scenes.Collect();

                Layer2Ds.Collect();
                Object2Ds.Collect();

                Layer3Ds.Collect();
                Object3Ds.Collect();

                PostEffects.Collect();

                Transitions.Collect();

                StaticFiles.Collect();
                StreamFiles.Collect();

                Shapes.Collect();
                Collider2Ds.Collect();
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// 当收到请求时发生。
 /// </summary>
 /// <param name="request"></param>
 protected virtual void OnRequest(HttpRequest request)
 {
     using (var response = request.Context.Response)
     {
         var apiHandle = ApiHandles.FirstOrDefault((item) => request.Url.AbsolutePath.StartsWith(item.Key, StringComparison.OrdinalIgnoreCase));
         if (!string.IsNullOrEmpty(apiHandle.Key))                                 //api处理器
         {
             response.AddHeader("Content-type", "application/json;charset=utf-8"); //添加响应头信息
             response.ContentEncoding = Encoding.UTF8;
             DotNet.Result result = new DotNet.Result()
             {
                 Message = "系统错误"
             };
             try
             {
                 result = OnBeginRequest(request, apiHandle);
             }
             catch (Exception ex)
             {
                 result = new DotNet.Result()
                 {
                     Message = "系统错误:" + ex.Message
                 };
             }
             finally
             {
                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(response.OutputStream))
                 {
                     sw.Write(result.ToJson());
                 }
             }
             response.Close();
             return;
         }
         var staticFile = StaticFiles.FirstOrDefault((item) => request.Url.AbsolutePath.StartsWith(item.Key, StringComparison.OrdinalIgnoreCase));
         if (!string.IsNullOrEmpty(staticFile.Value))//静态资源
         {
             var path    = staticFile.Value;
             var urlPath = request.Url.AbsolutePath.Remove(0, staticFile.Key.Length);
             if (!string.IsNullOrEmpty(urlPath))
             {
                 urlPath = urlPath.Remove(0, 1).Replace('/', System.IO.Path.DirectorySeparatorChar);
             }
             WriteStaticFile(request, urlPath, staticFile.Value);
             return;
         }
         else
         {
             WriteStaticFile(request, request.Url.AbsolutePath.Remove(0, 1), WorkPath);
             return;
         }
     }
 }
Exemplo n.º 14
0
 /// <summary>
 /// 添加静态资源访问。
 /// </summary>
 /// <param name="uriPrefix">静态资源前缀</param>
 /// <param name="path">物理路径。</param>
 /// <returns></returns>
 public virtual Result AddStaticFile(string uriPrefix, string path)
 {
     if (!uriPrefix.StartsWith("/"))
     {
         return(new Result()
         {
             Message = $"参数{nameof(uriPrefix)}必须以/开头。"
         });
     }
     StaticFiles.Add(uriPrefix, path);
     return(true);
 }
Exemplo n.º 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // configure the app settings and bind it to a setting instance
            var appSettingsConfig = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsConfig);

            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite("DataSource=scanners.db"));

            // configure the jwt auth
            var appSettings = appSettingsConfig.Get <AppSettings>();

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Secret)),
                    ValidateLifetime         = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddControllers()
            .AddJsonOptions(options => {
                options.JsonSerializerOptions.WriteIndented    = true;
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "Client/build";
            });

            services.AddScoped <IShellService, ShellService>();
            services.AddScoped <ISaneService, SaneService>();

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ICustomPasswordValidator, CustomPasswordValidator>();

            StaticFiles.CreateStaticFilesDirs();
        }
Exemplo n.º 16
0
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/")] HttpRequest req,
            ILogger log)
        {
            req.HttpContext.Response.Headers["Cache-Control"] = "no-cache";
            req.HttpContext.Response.Headers["Expires"]       = DateTime.UtcNow.AddMinutes(1).ToString("R");

            var html = GetHtml(StaticFiles.Path($"wwwroot/index.html"));

            return(new ContentResult
            {
                StatusCode = 200,
                Content = html,
                ContentType = "text/html"
            });
        }
Exemplo n.º 17
0
        private async Task <StaticFiles> copyStaticFiles(dynamic qualificationPlan)
        {
            var staticFiles = new StaticFiles();

            //Sections
            IReadOnlyList <Section> sections = retrieveSections(qualificationPlan);

            staticFiles.Sections = copySectionContents(sections.ToArray());

            //Observed Data
            IReadOnlyList <ObservedDataMapping> observedDataSets = getStaticObservedDataSetFrom(qualificationPlan);

            staticFiles.ObservedDatSets = await Task.WhenAll(observedDataSets.Select(copyObservedData));

            //Intro files
            staticFiles.IntroFiles = await copyIntroFiles(qualificationPlan);

            return(staticFiles);
        }
        private async Task <Executable> CreateExecutableAsync(
            byte[] contents, string ext, bool cmp)
        {
            var execName = $"p{Problem.ProblemId}{(cmp ? "cmp" : "run")}";
            var testlib  = StaticFiles.GetFileInfo("static/testlib.h");

            if (!testlib.Exists)
            {
                throw new InvalidOperationException("testlib.h not found");
            }

            var stream = new MemoryStream();

            using (var newzip = new ZipArchive(stream, ZipArchiveMode.Create, true))
            {
                var f = newzip.CreateEntryFromByteArray(contents, "main" + ext);
                f.ExternalAttributes = LINUX644;
                var f2 = newzip.CreateEntryFromFile(testlib.PhysicalPath, "testlib.h");
                f2.ExternalAttributes = LINUX644;
            }

            stream.Position = 0;
            var content = new byte[stream.Length];
            int pos     = 0;

            while (pos < stream.Length)
            {
                pos += await stream.ReadAsync(content, pos, (int)stream.Length - pos);
            }

            return(await Executables.CreateAsync(new Executable
            {
                Description = $"output validator for p{Problem.ProblemId}",
                ZipFile = content,
                Md5sum = content.ToMD5().ToHexDigest(true),
                ZipSize = pos,
                ExecId = execName,
                Type = cmp ? "compare" : "run",
            }));
        }
Exemplo n.º 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseDeveloperExceptionPage();
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            Cors.Configure(app, env);

            Authentication.Configure(app, env);

            MVC.Configure(app, env);

            SPA.Configure(app, env);

            StaticFiles.Configure(app, env);
        }
Exemplo n.º 20
0
        //[Singleton]
        public async Task Run([QueueTrigger("video-%Meeemories:ContainerName%")] string id, ILogger log)
        {
            var media = await _service.FindAsync(id);

            if (media == null)
            {
                log.LogInformation($"NotFound {id}");
                return;
            }

            media.Status = MediaStatus.Converting;
            await _service.UpdateAsync(media);

            var rawPath     = Path.GetTempFileName();
            var jpgPath     = $"{rawPath}.jpg";
            var thumbPath   = $"{rawPath}_thumb.jpg";
            var resizedPath = $"{rawPath}_resized.mp4";

            try
            {
                var raw = _service.OpenBlob(media);
                await raw.DownloadToFileAsync(rawPath, FileMode.OpenOrCreate);

                var ffmpeg      = new Engine(StaticFiles.Path("ffmpeg.exe"));
                var inputFile   = new MediaFile(rawPath);
                var jpgFile     = new MediaFile(jpgPath);
                var thumbFile   = new MediaFile(thumbPath);
                var resizedFile = new MediaFile(resizedPath);

                await ffmpeg.GetThumbnailAsync(inputFile, jpgFile, new ConversionOptions
                {
                    Seek = TimeSpan.FromMilliseconds(10)
                });

                double aspect;
                using (var image = new MagickImage(jpgPath))
                {
                    aspect = (double)image.Height / image.Width;
                }

                int width = 400, height = (int)(aspect * width);

                if (height % 2 == 1)
                {
                    height += 1;
                }

                await ffmpeg.ConvertAsync(inputFile, resizedFile, new ConversionOptions
                {
                    CustomWidth  = width,
                    CustomHeight = height,
                    VideoSize    = FFmpeg.NET.Enums.VideoSize.Custom,
                });

                await ffmpeg.GetThumbnailAsync(inputFile, thumbFile, new ConversionOptions
                {
                    Seek = TimeSpan.FromSeconds(3)
                });

                var sources = new List <MediaSource>();

                var thumbBlob   = _service.CreateBlob($"{width:000}w/{raw.Name}.jpg");
                var resizedBlob = _service.CreateBlob($"{width:000}w/{raw.Name}.mp4");

                await thumbBlob.UploadFromFileAsync(thumbPath);

                thumbBlob.Properties.ContentType = "image/jpeg";
                await thumbBlob.SetPropertiesAsync();

                sources.Add(new MediaSource
                {
                    Url      = thumbBlob.Uri.ToString(),
                    Width    = width,
                    Height   = height,
                    MimeType = "image/jpeg"
                });

                await resizedBlob.UploadFromFileAsync(resizedPath);

                resizedBlob.Properties.ContentType = "video/mp4";
                await resizedBlob.SetPropertiesAsync();

                sources.Add(new MediaSource
                {
                    Url      = resizedBlob.Uri.ToString(),
                    Width    = width,
                    Height   = height,
                    MimeType = "video/mp4"
                });

                media.Sources = sources;
                media.Status  = MediaStatus.Complete;
                await _service.UpdateAsync(media);
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
                media.Status = MediaStatus.Fail;
                await _service.UpdateAsync(media);
            }
            finally
            {
                if (File.Exists(rawPath))
                {
                    File.Delete(rawPath);
                }

                if (File.Exists(jpgPath))
                {
                    File.Delete(jpgPath);
                }

                if (File.Exists(thumbPath))
                {
                    File.Delete(thumbPath);
                }

                if (File.Exists(resizedPath))
                {
                    File.Delete(resizedPath);
                }
            }
        }
Exemplo n.º 21
0
        public static bool IsStaticFile(string file)
        {
            var extension = file.Substring(file.LastIndexOf('.') + 1);

            return(StaticFiles.ContainsKey(extension));
        }
Exemplo n.º 22
0
        public async Task RunBatchAsync(QualificationRunOptions runOptions)
        {
            _runOptions = runOptions;

            if (!FileHelper.FileExists(runOptions.ConfigurationFile))
            {
                throw new QualificationRunException(ConfigurationFileNotFound(runOptions.ConfigurationFile));
            }

            setupOutputFolder();

            dynamic qualificationPlan = await _jsonSerializer.Deserialize <dynamic>(runOptions.ConfigurationFile);

            IReadOnlyList <Project> projects = GetListFrom <Project>(qualificationPlan.Projects);

            if (projects == null)
            {
                throw new QualificationRunException(ProjectsNotDefinedInQualificationFile);
            }

            IReadOnlyList <SimulationPlot> allPlots  = retrieveProjectPlots(qualificationPlan);
            IReadOnlyList <Input>          allInputs = retrieveInputs(qualificationPlan);

            var begin = DateTime.UtcNow;

            await updateProjectsFullPath(projects);

            //Configurations only need to be created once!
            var projectConfigurations = await Task.WhenAll(projects.Select(p => createQualifcationConfigurationFor(p, projects, allPlots, allInputs)));

            _logger.AddDebug("Copying static files");
            StaticFiles staticFiles = await copyStaticFiles(qualificationPlan);

            _logger.AddInfo("Starting validation runs...");
            var validations = await Task.WhenAll(projectConfigurations.Select(validateProject));

            var invalidConfigurations = validations.Where(x => !x.Success).ToList();

            if (invalidConfigurations.Any())
            {
                throw new QualificationRunException(errorMessageFrom(invalidConfigurations));
            }

            //Run all qualification projects
            _logger.AddInfo("Starting qualification runs...");
            var runResults = await Task.WhenAll(projectConfigurations.Select(runQualification));

            var invalidRunResults = runResults.Where(x => !x.Success).ToList();

            if (invalidRunResults.Any())
            {
                throw new QualificationRunException(errorMessageFrom(invalidRunResults));
            }

            await createReportConfigurationPlan(runResults, staticFiles, qualificationPlan);

            var end       = DateTime.UtcNow;
            var timeSpent = end - begin;

            _logger.AddInfo($"Qualification scenario finished in {timeSpent.ToDisplay()}");
        }
Exemplo n.º 23
0
        private async Task createReportConfigurationPlan(QualificationRunResult[] runResults, StaticFiles staticFiles, dynamic qualificationPlan)
        {
            dynamic reportConfigurationPlan = new JObject();

            var mappings = await Task.WhenAll(runResults.Select(x => _jsonSerializer.Deserialize <QualificationMapping>(x.MappingFile)));

            reportConfigurationPlan.SimulationMappings = toJArray(mappings.SelectMany(x => x.SimulationMappings));

            reportConfigurationPlan.ObservedDataSets = toJArray(mappings.SelectMany(x => x.ObservedDataMappings).Union(staticFiles.ObservedDatSets));

            var plots = qualificationPlan.Plots;

            RemoveByName(plots, Configuration.ALL_PLOTS);

            plots.TimeProfile             = toJArray(mappings.SelectMany(x => x.Plots));
            reportConfigurationPlan.Plots = plots;

            reportConfigurationPlan.Inputs = toJArray(mappings.SelectMany(x => x.Inputs));

            reportConfigurationPlan.Sections = toJArray(staticFiles.Sections);

            reportConfigurationPlan.Intro = toJArray(staticFiles.IntroFiles);

            await _jsonSerializer.Serialize(reportConfigurationPlan, _runOptions.ReportConfigurationFile);
        }
Exemplo n.º 24
0
        /// <summary>
        /// 更新文件
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task <BaseResult> UpdateStaticFileAsync(SaveStaticFilesParamBase param, StaticFiles model)
        {
            var fileName = param.SavePath.Substring(param.SavePath.LastIndexOf('/') + 1);

            //文件不存在则是新上传的
            //if (!File.Exists(Directory.GetCurrentDirectory() + $"/{BaseCore.Configuration["ImgPath:savePath"]}/"+fileName))
            if (model.SavePath != fileName)
            {
                //MoveFile(fileName);
                //同时删除原图片。。
                DeleteFile(model.SavePath);
            }
            //只保存文件名
            param.SavePath = param.SavePath.Substring(param.SavePath.LastIndexOf('/') + 1);
            var updateResult = await _staticFilesRep.UpdateAsync(Mapper.Map <StaticFiles>(param));

            if (updateResult > 0)
            {
                return(new Success("保存成功"));
            }
            else
            {
                return(new Fail("操作失败"));
            }
        }