예제 #1
0
 // Update the tokens in the changelog file from the config Json
 private void UpdateChangelog(ConfigJson configJson, string package_version)
 {
     try
     {
         string changelogFile = Path.Combine(InputDir, "templates", "changelog");
         if (!File.Exists(changelogFile))
         {
             throw new FileNotFoundException($"Expected file {changelogFile} was not found.");
         }
         string str = File.ReadAllText(changelogFile);
         str = str.Replace("{PACKAGE_NAME}", configJson.Package_Name);
         str = str.Replace("{PACKAGE_VERSION}", package_version);
         str = str.Replace("{PACKAGE_REVISION}", configJson.Release.Package_Revision);
         str = str.Replace("{URGENCY}", configJson.Release.Urgency);
         str = str.Replace("{CHANGELOG_MESSAGE}", configJson.Release.Changelog_Message);
         str = str.Replace("{MAINTAINER_NAME}", configJson.Maintainer_Name);
         str = str.Replace("{MAINTAINER_EMAIL}", configJson.Maintainer_Email);
         // The date format needs to be like Wed May 17 2017
         str = str.Replace("{DATE}", DateTime.UtcNow.ToString("ddd MMM dd yyyy"));
         File.WriteAllText(changelogFile, str);
     }
     catch (Exception e)
     {
         Log.LogError("Exception while updating the changelog file: " + e.Message);
     }
 }
예제 #2
0
        public static async Task <string> ReadJsonConfig()
        {
            string result;

            try
            {
                await using (FileStream fs = File.OpenRead("config.json"))
                    using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
                        result = await sr.ReadToEndAsync();
                if (result.Length == 0)
                {
                    throw new FileNotFoundException();
                }
            }
            catch (FileNotFoundException)
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.WriteLine("Config file not found or it's empty. Creating config.json ...");
                Console.ResetColor();
                var defaultJsonConfig = new ConfigJson();
                var options           = new JsonSerializerOptions {
                    WriteIndented = true
                };
                string defaultConfig = JsonSerializer.Serialize(defaultJsonConfig, options);
                await CreateWriteTxtFile("config.json", defaultConfig);

                result = "default";
            }

            return(result);
        }
예제 #3
0
        public static ConfigJson LoadConfig(string configFile = "", bool error = true, bool fillMissingFields = false)
        {
            if (configFile == "")
            {
                configFile = GetUserConfig();
            }

            string basicError = String.Format("Ошибка открытия файла конфигурации {0}", configFile);

            try
            {
                var config = ConfigJson.FromJson(FileUtilities.GetFileContents(configFile));

                //if (fillMissingFields == true) FillMissingConfigFields(logger, config);

                return(config);
            }
            catch (IOException exc)
            {
                string errorStr = String.Format("{0} : ошибка открытия файла ({1})", basicError, exc.Message);

                var logger = Application.Resolve <ILoggingService>();
                logger.Error(errorStr);
            }
            catch (Exception exc)
            {
                Debug.WriteLine(1);
            }

            return(null);
        }
예제 #4
0
        public static string GetColorDefinitionFileName()
        {
            var configJson = ConfigJson.Load();
            var file       = Path.Combine(ConfigJson.GetExtensionPath(), configJson.GetColorDefinitionFileName());

            return(file);
        }
예제 #5
0
        public static void OpenIntellisenseDefinitionFileInTextEditor()
        {
            var configJson = ConfigJson.Load();
            var file       = Path.Combine(ConfigJson.GetExtensionPath(), configJson.GetIntellisenseDefinitionFileName());

            TextHighlighterConfigApi.OpenFileInVS(file);
        }
예제 #6
0
        public static void CreateWebsocketHandler()
        {
            WebSocketConfigForJsonConfig websocketConfig = ConfigJson <WebSocketConfigForJsonConfig> .GetJsonFromConfigFile().Result;

            socketServer = new WebSocketTcpListener(websocketConfig);
            socketServer.RunServer(); // Start the Listener
        }
예제 #7
0
        private void SendSummaryEmail(ConfigJson configJson)
        {
            string  logSummaryText = MigratorLogging.GetLogSummaryText();
            Emailer emailer        = new Emailer();

            emailer.SendEmail(configJson, logSummaryText);
        }
예제 #8
0
        private void ConfigureCommands(ConfigJson config)
        {
            Client.Logger.LogInformation(Program.BotEventId, $"Setting up commands...");
            var ccfg = new CommandsNextConfiguration()
            {
                StringPrefixes      = config.CommandPrefix,
                CaseSensitive       = false,
                EnableDms           = true,
                EnableMentionPrefix = true
            };

            Commands = Client.UseCommandsNext(ccfg);

            // Add event callbacks
            Commands.CommandExecuted += StaticEvents.Commands_CommandExecuted;
            Commands.CommandErrored  += StaticEvents.Commands_CommandErrored;

            // Register commands
            Commands.RegisterCommands <Bunnies>();
            Commands.RegisterCommands <Commands.Utilities>();
            Commands.RegisterCommands <Games>();
            Commands.RegisterCommands <Searches>();
            Commands.RegisterCommands <Counters>();
            Commands.RegisterCommands <Help>();

            // Set custom helpformatter
            Commands.SetHelpFormatter <HelpFormatter>();
        }
 public static void MainMethod()
 {
     try
     {
         commandLineArgs = Environment.GetCommandLineArgs();
         if (commandLineArgs.Length < 11)
         {
             throw new System.Exception("srcPath不能为空");
         }
         if (commandLineArgs.Length < 12)
         {
             throw new System.Exception("outpath不能为空");
         }
         srcPath = commandLineArgs[10];
         outPath = commandLineArgs[11];
         //获取扩展设置
         string configInfoJson = "";
         if (commandLineArgs.Length > 12)
         {
             configInfoJson = commandLineArgs[12];
         }
         configJson = JsonTools.ResolutionJsonFromString <ConfigJson>(configInfoJson);
         StartBuildSDF();
         LogTools.Info("打包结束,未发现异常.srcPath:" + commandLineArgs [10] + " outPath:" + commandLineArgs[11]);
     }
     catch (System.Exception e)
     {
         PrintExcepitonLog(e);
     }
 }
        private void LoadColorDefinitions()
        {
            var fullColorDefinitionFileName = Path.Combine(ConfigJson.GetExtensionPath(), this.GetColorDefinitionFileName());

            Log("Loading color definition {0}".format(fullColorDefinitionFileName));
            this._colorDefinition = new TextHighlighterColorDefinition.ColorDefinition(fullColorDefinitionFileName);
        }
예제 #11
0
 public void AddConfig(string name, ConfigJson configJson)
 {
     if (!HealthConfigDic.ContainsKey(name))
     {
         HealthConfigDic[name] = configJson;
     }
 }
        private static void BeginSession(string configFile, ConfigJson config, bool force, IJiraProvider jiraProvider, int itemsCount)
        {
            var toolVersion = VersionInfo.GetVersionInfo();
            var osVersion = System.Runtime.InteropServices.RuntimeInformation.OSDescription.Trim();
            var machine = System.Environment.MachineName;
            var user = $"{System.Environment.UserDomainName}\\{System.Environment.UserName}";
            var jiraVersion = jiraProvider.GetJiraVersion();

            Logger.Log(LogLevel.Info, $"Export started. Exporting {itemsCount} items.");

            Logger.StartSession("Jira Export",
                "jira-export-started",
                new Dictionary<string, string>() {
                    { "Tool version :", toolVersion },
                    { "Start time   :", DateTime.Now.ToString() },
                    { "Telemetry    :", Logger.TelemetryStatus },
                    { "Session id   :", Logger.SessionId },
                    { "Tool user    :"******"Config       :", configFile },
                    { "Force        :", force ? "yes" : "no" },
                    { "Log level    :", config.LogLevel },
                    { "Machine      :", machine },
                    { "System       :", osVersion },
                    { "Jira url     :", jiraProvider.Settings.Url },
                    { "Jira user    :"******"Jira version :", jiraVersion.Version },
                    { "Jira type    :", jiraVersion.DeploymentType }
                    },
                new Dictionary<string, string>() {
                    { "item-count", itemsCount.ToString() },
                    { "system-version", jiraVersion.Version },
                    { "hosting-type", jiraVersion.DeploymentType } });
        }
 public JiraMapper(JiraProvider jiraProvider, ConfigJson config) : base(jiraProvider?.Settings?.UserMappingFile)
 {
     _jiraProvider         = jiraProvider;
     _config               = config;
     _targetTypes          = InitializeTypeMappings();
     _fieldMappingsPerType = InitializeFieldMappings();
 }
예제 #14
0
        public static void CheckAndMergeValuesFromReference(ConfigJson currentDict, ConfigJson referenceDict, List <string> exceptionList, Logger logger = null)
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            ComparisonResult result = compareLogic.Compare(currentDict, referenceDict);

            //These will be different, write out the differences
            if (!result.AreEqual)
            {
                Debug.WriteLine(result.DifferencesString);
            }


            /*foreach (PropertyInfo pi in rePropInfos)
             * {
             *      string key = elem.Key;
             *      JToken val = elem.Value;
             *
             *      if (currentDict.ContainsKey(key) == false)
             *      {
             *              currentDict.Add(new JProperty(key, val));
             *
             *              if (logger != null) logger.Warning($"В конфигурации пропущен ключ{key} in configuration, было добавлено значение по умолчанию: {val}");
             *      }
             *      else if (val.Type == JTokenType.Object && exceptionList.Contains(key) == false)
             *      {
             *              CheckAndMergeValuesFromReference((JObject)currentDict[key], (JObject)val, exceptionList, logger);
             *      }
             * }*/
        }
예제 #15
0
    private IEnumerator LoadConfig()
    {
        //读取config.txt
        //StreamReader reader = new StreamReader(Application.streamingAssetsPath + "/config.txt");
        //string config = reader.ReadLine();
        //reader.Close();

        // 重新导入
        ////AssetDatabase.ImportAsset("Assets/Resources/config.txt");
        //TextAsset textAsset = Resources.Load<TextAsset>("config");
        //string config = textAsset.text;

        WWW www = new WWW(Application.streamingAssetsPath + "/config.txt");

        yield return(www);

        byte[] bytes = www.bytes;
        // BOM是“Byte Order Mark”标记文件的编码 EF BB BF     UTF-8保存的文本有,ANSI无
        byte[] configBytes = new byte[bytes.Length - 3];
        Array.Copy(bytes, 3, configBytes, 0, configBytes.Length);
        ConfigJson configJson = JsonUtility.FromJson <ConfigJson>(System.Text.Encoding.Default.GetString(configBytes));

        Config.IsServer      = configJson.IsServer;
        Config.ServerAddress = configJson.ServerAddress;
        Config.PlayerId      = configJson.PlayerId;
        Log4U.Init();
        Log4U.LogDebug("IsServer=", configJson.IsServer);
        Log4U.LogDebug("ServerAddress=", configJson.ServerAddress);
        Log4U.LogDebug("PlayerId=", configJson.PlayerId);
        InitGame();
    }
예제 #16
0
        public static void SetBackGroundColorDefinition(string theme)
        {
            ConfigJson configJson = ConfigJson.Load();

            configJson.BackGroundColorTheme = theme;
            configJson.Save();
        }
예제 #17
0
        private void AdminSaleOrder_Load(object sender, EventArgs e)
        {
            int region = new ConfigJson().SubsidiaryCompaniesRegion();

            listEmp.DataSource = db.Employees.Where(s => (s.User_access.type == "продавец" &&
                                                          s.id_subsidiary_companies_region == region)
                                                    ).Select(s => new { id = s.User_access.id, fio = s.first_name + " " + s.middle_name + " " + s.last_name }).ToList();
            listEmp.DisplayMember = "fio";
            listEmp.ValueMember   = "id";

            listGoods.DataSource    = db.Goods.Select(g => new { id = g.id, title = g.Goods_category.title + " / " + g.title }).ToList();
            listGoods.DisplayMember = "title";
            listGoods.ValueMember   = "id";


            if (interval.Checked)
            {
                end.Enabled = true;
            }
            if (allEmp.Checked)
            {
                listEmp.Enabled = false;
            }
            if (allGoods.Checked)
            {
                listGoods.Enabled = false;
            }
        }
예제 #18
0
        /// <summary>
        /// プリセット情報の読み込み
        /// </summary>
        /// <param name="id">読み込むプリセットID</param>
        /// <returns></returns>
        public async Task LoadPresetAsync(string id)
        {
            IsBusy = true;
            using (new OnDisposeAction(() => IsBusy = false))
            {
                var preset = UserSettings.PresetInfos.Where(e => e.Id == id).FirstOrDefault();
                if (preset == null)
                {
                    Trace.TraceInformation($"プリセットID不正:{id}");
                    ErrorOccurred?.Invoke(this,
                                          new ConfigJsonErrorEventArgs(ConfigJsonErrorEventArgs.Cause.ReadPresetError, new FileNotFoundException("プリセットが見つかりません。"), id));
                    return;
                }
                var path = Path.Combine(UserSettingsService.AppSettings.AppDataPath, preset.FileName);

                try
                {
                    ConfigJson = await FileService.ReadAsync(path);

                    CurrentPreset = preset;
                }
                catch (Exception e) when(e is IOException || e is JsonException)
                {
                    Trace.TraceInformation($"プリセット[{preset.Id}]読み込み失敗。{path}:{e.Message}");
                    ErrorOccurred?.Invoke(this, new ConfigJsonErrorEventArgs(ConfigJsonErrorEventArgs.Cause.ReadPresetError, e, path));
                    ConfigJson    = new ConfigJson();
                    CurrentPreset = preset;
                }
            }
        }
예제 #19
0
        //constructor
        public Bot(IServiceProvider services)
        {
            //creates the string to hold the config file
            string json = string.Empty;

            //reads the config file
            using (FileStream fs = File.OpenRead("config.json"))
                using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false)))
                    json = sr.ReadToEnd();

            //deserializes the json into a struct
            ConfigJson configJson = JsonConvert.DeserializeObject <ConfigJson>(json);

            //configures up the bot's settings
            DiscordConfiguration config = new DiscordConfiguration
            {
                Token                 = configJson.Token,
                TokenType             = TokenType.Bot,
                AutoReconnect         = true,
                LogLevel              = LogLevel.Debug,
                UseInternalLogHandler = true
            };

            //initializes the client
            Client = new DiscordClient(config);

            //readies the bot
            Client.Ready += OnClientReady;

            //configures the interactivity settings
            Client.UseInteractivity(new InteractivityConfiguration
            {
                PollBehaviour = DSharpPlus.Interactivity.Enums.PollBehaviour.KeepEmojis
            });

            //configures the command settings
            CommandsNextConfiguration commandsConfig = new CommandsNextConfiguration
            {
                StringPrefixes      = new string[] { configJson.Prefix },
                EnableDms           = false,
                EnableMentionPrefix = true,
                DmHelp   = true,
                Services = services
            };

            //activates commands
            Commands = Client.UseCommandsNext(commandsConfig);

            //register all commands for the bot
            Commands.RegisterCommands <FunCommands>();
            Commands.RegisterCommands <LinkCommands>();
            Commands.RegisterCommands <RoleCommands>();
            Commands.RegisterCommands <PollCommand>();
            Commands.RegisterCommands <TestCommands>();
            Commands.RegisterCommands <ItemCommands>();
            Commands.RegisterCommands <ProfileCommands>();

            //connects to the server
            Client.ConnectAsync();
        }
    private static void SetTransform(ConfigJson configJson, GameObject go)
    {
        Vector3 pos = go.transform.position;

        go.transform.position = Vector3.zero;
        go.transform.rotation = Quaternion.identity;
        PerspectiveMode perspectiveMode = configJson.m_ModelConfig.m_PerspectiveMode;

        switch (perspectiveMode.m_CaululateType)
        {
        case CalculateModelNativePos.CalculateType.FullScreen:
        case CalculateModelNativePos.CalculateType.Real:
            pos = CalculateModelNativePos.Calculate(go.transform, perspectiveMode.m_CalculateCamera, go.transform.position, perspectiveMode.m_CaululateType);
            break;

        case CalculateModelNativePos.CalculateType.Node:
            Transform node = go.transform.Find(perspectiveMode.m_CalculateChildPath);
            if (node == null)
            {
                node = go.transform;
            }
            pos = CalculateModelNativePos.Calculate(node, perspectiveMode.m_CalculateCamera, go.transform.position, perspectiveMode.m_CaululateType);
            break;

        default:
            break;
        }
        go.transform.position = pos;
    }
예제 #21
0
        public void SendEmail(ConfigJson configJson, string body)
        {
            bool sendEmailNotification          = configJson.SendEmailNotification;
            EmailNotification emailNotification = configJson.EmailNotification;

            // only proceed if sendEmailNotification && emailNotification != null
            if (sendEmailNotification && emailNotification == null)
            {
                throw new Exception("send-email-notification is set to true but there are no email-notification" +
                                    " details specified. Please set send-email-notification to false or specify details for" +
                                    " email-notification in the configuration-file.");
            }
            else if (!sendEmailNotification || emailNotification == null)
            {
                return;
            }

            SmtpClient client = new SmtpClient(emailNotification.SmtpServer, emailNotification.Port);

            //client.EnableSsl = true; // need to figure this out! Maybe don't need?
            client.UseDefaultCredentials = false;
            client.Credentials           = new NetworkCredential(emailNotification.UserName, emailNotification.Password);
            MailMessage message = new MailMessage();

            MailAddress from = new MailAddress(emailNotification.FromAddress);

            message.From = from;

            if (emailNotification.RecipientAddresses == null || emailNotification.RecipientAddresses.Count == 0)
            {
                throw new Exception("You must specify one or more recipient-addresses under email-notification.");
            }

            foreach (string address in emailNotification.RecipientAddresses)
            {
                message.To.Add(address);
            }

            message.Body            = body;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = $"WiMigrator Summary at {DateTime.Now.ToString()}";
            message.SubjectEncoding = System.Text.Encoding.UTF8;

            try
            {
                client.Send(message);
            }
            catch (SmtpException e)
            {
                Logger.LogError(LogDestination.File, e, "Could not send run summary email because of an issue with the SMTP server." +
                                " Please ensure that the server works and your configuration file input is correct");
            }
            catch (Exception e)
            {
                Logger.LogError(LogDestination.File, e, "Could not send run summary email because of an Exception");
            }

            message.Dispose();
        }
예제 #22
0
        public Tuple <string[], string> ReadConfig(string path)
        {
            string     json = ReadData(path);
            ConfigJson cfg  = JsonConvert.DeserializeObject <ConfigJson>(json);

            _root = cfg.RootFolder;
            return(Tuple.Create(cfg.Parameters, _root));
        }
예제 #23
0
        public Weather(IMapper mapper)
        {
            var config = File.ReadAllText(path);

            config_json = JsonConvert.DeserializeObject <ConfigJson>(config);

            _mapper = mapper;
        }
예제 #24
0
        public Translate(IMapper mapper)
        {
            string config = File.ReadAllText(path);

            config_json = JsonConvert.DeserializeObject <ConfigJson>(config);

            _mapper = mapper;
        }
예제 #25
0
 /// <summary>
 /// config.jsonファイルを保存する
 /// </summary>
 /// <param name="path">保存するパス</param>
 /// <param name="configJson">保存する情報</param>
 /// <param name="mergeUnknown">不明なプロパティをマージするかのフラグ</param>
 /// <returns></returns>
 public async Task WriteAsync(string path, ConfigJson configJson, bool mergeUnknown)
 {
     using (var writer = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write), new UTF8Encoding(false)))
     {
         var jsonString = configJson.SerializeToJson(mergeUnknown);
         await writer.WriteAsync(jsonString);
     }
 }
예제 #26
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 /// <param name="userSettingService">ユーザー設定情報サービス</param>
 /// <param name="fileService">ファイルサービス</param>
 public ConfigJsonService(IUserSettingsService userSettingService, IConfigJsonFileService fileService)
 {
     UserSettingsService = userSettingService;
     UserSettings        = userSettingService.UserSettings;
     FileService         = fileService;
     ConfigJson          = new ConfigJson();
     IsBusy = false;
 }
예제 #27
0
        public void TestPortableConfig()
        {
            var setting = new ConfigJson <TestSettings>(ConfigType.Executeable, "ConfigTest", "ConfigTest.json");

            setting.Load();
            setting.Configuration.BoolParameter    = true;
            setting.Configuration.StringArrayParam = new[] { "eins", "zwei", "drei" };
            setting.Configuration.StringParameter  = "stringParam";
            setting.Save();
        }
        public ValidationContext(ConfigJson configJson)
        {
            this.Config = configJson;
            MigratorLogging.configMinimumLogLevel = this.Config.LogLevelForFile;

            LogConfigData();

            this.SourceClient = this.CreateValidationClient(this.Config.SourceConnection);
            this.TargetClient = this.CreateValidationClient(this.Config.TargetConnection);
        }
예제 #29
0
        private void but_ok_Click(object sender, RoutedEventArgs e)
        {
            bool b = ControlSql(false);

            if (b && ConfigJson.AddLink(ref m_linkconfig))
            {
                Tag = m_linkconfig;
                SystemError.Information("数据库创建成功");
                DialogResult = true;
            }
        }
예제 #30
0
 void SetTreeNodeMain()
 {
     m_linkconfiglist        = ConfigJson.LoadLink();
     tree_server.ItemsSource = m_treenodemainlist;
     m_treenodemainlist.Add(new TreeNodeMain()
     {
         text    = "服务器列表",
         childer = m_treenodeserverlist
     });
     SetTreeNodeServer();
 }