Beispiel #1
0
        public ApiResponse AddJsFile([FromQuery] string project, [FromRoute] string name, [FromQuery] string jsFileName) // TODO: Change from jsFilename to jsFileGuid?
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var ret = app.AddJsFile(jsFileName);

                if (ret.IsSuccess)
                {
                    SettingsInstance.SaveSettingsToFile();
                    //?!GeneratorThreadDispatcher.SetOutputFilesDirty(cs);
                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #2
0
        public ApiResponse DeleteJsFile([FromQuery] string project, [FromRoute] string name, [FromRoute] string file)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var existing = app.GetJsFile(file);

                if (existing == null)
                {
                    return(ApiResponse.ExclamationModal($"The output file \"{file}\" does not exist in \"{project}/{name}\""));
                }

                app.JsFiles.Remove(existing);

                SettingsInstance.SaveSettingsToFile();

                //!GeneratorThreadDispatcher.SetOutputFilesDirty(cs);

                return(ApiResponse.Success());
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #3
0
        public ApiResponse UpdateApplication([FromBody] string name, [FromQuery] string oldName,
                                             [FromQuery] string project, [FromQuery] string jsNamespace, [FromQuery] int?defaultRuleMode)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, oldName, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var anotherExisting = proj.GetApplication(name);

                if (anotherExisting != null)
                {
                    return(ApiResponse.ExclamationModal($"The application \"{ name }\" already exists on project \" { project }\"."));
                }

                var ret = app.Update(name, jsNamespace, defaultRuleMode);

                if (!ret.IsSuccess)
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }

                Hubs.WorkerMonitor.Instance.NotifyObservers();

                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #4
0
        public ApiResponse IsOrmInstalled([FromRoute] string name, [FromQuery] string projectName, [FromQuery] string dbSourceName, [FromQuery] bool forceRecheck)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(projectName, dbSourceName, out var proj, out var dbSource, out var resp))
                {
                    return(resp);
                }

                if (!dbSource.GetEndpoint(name, out var endpoint, out var resp2))
                {
                    return(ApiResponse.ExclamationModal(resp2.userErrorVal));
                }

                if (!forceRecheck && endpoint.IsOrmInstalled)
                {
                    return(ApiResponse.Payload(null));
                }

                var missingDeps = endpoint.CheckForMissingOrmPreRequisitesOnDatabase();

                endpoint.IsOrmInstalled = missingDeps == null;

                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Payload(missingDeps));
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #5
0
 private void SettingsWindow_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
 {
     if ((bool)e.NewValue && !e.NewValue.Equals(e.OldValue))
     {
         SettingsInstance.BeginEditAll();
     }
 }
Beispiel #6
0
        public ApiResponse Post([FromRoute] string name, [FromQuery] string project, [FromQuery] string dbSourceName)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, dbSourceName, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var ret = app.AddEndpoint(name);

                if (ret.IsSuccess)
                {
                    app.GetEndpoint(name, out var endpoint, out var _);
                    WorkSpawner.CreateNewWorker(endpoint);
                    SettingsInstance.SaveSettingsToFile();
                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #7
0
 private void Discard_Click(object sender, RoutedEventArgs e)
 {
     SettingsInstance.DiscardEditAll();
     _clicked = true;
     Close();
     _clicked = false;
 }
Beispiel #8
0
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (!_clicked && IsVisible)
            {
                var r = MessageBox.Show("Save changes?", "Sky Jukebox Settings",
                                        _close ? MessageBoxButton.YesNo : MessageBoxButton.YesNoCancel,
                                        MessageBoxImage.Question, _close ? MessageBoxResult.No : MessageBoxResult.Cancel);
                switch (r)
                {
                case MessageBoxResult.Cancel:
                    e.Cancel = true;
                    return;

                case MessageBoxResult.No:
                    SettingsInstance.DiscardEditAll();
                    break;

                case MessageBoxResult.Yes:
                    SettingsInstance.SaveEditAll();
                    break;
                }
            }
            if (_close)
            {
                return;
            }
            e.Cancel = true;
            Hide();
        }
Beispiel #9
0
        public ApiResponse ClearCache([FromRoute] string endpoint, [FromQuery] string projectName, [FromQuery] string dbSource)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(projectName, dbSource, out var proj, out var dbs, out var resp))
                {
                    return(resp);
                }

                if (!dbs.GetEndpoint(endpoint, out var ep, out var resp2))
                {
                    return(ApiResponse.ExclamationModal(resp2.userErrorVal));
                }


                if (ep.ClearCache())
                {
                    SettingsInstance.SaveSettingsToFile();

                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal("Failed to clear cache. Check session log for errors."));
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #10
0
        public ApiResponse UninstallOrm([FromRoute] string name, [FromQuery] string projectName, [FromQuery] string dbSourceName)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(projectName, dbSourceName, out var proj, out var dbSource, out var resp))
                {
                    return(resp);
                }

                if (!dbSource.GetEndpoint(name, out var endpoint, out var resp2))
                {
                    return(ApiResponse.ExclamationModal(resp2.userErrorVal));
                }

                var success = endpoint.UnInstallOrm();

                if (success)
                {
                    endpoint.IsOrmInstalled = false;
                    SettingsInstance.SaveSettingsToFile();

                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal("Failed to uninstall ORM"));
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #11
0
        public ApiResponse AddUpdateConnection([FromRoute] string endpoint, [FromQuery] string projectName, [FromQuery] string dbSourceName,
                                               [FromBody] Newtonsoft.Json.Linq.JObject json
                                               )
        {
            try
            {
                bool   isMetadata         = (bool)json["isMetadata"].ToObject(typeof(bool));
                string dataSource         = json["dataSource"].ToString();
                string catalog            = json["catalog"].ToString();
                string username           = json["username"].ToString();
                string password           = json["password"].ToString();
                int?   port               = json["port"].ToObject(typeof(int?)) as int?;
                bool   integratedSecurity = json["authType"].ToString() == "100";

                if (integratedSecurity)
                {
                    username = password = null;
                }

                if (!port.HasValue)
                {
                    port = 1433;
                }

                if (!ControllerHelper.GetProjectAndApp(projectName, dbSourceName, out var proj, out var dbSource, out var resp))
                {
                    return(resp);
                }

                if (!dbSource.GetEndpoint(endpoint, out var ep, out var resp2))
                {
                    return(ApiResponse.ExclamationModal(resp2.userErrorVal));
                }

                CommonReturnValueWithApplication ret = null;

                if (isMetadata)
                {
                    ret = ep.UpdateMetadataConnection(dataSource, catalog, username, password, port.Value);
                }
                else
                {
                    ret = ep.UpdateExecConnection(dataSource, catalog, username, password, port.Value);
                }

                if (!ret.IsSuccess)
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }

                WorkSpawner.RestartWorker(ep);
                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #12
0
        public ApiResponse DeleteEndpoint([FromRoute] string name, [FromQuery] string project, [FromQuery] string dbSourceName)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, dbSourceName, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                if (!app.GetEndpoint(name, out var endpoint, out var resp2))
                {
                    return(ApiResponse.ExclamationModal($"The endpoint '{name}' not found."));
                }
                var ret = app.DeleteEndpoint(name);

                if (ret.IsSuccess)
                {
                    WorkSpawner.RemoveEndpoint(endpoint);
                    SettingsInstance.SaveSettingsToFile();
                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
        public ApiResponse CreateRule([FromQuery] string project, [FromQuery(Name = "app")] string appName, [FromQuery] string file, [FromBody] Newtonsoft.Json.Linq.JObject json)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, appName, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var    type  = (RuleType)int.Parse(json["Type"].ToString());
                string value = json["Value"].ToString();


                if (file == null)
                { // DB-level
                    var ret = app.AddRule(type, value);

                    if (ret.IsSuccess)
                    {
                        SettingsInstance.SaveSettingsToFile();

                        WorkSpawner.SetRulesDirty(app);

                        return(ApiResponse.Success());
                    }
                    else
                    {
                        return(ApiResponse.ExclamationModal(ret.userErrorVal));
                    }
                }
                else
                {
                    var jsFile = app.GetJsFile(file);

                    if (jsFile == null)
                    {
                        return(ApiResponse.ExclamationModal("The specified output file was not found."));
                    }

                    var ret = jsFile.AddRule(type, value);

                    if (ret.IsSuccess)
                    {
                        SettingsInstance.SaveSettingsToFile();

                        WorkSpawner.SetRulesDirty(app, jsFile);

                        return(ApiResponse.Success());
                    }
                    else
                    {
                        return(ApiResponse.ExclamationModal(ret.userErrorVal));
                    }
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #14
0
        public ApiResponse SavePluginConfig([FromQuery] string project, [FromRoute] string name, [FromBody] List <dynamic> pluginList)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var ret = app.UpdatePluginList(pluginList);

                if (ret.IsSuccess)
                {
                    SettingsInstance.SaveSettingsToFile();
                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #15
0
        } // Run

        private async Task ProcessAsync(SqlConnection con, string connectionString)
        {
            var changesCount = await OrmDAL.GetRoutineListCntAsync(con, this.MaxRowDate);

            if (changesCount > 0)
            {
                last0Cnt = null;

                // commented out changes line, happens too frequently with just 1 change
                //this.log.Info($"{ changesCount } change(s) found using row date { this.MaxRowDate }");
                this.Status = $"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - { changesCount } change(s) found using rowdate { this.MaxRowDate}";

                var changesList = await GetAndProcessRoutineChangesAsync(con, connectionString, changesCount);

                if (changesList?.Count > 0)
                {
                    // call save for final changes
                    await this.Endpoint.SaveCacheAsync();

                    this.GenerateOutputFiles(this.Endpoint, changesList);
                    // save "settings" to persist JsFile version changes
                    SettingsInstance.SaveSettingsToFile();
                }
            }// if changeCount > 0
            else
            {
                if (last0Cnt == null)
                {
                    last0Cnt = DateTime.Now;
                }

                // only update status if we've been receiving 0 changes for a while
                if (DateTime.Now.Subtract(last0Cnt.Value).TotalSeconds > 30)
                {
                    last0Cnt    = DateTime.Now;
                    this.Status = $"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - no changes found";
                }

                // handle the case where the output files no longer exist but we have also not seen any changes on the DB again
                // TODO: !!!
                // dbSource.JsFiles.forEach(jsFile =>
                // {
                //     let path = dbSource.outputFilePath(jsFile);

                //     if (!fs.existsSync(path))
                //     {
                //         this.progress('Generating ' + jsFile.Filename);
                //         JsFileGenerator.generateJsFile(dbSource, jsFile);

                //         //!this.IsRulesDirty = false;
                //         //!this.IsOutputFilesDirty = false;
                //         dbSource.LastUpdateDate = new Date();
                //     }

                // });
            }
        } // Process
        public ApiResponse UpdateRule([FromQuery] string project, [FromQuery(Name = "app")] string appName, [FromQuery] string file, [FromRoute] string ruleId, [FromBody] Newtonsoft.Json.Linq.JObject json)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, appName, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                var    type  = (RuleType)int.Parse(json["Type"].ToString());
                string value = json["Value"].ToString();

                CommonReturnValue ret;
                JsFile            jsFile = null;

                if (file == null)
                { // DB-level
                    ret = app.UpdateRule(ruleId, value);
                }
                else
                {
                    jsFile = app.GetJsFile(file);

                    // TODO: Move check and error message down to App api?
                    if (jsFile == null)
                    {
                        return(ApiResponse.ExclamationModal("The specified output file was not found."));
                    }

                    ret = jsFile.UpdateRule(ruleId, value);
                }

                if (ret.IsSuccess)
                {
                    SettingsInstance.SaveSettingsToFile();

                    if (jsFile == null)
                    {
                        WorkSpawner.SetRulesDirty(app);
                    }
                    else
                    {
                        WorkSpawner.SetRulesDirty(app, jsFile);
                    }

                    return(ApiResponse.Success());
                }
                else
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
        public ApiResponse DeleteRule([FromQuery] string project, [FromQuery(Name = "app")] string appName, [FromQuery] string file, [FromRoute] string ruleId)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, appName, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                if (file == null)
                { // DB level
                    var ret = app.DeleteRule(ruleId);

                    if (ret.IsSuccess)
                    {
                        WorkSpawner.SetRulesDirty(app);
                        SettingsInstance.SaveSettingsToFile();
                        return(ApiResponse.Success());
                    }
                    else
                    {
                        return(ApiResponse.ExclamationModal(ret.userErrorVal));
                    }
                }
                else
                {
                    var jsFile = app.GetJsFile(file);

                    if (jsFile == null)
                    {
                        return(ApiResponse.ExclamationModal("The specified output file was not found."));
                    }

                    var ret = jsFile.DeleteRule(ruleId);

                    if (ret.IsSuccess)
                    {
                        WorkSpawner.SetRulesDirty(app, jsFile);
                        SettingsInstance.SaveSettingsToFile();
                        return(ApiResponse.Success());
                    }
                    else
                    {
                        return(ApiResponse.ExclamationModal(ret.userErrorVal));
                    }
                }
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
        public ApiResponse Delete([FromBody] string name)
        {
            var ret = SettingsInstance.Instance.DeleteProject(name);

            if (ret.IsSuccess)
            {
                SettingsInstance.SaveSettingsToFile();
                return(ApiResponse.Success());
            }
            else
            {
                return(ApiResponse.ExclamationModal(ret.userErrorVal));
            }
        }
        public ApiResponse UpdateProject([FromRoute] string name, [FromBody] string newName) // TODO: clean up interface...get some consistency
        {
            var ret = SettingsInstance.Instance.UpdateProject(name, newName);

            if (ret.IsSuccess)
            {
                Hubs.WorkerMonitor.Instance.NotifyObservers();
                SettingsInstance.SaveSettingsToFile();
                return(ApiResponse.Success());
            }
            else
            {
                return(ApiResponse.ExclamationModal(ret.userErrorVal));
            }
        }
Beispiel #20
0
        public ApiResponse SetupSharedMetadata([FromRoute] string endpointName, [FromQuery(Name = "project")] string projectName, [FromQuery(Name = "app")] string appName, [FromQuery(Name = "srcEndpointId")] string shareFromEndpointId)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndAppAndEndpoint(projectName, appName, endpointName, out var project, out var app, out var endpoint, out var resp))
                {
                    return(resp);
                }

                var shareDependencies = Settings.SettingsInstance.Instance
                                        .ProjectList
                                        .SelectMany(p => p.Applications)
                                        .SelectMany(a => a.Endpoints)
                                        .Where(ep => ep.PullMetadataFromEndpointId?.Equals(endpoint.Id, StringComparison.Ordinal) ?? false)
                                        .Select(ep => ep.Pedigree)
                ;

                if (shareDependencies.Count() > 0)
                {
                    return(ApiResponse.ExclamationModal($"This endpoint cannot be configured with metadata sharing while other endpoints dependent on it. The following endpoint(s) share metadata from this endpoint:<p>{string.Join("<br>", shareDependencies.ToArray())}</p>"));
                }

                var srcEndpoint = Settings.SettingsInstance.Instance.ProjectList.SelectMany(p => p.Applications).SelectMany(a => a.Endpoints).FirstOrDefault(ep => ep.Id.Equals(shareFromEndpointId, StringComparison.Ordinal));


                if (srcEndpoint == null)
                {
                    return(ApiResponse.ExclamationModal($"Failed to find source endpoint with id: {shareFromEndpointId ?? "(null)"}"));
                }
                else if (srcEndpoint == endpoint)
                {
                    return(ApiResponse.ExclamationModal($"Endpoint cannot share with itself"));
                }

                endpoint.ShareMetadaFrom(srcEndpoint);
                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #21
0
        public ApiResponse ClearSharedMetadata([FromRoute] string endpointName, [FromQuery(Name = "project")] string projectName, [FromQuery(Name = "app")] string appName)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndAppAndEndpoint(projectName, appName, endpointName, out var project, out var app, out var endpoint, out var resp))
                {
                    return(resp);
                }

                endpoint.ShareMetadaFrom(null);
                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #22
0
        public ApiResponse CreateApplication([FromBody] string name, [FromQuery] string project, [FromQuery] string jsNamespace, [FromQuery] int?defaultRuleMode)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(name))
                {
                    return(ApiResponse.ExclamationModal("Please provide a valid application name."));
                }

                if (!defaultRuleMode.HasValue)
                {
                    return(ApiResponse.ExclamationModal("Please specify the default rule mode."));
                }

                if (!ControllerHelper.GetProject(project, out var proj, out var resp))
                {
                    return(resp);
                }

                var existing = proj.GetApplication(name);

                if (existing != null)
                {
                    return(ApiResponse.ExclamationModal($"The application \"{ name }\" already exists on project \" { project }\"."));
                }

                var ret = proj.AddApplication(name, jsNamespace, defaultRuleMode.Value);

                if (!ret.IsSuccess)
                {
                    return(ApiResponse.ExclamationModal(ret.userErrorVal));
                }

                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #23
0
        public ApiResponse UpdateEndpoint([FromRoute] string name, [FromBody] string newName, [FromQuery] string project, [FromQuery] string dbSourceName)
        {
            if (!ControllerHelper.GetProjectAndApp(project, dbSourceName, out var proj, out var dbSource, out var resp))
            {
                return(resp);
            }

            var ret = dbSource.UpdateEndpoint(name, newName);

            if (ret.IsSuccess)
            {
                SettingsInstance.SaveSettingsToFile();
                Hubs.WorkerMonitor.Instance.NotifyObservers();
                return(ApiResponse.Success());
            }
            else
            {
                return(ApiResponse.ExclamationModal(ret.userErrorVal));
            }
        }
Beispiel #24
0
        public ApiResponse EnableDisableMetadataCapturing([FromRoute] string name, [FromQuery(Name = "project")] string projectName, [FromQuery(Name = "dbSource")] string dbSourceName, [FromQuery] bool enable)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(projectName, dbSourceName, out var proj, out var dbSource, out var resp))
                {
                    return(resp);
                }

                if (!dbSource.GetEndpoint(name, out var endpoint, out var resp2))
                {
                    return(ApiResponse.ExclamationModal(resp2.userErrorVal));
                }

                if (!enable)
                {
                    var shareDependencies = Settings.SettingsInstance.Instance
                                            .ProjectList
                                            .SelectMany(p => p.Applications)
                                            .SelectMany(a => a.Endpoints)
                                            .Where(ep => ep.PullMetadataFromEndpointId?.Equals(endpoint.Id, StringComparison.Ordinal) ?? false)
                                            .Select(ep => ep.Pedigree)
                    ;

                    if (shareDependencies.Count() > 0)
                    {
                        return(ApiResponse.ExclamationModal($"Cannot disable metadata capturing on this endpoint while other endpoints depend on it. The following endpoint(s) share metadata from this endpoint:<p>{string.Join("<br>", shareDependencies.ToArray())}</p>"));
                    }
                }

                endpoint.DisableMetadataCapturing = !enable;

                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #25
0
        public ApiResponse UpdateJsFile([FromQuery] string project, [FromRoute] string name, [FromQuery] string oldName, [FromQuery] string newName)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                //!if (!newName.ToLower().EndsWith(".js")) newName += ".js";

                // TODO: All validation needs to be move OM API
                var existing = app.JsFiles.FirstOrDefault(js => js.Filename.Equals(oldName, StringComparison.OrdinalIgnoreCase));

                if (existing == null)
                {
                    return(ApiResponse.ExclamationModal($"The output file \"{oldName}\" does not exist in \"{project}/{name}\""));
                }

                var existingNewName = app.JsFiles.FirstOrDefault(js => js.Filename.Equals(newName, StringComparison.OrdinalIgnoreCase));

                if (existingNewName != null)
                {
                    return(ApiResponse.ExclamationModal($"The output file \"{newName}\" already exists in \"{project}/{name}\""));
                }

                existing.Filename = newName;
                SettingsInstance.SaveSettingsToFile();

                //!GeneratorThreadDispatcher.SetOutputFilesDirty(cs);

                return(ApiResponse.Success());
            }
            catch (Exception ex)
            {
                return(ApiResponse.Exception(ex));
            }
        }
Beispiel #26
0
        public ApiResponse UpdateWhitelist([FromQuery] string project, [FromRoute] string name, [FromQuery] string whitelist, [FromQuery] bool allowAllPrivate)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                app.WhitelistAllowAllPrivateIPs = allowAllPrivate;

                if (whitelist != null)
                {
                    var ar = whitelist.Split('\n').Select(w => w.Trim()).Where(w => !string.IsNullOrEmpty(w));

                    if (ar.Count() > 0)
                    {
                        app.WhitelistedDomainsCsv = string.Join(",", ar);
                    }
                    else
                    {
                        app.WhitelistedDomainsCsv = null;
                    }
                }
                else
                {
                    app.WhitelistedDomainsCsv = null;
                }

                SettingsInstance.SaveSettingsToFile();

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #27
0
        public ApiResponse DeleteApplication([FromQuery] string project, string name)
        {
            try
            {
                if (!ControllerHelper.GetProjectAndApp(project, name, out var proj, out var app, out var resp))
                {
                    return(resp);
                }

                if (proj.DeleteApplication(app))
                {
                    SettingsInstance.SaveSettingsToFile();

                    //!WorkSpawner.RemoveApplication(cs); TODO: Move to endpoint
                }

                return(ApiResponse.Success());
            }
            catch (Exception e)
            {
                return(ApiResponse.Exception(e));
            }
        }
Beispiel #28
0
 public DelPerm(SettingsInstance settings)
 {
     _settings = settings;
 }
Beispiel #29
0
        protected PageRenderer editPage(SettingsProperties props, string backPage, Dictionary <string, PageRenderer> pages, Action <Flow> onBackHandler = null)
        {
            RowLayoutRenderer rows = new RowLayoutRenderer();
            List <ISettingsFieldProperties> fis = props.fields;

            foreach (ISettingsFieldProperties p in fis)
            {
                if (!p.isList && p.isSelectable)
                {
                    ISettingsFieldPropertiesSelectSingle pSelect = (ISettingsFieldPropertiesSelectSingle)p;
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(pSelect.label, 200f).attachTooltip(p.labelTooltip))
                                  .AddChild(new ButtonTextRenderer(f => pSelect.labelProducer(((ISettingsInstance)f.flowScope["edit"]).get <object>(p.id)),
                                                                   f => Find.WindowStack.Add(new Dialog_Select <object>(pSelect.onSelectItem(f), pSelect.selectableItems(f), pSelect.labelProducer)),
                                                                   GameFont.Small, 200f)));
                }
                else if (p.type == typeof(bool))
                {
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 200f).attachTooltip(p.labelTooltip))
                                  .AddChild(new CheckboxRenderer(f => ((ISettingsInstance)f.flowScope["edit"]).get <bool>(p.id), (f, v) => ((ISettingsInstance)f.flowScope["edit"]).set(p.id, v))));
                }
                else if (p.type == typeof(int))
                {
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 200f).attachTooltip(p.labelTooltip))
                                  .AddChild(new EditNumericRenderer <int>(f => ((ISettingsInstance)f.flowScope["edit"]).get <int>(p.id), (f, v) => ((ISettingsInstance)f.flowScope["edit"]).set(p.id, v),
                                                                          200f, ((ISettingsFieldPropertiesPrimitiveInt)p).minValue, ((ISettingsFieldPropertiesPrimitiveInt)p).maxValue)));
                }
                else if (p.type == typeof(float))
                {
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 200f).attachTooltip(p.labelTooltip))
                                  .AddChild(new EditNumericRenderer <float>(f => ((ISettingsInstance)f.flowScope["edit"]).get <float>(p.id), (f, v) => ((ISettingsInstance)f.flowScope["edit"]).set(p.id, v),
                                                                            200f, ((ISettingsFieldPropertiesPrimitiveFloat)p).minValue, ((ISettingsFieldPropertiesPrimitiveFloat)p).maxValue)));
                }
                else if (p.type == typeof(string))
                {
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 200f).attachTooltip(p.labelTooltip))
                                  .AddChild(new EditTextRenderer(f => ((ISettingsInstance)f.flowScope["edit"]).get <string>(p.id), (f, v) => ((ISettingsInstance)f.flowScope["edit"]).set(p.id, v),
                                                                 200f, ((ISettingsFieldPropertiesPrimitiveString)p).maxNumOfChars, ((ISettingsFieldPropertiesPrimitiveString)p).inputValidator)));
                }
                else if (p.type == typeof(Color))
                {
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 200f).attachTooltip(p.labelTooltip))
                                  .AddChild(new EditColorRenderer(f => ((ISettingsInstance)f.flowScope["edit"]).get <Color>(p.id),
                                                                  (f, c) => ((ISettingsInstance)f.flowScope["edit"]).set <Color>(p.id, c),
                                                                  200f)));
                }
                else if (p.isList && ((ISettingsFieldPropertiesList)p).isListSettings)
                {
                    SettingsFieldPropertiesListSettings pList = (SettingsFieldPropertiesListSettings)p;
                    SettingsProperties props2         = SettingsStorage.getSettingsProperties(pList.idEnclosedSettings);
                    string             deepEditPageId = backPage + "edit" + pList.id + props2.id;
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 400f, GameFont.Small, TextAnchor.MiddleCenter).attachTooltip(p.labelTooltip)));
                    rows.AddChild(new ListRenderer(f => {
                        List <SettingsInstance> lst = ((ISettingsInstance)f.flowScope["edit"]).get <List <SettingsInstance> >(pList.id);
                        //avoiding nullpointer if the default value for a list is null or if a save state didnt contain the list
                        if (lst == null)
                        {
                            lst = new List <SettingsInstance>();
                            ((ISettingsInstance)f.flowScope["edit"]).set <List <SettingsInstance> >(pList.id, lst);
                        }
                        return(lst);
                    }, 400f + QOLMod.VerticalScrollbarWidth(), QOLMod.LineHeight(GameFont.Small) * 3)

                                  .AddChild(new ButtonTextRenderer(f => ((ISettingsInstance)((IterationItem)f.pageScope["curItem"]).curItem).getLabel(),
                                                                   f => {
                        f.flowScope["edit"] = ((IterationItem)f.pageScope["curItem"]).curItem;
                        f.navigate(deepEditPageId);
                    }, GameFont.Small, pList.isRemovalAllowed ? 380f : 400f))
                                  .AddChild(pList.isRemovalAllowed ? new ButtonTextRenderer("-", f => {
                        ISettingsInstance setting = (ISettingsInstance)f.flowScope["edit"];
                        SettingsInstance lstItem  = (SettingsInstance)((IterationItem)f.pageScope["curItem"]).curItem;
                        f.addPostRenderCallback(fl => {
                            if (setting.get <List <SettingsInstance> >(p.id).Remove(lstItem))
                            {
                                setting.markAsChanged();
                            }
                        });
                    }, GameFont.Small, 20f) : null));
                    rows.AddChild(pList.isAddingAllowed ? new ColumnLayoutRenderer()
                                  .AddChild(new ButtonTextRenderer("+",
                                                                   f => {
                        SettingsInstance newItem = (SettingsInstance)pList.createNewEntry();
                        if (newItem != null)
                        {
                            ((ISettingsInstance)f.flowScope["edit"]).get <List <SettingsInstance> >(p.id).Add(newItem);
                            newItem.attach(((ISettingsInstance)f.flowScope["edit"]));
                            ((ISettingsInstance)f.flowScope["edit"]).markAsChanged();
                        }
                    },
                                                                   GameFont.Small, 400f)) : null);
                    pages.Add(deepEditPageId, editPage(props2, "edit" + props.id, pages, f => { f.flowScope["edit"] = ((ISettingsInstance)f.flowScope["edit"]).getParentObject(); }));
                }
                else if (p.isList && ((ISettingsFieldPropertiesList)p).isListPrimitive)
                {
                    SettingsFieldPropertiesListPrimitive pList = (SettingsFieldPropertiesListPrimitive)p;
                    Type listItemType = pList.type.GetGenericArguments()[0];
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 400f, GameFont.Small, TextAnchor.MiddleCenter).attachTooltip(p.labelTooltip)));
                    ListRenderer lstRenderer = new ListRenderer(f => {
                        IList lst = ((ISettingsInstance)f.flowScope["edit"]).get <IList>(pList.id);
                        //avoiding nullpointer if the default value for a list is null or if a save state didnt contain the list
                        if (lst == null)
                        {
                            lst = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(listItemType), null);
                            ((ISettingsInstance)f.flowScope["edit"]).set <IList>(pList.id, lst);
                        }
                        return(lst);
                    }, 400f + QOLMod.VerticalScrollbarWidth(), QOLMod.LineHeight(GameFont.Small) * 3);

                    float editRendererWidth;
                    if (pList.listLabelProducer != null)
                    {
                        lstRenderer.AddChild(new LabelRenderer(f => pList.listLabelProducer((ISettingsInstance)f.flowScope["edit"], f), 200f));
                        editRendererWidth = 200f;
                    }
                    else
                    {
                        editRendererWidth = 400f;
                    }
                    //Currently no min max etc for the list item type
                    if (listItemType == typeof(float))
                    {
                        lstRenderer.AddChild(new EditNumericRenderer <float>(f => (float)((IterationItem)f.pageScope["curItem"]).curItem,
                                                                             (f, v) => { ((ISettingsInstance)f.flowScope["edit"]).get <IList>(pList.id)[((IterationItem)f.pageScope["curItem"]).index] = v; ((ISettingsInstance)f.flowScope["edit"]).markAsChanged(); },
                                                                             editRendererWidth /*,((ISettingsFieldPropertiesPrimitiveFloat)p).minValue,((ISettingsFieldPropertiesPrimitiveFloat)p).maxValue*/));
                    }
                    else if (listItemType == typeof(int))
                    {
                        lstRenderer.AddChild(new EditNumericRenderer <int>(f => (int)((IterationItem)f.pageScope["curItem"]).curItem,
                                                                           (f, v) => { ((ISettingsInstance)f.flowScope["edit"]).get <IList>(pList.id)[((IterationItem)f.pageScope["curItem"]).index] = v; ((ISettingsInstance)f.flowScope["edit"]).markAsChanged(); },
                                                                           editRendererWidth /*,((ISettingsFieldPropertiesPrimitiveInt)p).minValue,((ISettingsFieldPropertiesPrimitiveInt)p).maxValue*/));
                    }
                    else if (listItemType == typeof(bool))
                    {
                        lstRenderer.AddChild(new CheckboxRenderer(f => (bool)((IterationItem)f.pageScope["curItem"]).curItem,
                                                                  (f, v) => { ((ISettingsInstance)f.flowScope["edit"]).get <IList>(pList.id)[((IterationItem)f.pageScope["curItem"]).index] = v; ((ISettingsInstance)f.flowScope["edit"]).markAsChanged(); }));
                    }
                    else if (listItemType == typeof(string))
                    {
                        lstRenderer.AddChild(new EditTextRenderer(f => (string)((IterationItem)f.pageScope["curItem"]).curItem,
                                                                  (f, v) => { ((ISettingsInstance)f.flowScope["edit"]).get <IList>(pList.id)[((IterationItem)f.pageScope["curItem"]).index] = v; ((ISettingsInstance)f.flowScope["edit"]).markAsChanged(); },
                                                                  editRendererWidth /*,((ISettingsFieldPropertiesPrimitiveString)p).maxNumOfChars,((ISettingsFieldPropertiesPrimitiveString)p).inputValidator*/));
                    }
                    rows.AddChild(lstRenderer);
                }
                else if (p.isList && ((ISettingsFieldPropertiesList)p).isSelectable)
                {
                    SettingsFieldPropertiesListSelectable pList = (SettingsFieldPropertiesListSelectable)p;
                    Type listItemType = pList.type.GetGenericArguments()[0];
                    rows.AddChild(new ColumnLayoutRenderer()
                                  .AddChild(new LabelRenderer(p.label, 400f, GameFont.Small, TextAnchor.MiddleCenter).attachTooltip(p.labelTooltip)));
                    ListRenderer lstRenderer = new ListRenderer(f => {
                        IList lst = ((ISettingsInstance)f.flowScope["edit"]).get <IList>(pList.id);
                        //avoiding nullpointer if the default value for a list is null or if a save state didnt contain the list
                        if (lst == null)
                        {
                            lst = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(listItemType), null);
                            ((ISettingsInstance)f.flowScope["edit"]).set <IList>(pList.id, lst);
                        }
                        return(lst);
                    }, 400f + QOLMod.VerticalScrollbarWidth(), QOLMod.LineHeight(GameFont.Small) * 3);

                    lstRenderer.AddChild(new ButtonTextRenderer(f => pList.labelProducer(((IterationItem)f.pageScope["curItem"]).curItem),
                                                                f => Find.WindowStack.Add(new Dialog_Select <object>(pList.onSelectItem(f), pList.selectableItems(f), pList.labelProducer, null, pList.tooltipProducer)),
                                                                GameFont.Small, pList.isRemovalAllowed ? 380f : 400f));
                    if (pList.tooltipProducer != null)
                    {
                        lstRenderer.childs[0].attachTooltip(f => pList.tooltipProducer(((IterationItem)f.pageScope["curItem"]).curItem));
                    }
                    lstRenderer.AddChild(pList.isRemovalAllowed ? new ButtonTextRenderer("-", f => {
                        ISettingsInstance setting = (ISettingsInstance)f.flowScope["edit"];
                        object lstItem            = ((IterationItem)f.pageScope["curItem"]).curItem;
                        f.addPostRenderCallback(fl => {
                            IList lst = setting.get <IList>(p.id);
                            if (lst.Contains(lstItem))
                            {
                                lst.Remove(lstItem);
                                setting.markAsChanged();
                            }
                        });
                    },
                                                                                         GameFont.Small, 20f):null);

                    rows.AddChild(lstRenderer);

                    rows.AddChild(pList.isAddingAllowed ? new ColumnLayoutRenderer()
                                  .AddChild(new ButtonTextRenderer("+",
                                                                   f => {
                        object newItem = pList.createNewEntry();
                        if (newItem != null)
                        {
                            ISettingsInstance currentSettings = ((ISettingsInstance)f.flowScope["edit"]);
                            IList lst = currentSettings.get <IList>(p.id);
                            f.addPostRenderCallback(fl => {
                                lst.Add(newItem);
                                if (pList.isSettings)
                                {
                                    ((ISettingsInstance)newItem).attach(currentSettings);
                                }
                                currentSettings.markAsChanged();
                            });
                        }
                    },
                                                                   GameFont.Small, 400f)) : null);
                }
            }

            return(new PageRenderer(((ISettingsVisualizationEdit)props.visualization).getEditPageTitle, null, () => backPage, onBackHandler).AddChild(new VerticalScrollViewRenderer().AddChild(rows)));
        }
Beispiel #30
0
 public ListPerms(SettingsInstance instance, Func<MessageSource, bool> predicate)
 {
     _instance = instance;
     _predicate=predicate;
 }
Beispiel #31
0
 public ListPerms(SettingsInstance instance)
     : this(instance, x => true)
 {
 }
Beispiel #32
0
 public AddPerm(SettingsInstance settings)
 {
     _settings = settings;
 }
Beispiel #33
0
 public DelStream(StreamHandler handler, SettingsInstance settings)
 {
     _handler=handler;
     _settings = settings;
 }
Beispiel #34
0
        public BackgroundWorker InstallOrm()
        {
            var missing = CheckForMissingOrmPreRequisitesOnDatabase();

            if (string.IsNullOrEmpty(missing))
            {
                return(null);
            }

            var sqlScriptPath    = Path.GetFullPath("./resources/install-orm.sql");
            var installSqlScript = File.ReadAllText(sqlScriptPath, System.Text.Encoding.UTF8);

            //https://stackoverflow.com/a/18597052
            var statements = Regex.Split(installSqlScript, @"^[\s]*GO[\s]*\d*[\s]*(?:--.*)?$", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);

            var statementsToExec = statements.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim(' ', '\r', '\n'));

            using (var con = new SqlConnection())
            {
                con.ConnectionString = this.MetadataConnection.ConnectionStringDecrypted;
                con.Open();

                var trans = con.BeginTransaction();

                try
                {
                    foreach (var st in statementsToExec)
                    {
                        var cmd = new SqlCommand();

                        cmd.Connection     = con;
                        cmd.Transaction    = trans;
                        cmd.CommandType    = System.Data.CommandType.Text;
                        cmd.CommandText    = st;
                        cmd.CommandTimeout = 80;

                        cmd.ExecuteNonQuery();
                    }

                    trans.Commit();
                }
                catch (Exception ex)
                {
                    if (trans != null)
                    {
                        trans.Rollback();
                    }
                    SessionLog.Exception(ex);
                }

                con.Close();

                BackgroundWorker backgroundWorker = null;

                backgroundWorker = BackgroundTask.Queue($"{GetBgTaskKey()}.ORM_INIT", $"{Application.Project.Name}/{Application.Name}/{this.Name} ORM initilisation", () =>
                {
                    // try
                    // {
                    using (var conInit = new SqlConnection())
                    {
                        con.FireInfoMessageEventOnUserErrors = true;
                        conInit.ConnectionString             = this.MetadataConnection.ConnectionStringDecrypted;
                        conInit.Open();

                        var cmdInit = new SqlCommand();

                        cmdInit.Connection     = conInit;
                        cmdInit.CommandText    = "ormv2.Init";
                        cmdInit.CommandTimeout = 600;

                        conInit.InfoMessage += (sender, e) =>
                        {
                            if (!backgroundWorker.IsDone && double.TryParse(e.Message, out var p))
                            {
                                backgroundWorker.Progress = p;
                                Hubs.BackgroundTaskMonitor.Instance.NotifyOfChange(backgroundWorker);
                            }
                        };

                        cmdInit.ExecuteScalar();


                        WorkSpawner.HandleOrmInstalled(this);
                        SettingsInstance.SaveSettingsToFile();

                        return(true);
                    }
                    // }
                    // catch (Exception ex)
                    // {
                    //     return ex;
                    //     //return ex;
                    // }
                });

                return(backgroundWorker);
            }
        }
Beispiel #35
0
        public static void Main(string[] args)
        {
            IsShuttingDown = false;

            var loggerConfig = new LoggerConfiguration()
                               .MinimumLevel.Debug()
                               .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                               .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                               .Enrich.FromLogContext()

                               .WriteTo.File("log/detail-.txt",
                                             //?restrictedToMinimumLevel: LogEventLevel.Warning,
                                             rollingInterval: RollingInterval.Day,
                                             retainedFileCountLimit: 7,
                                             shared: true,
                                             outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3} {Message:lj}{NewLine}{Exception}"
                                             )
                               // .WriteTo.File("log/info-.txt",
                               //         rollingInterval: RollingInterval.Day,
                               //         shared: true,
                               //         outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3} {Message:lj}{NewLine}{Exception}",
                               //         restrictedToMinimumLevel: LogEventLevel.Information
                               //         )
            ;

            try
            {
                CTS = new CancellationTokenSource();

                var isService = args.Length == 1 && args[0].Equals("--service", StringComparison.OrdinalIgnoreCase);
                var justRun   = args.Length == 1 && args[0].Equals("--run", StringComparison.OrdinalIgnoreCase);

                if (isService)
                {
                    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
                    var pathToContentRootService = Path.GetDirectoryName(pathToExe);
                    Directory.SetCurrentDirectory(pathToContentRootService);
                }
                else if (!Debugger.IsAttached && !justRun)
                {
                    TerminalUI.Init();
                    return;
                }
                else
                {
                    loggerConfig.WriteTo.Console();
                }

                Log.Logger = loggerConfig.CreateLogger();

                var pathToContentRoot = Directory.GetCurrentDirectory();

                if (Debugger.IsAttached)
                {
                    // var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
                    //  pathToContentRoot = Path.GetDirectoryName(pathToExe);
                }
                else
                {
                    // now relying on serilog
                    // OverrideStdout();
                }

                AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
                {
                    var isTerminating = e.IsTerminating;

                    Log.Fatal("Unhandled exception", e.ExceptionObject);
                    ExceptionLogger.LogException(e.ExceptionObject as Exception);
                };

                AppConfigSettings appConfigSettings = null;

                try
                {
                    var appSettingsJson = File.ReadAllText("./appsettings.json");

                    appConfigSettings = System.Text.Json.JsonSerializer.Deserialize <AppConfigSettings>(appSettingsJson);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to read appsettings.json");
                }

                _startDate = DateTime.Now;

                var _ = UptimeLogger.LogServerUptimeAsync();

                Log.Information($"Application started with process id {System.Diagnostics.Process.GetCurrentProcess().Id}.");

                // I forget what the different msg types look like
                Log.Warning("This is what a warning looks like");
                Log.Error("This is what an error looks like");
                Log.Fatal("This is what a fatal error looks like");

                Log.Information("Loading users");
                UserManagement.LoadUsersFromFile();

                Log.Information("Initialising exception logger");
                ExceptionLogger.Instance.Init();

                Log.Information("Loading settings");
                SettingsInstance.LoadSettingsFromFile();

                Log.Information("Initialising real-time tracker");
                RealtimeTrackerThread.Instance.Init();

                if (appConfigSettings?.AppSettings?.Startup?.HealthMonitor ?? false)
                {
                    Log.Information("Initialising jsDAL health monitor");
                    jsDALHealthMonitorThread.Instance.Init();
                }
                else
                {
                    Log.Information("jsDAL health monitor not configured to run at startup");
                }

                if (appConfigSettings?.AppSettings?.Startup?.DataCollector ?? false)
                {
                    Log.Information("Initialising data collector");
                    DataCollectorThread.Instance.Init();
                }
                else
                {
                    Log.Information("Data collector not configured to run at startup");
                }

                Log.Information("Initialising inline module manifest");
                InlineModuleManifest.Instance.Init();


                Log.Information("Configuring global culture");
                var globalCulture = new System.Globalization.CultureInfo("en-US");

                // set global culture to en-US - will help with things like parsing numbers from Javascript(e.g. 10.123) as double/decimal even if server uses a comma as decimal separator for example
                CultureInfo.DefaultThreadCurrentCulture   = globalCulture;
                CultureInfo.DefaultThreadCurrentUICulture = globalCulture;

                Log.Information("Building web host");
                var builder = BuildWebHost(pathToContentRoot, args);
                var host    = builder.Build();

                if (isService)
                {
                    host.RunAsCustomService();
                }
                else
                {
                    host.RunAsync();

                    Console.WriteLine("\r\nPress CTRL+X to shutdown server");

                    while (true)
                    {
                        var keyInfo = Console.ReadKey(true);

                        if (keyInfo.Key == ConsoleKey.X && (keyInfo.Modifiers & ConsoleModifiers.Control) == ConsoleModifiers.Control)
                        {
                            //host.StopAsync();
                            ShutdownAllBackgroundThreads();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application terminated unexpectedly");
                SessionLog.Exception(ex);

                ShutdownAllBackgroundThreads();
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }