コード例 #1
0
        public static string ServerSidePageHandler(string requestUriPath, IDBService dbProxy, IHttpContextProxy httpProxy, IViewEngine viewEngine, IActionExecuter actionExecuter, ILogger logger, Dictionary <string, dynamic> pageModel = null)
        {
            var fi   = new FileInfo(requestUriPath);
            var data = StaticContentHandler.GetStringContent(dbProxy, logger, requestUriPath);

            if (data != null)
            {
                if (pageModel == null)
                {
                    pageModel = new Dictionary <string, dynamic>();
                }
                var folderPath = requestUriPath.Replace(fi.Name, "");

                UpdateBaseModel(pageModel, requestUriPath, fi.Name);

                data = viewEngine.Compile(data, requestUriPath, ServerPageModelHelper.SetDefaultModel(dbProxy, httpProxy, logger, viewEngine, actionExecuter, pageModel, folderPath));
                if (pageModel.ContainsKey(CommonConst.CommonValue.PAGE_TEMPLATE_PATH))
                {
                    FileInfo fiTemplete       = new FileInfo(pageModel[CommonConst.CommonValue.PAGE_TEMPLATE_PATH]);
                    var      templateFileData = StaticContentHandler.GetStringContent(dbProxy, logger, pageModel[CommonConst.CommonValue.PAGE_TEMPLATE_PATH]);
                    pageModel[CommonConst.CommonValue.RENDERBODY_DATA] = data;
                    data = viewEngine.Compile(templateFileData, pageModel[CommonConst.CommonValue.PAGE_TEMPLATE_PATH],
                                              ServerPageModelHelper.SetDefaultModel(dbProxy, httpProxy, logger, viewEngine, actionExecuter, pageModel, pageModel[CommonConst.CommonValue.PAGE_TEMPLATE_PATH].Replace(fiTemplete.Name, "")));
                }
                return(data);
            }
            else
            {
                return(string.Empty);
            }
        }
コード例 #2
0
        public byte[] GetContent(string path)
        {
            path = StaticContentHandler.MappedUriPath(path);
            var data = StaticContentHandler.GetContent(_dbProxy, _logger, path);

            return(data);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: Jorch72/CS-staccato
        public static void Main(string[] args)
        {
            Configuration = new Configuration();
            if (!File.Exists("config.json"))
            {
                File.WriteAllText("config.json", JsonConvert.SerializeObject(Configuration, Formatting.Indented));
                Console.WriteLine("Empty config.json file created. Populate it and restart.");
                return;
            }
            JsonConvert.PopulateObject(File.ReadAllText("config.json"), Configuration);
            File.WriteAllText("config.json", JsonConvert.SerializeObject(Configuration, Formatting.Indented));

            if (Configuration.Irc.Enabled)
            {
                IrcBot = new IrcBot();
            }
            var httpd  = new HttpServer();
            var router = new HttpRouter();

            httpd.LogRequests = Configuration.LogRequests;
            httpd.Request     = router.Route;

            var staticContent = new StaticContentHandler(Configuration.MusicPath);

            router.AddRoute(new StaticContentRoute(staticContent));
            var staticResources = new StaticContentHandler(Path.Combine(".", "Static"));

            router.AddRoute(new StaticContentRoute(staticResources));

            var mvc = new MvcRouter();

            mvc.RegisterController(new IndexController());
            mvc.AddRoute("Default", "{action}", new { controller = "Index", action = "Index" });
            router.AddRoute(mvc);

            router.AddRoute(new RegexRoute("/download/(?<path>.*)", (context, request, response) =>
            {
                response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(context["path"])));
                staticContent.Serve(context["path"], request, response);
            }));

            MusicRunner.Start();
            httpd.Start(new IPEndPoint(IPAddress.Parse(Configuration.EndPoint), Configuration.Port));
            if (Configuration.Irc.Enabled)
            {
                IrcBot.Start();
            }

            Console.WriteLine("Type 'quit' to exit, or 'help' for help.");
            string command = null;

            while (command != "quit")
            {
                command = Console.ReadLine();
                HandleCommand(command);
            }
        }
コード例 #4
0
 public string GetStringContent(string path)
 {
     path = StaticContentHandler.MappedUriPath(path);
     if (CommonUtility.IsServerSidePage(path))
     {
         var response = ServerPageModelHelper.ServerSidePageHandler(path, _dbProxy, _httpProxy, _viewEngine, _actionExecuter, _logger);
         return(response);
     }
     else
     {
         var data = StaticContentHandler.GetStringContent(_dbProxy, _logger, path);
         return(data);
     }
 }
コード例 #5
0
        private static void UpdateBaseModel(Dictionary <string, dynamic> pageModel, string requestUriPath, string pageName)
        {
            var uri = StaticContentHandler.UnmappedUriPath(requestUriPath);

            if (StaticContentHandler.IsAdminPage(requestUriPath))
            {
                pageModel[CommonConst.CommonField.BASE_URI] = string.Format("{0}{1}", ApplicationConfig.AppPath, ApplicationConfig.AppBackendPath);
            }
            else
            {
                pageModel[CommonConst.CommonField.BASE_URI] = ApplicationConfig.AppPath;
            }
            pageModel[CommonConst.CommonField.PAGE_NAME] = pageName;
            pageModel[CommonConst.CommonField.URI]       = uri;
            AddBaseData(pageModel);
        }
コード例 #6
0
        public async ValueTask TryHandleFileAction_CausesBrowserRefreshForNonCssFile()
        {
            // Arrange
            var server = new Mock <BrowserRefreshServer>(NullReporter.Singleton);

            byte[]? writtenBytes = null;
            server.Setup(s => s.SendMessage(It.IsAny <byte[]>(), It.IsAny <CancellationToken>()))
            .Callback((byte[] bytes, CancellationToken cts) =>
            {
                writtenBytes = bytes;
            });

            // Act
            await StaticContentHandler.TryHandleFileAction(server.Object, new FileItem("Test.js", FileKind.StaticFile, "content/Test.js"), default);

            // Assert
            Assert.NotNull(writtenBytes);
            var writtenString = Encoding.UTF8.GetString(writtenBytes !);

            Assert.Equal("Reload", writtenString);
        }
コード例 #7
0
        private static Dictionary <string, dynamic> SetDefaultModel(IDBService dbProxy, IHttpContextProxy httpProxy, ILogger logger, IViewEngine viewEngine, IActionExecuter actionExecuter, Dictionary <string, dynamic> model, string folderPath = null)
        {
            ISessionProvider sessionProvider = new SessionProvider(httpProxy, dbProxy, logger);

            if (model == null)
            {
                model = new Dictionary <string, dynamic>();
            }
            model[CommonConst.CommonValue.METHODS] = new Dictionary <string, dynamic>();

            Func <string, string, JArray> getData =
                (string collection, string filter) =>
            {
                return(dbProxy.Get(collection, filter));
            };
            Func <string, string> getAppSetting =
                (string key) =>
            {
                var response = AppSettingService.Instance.GetAppSettingData(key);
                if (string.IsNullOrEmpty(response))
                {
                    response = ConfigurationManager.AppSettings[key];
                }
                return(response);
            };
            Func <string, JObject> getSessionValue =
                (string key) =>
            {
                return(sessionProvider.GetValue <JObject>(key));
            };
            Func <string, string> includeTemplete = (string templatePath) =>
            {
                FileInfo fi   = new FileInfo(string.Format("c:\\{0}{1}", folderPath, templatePath));
                string   path = fi.FullName.Replace("c:", "");
                model[CommonConst.CommonValue.PAGE_TEMPLATE_PATH] = path;
                return(string.Empty);
            };
            Func <string, bool> authorized = (string authGroups) =>
            {
                var sessionUser = sessionProvider.GetValue <UserModel>(CommonConst.CommonValue.SESSION_USER_KEY);
                if (sessionUser == null)
                {
                    return(false);
                }

                if (!authGroups.Split(',').Where(i => sessionUser.groups.Contains(i)).Any())
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            };
            Func <string, JObject, JObject> ActionExecute =
                (string actionPath, JObject data) =>
            {
                var param = ActionExecuterHelper.CreateParamContainer(null, httpProxy, logger, actionExecuter);

                if (data != null)
                {
                    foreach (var item in data)
                    {
                        Func <dynamic> funcValue = () => { return(item.Value); };
                        param.AddKey(item.Key, funcValue);
                    }
                }
                return(actionExecuter.Exec <JObject>(actionPath, dbProxy, param));
            };

            Func <string, JObject, Dictionary <string, dynamic> > IncludeModel =
                (string includeModelPath, JObject data) =>
            {
                try
                {
                    var param = ActionExecuterHelper.CreateParamContainer(null, httpProxy, logger, actionExecuter);

                    Dictionary <string, dynamic> modelData = new Dictionary <string, dynamic>();

                    if (data != null)
                    {
                        foreach (var item in data)
                        {
                            Func <dynamic> funcValue = () => { return(item.Value); };
                            param.AddKey(item.Key, funcValue);
                        }
                    }

                    object response = actionExecuter.Exec(includeModelPath, dbProxy, param);
                    if (response is Dictionary <string, dynamic> )
                    {
                        return(response as Dictionary <string, dynamic>);
                    }
                    else
                    {
                        throw new InvalidCastException(string.Format("Invalid respone from {0}", includeModelPath));
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    logger.Error(string.Format("Error While executing Route : {0}, Error : {1}", includeModelPath, ex.Message), ex);
                    throw;
                }
            };

            model[CommonConst.CommonValue.METHODS]["IncludeModel"] = IncludeModel;

            model[CommonConst.CommonValue.METHODS]["ExecuteAction"] = ActionExecute;

            model[CommonConst.CommonValue.METHODS]["InclueTemplate"] = includeTemplete;

            model[CommonConst.CommonValue.METHODS]["GetData"] = getData;

            Func <JObject> requestBody = () => httpProxy.GetRequestBody <JObject>();

            model[CommonConst.CommonValue.METHODS]["RequestBody"] = requestBody;

            Func <string, string> queryString = (string key) => httpProxy.GetQueryString(key);

            model[CommonConst.CommonValue.METHODS]["QueryString"] = queryString;

            model[CommonConst.CommonValue.METHODS]["AppSetting"] = getAppSetting;

            model[CommonConst.CommonValue.METHODS]["GetSessionData"] = getSessionValue;

            model[CommonConst.CommonValue.METHODS]["Authorized"] = authorized;

            Func <string, JObject, string> includeBlock =
                (string blockPath, JObject blockModel) =>
            {
                var inputBlockModel = new Dictionary <string, dynamic>();
                if (blockModel != null)
                {
                    foreach (var item in blockModel)
                    {
                        inputBlockModel[item.Key] = item.Value;
                    }
                }
                if (model != null)
                {
                    foreach (var item in model)
                    {
                        inputBlockModel[item.Key] = item.Value;
                    }
                }
                FileInfo fi   = new FileInfo(string.Format("c:\\{0}{1}", folderPath, blockPath));
                string   path = fi.FullName.Replace("c:", "");
                var      data = StaticContentHandler.GetStringContent(dbProxy, logger, path);
                data = viewEngine.Compile(data, path, ServerPageModelHelper.SetDefaultModel(dbProxy, httpProxy, logger, viewEngine, actionExecuter, inputBlockModel, path.Replace(fi.Name, "")));
                return(data);
            };

            model[CommonConst.CommonValue.METHODS]["Include"] = includeBlock;

            Func <string> randerBody = () =>
            {
                if (model.ContainsKey(CommonConst.CommonValue.RENDERBODY_DATA))
                {
                    return(model[CommonConst.CommonValue.RENDERBODY_DATA]);
                }
                else
                {
                    return(string.Empty);
                }
            };

            model[CommonConst.CommonValue.METHODS]["RenderBody"] = randerBody;

            return(model);
        }
コード例 #8
0
        public async Task WatchAsync(ProcessSpec processSpec, CancellationToken cancellationToken)
        {
            Ensure.NotNull(processSpec, nameof(processSpec));

            var cancelledTaskSource = new TaskCompletionSource();

            cancellationToken.Register(state => ((TaskCompletionSource)state).TrySetResult(),
                                       cancelledTaskSource);

            var initialArguments = processSpec.Arguments.ToArray();
            var context          = new DotNetWatchContext
            {
                Iteration   = -1,
                ProcessSpec = processSpec,
                Reporter    = _reporter,
                SuppressMSBuildIncrementalism = _dotnetWatchOptions.SuppressMSBuildIncrementalism,
            };

            if (context.SuppressMSBuildIncrementalism)
            {
                _reporter.Verbose("MSBuild incremental optimizations suppressed.");
            }

            while (true)
            {
                context.Iteration++;

                // Reset arguments
                processSpec.Arguments = initialArguments;

                for (var i = 0; i < _filters.Length; i++)
                {
                    await _filters[i].ProcessAsync(context, cancellationToken);
                }

                // Reset for next run
                context.RequiresMSBuildRevaluation = false;

                processSpec.EnvironmentVariables["DOTNET_WATCH_ITERATION"] = (context.Iteration + 1).ToString(CultureInfo.InvariantCulture);

                var fileSet = context.FileSet;
                if (fileSet == null)
                {
                    _reporter.Error("Failed to find a list of files to watch");
                    return;
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                using (var currentRunCancellationSource = new CancellationTokenSource())
                    using (var combinedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(
                               cancellationToken,
                               currentRunCancellationSource.Token))
                        using (var fileSetWatcher = new FileSetWatcher(fileSet, _reporter))
                        {
                            var processTask = _processRunner.RunAsync(processSpec, combinedCancellationSource.Token);
                            var args        = ArgumentEscaper.EscapeAndConcatenate(processSpec.Arguments);
                            _reporter.Verbose($"Running {processSpec.ShortDisplayName()} with the following arguments: {args}");

                            _reporter.Output("Started");

                            Task <FileItem?> fileSetTask;
                            Task             finishedTask;

                            while (true)
                            {
                                fileSetTask  = fileSetWatcher.GetChangedFileAsync(combinedCancellationSource.Token);
                                finishedTask = await Task.WhenAny(processTask, fileSetTask, cancelledTaskSource.Task);

                                if (context.BrowserRefreshServer is not null &&
                                    finishedTask == fileSetTask &&
                                    fileSetTask.Result is FileItem {
                                    FileKind : FileKind.StaticFile
                                } file)
                                {
                                    _reporter.Verbose($"Handling file change event for static content {file.FilePath}.");

                                    // If we can handle the file change without a browser refresh, do it.
                                    await StaticContentHandler.TryHandleFileAction(context.BrowserRefreshServer, file, combinedCancellationSource.Token);
                                }