Exemplo n.º 1
0
        public void TestInstanceClassWithoutKey()
        {
            InstanceConfig config = new InstanceConfig();

            ConfigManager configManager = new ConfigManager();

            configManager.Register(config);
            configManager.RegisterProvider(new ConfigurationProviderAppConfig());
            configManager.Update();

            Assert.AreEqual("xx1", config.Test1);
            Assert.AreEqual(99, config.SubObject1.TestInt1);

            Assert.IsNotNull(config.IntValues);
            Assert.IsNotNull(config.StringValues);

            Assert.AreEqual("x", config.StringValues["ValX"]);
            Assert.AreEqual("y", config.StringValues["ValY"]);
            Assert.AreEqual("z", config.StringValues["ValZ"]);

            Assert.AreEqual(3, config.StringValues.Count);

            Assert.AreEqual(1, config.IntValues["Val1"]);
            Assert.AreEqual(2, config.IntValues["Val2"]);
            Assert.AreEqual(3, config.IntValues["Val3"]);

            Assert.AreEqual(3, config.IntValues.Count);
        }
Exemplo n.º 2
0
        public void TestInstanceClassWithoutKey()
        {
            InstanceConfig config = new InstanceConfig();

            ConfigManager configManager = new ConfigManager();

            configManager.Register(config);
            configManager.RegisterProvider(new ConfigurationProviderAppConfig());
            configManager.Update();

            Assert.AreEqual("xx1", config.Test1);
            Assert.AreEqual(99, config.SubObject1.TestInt1);

            Assert.IsNotNull(config.IntValues);
            Assert.IsNotNull(config.StringValues);

            Assert.AreEqual("x", config.StringValues["ValX"]);
            Assert.AreEqual("y", config.StringValues["ValY"]);
            Assert.AreEqual("z", config.StringValues["ValZ"]);

            Assert.AreEqual(3, config.StringValues.Count);

            Assert.AreEqual(1, config.IntValues["Val1"]);
            Assert.AreEqual(2, config.IntValues["Val2"]);
            Assert.AreEqual(3, config.IntValues["Val3"]);

            Assert.AreEqual(3, config.IntValues.Count);
        }
Exemplo n.º 3
0
        public HttpResponseMessage GetSetupModulesMetadata([FromUri] InstanceConfig config)
        {
            try
            {
                var instance = new InstanceInfo(config);
                var version  = instance.Version;

                // Get all modules of given version which are in 'Setup' category
                var modules = ModuleLoader.Modules
                              .Select(x => x.GetModuleMetadata())
                              .Where(x => x.SupportedVersions.Contains(version))
                              .Where(x => x.Category != null && x.Category.StartsWith("Setup", StringComparison.InvariantCultureIgnoreCase));

                if (!modules.Any())
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, $"There are no modules available for version {version}."));
                }

                return(Request.CreateResponse(HttpStatusCode.OK, modules));
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }
        }
Exemplo n.º 4
0
        public async Task GetInstanceConfigAsync()
        {
            Mock <InstanceAdmin.InstanceAdminClient> mockGrpcClient = new Mock <InstanceAdmin.InstanceAdminClient>(MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient())
            .Returns(new Mock <Operations.OperationsClient>().Object);
            GetInstanceConfigRequest expectedRequest = new GetInstanceConfigRequest
            {
                InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"),
            };
            InstanceConfig expectedResponse = new InstanceConfig
            {
                InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"),
                DisplayName        = "displayName1615086568",
            };

            mockGrpcClient.Setup(x => x.GetInstanceConfigAsync(expectedRequest, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <InstanceConfig>(Task.FromResult(expectedResponse), null, null, null, null));
            InstanceAdminClient client   = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
            InstanceConfigName  name     = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]");
            InstanceConfig      response = await client.GetInstanceConfigAsync(name);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Loads culture from the instance configuration file.
        /// </summary>
        public static bool LoadCulture(string fileName, out string errMsg)
        {
            InstanceConfig instanceConfig = new InstanceConfig();
            bool           result         = instanceConfig.Load(fileName, out errMsg);

            SetCulture(instanceConfig.Culture);
            return(result);
        }
Exemplo n.º 6
0
 protected JobThread(string name, bool wait, LogType logType, string[] args)
 {
     this.name              = name;
     this.wait              = wait;
     this.args              = args;
     this.logType           = logType;
     this.traceSwitch       = new TraceSwitch(name, name + " Trace Switch");
     this.traceSwitch.Level = InstanceConfig.ConvertLogLevel(logType.LogLevel);
 }
Exemplo n.º 7
0
        public SqlInstanceAuditor(TraceContext context)
        {
            this.trace    = context.Trace;
            this.instance = trace.Instance;
            this.context  = context;
            ts            = new CancellationTokenSource();
            tsk           = new Task(InternalStart, ts.Token, TaskCreationOptions.LongRunning);

            queue          = new ConcurrentQueue <TraceEvent>();
            this.observers = context.TraceObservers;
        }
Exemplo n.º 8
0
 /// <summary>Snippet for GetInstanceConfig</summary>
 public void GetInstanceConfig()
 {
     // Snippet: GetInstanceConfig(InstanceConfigName,CallSettings)
     // Create client
     InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();
     // Initialize request argument(s)
     InstanceConfigName name = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]");
     // Make the request
     InstanceConfig response = instanceAdminClient.GetInstanceConfig(name);
     // End snippet
 }
Exemplo n.º 9
0
        public void EnsureTrailingSlash(string url, string expected)
        {
            var instanceConfig = new InstanceConfig
            {
                Url = url
            };

            var instanceInfo = new InstanceInfo(instanceConfig);

            Assert.AreEqual(expected, instanceInfo.Uri.AbsoluteUri);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Starts the service.
        /// </summary>
        public bool StartService()
        {
#if DEBUG
            System.Diagnostics.Debugger.Launch();
#endif

            // load instance configuration
            AppDirs.Init(Assembly.GetExecutingAssembly());
            InstanceConfig instanceConfig = new InstanceConfig();
            Locale.SetCultureToEnglish();

            if (instanceConfig.Load(InstanceConfig.GetConfigFileName(AppDirs.InstanceDir), out string errMsg))
            {
                Locale.SetCulture(instanceConfig.Culture);
                AppDirs.UpdateLogDir(instanceConfig.LogDir);
            }
            else
            {
                Console.WriteLine(errMsg);
                Locale.SetCultureToDefault();
            }

            // initialize log
            log = new LogFile(LogFormat.Full, Path.Combine(AppDirs.LogDir, EngineUtils.LogFileName));
            log.WriteBreak();

            // prepare to start service
            log.WriteAction(Locale.IsRussian ?
                            "Агент {0} запущен" :
                            "Agent {0} started", EngineUtils.AppVersion);

            AgentConfig appConfig = new AgentConfig();

            if (AppDirs.CheckExistence(out errMsg) &&
                LocalizeApp() &&
                appConfig.Load(Path.Combine(AppDirs.ConfigDir, AgentConfig.DefaultFileName), out errMsg))
            {
                // start service
                coreLogic = new CoreLogic(appConfig, AppDirs, log);

                if (coreLogic.StartProcessing())
                {
                    return(true);
                }
            }
            else if (!string.IsNullOrEmpty(errMsg))
            {
                log.WriteError(errMsg);
            }

            log.WriteError(CommonPhrases.ExecutionImpossible);
            return(false);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Gets the connection options from the instance configuration.
        /// </summary>
        public static DbConnectionOptions GetConnectionOptions(InstanceConfig instanceConfig)
        {
            if (instanceConfig.Storages.TryGetValue(StorageCode, out XmlElement storageElem) &&
                storageElem.SelectSingleNode("Connection") is XmlNode connectionNode)
            {
                DbConnectionOptions connOptions = new DbConnectionOptions();
                connOptions.LoadFromXml(connectionNode);
                return(connOptions);
            }

            throw new ScadaException(CommonPhrases.ConnOptionsNotFound);
        }
Exemplo n.º 12
0
        private readonly ReaderWriterLockSlim configLock; // synchronizes access to the instance configuration


        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public ScadaInstance(AppDirs appDirs, ILog log, InstanceOptions instanceOptions, InstanceConfig instanceConfig)
        {
            if (appDirs == null)
            {
                throw new ArgumentNullException(nameof(appDirs));
            }

            this.log             = log ?? throw new ArgumentNullException(nameof(log));
            this.instanceOptions = instanceOptions ?? throw new ArgumentNullException(nameof(instanceOptions));
            this.instanceConfig  = instanceConfig ?? throw new ArgumentNullException(nameof(instanceConfig));
            configLock           = new ReaderWriterLockSlim();
            PathBuilder          = new PathBuilder(instanceOptions.Directory, instanceConfig.LogDir, appDirs.ExeDir);
        }
Exemplo n.º 13
0
 public HttpResponseMessage GetKenticoVersion([FromUri] InstanceConfig config)
 {
     try
     {
         var instance = new InstanceInfo(config);
         var version  = instance.Version;
         return(Request.CreateResponse(HttpStatusCode.OK, version));
     }
     catch (Exception e)
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
     }
 }
Exemplo n.º 14
0
        protected virtual void InternalExecuteProcedure(JobArgumentCollection args)
        {
            lock (_syncLock)
            {
                if (db == null)
                {
                    db = new Database(InstanceConfig.GetConnectionString());
                    CreateProcedure(db);
                }
            }

            ExecuteProcedure(args);
        }
Exemplo n.º 15
0
        public HttpResponseMessage GetModuleResult(string moduleName, [FromUri] InstanceConfig config)
        {
            try
            {
                var instance = new InstanceInfo(config);
                var result   = ModuleLoader.GetModule(moduleName).GetResults(instance);

                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, $"Error in \"{moduleName}\" module. Error message: {e.Message}"));
            }
        }
Exemplo n.º 16
0
 /// <summary>Snippet for GetInstanceConfig</summary>
 public void GetInstanceConfig_RequestObject()
 {
     // Snippet: GetInstanceConfig(GetInstanceConfigRequest,CallSettings)
     // Create client
     InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();
     // Initialize request argument(s)
     GetInstanceConfigRequest request = new GetInstanceConfigRequest
     {
         InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"),
     };
     // Make the request
     InstanceConfig response = instanceAdminClient.GetInstanceConfig(request);
     // End snippet
 }
Exemplo n.º 17
0
        /// <summary>Snippet for GetInstanceConfigAsync</summary>
        public async Task GetInstanceConfigAsync()
        {
            // Snippet: GetInstanceConfigAsync(InstanceConfigName,CallSettings)
            // Additional: GetInstanceConfigAsync(InstanceConfigName,CancellationToken)
            // Create client
            InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();

            // Initialize request argument(s)
            InstanceConfigName name = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]");
            // Make the request
            InstanceConfig response = await instanceAdminClient.GetInstanceConfigAsync(name);

            // End snippet
        }
Exemplo n.º 18
0
        /// <summary>
        /// Loads the instance configuration.
        /// </summary>
        private void LoadInstanceConfig()
        {
            Locale.SetCultureToEnglish();

            if (InstanceConfig.Load(InstanceConfig.GetConfigFileName(AppDirs.InstanceDir), out string errMsg))
            {
                Locale.SetCulture(InstanceConfig.Culture);
                AppDirs.UpdateLogDir(InstanceConfig.LogDir);
            }
            else
            {
                Console.WriteLine(errMsg);
                Locale.SetCultureToDefault();
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Saves the specified culture to the instance configuration file.
        /// </summary>
        public static bool SaveCulture(string fileName, string cultureName, out string errMsg)
        {
            InstanceConfig instanceConfig = new InstanceConfig();

            if (instanceConfig.Load(fileName, out errMsg))
            {
                instanceConfig.Culture = cultureName;

                if (instanceConfig.Save(fileName, out errMsg))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 20
0
 public TraceConnection(TraceContext context)
 {
     this.context  = context;
     this.instance = context.Trace.Instance;
     connection    = new SqlConnection(instance.ConnectionString);
     traceid       = -1;
     Open();
     DecodeFunctions = new Dictionary <SqlDbType, Action <TraceEvent, int> >();
     DecodeFunctions.Add(SqlDbType.Int, SetIntColumn);
     DecodeFunctions.Add(SqlDbType.BigInt, SetLongColumn);
     DecodeFunctions.Add(SqlDbType.DateTime, SetDateTimeColumn);
     DecodeFunctions.Add(SqlDbType.NVarChar, SetStringColumn);
     DecodeFunctions.Add(SqlDbType.Image, SetByteColumn);
     DecodeFunctions.Add(SqlDbType.Text, SetStringColumn);
     DecodeFunctions.Add(SqlDbType.UniqueIdentifier, SetGuidColumn);
 }
Exemplo n.º 21
0
        public async Task GetInstanceConfigAsync_RequestObject()
        {
            // Snippet: GetInstanceConfigAsync(GetInstanceConfigRequest,CallSettings)
            // Create client
            InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();

            // Initialize request argument(s)
            GetInstanceConfigRequest request = new GetInstanceConfigRequest
            {
                Name = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]").ToString(),
            };
            // Make the request
            InstanceConfig response = await instanceAdminClient.GetInstanceConfigAsync(request);

            // End snippet
        }
Exemplo n.º 22
0
        /// <summary>
        /// Prepares the logic processing.
        /// </summary>
        private void PrepareProcessing()
        {
            terminated    = false;
            utcStartDT    = DateTime.UtcNow;
            startDT       = utcStartDT.ToLocalTime();
            serviceStatus = ServiceStatus.Starting;
            WriteInfo();

            listener  = new AgentListener(this, appConfig.ListenerOptions, appConfig.ReverseConnectionOptions);
            instances = new Dictionary <string, ScadaInstance>(appConfig.Instances.Count);

            // create instances
            foreach (InstanceOptions instanceOptions in appConfig.Instances)
            {
                if (!instanceOptions.Active || string.IsNullOrEmpty(instanceOptions.Name) ||
                    instances.ContainsKey(instanceOptions.Name))
                {
                    // ignore instance silently
                    continue;
                }

                if (!instanceOptions.ProxyMode && string.IsNullOrEmpty(instanceOptions.Directory))
                {
                    Log.WriteError(Locale.IsRussian ?
                                   "Экземпляр {0} игнорируется, потому что директория не задана" :
                                   "The {0} instance is ignored because the directory is not specified",
                                   instanceOptions.Name);
                    continue;
                }

                InstanceConfig instanceConfig = new InstanceConfig();

                if (!instanceOptions.ProxyMode &&
                    !instanceConfig.Load(InstanceConfig.GetConfigFileName(instanceOptions.Directory),
                                         out string errMsg))
                {
                    Log.WriteError(Locale.IsRussian ?
                                   "Ошибка при загрузке конфигурации экземпляра {0}: {1}" :
                                   "Error loading the {0} instance configuration: {1}", instanceOptions.Name, errMsg);
                }

                instances.Add(instanceOptions.Name, new ScadaInstance(AppDirs, Log, instanceOptions, instanceConfig));
            }
        }
Exemplo n.º 23
0
    public async Async.Task <Vm> GetVm(Repro repro, InstanceConfig config)
    {
        var taskOperations = _context.TaskOperations;
        var tags           = config.VmTags;
        var task           = await taskOperations.GetByTaskId(repro.TaskId);

        if (task == null)
        {
            throw new Exception($"previous existing task missing: {repro.TaskId}");
        }

        var vmConfig = await taskOperations.GetReproVmConfig(task);

        if (vmConfig == null)
        {
            if (!DEFAULT_OS.ContainsKey(task.Os))
            {
                throw new NotImplementedException($"unsupport OS for repro {task.Os}");
            }

            vmConfig = new TaskVm(
                await _context.Creds.GetBaseRegion(),
                DEFAULT_SKU,
                DEFAULT_OS[task.Os],
                null
                );
        }

        if (repro.Auth == null)
        {
            throw new Exception("missing auth");
        }

        return(new Vm(
                   repro.VmId.ToString(),
                   vmConfig.Region,
                   vmConfig.Sku,
                   vmConfig.Image,
                   repro.Auth,
                   null,
                   tags
                   ));
    }
Exemplo n.º 24
0
        public CardsavrSession()
        {
            string localGeneratedConfig = "../../../docker.local.json";

            if (File.Exists(localGeneratedConfig))
            {
                using (StreamReader r = new StreamReader("../../../docker.local.json"))
                {
                    string     json  = r.ReadToEnd();
                    KeyValue[] array = JsonConvert.DeserializeObject <KeyValue[]>(json);
                    Dictionary <string, string> dl = new Dictionary <string, string>();
                    foreach (KeyValue kv in array)
                    {
                        dl[kv.key] = kv.value;
                    }

                    this.config.app_name        = dl["testing/credentials/primary/integrator/name"];
                    this.config.app_key         = dl["testing/credentials/primary/integrator/key"];
                    this.config.app_password    = dl["testing/credentials/primary/user/password"];
                    this.config.app_username    = dl["testing/credentials/primary/user/username"];
                    this.config.cardsavr_server = "https://api." + dl["cardsavr/config/base_url"];
                }
            }
            else
            {
                using (StreamReader r = new StreamReader("../../../strivve_creds.json"))
                {
                    string json = r.ReadToEnd();
                    this.config = JsonConvert.DeserializeObject <InstanceConfig>(json);
                }
            }
            this.http = new CardSavrHttpClient(CardsavrSession.rejectUnauthorized);
            InstanceConfig conf = this.getConfig();

            this.http.Setup(
                conf.cardsavr_server,
                conf.app_key,
                conf.app_name,
                conf.app_username,
                conf.app_password);
            this.http.Init().Wait();
        }
Exemplo n.º 25
0
        public HttpResponseMessage GetModulesMetadata([FromUri] InstanceConfig config, [FromUri] string category = null)
        {
            try
            {
                var instance = new InstanceInfo(config);
                var version  = instance.Version;

                // Get all modules of given version
                var modules = ModuleLoader.Modules
                              .Select(x => x.GetModuleMetadata())
                              .Where(x => x.SupportedVersions.Contains(version));

                // Filter modules by category - return either specified category, or the rest
                if (String.IsNullOrEmpty(category))
                {
                    foreach (var separateCategory in SeparateCategories)
                    {
                        modules = modules.Where(x => x.Category == null || !x.Category.StartsWith(separateCategory, StringComparison.InvariantCultureIgnoreCase));
                    }
                }
                else
                {
                    modules = modules.Where(x => x.Category != null && x.Category.StartsWith(category, StringComparison.InvariantCultureIgnoreCase));
                }

                if (!modules.Any())
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  String.Format("There are no modules available for version {0}.", version)));
                }

                return(Request.CreateResponse(HttpStatusCode.OK, modules));
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
            }
        }
Exemplo n.º 26
0
        private Stats stats;                       // provides a statistics ID


        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public WebContext()
        {
            storageWrapper       = null;
            configThread         = null;
            terminated           = false;
            pluginsReady         = false;
            configUpdateRequired = false;
            configUpdateStep     = ConfigUpdateStep.Idle;
            stats = null;

            IsReady                    = false;
            IsReadyToLogin             = false;
            InstanceConfig             = new InstanceConfig();
            AppConfig                  = new WebConfig();
            AppDirs                    = new WebDirs();
            Log                        = LogStub.Instance;
            ConfigDatabase             = new ConfigDatabase();
            ClientPool                 = new ScadaClientPool();
            PluginHolder               = new PluginHolder();
            CacheExpirationTokenSource = new CancellationTokenSource();

            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
        }
Exemplo n.º 27
0
        public void GetInstanceConfig2()
        {
            Mock <InstanceAdmin.InstanceAdminClient> mockGrpcClient = new Mock <InstanceAdmin.InstanceAdminClient>(MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient())
            .Returns(new Mock <Operations.OperationsClient>().Object);
            GetInstanceConfigRequest request = new GetInstanceConfigRequest
            {
                InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"),
            };
            InstanceConfig expectedResponse = new InstanceConfig
            {
                InstanceConfigName = new InstanceConfigName("[PROJECT]", "[INSTANCE_CONFIG]"),
                DisplayName        = "displayName1615086568",
            };

            mockGrpcClient.Setup(x => x.GetInstanceConfig(request, It.IsAny <CallOptions>()))
            .Returns(expectedResponse);
            InstanceAdminClient client   = new InstanceAdminClientImpl(mockGrpcClient.Object, null);
            InstanceConfig      response = client.GetInstanceConfig(request);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
Exemplo n.º 28
0
        public HttpResponseMessage GetModuleExport([FromUri] IEnumerable <string> moduleNames, [FromUri] InstanceConfig config, [FromUri] string exportModuleCodeName)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var instanceInfo = new InstanceInfo(config);

            if (instanceInfo == null)
            {
                throw new ArgumentException(nameof(config));
            }

            if (moduleNames == null)
            {
                throw new ArgumentNullException(nameof(moduleNames));
            }

            var module = ExportModuleLoader.Modules.FirstOrDefault(m => m.ModuleMetaData.ModuleCodeName == exportModuleCodeName);

            if (module == null)
            {
                throw new ArgumentException(nameof(exportModuleCodeName));
            }

            try
            {
                var stream = module.GetExportStream(moduleNames.Distinct(), instanceInfo);
                if (stream == null)
                {
                    throw new Exception("Empty export file");
                }

                // Send stream
                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType        = new MediaTypeHeaderValue(module.ModuleMetaData.ModuleFileMimeType);
                response.Content.Headers.ContentLength      = stream.Length;
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"KInspectorExport_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.{module.ModuleMetaData.ModuleFileExtension}"
                };
                response.Headers.ConnectionClose = true;

                return(response);
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, $"Error in processing modules. Error message: {e.Message}"));
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Migrate to the new <see cref="ServerConfig"/> since the <see cref="Server.Server"/> won't know about it until it's upgraded
        /// </summary>
        bool AttemptMigrationOfNetSettings()
        {
            if (!attemptNetSettingsMigration)
            {
                return(true);
            }
            var sc = new ServerConfig();

            try
            {
                sc.PythonPath = Interface.Server.Management.PythonPath();
            }
            catch { }
            try
            {
                sc.RemoteAccessPort = Interface.Server.Management.RemoteAccessPort();
            }
            catch { }
            try
            {
                foreach (var I in Interface.Server.Instances)
                {
                    sc.InstancePaths.Add(I.Metadata.Path);
                }
            }
            catch { }

            try
            {
                if (sc.InstancePaths.Count > 0)                 //nice suprise, this is uneeded
                {
                    return(true);
                }

                //stopping the service here is MANDATORY to get the correct reattach values
                using (var controller = new ServiceController("TG Station Server"))
                {
                    controller.Stop();
                    controller.WaitForStatus(ServiceControllerStatus.Stopped);
                    //we need to find the old user.config
                    //check wow64 first
                    var path = @"C:\Windows\SysWOW64\config\systemprofile\AppData\Local\TGServerService";
                    if (!Directory.Exists(path))
                    {
                        //ok... check the System32 path
                        path = @"C:\Windows\System32\config\systemprofile\AppData\Local\TGServerService";
                        if (!Directory.Exists(path))
                        {
                            //well, i'm out of ideas, just use the default location
                            var res = HandleNoConfigMigration(sc);
                            if (!res)
                            {
                                controller.Start();
                                return(false);
                            }
                        }
                    }

                    //now who knows wtf windows calls the damn folder
                    //take our best guess based on last modified time
                    DirectoryInfo lastModified = null;
                    foreach (var D in new DirectoryInfo(path).GetDirectories())
                    {
                        if (lastModified == null || D.LastWriteTime > lastModified.LastWriteTime)
                        {
                            lastModified = D;
                        }
                    }

                    if (lastModified == null)
                    {
                        //well, i'm out of ideas, just use the default location
                        var res = HandleNoConfigMigration(sc);
                        if (!res)
                        {
                            controller.Start();
                            return(false);
                        }
                    }

                    var next = lastModified;
                    lastModified = null;
                    foreach (var D in next.GetDirectories())
                    {
                        if (lastModified == null || D.LastWriteTime > lastModified.LastWriteTime)
                        {
                            lastModified = D;
                        }
                    }

                    if (lastModified == null)
                    {
                        //well, i'm out of ideas, just use the default location
                        var res = HandleNoConfigMigration(sc);
                        if (!res)
                        {
                            controller.Start();
                            return(false);
                        }
                    }

                    path = Path.Combine(tempDir, "user.config");
                    var netConfigPath = Path.Combine(lastModified.FullName, "user.config");
                    File.Copy(netConfigPath, path, true);
                    new InstanceConfig(tempDir).Save();

                    var instanceConfigPath = Path.Combine(tempDir, "Instance.json");

                    if (MessageBox.Show(String.Format("The 3.2 settings migration is a manual process, please open \"{0}\" with your favorite text editor and copy the values under TGServerService.Properties.Settings to the relevent fields at \"{1}\". If something in the original config appears wrong to you, correct it in the new config, but do not modify the \"Version\", \"Enabled\", or \"Name\" fields at all. See field mappings here: https://github.com/tgstation/tgstation-server/blob/a372b22fd3367dd60ee0cbebd9210f4b072c952d/TGServerService/DeprecatedInstanceConfig.cs#L23-L39", path, instanceConfigPath), "Manual Migration Required", MessageBoxButtons.OKCancel) != DialogResult.OK)
                    {
                        controller.Start();
                        return(false);
                    }

                    var name = TextPrompt("Set Instance Directory", String.Format("Please enter the ServerDirectory entry from the original config here.{0}Use backslashes and uppercase letters. Leave this blank if it is not present.", Environment.NewLine));
                    if (name == null)
                    {
                        controller.Start();
                        return(false);
                    }

                    if (String.IsNullOrWhiteSpace(name))
                    {
                        name = @"C:\TGSTATION-SERVER-3";
                    }

                    sc.InstancePaths.Add(name);

                    if (MessageBox.Show(String.Format("Please confirm you have finished copying settings from \"{0}\" to \"{1}\"!", path, instanceConfigPath), "Last Confirmation", MessageBoxButtons.OKCancel) != DialogResult.OK)
                    {
                        controller.Start();
                        return(false);
                    }
                    //validate it for good measure
                    try
                    {
                        InstanceConfig.Load(tempDir);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(String.Format("JSON Validation Error: {0}", e.Message));
                        controller.Start();
                        return(false);
                    }
                    File.Copy(instanceConfigPath, Path.Combine(name, "Instance.json"), true);
                    return(true);
                }
            }
            finally
            {
                Directory.CreateDirectory(Server.Server.MigrationConfigDirectory);
                sc.Save(Server.Server.MigrationConfigDirectory);
            }
        }
Exemplo n.º 30
0
 public JsOutputVisitor(Errors errorsSink = null, InstanceConfig config = null)
     : base(errorsSink)
 {
     Config = config ?? new InstanceConfig();
 }
Exemplo n.º 31
0
 public DiscordAuthentication(TokenCredential tokenCredential, InstanceConfig config)
 {
     _secretClient = new SecretClient(config.Discord.BotTokenVault, tokenCredential);
     _secretName   = config.Discord.BotTokenSecretName;
 }