Exemplo n.º 1
0
        /// <summary>
        /// Implementation of the IPlugin.Configure
        /// </summary>
        public virtual void Configure()
        {
            if (!HasModi())
            {
                MessageBox.Show("Sorry, is seems that Microsoft Office Document Imaging (MODI) is not installed, therefor the OCR Plugin cannot work.");
                return;
            }
            SettingsForm settingsForm = new SettingsForm(Enum.GetNames(typeof(ModiLanguage)), config);
            DialogResult result       = settingsForm.ShowDialog();

            if (result == DialogResult.OK)
            {
                // "Re"set hotkeys
                IniConfig.Save();
            }
        }
        public void WriteToFile()
        {
            IniConfig  config  = new IniConfig();
            IniSection section = config.AddSection("TestSection");

            section.Comments.AddRange(new string[]
            {
                "Test1", "Comment2"
            });

            IniProperty property = section.AddProperty("name", "Test", new string[] { "Property1", "TestProperty" }, new string[] { "Test1", "Test2" });

            string content = IniWriter.WriteToString(config);

            File.WriteAllText(@"D:\ini-config.txt", content);
        }
Exemplo n.º 3
0
        void QuickSettingItemChanged(object sender, EventArgs e)
        {
            ToolStripMenuSelectList     selectList = (ToolStripMenuSelectList)sender;
            ToolStripMenuSelectListItem item       = ((ItemCheckedChangedEventArgs)e).Item;

            if (selectList.Identifier.Equals("destination"))
            {
                Destination selectedDestination = (Destination)item.Data;
                if (item.Checked && !conf.OutputDestinations.Contains(selectedDestination))
                {
                    conf.OutputDestinations.Add(selectedDestination);
                }
                if (!item.Checked && conf.OutputDestinations.Contains(selectedDestination))
                {
                    conf.OutputDestinations.Remove(selectedDestination);
                }
                IniConfig.Save();
            }
            else if (selectList.Identifier.Equals("printoptions"))
            {
                if (item.Data.Equals("AllowPrintShrink"))
                {
                    conf.OutputPrintAllowShrink = item.Checked;
                }
                else if (item.Data.Equals("AllowPrintEnlarge"))
                {
                    conf.OutputPrintAllowEnlarge = item.Checked;
                }
                else if (item.Data.Equals("AllowPrintRotate"))
                {
                    conf.OutputPrintAllowRotate = item.Checked;
                }
                else if (item.Data.Equals("AllowPrintCenter"))
                {
                    conf.OutputPrintCenter = item.Checked;
                }
                IniConfig.Save();
            }
            else if (selectList.Identifier.Equals("effects"))
            {
                if (item.Data.Equals("PlaySound"))
                {
                    conf.PlayCameraSound = item.Checked;
                }
                IniConfig.Save();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Upload the capture to imgur
        /// </summary>
        /// <param name="captureDetails"></param>
        /// <param name="image"></param>
        /// <param name="uploadURL">out string for the url</param>
        /// <returns>true if the upload succeeded</returns>
        public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadURL)
        {
            SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);

            try {
                string    filename  = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
                ImgurInfo imgurInfo = null;

                // Run upload in the background
                new PleaseWaitForm().ShowAndWait("Imgur plug-in", Language.GetString("imgur", LangKey.communication_wait),
                                                 delegate() {
                    imgurInfo = ImgurUtils.UploadToImgur(surfaceToUpload, outputSettings, captureDetails.Title, filename);
                    LOG.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash);
                    config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash);
                    config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo);
                    CheckHistory();
                }
                                                 );

                // TODO: Optimize a second call for export
                using (Image tmpImage = surfaceToUpload.GetImageForExport()) {
                    imgurInfo.Image = ImageHelper.CreateThumbnail(tmpImage, 90, 90);
                }
                IniConfig.Save();
                uploadURL = null;
                try {
                    if (config.UsePageLink)
                    {
                        uploadURL = imgurInfo.Page;
                        ClipboardHelper.SetClipboardData(imgurInfo.Page);
                    }
                    else
                    {
                        uploadURL = imgurInfo.Original;
                        ClipboardHelper.SetClipboardData(imgurInfo.Original);
                    }
                } catch (Exception ex) {
                    LOG.Error("Can't write to clipboard: ", ex);
                }
                return(true);
            } catch (Exception e) {
                LOG.Error(e);
                MessageBox.Show(Language.GetString("imgur", LangKey.upload_failure) + " " + e.Message);
            }
            uploadURL = null;
            return(false);
        }
        /// <summary>
        /// Store all GreenshotControl values to the configuration
        /// </summary>
        protected void StoreFields()
        {
            bool iniDirty = false;

            foreach (FieldInfo field in this.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (!field.FieldType.IsSubclassOf(typeof(Control)))
                {
                    continue;
                }
                if (!typeof(IGreenshotConfigBindable).IsAssignableFrom(field.FieldType))
                {
                    continue;
                }
                Object controlObject = field.GetValue(this);
                IGreenshotConfigBindable configBindable = controlObject as IGreenshotConfigBindable;

                if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName))
                {
                    IniSection section = IniConfig.GetIniSection(configBindable.SectionName);
                    if (section != null)
                    {
                        if (typeof(CheckBox).IsAssignableFrom(field.FieldType))
                        {
                            CheckBox checkBox = controlObject as CheckBox;
                            section.Values[configBindable.PropertyName].Value = checkBox.Checked;
                            iniDirty = true;
                        }
                        else if (typeof(TextBox).IsAssignableFrom(field.FieldType))
                        {
                            TextBox textBox = controlObject as TextBox;
                            section.Values[configBindable.PropertyName].Value = textBox.Text;
                            iniDirty = true;
                        }
                        else if (typeof(GreenshotComboBox).IsAssignableFrom(field.FieldType))
                        {
                            GreenshotComboBox comboxBox = controlObject as GreenshotComboBox;
                            section.Values[configBindable.PropertyName].Value = comboxBox.GetSelectedEnum();
                        }
                    }
                }
            }
            if (iniDirty)
            {
                IniConfig.Save();
            }
        }
Exemplo n.º 6
0
        public FunctionResult Progress(CQGroupMessageEventArgs e)
        {
            FunctionResult result = new FunctionResult()
            {
                Result   = true,
                SendFlag = true,
            };

            //检查额度限制
            if (QuotaHelper.QuotaCheck(e.FromGroup, e.FromQQ) is false)
            {
                return(result);
            }
            PublicVariables.ReadOrderandAnswer();

            SendText sendText = new SendText();

            sendText.SendID = e.FromGroup;
            result.SendObject.Add(sendText);
            if (e.Message.Text.Trim().Length == GetOrderStr().Length)
            {
                sendText.MsgToSend.Add("指令无效,请在指令后添加pid");
                return(result);
            }
            if (!int.TryParse(e.Message.Text.Substring(GetOrderStr().Length).Replace(" ", ""), out int pid))
            {
                sendText.MsgToSend.Add("指令无效,检查是否为纯数字");
                return(result);
            }
            result.SendFlag = false;
            e.FromGroup.SendGroupMessage($"正在查询pid={pid}的插画信息,请等待……");
            IllustInfo illustInfo = PixivAPI.GetIllustInfo(pid);

            e.FromGroup.SendGroupMessage(illustInfo.IllustText);
            var message = e.FromGroup.SendGroupMessage(illustInfo.IllustCQCode);

            if (illustInfo.R18_Flag)
            {
                IniConfig ini  = MainSave.ConfigMain;
                Task      task = new Task(() =>
                {
                    Thread.Sleep(ini.Object["R18"]["RevokeTime"] * 1000);
                    e.CQApi.RemoveMessage(message.Id);
                }); task.Start();
            }
            return(result);
        }
Exemplo n.º 7
0
        public string BotLogin(string token)
        {
            string Rtn = null;

            try
            {
                //SSL/TLS连接
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
                //建立Bot客户端
                var botClient = new TelegramBotClient(token);
                //获取Bot资料
                var bot_info = botClient.GetMeAsync();
                Console.WriteLine($"=====================\n" +
                                  $"Well done.Login success." +
                                  $"\nAccount:{bot_info.Result.Id}\n" +
                                  $"Name:{bot_info.Result.FirstName}" +
                                  $"\n=====================\n");
                //写入Config
                string     path = Directory.GetCurrentDirectory() + "\\botInfo.ini";
                FileStream fs   = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite);
                if (File.Exists(path) == false)
                {
                    File.Create(path);
                    fs.Close();
                }
                else
                {
                    fs.Close();
                }
                IniConfig ini = new IniConfig(path);
                ini.Load();
                ini.Clear();
                ini.Object.Add(new ISection("BotAccount"));
                ini.Object["BotAccount"]["token"] = token;
                ini.Object["BotAccount"]["ID"]    = bot_info.Result.Id;
                ini.Object["BotAccount"]["Name"]  = bot_info.Result.FirstName;
                ini.Save();
                Rtn = "Login success.";
            }
            catch (Exception ex)
            {
                Rtn = ex.Message;
            }
            return(Rtn);
        }
Exemplo n.º 8
0
        static void Main()
        {
            //Error variable to check it's the program run ok
            bool error = false;
            //Directory of app
            string          directory = Environment.CurrentDirectory;
            ResourceManager IniConfig;
            CultureInfo     CI;
            Assembly        TGalvan_asm;
            ResourceManager TGalvan_rsc = null;

            try
            {
                //Search the initial resources of the app for apply those settings
                IniConfig = ResourceManager.CreateFileBasedResourceManager("IniConfig", directory + "\\Resources", null);
                string lang = IniConfig.GetString("Idioma");
                //Set the culture, the assembly and the resources asociated with it
                CI = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture   = CI;
                Thread.CurrentThread.CurrentUICulture = CI;
                TGalvan_asm = Assembly.LoadFrom(directory + "\\Resources\\" + lang + "TGalvan.resources.dll");
                TGalvan_rsc = new ResourceManager("TGalvan", TGalvan_asm);
            }
            catch
            {
                MessageBox.Show("There is a problem loading the initial configuration ", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                error = true;
            }
            if (error == false)
            {
                Stream TGlogo = TGalvan_rsc.GetStream("tecnologiagalvan");
                Stream Clogo  = TGalvan_rsc.GetStream("cliente_logo");
                Icon   TGicon = (Icon)TGalvan_rsc.GetObject("GALVAN");
                Start  Inicio = new Start();
                Inicio.pictureBox1.Image = new Bitmap(TGlogo);
                Inicio.pictureBox2.Image = new Bitmap(Clogo);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(Inicio);
                for (int i = 0; i < 10; i++)
                {
                    System.Threading.Thread.Sleep(1000);
                    Inicio.progressBar1.PerformStep();
                }
            }
        }
Exemplo n.º 9
0
        public static Image AnnotateImage(Image img, string imgPath, bool allowSave, string configPath,
                                          Action <Image> clipboardCopyRequested,
                                          Action <Image> imageUploadRequested,
                                          Action <Image, string> imageSaveRequested,
                                          Func <Image, string, string> imageSaveAsRequested,
                                          Action <Image> printImageRequested)
        {
            if (!IniConfig.isInitialized)
            {
                IniConfig.AllowSave = allowSave;
                IniConfig.Init(configPath);
            }

            using (Image cloneImage = img != null ? (Image)img.Clone() : LoadImage(imgPath))
                using (ICapture capture = new Capture {
                    Image = cloneImage
                })
                    using (Surface surface = new Surface(capture))
                        using (ImageEditorForm editor = new ImageEditorForm(surface, true))
                        {
                            editor.IsTaskWork = img != null;
                            editor.SetImagePath(imgPath);
                            editor.ClipboardCopyRequested += clipboardCopyRequested;
                            editor.ImageUploadRequested   += imageUploadRequested;
                            editor.ImageSaveRequested     += imageSaveRequested;
                            editor.ImageSaveAsRequested   += imageSaveAsRequested;
                            editor.PrintImageRequested    += printImageRequested;

                            DialogResult result = editor.ShowDialog();

                            if (result == DialogResult.OK && editor.IsTaskWork)
                            {
                                using (img)
                                {
                                    return(editor.GetImageForExport());
                                }
                            }

                            if (result == DialogResult.Abort)
                            {
                                return(null);
                            }
                        }

            return(img);
        }
Exemplo n.º 10
0
        private static bool ReloadIniConfig()
        {
            try
            {
                _iniConfig = IniConfigParser.Parse();
                Logger.SetMode(_iniConfig.LoggerMode);

                return(true);
            }
            catch (Exception e)
            {
                Logger.SetMode(Logger.Mode.DISABLED_WITH_ALERTS);
                Logger.Error(e.Message, e, true);

                return(false);
            }
        }
Exemplo n.º 11
0
        public void Reset()
        {
            var coreConfiguration = IniConfig.GetIniSection <CoreConfiguration>();

            if (null == coreConfiguration || string.IsNullOrEmpty(coreConfiguration.DestinationDefaultBorderEffect?.Trim()))
            {
                return;
            }
            var defaultBorderEffect = Newtonsoft.Json.JsonConvert.DeserializeObject <DefaultBorderEffect>(coreConfiguration.DestinationDefaultBorderEffect);

            if (null == defaultBorderEffect)
            {
                return;
            }
            this.Color = defaultBorderEffect.Color;
            this.Width = defaultBorderEffect.Width;
        }
Exemplo n.º 12
0
        private void AbyssHelper_Load(object sender, EventArgs e)
        {
            if (QMApi.CurrentApi != null)
            {
                var group = QMApiV2.GetGroupList(MainSave.RobotQQ);
                foreach (var item in (JArray)group["join"])
                {
                    grouplist.Add(Convert.ToInt64(item["gc"].ToString()));
                    checkedListBox_Group.Items.Add($"{item["gn"]}({item["gc"]})");
                }
            }
            else
            {
                Random rd = new Random();
                for (int i = 0; i < 10; i++)
                {
                    long groupid = rd.Next();
                    grouplist.Add(groupid);
                    checkedListBox_Group.Items.Add($"名称{i + 1}({groupid})");
                }
            }
            IniConfig ini = new IniConfig(MainSave.AppDirectory + "Config.ini"); ini.Load();

            textBox_timerInterval.Text = ini.Object["ExtraConfig"]["TimerInterval"].GetValueOrDefault("20");
            if (File.Exists(MainSave.AppDirectory + "AbyssHelper.json"))
            {
                abyssTimers = JsonConvert.DeserializeObject <List <AbyssTimer> >(File.ReadAllText(MainSave.AppDirectory + "AbyssHelper.json"));
            }

            foreach (var item in abyssTimers)
            {
                string grouptext = string.Empty;
                int    count     = 0;
                foreach (var group in item.GroupList)
                {
                    count++;
                    grouptext += group + (count == item.GroupList.Count ? "" : ",");
                    if (grouplist.IndexOf(group) != -1)
                    {
                        checkedListBox_Group.SetItemChecked(grouplist.IndexOf(group), true);
                    }
                }
                dataGridView_Details.Rows.Add(item.Enabled, comboBox_Week.Items[item.DayofWeek].ToString()
                                              , $"{item.Hour}:{item.Minute}", item.RemindText, grouptext);
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// Implementation of the IGreenshotPlugin.Initialize
 /// </summary>
 /// <param name="pluginHost">Use the IGreenshotPluginHost interface to register events</param>
 /// <param name="myAttributes">My own attributes</param>
 public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes)
 {
     // Register configuration (don't need the configuration itself)
     _config = IniConfig.GetIniSection <ConfluenceConfiguration>();
     if (_config.IsDirty)
     {
         IniConfig.Save();
     }
     try {
         TranslationManager.Instance.TranslationProvider = new LanguageXMLTranslationProvider();
         //resources = new ComponentResourceManager(typeof(ConfluencePlugin));
     } catch (Exception ex) {
         LOG.ErrorFormat("Problem in ConfluencePlugin.Initialize: {0}", ex.Message);
         return(false);
     }
     return(true);
 }
Exemplo n.º 14
0
        public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            ExportInformation     exportInformation = new ExportInformation(this.Designation, this.Description);
            CoreConfiguration     config            = IniConfig.GetIniSection <CoreConfiguration>();
            SurfaceOutputSettings outputSettings    = new SurfaceOutputSettings();

            string file     = FilenameHelper.GetFilename(OutputFormat.png, null);
            string filePath = Path.Combine(config.OutputFilePath, file);

            using (FileStream stream = new FileStream(filePath, FileMode.Create)) {
                ImageOutput.SaveToStream(surface, stream, outputSettings);
            }
            exportInformation.Filepath   = filePath;
            exportInformation.ExportMade = true;
            ProcessExport(exportInformation, surface);
            return(exportInformation);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Implementation of the IGreenshotPlugin.Initialize
        /// </summary>
        /// <param name="pluginHost">Use the IGreenshotPluginHost interface to register events</param>
        /// <param name="myAttributes">My own attributes</param>
        /// <returns>true if plugin is initialized, false if not (doesn't show)</returns>
        public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes)
        {
            _host      = pluginHost;
            Attributes = myAttributes;

            // Get configuration
            _config    = IniConfig.GetIniSection <ImgurConfiguration>();
            _resources = new ComponentResourceManager(typeof(ImgurPlugin));

            ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur")
            {
                Image = (Image)_resources.GetObject("Imgur")
            };

            _historyMenuItem = new ToolStripMenuItem(Language.GetString("imgur", LangKey.history))
            {
                Tag = _host
            };
            _historyMenuItem.Click += delegate {
                ImgurHistory.ShowHistory();
            };
            itemPlugInRoot.DropDownItems.Add(_historyMenuItem);

            _itemPlugInConfig = new ToolStripMenuItem(Language.GetString("imgur", LangKey.configure))
            {
                Tag = _host
            };
            _itemPlugInConfig.Click += delegate {
                _config.ShowConfigDialog();
            };
            itemPlugInRoot.DropDownItems.Add(_itemPlugInConfig);

            PluginUtils.AddToContextMenu(_host, itemPlugInRoot);
            Language.LanguageChanged += OnLanguageChanged;

            // retrieve history in the background
            Thread backgroundTask = new Thread(CheckHistory)
            {
                Name         = "Imgur History",
                IsBackground = true
            };

            backgroundTask.SetApartmentState(ApartmentState.STA);
            backgroundTask.Start();
            return(true);
        }
Exemplo n.º 16
0
        public void SaveTo()
        {
            File.Delete(iniTestFilePath);
            IIniConfig ini = IniConfig.Parse(Constants.INI);

            ini.GetSection("User").AddOrReplace("Name", "Olaf");
            ini.GetSection("User").AddOrReplaceKey("Age");
            using (var ms = new MemoryStream())
            {
                ini.SaveTo(ms);
                ms.Position = 0;
                ini         = IniConfig.From(ms);
            }

            Assert.IsTrue(ini["User"].GetValue("Name").ToString() == "Olaf");
            Assert.IsTrue(ini["User"].GetValue("Age").ToString() == "");
        }
Exemplo n.º 17
0
        private static string MakeCQImage(PicMessage.Grouppic item)
        {
            string md5  = GenerateMD5(item.FileMd5).ToUpper();
            string path = $"data\\image\\{md5}.cqimg";

            if (!File.Exists(path))
            {
                IniConfig ini = new IniConfig(path);
                ini.Object.Add(new ISection("image"));
                ini.Object["image"]["md5"]  = item.FileMd5;
                ini.Object["image"]["size"] = item.FileSize;
                ini.Object["image"]["url"]  = item.Url;
                ini.Save();
            }

            return(CQApi.CQCode_Image(md5).ToSendString());
        }
    public void Test()
    {
        var project = new IniConfig.Section
        {
            ["Name"] = nameof(IniConfig_Tests),
        };

        project.Add(nameof(DateTime), DateTime.Now);
        project.Add(nameof(Guid), Guid.NewGuid());

        project.Add(nameof(AppVersion),
                    new AppVersion(1,
                                   2,
                                   3,
                                   4,
                                   5,
                                   6));

        var server = new IniConfig.Section
        {
            ["Name"] = nameof(ServicePoint),
        };

        server.Add("Port", 5000);
        server.Add(nameof(IPAddress), IPAddress.Broadcast);

        var ini = new IniConfig
        {
            [nameof(project)] = project,
            [nameof(server)]  = server
        };

        ini[nameof(Random)].Add(nameof(Random.Next), new Random().Next());
        ini[nameof(IniConfig_Tests)].Add(nameof(Random.Next), new Random().Next());

        var s = ini.ToString();

        s.WriteToConsole();
        IniConfig?results = IniConfig.FromString(s);

        results?.WriteToConsole();
        NotNull(results);
        AreEqual(results, ini);
        AreEqual(results?[nameof(project)], project);
    }
Exemplo n.º 19
0
        public static void Start()
        {
            remindTimer.Elapsed -= RemindTimer_Elapsed;
            remindTimer.Stop();
            IniConfig ini = new IniConfig(MainSave.AppDirectory + "Config.ini"); ini.Load();

            if (File.Exists(MainSave.AppDirectory + "AbyssHelper.json"))
            {
                abyssTimers = JsonConvert.DeserializeObject <List <AbyssTimer> >(File.ReadAllText(MainSave.AppDirectory + "AbyssHelper.json"));
            }
            remindTimer.Interval = Convert.ToDouble(ini.Object["ExtraConfig"]["TimerInterval"].GetValueOrDefault("20")) * 1000;
            remindTimer.Elapsed += RemindTimer_Elapsed;
            if (abyssTimers.Count != 0)
            {
                remindTimer.Start();
                QMLog.CurrentApi.Info($"深渊提醒助手,定时生效,周期{remindTimer.Interval/1000}秒");
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Implementation of the IGreenshotPlugin.Initialize
        /// </summary>
        /// <param name="host">Use the IGreenshotPluginHost interface to register events</param>
        /// <param name="captureHost">Use the ICaptureHost interface to register in the MainContextMenu</param>
        /// <param name="pluginAttribute">My own attributes</param>
        public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes)
        {
            this.host  = (IGreenshotHost)pluginHost;
            Attributes = myAttributes;

            // Get configuration
            config    = IniConfig.GetIniSection <PicasaConfiguration>();
            resources = new ComponentResourceManager(typeof(PicasaPlugin));

            itemPlugInRoot        = new ToolStripMenuItem();
            itemPlugInRoot.Text   = Language.GetString("picasa", LangKey.Configure);
            itemPlugInRoot.Tag    = host;
            itemPlugInRoot.Image  = (Image)resources.GetObject("Picasa");
            itemPlugInRoot.Click += new System.EventHandler(ConfigMenuClick);
            PluginUtils.AddToContextMenu(host, itemPlugInRoot);
            Language.LanguageChanged += new LanguageChangedHandler(OnLanguageChanged);
            return(true);
        }
Exemplo n.º 21
0
 private void Login_Btn_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
         var botClient = new TelegramBotClient(Bot_Token.Text);
         var bot_info  = botClient.GetMeAsync().Result;
         Login_Rtn.Foreground = new SolidColorBrush(Color.FromRgb(102, 204, 255));
         Login_Rtn.Text       = $"Welcome!\nHanaya.TgBot框架现在登录的是Bot账号 {bot_info.Id}\nBot名字为 {bot_info.FirstName}.";
         IniConfig ini = new IniConfig(Directory.GetCurrentDirectory() + "\\bot.config.ini");
         ini.Load();
         ini.Object.Add(new ISection("BotAccount"));
         ini.Object["BotAccount"]["token"] = Bot_Token.Text;
         ini.Object["BotAccount"]["ID"]    = bot_info.Id;
         ini.Object["BotAccount"]["Name"]  = bot_info.FirstName;
         ini.Save();
         MainWindow mainWindow = new MainWindow();
         Help_Login help       = new Help_Login();
         if (isOpen != false)
         {
             mainWindow.Show();
             help.Close();
             Close();
         }
         else
         {
             mainWindow.Show();
             Close();
         }
     }
     catch (AggregateException ex)
     {
         Login_Rtn.Text = "错误:System.AggregateException" + "\n请检查网络连接(国内连接Telegram需要代理)" + "\n以及检查Token是否正确\n" + ex.Message;
     }
     catch (WebException ex)
     {
         Login_Rtn.Text = "错误:System.Net.WebException\n" + ex.Message;
     }
     catch (Exception ex)
     {
         Login_Rtn.Text = "错误:System.Exception:请填写正确的Token(格式错误)\n" + ex.Message;
     }
 }
Exemplo n.º 22
0
        public void CQStartup(object sender, CQStartupEventArgs e)
        {
            CQSave.cq_start       = e;
            CQSave.AppDirectory   = e.CQApi.AppDirectory;
            CQSave.ImageDirectory = GetAppImageDirectory();
            CQSave.CQLog          = e.CQLog;
            CQSave.CQApi          = e.CQApi;
            ini = new IniConfig(e.CQApi.AppDirectory + "Config.ini");
            ini.Load();
            string temp = ini.Object["OCR"]["app_id"].GetValueOrDefault("");

            if (temp == "")
            {
                ini.Object["OCR"]["app_id"]  = new IValue("");
                ini.Object["OCR"]["app_key"] = new IValue("");
            }
            ini.Save();

            if (!File.Exists($@"{e.CQApi.AppDirectory}装备卡\框\抽卡背景.png"))
            {
                e.CQLog.Warning("错误", "数据包未安装,插件无法运行,请仔细阅读论坛插件说明安装数据包,之后重启酷Q");
            }
            else
            {
                if (!File.Exists($@"{e.CQApi.AppDirectory}data.db"))
                {
                    Event_GroupMessage.CreateDB($@"{e.CQApi.AppDirectory}data.db");
                    e.CQLog.WriteLine(Native.Sdk.Cqp.Enum.CQLogLevel.Info, "已创建数据库");
                }
                else
                {
                    FileInfo info = new FileInfo($@"{e.CQApi.AppDirectory}data.db");
                    if (info.Length == 0)
                    {
                        File.Delete($@"{e.CQApi.AppDirectory}data.db");
                        Event_GroupMessage.CreateDB($@"{e.CQApi.AppDirectory}data.db");
                        e.CQLog.WriteLine(Native.Sdk.Cqp.Enum.CQLogLevel.Info, "已创建数据库");
                        return;
                    }
                    Event_GroupMessage.CheckDB($@"{e.CQApi.AppDirectory}data.db", e);
                }
            }
            AbyssTimerHelper.Start();
        }
        protected void ApplyLanguage(Control applyTo)
        {
            IGreenshotLanguageBindable languageBindable = applyTo as IGreenshotLanguageBindable;

            if (languageBindable == null)
            {
                // check if it's a menu!
                if (applyTo is ToolStrip)
                {
                    ToolStrip toolStrip = applyTo as ToolStrip;
                    foreach (ToolStripItem item in toolStrip.Items)
                    {
                        ApplyLanguage(item);
                    }
                }
                return;
            }

            string languageKey = languageBindable.LanguageKey;

            // Apply language text to the control
            ApplyLanguage(applyTo, languageKey);
            // Repopulate the combox boxes
            if (typeof(IGreenshotConfigBindable).IsAssignableFrom(applyTo.GetType()))
            {
                if (typeof(GreenshotComboBox).IsAssignableFrom(applyTo.GetType()))
                {
                    IGreenshotConfigBindable configBindable = applyTo as IGreenshotConfigBindable;
                    if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName))
                    {
                        IniSection section = IniConfig.GetIniSection(configBindable.SectionName);
                        if (section != null)
                        {
                            GreenshotComboBox comboxBox = applyTo as GreenshotComboBox;
                            // Only update the language, so get the actual value and than repopulate
                            Enum currentValue = (Enum)comboxBox.GetSelectedEnum();
                            comboxBox.Populate(section.Values[configBindable.PropertyName].ValueType);
                            comboxBox.SetValue(currentValue);
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        internal bool LoadConfig(IniConfig config)
        {
            bool success = true;

            // panels
            {
                bool valid = true;
                for (int i = 0; i < _panels.Count; i++)
                {
                    EditorPanel panel = _panels[i];

                    string stringValue = config.Read(EditorConfigSections.PanelsOpen, panel.GetType().Name);

                    if (String.IsNullOrEmpty(stringValue))
                    {
                        continue;
                    }

                    if (bool.TryParse(stringValue, out bool val))
                    {
                        panel.Open = val;
                    }
                    else if (stringValue == "null")
                    {
                        panel.Open = null;
                    }
                    else
                    {
                        valid = false;
                        continue;
                    }
                }

                if (!valid)
                {
                    EditorApplication.Log.Trace($"invalid config section '{EditorConfigSections.PanelsOpen}'");
                }

                success = success && valid;
            }

            return(success);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Implementation of the IGreenshotPlugin.Initialize
        /// </summary>
        /// <param name="pluginHost">Use the IGreenshotPluginHost interface to register events</param>
        /// <param name="pluginAttribute">My own attributes</param>
        public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute pluginAttribute)
        {
            _host      = pluginHost;
            Attributes = pluginAttribute;

            // Register configuration (don't need the configuration itself)
            _config    = IniConfig.GetIniSection <BoxConfiguration>();
            _resources = new ComponentResourceManager(typeof(BoxPlugin));

            _itemPlugInConfig = new ToolStripMenuItem {
                Image = (Image)_resources.GetObject("Box"),
                Text  = Language.GetString("box", LangKey.Configure)
            };
            _itemPlugInConfig.Click += ConfigMenuClick;

            PluginUtils.AddToContextMenu(_host, _itemPlugInConfig);
            Language.LanguageChanged += OnLanguageChanged;
            return(true);
        }
 /// <summary>
 /// Fill all GreenshotControls with the values from the configuration
 /// </summary>
 protected void FillFields()
 {
     foreach (FieldInfo field in this.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
     {
         if (!field.FieldType.IsSubclassOf(typeof(Control)))
         {
             continue;
         }
         Object controlObject = field.GetValue(this);
         if (typeof(IGreenshotConfigBindable).IsAssignableFrom(field.FieldType))
         {
             IGreenshotConfigBindable configBindable = controlObject as IGreenshotConfigBindable;
             if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName))
             {
                 IniSection section = IniConfig.GetIniSection(configBindable.SectionName);
                 if (section != null)
                 {
                     if (!section.Values.ContainsKey(configBindable.PropertyName))
                     {
                         LOG.WarnFormat("Wrong property '{0}' configured for field '{1}'", configBindable.PropertyName, field.Name);
                         continue;
                     }
                     if (typeof(CheckBox).IsAssignableFrom(field.FieldType))
                     {
                         CheckBox checkBox = controlObject as CheckBox;
                         checkBox.Checked = (bool)section.Values[configBindable.PropertyName].Value;
                     }
                     else if (typeof(TextBox).IsAssignableFrom(field.FieldType))
                     {
                         TextBox textBox = controlObject as TextBox;
                         textBox.Text = (string)section.Values[configBindable.PropertyName].Value;
                     }
                     else if (typeof(GreenshotComboBox).IsAssignableFrom(field.FieldType))
                     {
                         GreenshotComboBox comboxBox = controlObject as GreenshotComboBox;
                         comboxBox.Populate(section.Values[configBindable.PropertyName].ValueType);
                         comboxBox.SetValue((Enum)section.Values[configBindable.PropertyName].Value);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 27
0
        void Button_okClick(object sender, EventArgs e)
        {
            this.AllowPrintCenter  = this.checkboxAllowCenter.Checked;
            this.AllowPrintEnlarge = this.checkboxAllowEnlarge.Checked;
            this.AllowPrintRotate  = this.checkboxAllowRotate.Checked;
            this.AllowPrintShrink  = this.checkboxAllowShrink.Checked;
            this.PrintDateTime     = this.checkboxDateTime.Checked;
            this.PrintInverted     = this.checkboxPrintInverted.Checked;

            // update config
            conf.OutputPrintCenter        = this.AllowPrintCenter;
            conf.OutputPrintAllowEnlarge  = this.AllowPrintEnlarge;
            conf.OutputPrintAllowRotate   = this.AllowPrintRotate;
            conf.OutputPrintAllowShrink   = this.AllowPrintShrink;
            conf.OutputPrintTimestamp     = this.PrintDateTime;
            conf.OutputPrintInverted      = this.PrintInverted;
            conf.OutputPrintPromptOptions = !this.checkbox_dontaskagain.Checked;
            IniConfig.Save();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Implementation of the IGreenshotPlugin.Initialize
        /// </summary>
        /// <param name="host">Use the IGreenshotPluginHost interface to register events</param>
        /// <param name="pluginAttribute">My own attributes</param>
        public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes)
        {
            this.host  = (IGreenshotHost)pluginHost;
            Attributes = myAttributes;

            // Register configuration (don't need the configuration itself)
            config    = IniConfig.GetIniSection <DropboxPluginConfiguration>();
            resources = new ComponentResourceManager(typeof(DropboxPlugin));

            itemPlugInConfig        = new ToolStripMenuItem();
            itemPlugInConfig.Text   = Language.GetString("dropbox", LangKey.Configure);
            itemPlugInConfig.Tag    = host;
            itemPlugInConfig.Click += new System.EventHandler(ConfigMenuClick);
            itemPlugInConfig.Image  = (Image)resources.GetObject("Dropbox");

            PluginUtils.AddToContextMenu(host, itemPlugInConfig);
            Language.LanguageChanged += new LanguageChangedHandler(OnLanguageChanged);
            return(true);
        }
Exemplo n.º 29
0
        public static IniConfig ReadConfigFrom(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return(null);
            }
            string text = File.ReadAllText(filePath);

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

            IniConfig config = new IniConfig();

            config.ParseText(text);

            return(config);
        }
Exemplo n.º 30
0
 public static ILanguage GetInstance()
 {
     if (uniqueInstance == null)
     {
         uniqueInstance = new LanguageContainer();
         uniqueInstance.LanguageFilePattern = LANGUAGE_FILENAME_PATTERN;
         uniqueInstance.Load();
         CoreConfiguration conf = IniConfig.GetIniSection <CoreConfiguration>();
         if (string.IsNullOrEmpty(conf.Language))
         {
             uniqueInstance.SynchronizeLanguageToCulture();
         }
         else
         {
             uniqueInstance.SetLanguage(conf.Language);
         }
     }
     return(uniqueInstance);
 }
		public async Task TestStartupShutdown()
		{
			// Especially for testing
			SetEntryAssembly(GetType().Assembly);
			using (IApplicationBootstrapper bootstrapper = new ApplicationBootstrapper(ApplicationName))
			{
				// Add all file starting with Dapplo and ending on .dll or .dll.gz
				bootstrapper.FindAndLoadAssemblies("Dapplo*");

				var iniConfig = new IniConfig(ApplicationName, ApplicationName);
				// Fix startup issues due to unloaded configuration
				await iniConfig.LoadIfNeededAsync();
				bootstrapper.ExportProviders.Add(new ServiceProviderExportProvider(iniConfig, bootstrapper));

				// Add test project, without having a direct reference
#if DEBUG
				bootstrapper.AddScanDirectory(@"..\..\..\Dapplo.Addons.TestAddon\bin\Debug");
#else
				bootstrapper.AddScanDirectory(@"..\..\..\Dapplo.Addons.TestAddon\bin\Release");
#endif
				bootstrapper.FindAndLoadAssembly("Dapplo.Addons.TestAddon");

				// Test if our test addon was loaded
				Assert.True(bootstrapper.KnownFiles.Count(addon => addon.EndsWith("TestAddon.dll")) > 0);

				// Initialize, so we can export
				Assert.True(await bootstrapper.InitializeAsync().ConfigureAwait(false), "Not initialized");

				// test Export, this should work before Run as some of the addons might need some stuff.

				var part = bootstrapper.Export(this);

				// Start the composition, and IStartupActions
				Assert.True(await bootstrapper.RunAsync().ConfigureAwait(false), "Couldn't run");

				// test import
				Assert.NotNull(bootstrapper.GetExport<ApplicationBootstrapperTests>().Value);

				// test release
				bootstrapper.Release(part);
				Assert.False(bootstrapper.GetExports<ApplicationBootstrapperTests>().Any());

				// Test localization of a test addon, with the type specified. This is possible due to Export[typeof(SomeAddon)]
				Assert.True(bootstrapper.GetExports<IStartupAction>().Count() == 2);

				// Test localization of a IStartupAction with meta-data, which is exported via [StartupAction(DoNotAwait = true)]
				var hasAwaitStartFalse = bootstrapper.GetExports<IStartupAction, IStartupActionMetadata>().Any(x => x.Metadata.AwaitStart == false);
				Assert.True(hasAwaitStartFalse);
			}
			// Dispose automatically calls IShutdownActions
		}