public MessageBoxViewModel(MessageBox manager, MessageBoxConfiguration options)
 {
     _configuration = options;
     DetailText = options.DetailText;
     SummaryText = options.SummaryText;
     // If there is no caption, then just put the caption-prefix without the spacer.
     if (StringLib.HasNothing(options.CaptionAfterPrefix))
     {
         if (StringLib.HasNothing(options.CaptionPrefix))
         {
             Title = manager.CaptionPrefix;
         }
         else
         {
             Title = options.CaptionPrefix;
         }
     }
     else
     {
         if (StringLib.HasNothing(options.CaptionPrefix))
         {
             Title = manager.CaptionPrefix + ": " + options.CaptionAfterPrefix;
         }
         else
         {
             Title = options.CaptionPrefix + ": " + options.CaptionAfterPrefix;
         }
     }
     IsCustomElementVisible = true;
     IsGradiantShown = false;
     SummaryTextColor = new SolidColorBrush(Colors.Black);
 }
        public void Initialize()
        {
            if (!Directory.Exists(_path))
            {
                try
                {
                    Directory.CreateDirectory(_path);
                }
                catch (IOException exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
                catch (UnauthorizedAccessException exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
                catch (Exception exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
            }

            if (!File.Exists(_optionsFile))
            {
                try
                {
                    File.Create(_optionsFile).Close();
                }
                catch (IOException exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
                catch (UnauthorizedAccessException exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
                catch (Exception exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
            }

            if (!File.Exists(_serverListFile))
            {
                try
                {
                    File.Create(_serverListFile).Close();
                }
                catch (IOException exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
                catch (UnauthorizedAccessException exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
                catch (Exception exception)
                {
                    MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    Console.WriteLine(exception);
                }
            }
        }
Exemplo n.º 3
0
        private void SaveOmni()
        {
            if (!ChangesMade)
            {
                return;
            }

            if (OmniTags.Count == 0)
            {
                var result = MessageBox.Show("This Omni is not associated with any tags. This will prevent it from " +
                                             "being listed if any tag filters are chosen during searches.\n\n" +
                                             "Are you sure you want to continue " +
                                             "without associating a tag?", "Warning", MessageBoxButton.YesNo,
                                             MessageBoxImage.Warning, MessageBoxResult.No);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
            }

            if (CurrentOmni.Summary != OmniSummary)
            {
                if (OmniSummary.Length > 100)
                {
                    MessageBox.Show("Omni summary cannot be longer than 100 characters (including spaces). The current " +
                                    $"length of the summary is {OmniSummary.Length} characters.", "Error", MessageBoxButton.OK,
                                    MessageBoxImage.Error, MessageBoxResult.OK);
                    return;
                }
                CurrentOmni.Summary          = OmniSummary;
                CurrentOmni.LastModifiedDate = DateTime.Now;
            }
            if (CurrentOmni.Description != OmniDescription)
            {
                CurrentOmni.Description      = OmniDescription;
                CurrentOmni.LastModifiedDate = DateTime.Now;

                foreach (var imageFileName in CurrentOmni.Images.Select(i => i.FileName).ToList())
                {
                    if (!CurrentOmni.Description.Contains(imageFileName.Replace(" ", "%20")))
                    {
                        var img = Context.Images.Single(i => i.FileName == imageFileName);
                        Context.Images.Remove(img);
                    }
                }
            }

            if (!OmniTags.IsEqualTo(CurrentOmni.Tags))
            {
                CurrentOmni.Tags             = OmniTags;
                CurrentOmni.LastModifiedDate = DateTime.Now;
            }

            foreach (var tag in AddedTags)
            {
                Context.Tags.Add(tag);
                CurrentOmni.LastModifiedDate = DateTime.Now;

                if (tag.Omnis.Count >= _autoVerifyThreshold)
                {
                    tag.IsVerified = true;
                }
            }
            AddedTags.Clear();

            foreach (var tag in DeletedTags)
            {
                if ((!tag.ManuallyVerified) && (tag.Omnis.Count < _autoVerifyThreshold))
                {
                    tag.IsVerified = false;
                }

                // If an unverified tag isn't being used, we delete it since the user hasn't marked the tag as important.
                if ((!tag.ManuallyVerified) && (tag.Omnis.Count == 1)) // use 1 here to represent the current tag and no others
                {
                    tag.DateDeleted = DateTime.Now;
                }

                CurrentOmni.LastModifiedDate = DateTime.Now;
            }
            DeletedTags.Clear();

            if (_isNewOmni)
            {
                Context.Omnis.Add(CurrentOmni);
            }

            Context.SaveChanges();

            foreach (var tag in OmniTags)
            {
                if (tag.Omnis.Count >= _autoVerifyThreshold)
                {
                    tag.IsVerified = true;
                }
            }
            Context.SaveChanges();

            ChangesMade = false;
            _isNewOmni  = false;
            CurrentOmniLastUpdatedTime = CurrentOmni.LastModifiedDate;
            OnDataChanged();
        }
        private void OnRenameTags(string newName)
        {
            ShowBusy(true);

            //check if new name provided is a new tag or existing
            var tagExistResponse = _tagService.GetTagByName(newName).Result;

            if (tagExistResponse.Exception != null)
            {
                StatusMessage = "Renaming tag...";
                var selectedTag = SelectedTags?.FirstOrDefault();
                if (selectedTag == null)
                {
                    return;
                }

                StatusMessage = $"Renaming tag...{selectedTag.Name}";

                var response = _tagService.RenameTag(selectedTag.Name, newName.Trim()).Result;
                if (response.Exception != null)
                {
                    _log.Error("Error renaming tag - Data: {@data}, Exception: {@exception}", response.Data, response.Exception);
                    ShowBusy(false);
                    _eventAggregator.GetEvent <NotifyErrorTagAdminPage>().Publish(response.Exception.Message);
                    return;
                }
                //trigger refresh
                StatusMessage = "Refreshing...";
                _eventAggregator.GetEvent <TriggerGetTags>().Publish(_teamFoundationContext);
            }
            else if (tagExistResponse.Data != null)
            {
                //tag already exist
                ShowBusy(false);
                if (TaskDialog.OSSupportsTaskDialogs)
                {
                    using (TaskDialog dialog = new TaskDialog())
                    {
                        dialog.WindowTitle     = "Tag Admin";
                        dialog.MainInstruction = "Tag name already exists!";
                        dialog.Content         = $"Tag '{newName}' already exists, please choose another name.";
                        TaskDialogButton okButton = new TaskDialogButton("Try new name");
                        dialog.Buttons.Add(okButton);
                        var cancelButton = new TaskDialogButton("Cancel rename");
                        dialog.Buttons.Add(cancelButton);
                        var taskDialogButton = dialog.ShowDialog();
                        if (taskDialogButton == okButton)
                        {
                            OnRenameTagCommand(null);
                            return;
                        }
                        if (taskDialogButton == cancelButton)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    var messageBoxResult = MessageBox.Show(
                        $"Tag '{newName}' already exists, please choose another name.", "Tag Admin", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                    if (messageBoxResult == MessageBoxResult.OK)
                    {
                        OnRenameTagCommand(null);
                        return;
                    }
                    if (messageBoxResult == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
            }


            ShowBusy(false);
        }
Exemplo n.º 5
0
        protected override async void OnStartup(StartupEventArgs e)
        {
            var languageService = ServiceLocator.Default.ResolveType <ILanguageService>();

            languageService.PreferredCulture = new CultureInfo("en-US");

            languageService.FallbackCulture = new CultureInfo("en-US");

#if DEBUG
            _debugListener = LogManager.AddDebugListener(true);
#endif
            var fileLogListener = new FileLogListener
            {
                IgnoreCatelLogging = true,
                FilePath           = FileLocations.LogFile,
                TimeDisplay        = TimeDisplay.DateTime
            };
            LogManager.IgnoreDuplicateExceptionLogging = false;
            LogManager.AddListener(fileLogListener);
            LogManager.GetCurrentClassLogger().Debug($"Started with command line {Environment.CommandLine}");

            var serviceLocator = ServiceLocator.Default;
            var updateService  = serviceLocator.ResolveType <IUpdateService>();
            updateService.Initialize(Settings.Application.AutomaticUpdates.AvailableChannels,
                                     Settings.Application.AutomaticUpdates.DefaultChannel,
                                     Settings.Application.AutomaticUpdates.CheckForUpdatesDefaultValue);

            if (updateService.IsUpdateSystemAvailable)
            {
                LogManager.GetCurrentClassLogger().Debug("Update system available, processing squirrel events");
                using (var mgr = new UpdateManager(updateService.CurrentChannel.DefaultUrl))
                {
                    // Note, in most of these scenarios, the app exits after this method
                    // completes!
                    SquirrelAwareApp.HandleEvents(
                        onInitialInstall: v =>
                    {
                        LogManager.GetCurrentClassLogger().Debug("Installing shortcuts");
                        mgr.CreateShortcutForThisExe();
                        Environment.Exit(0);
                    },
                        onAppUpdate: v =>
                    {
                        LogManager.GetCurrentClassLogger().Debug("Update: Installing shortcuts");
                        mgr.CreateShortcutForThisExe();
                        Environment.Exit(0);
                    },
                        onAppUninstall: v =>
                    {
                        mgr.RemoveShortcutForThisExe();
                        Environment.Exit(0);
                    });
                }
            }


            LogManager.GetCurrentClassLogger().Debug("Startup");

            try
            {
                RotateLogFile(fileLogListener.FilePath);
            }
            catch (Exception exception)
            {
                LogManager.GetCurrentClassLogger().Error("Tried to rotate the log file, but it failed.");
                LogManager.GetCurrentClassLogger().Error(exception);
                MessageBox.Show(
                    $"Unable to rotate the log file {fileLogListener.FilePath}. Please verify that you have access to that file. " +
                    $"We will continue, but no logging will be available. Additional information: {Environment.NewLine}{Environment.NewLine}{exception}",
                    "Log File Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

            // Clean up old RemoteVstHost logs
            VstUtils.CleanupVstWorkerLogDirectory();

            await StartShell();
        }
Exemplo n.º 6
0
 private void Scripting_ResetDataStorage(object sender, RoutedEventArgs e)
 {
     ScriptProvider?.DataStorage.Reset();
     MessageBox.Show(
         "Script Data Storage was reset.", "FFXIVMon Reborn", MessageBoxButton.OK, MessageBoxImage.Asterisk);
 }
Exemplo n.º 7
0
        public void ShowRemoteHost(uint id)
        {
            Debug.Assert(id > 0);
            Debug.Assert(GlobalData.Instance.ServerList.Any(x => x.Id == id));
            var server = GlobalData.Instance.ServerList.First(x => x.Id == id);

            // update last conn time
            server.LastConnTime = DateTime.Now;
            Server.AddOrUpdate(server);

            // start conn
            if (server.OnlyOneInstance && _protocolHosts.ContainsKey(id.ToString()))
            {
                _protocolHosts[id.ToString()].ParentWindow?.Activate();
                return;
            }

            TabWindow tab = null;

            try
            {
                if (server.IsConnWithFullScreen())
                {
                    // for those people using 2+ monitor which are in different scale factors, we will try "mstsc.exe" instead of "PRemoteM".
                    if (Screen.AllScreens.Length > 1 &&
                        server is ProtocolServerRDP rdp &&
                        rdp.RdpFullScreenFlag == ERdpFullScreenFlag.EnableFullAllScreens)
                    {
                        int factor = (int)(new ScreenInfoEx(Screen.PrimaryScreen).ScaleFactor * 100);
                        // check if screens are in different scale factors
                        bool differentScaleFactorFlag = Screen.AllScreens.Select(screen => (int)(new ScreenInfoEx(screen).ScaleFactor * 100)).Any(factor2 => factor != factor2);
                        if (differentScaleFactorFlag)
                        {
                            var tmp     = Path.GetTempPath();
                            var dp      = rdp.DispName;
                            var invalid = new string(Path.GetInvalidFileNameChars()) +
                                          new string(Path.GetInvalidPathChars());
                            dp = invalid.Aggregate(dp, (current, c) => current.Replace(c.ToString(), ""));
                            var rdpFile = Path.Combine(tmp, dp + ".rdp");
                            try
                            {
                                File.WriteAllText(rdpFile, rdp.ToRdpConfig().ToString());
                                var p = new Process
                                {
                                    StartInfo =
                                    {
                                        FileName               = "cmd.exe",
                                        UseShellExecute        = false,
                                        RedirectStandardInput  = true,
                                        RedirectStandardOutput = true,
                                        RedirectStandardError  = true,
                                        CreateNoWindow         = true
                                    }
                                };
                                p.Start();
                                p.StandardInput.WriteLine("mstsc -admin " + rdpFile);
                                p.StandardInput.WriteLine("exit");
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            finally
                            {
                                var t = new Task(() =>
                                {
                                    Thread.Sleep(1000 * 10);
                                    if (File.Exists(rdpFile))
                                    {
                                        File.Delete(rdpFile);
                                    }
                                });
                                t.Start();
                            }
                            return;
                        }
                    }


                    var host = ProtocolHostFactory.Get(server);
                    host.OnClosed            += OnProtocolClose;
                    host.OnFullScreen2Window += OnFullScreen2Window;
                    AddProtocolHost(host);
                    MoveProtocolHostToFullScreen(host.ConnectionId);
                    host.Conn();
                    SimpleLogHelper.Debug($@"Start Conn: {server.DispName}({server.GetHashCode()}) by host({host.GetHashCode()}) with full");
                }
                else
                {
                    if (!string.IsNullOrEmpty(_lastTabToken) && _tabWindows.ContainsKey(_lastTabToken))
                    {
                        tab = _tabWindows[_lastTabToken];
                    }
                    else
                    {
                        var token = DateTime.Now.Ticks.ToString();
                        AddTab(new TabWindow(token));
                        tab = _tabWindows[token];
                        tab.Show();
                        _lastTabToken = token;
                    }
                    tab.Activate();
                    var size = tab.GetTabContentSize();
                    var host = ProtocolHostFactory.Get(server, size.Width, size.Height);
                    host.OnClosed            += OnProtocolClose;
                    host.OnFullScreen2Window += OnFullScreen2Window;
                    host.ParentWindow         = tab;
                    tab.Vm.Items.Add(new TabItemViewModel()
                    {
                        Content = host,
                        Header  = server.DispName,
                    });
                    tab.Vm.SelectedItem = tab.Vm.Items.Last();
                    host.Conn();
                    _protocolHosts.Add(host.ConnectionId, host);
                    SimpleLogHelper.Debug($@"Start Conn: {server.DispName}({server.GetHashCode()}) by host({host.GetHashCode()}) with Tab({tab.GetHashCode()})");
                    SimpleLogHelper.Debug($@"ProtocolHosts.Count = {_protocolHosts.Count}, FullWin.Count = {_host2FullScreenWindows.Count}, _tabWindows.Count = {_tabWindows.Count}");
                }
            }
            catch (Exception e)
            {
                if (tab?.Vm != null && (tab.Vm?.Items?.Count ?? 0) == 0)
                {
                    CloseTabWindow(tab.Vm.Token);
                }
                SimpleLogHelper.Error(e);
                MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public MainWindow()
        {
            InitializeComponent();

            WindowStyle = WindowStyle.SingleBorderWindow;
            Grid.Effect = new BlurEffect()
            {
                Radius = 5, RenderingBias = RenderingBias.Performance
            };

            if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45)
            {
                //Mainland China PRC
                DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29");
                DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list";
                UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/";
            }
            else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237)
            {
                //Taiwan ROC
                DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101");
                DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list";
            }
            else if (RegionInfo.CurrentRegion.GeoId == 104)
            {
                //HongKong SAR
                UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list";
            }

            if (File.Exists($"{SetupBasePath}url.json"))
            {
                UrlSettings.ReadConfig($"{SetupBasePath}url.json");
            }

            if (File.Exists($"{SetupBasePath}config.json"))
            {
                DnsSettings.ReadConfig($"{SetupBasePath}config.json");
            }

            if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list"))
            {
                DnsSettings.ReadBlackList($"{SetupBasePath}black.list");
            }

            if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list"))
            {
                DnsSettings.ReadWhiteList($"{SetupBasePath}white.list");
            }

            if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list"))
            {
                DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list");
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

//            if (false)
//                ServicePointManager.ServerCertificateValidationCallback +=
//                    (sender, cert, chain, sslPolicyErrors) => true;
//                //强烈不建议 忽略 TLS 证书安全错误
//
//            switch (0.0)
//            {
//                case 1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
//                    break;
//                case 1.1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
//                    break;
//                case 1.2:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//                    break;
//                default:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
//                    break;
//            }

            LocIPAddr = IPAddress.Parse(IpTools.GetLocIp());
            IntIPAddr = IPAddress.Parse(IpTools.GetIntIp());

            MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10);
            MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived;
            MDnsSvrWorker.DoWork     += (sender, args) => MDnsServer.Start();
            MDnsSvrWorker.Disposed   += (sender, args) => MDnsServer.Stop();

            NotifyIcon = new NotifyIcon()
            {
                Text = @"AuroraDNS", Visible = false,
                Icon = Properties.Resources.AuroraWhite
            };
            WinFormMenuItem showItem    = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal);
            WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) =>
            {
                if (MDnsSvrWorker.IsBusy)
                {
                    MDnsSvrWorker.Dispose();
                }
                Process.Start(new ProcessStartInfo {
                    FileName = GetType().Assembly.Location
                });
                Environment.Exit(Environment.ExitCode);
            });
            WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) =>
            {
                if (File.Exists(
                        $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log"))
                {
                    Process.Start(new ProcessStartInfo("notepad.exe",
                                                       $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log"));
                }
                else
                {
                    MessageBox.Show("找不到当前日志文件,或当前未产生日志文件。");
                }
            });
            WinFormMenuItem abootItem    = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().ShowDialog());
            WinFormMenuItem updateItem   = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location));
            WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().ShowDialog());
            WinFormMenuItem exitItem     = new WinFormMenuItem("退出", (sender, args) => Environment.Exit(Environment.ExitCode));

            NotifyIcon.ContextMenu =
                new WinFormContextMenu(new[]
            {
                showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem
            });

            NotifyIcon.DoubleClick += MinimizedNormal;

            if (MyTools.IsNslookupLocDns())
            {
                IsSysDns.ToolTip = "已设为系统 DNS";
            }
        }
Exemplo n.º 9
0
 private void ConnectedToServer(SocketClient a)
 {
     AppendRichtTextBoxLog("The client has connected to the server.");
     ChangeStatus("CONNECTED");
     MessageBox.Show("Client has connected to the server on ip : " + a.Ip);
 }
Exemplo n.º 10
0
 void Disconnected(SocketClient a, string ip, int port)
 {
     AppendRichtTextBoxLog("Client has disconnected from the server.");
     ChangeStatus("DISCONNECTED");
     MessageBox.Show("Client has disconnected to the server on ip : " + ip + " on port " + port);
 }
Exemplo n.º 11
0
        void btnSaveDatabaseSettings_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                btnSaveDatabaseSettings.IsEnabled   = false;
                cboDatabaseType.IsEnabled           = false;
                btnRefreshMSSQLServerList.IsEnabled = false;

                if (ServerState.Instance.DatabaseIsSQLite)
                {
                    ServerSettings.Instance.Database.Type = Constants.DatabaseType.Sqlite;
                }
                else if (ServerState.Instance.DatabaseIsSQLServer)
                {
                    if (string.IsNullOrEmpty(txtMSSQL_DatabaseName.Text) ||
                        string.IsNullOrEmpty(txtMSSQL_Password.Password) ||
                        string.IsNullOrEmpty(cboMSSQLServerList.Text) ||
                        string.IsNullOrEmpty(txtMSSQL_Username.Text))
                    {
                        MessageBox.Show(Commons.Properties.Resources.Server_FillOutSettings,
                                        Commons.Properties.Resources.Error,
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        txtMSSQL_DatabaseName.Focus();
                        return;
                    }

                    ServerSettings.Instance.Database.Type     = Constants.DatabaseType.SqlServer;
                    ServerSettings.Instance.Database.Schema   = txtMSSQL_DatabaseName.Text;
                    ServerSettings.Instance.Database.Password = txtMSSQL_Password.Password;
                    ServerSettings.Instance.Database.Hostname = cboMSSQLServerList.Text;
                    ServerSettings.Instance.Database.Username = txtMSSQL_Username.Text;
                }
                else if (ServerState.Instance.DatabaseIsMySQL)
                {
                    if (string.IsNullOrEmpty(txtMySQL_DatabaseName.Text) ||
                        string.IsNullOrEmpty(txtMySQL_Password.Password) ||
                        string.IsNullOrEmpty(txtMySQL_ServerAddress.Text) ||
                        string.IsNullOrEmpty(txtMySQL_Username.Text))
                    {
                        MessageBox.Show(Commons.Properties.Resources.Server_FillOutSettings,
                                        Commons.Properties.Resources.Error,
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                        txtMySQL_DatabaseName.Focus();
                        return;
                    }

                    ServerSettings.Instance.Database.Type     = Constants.DatabaseType.MySQL;
                    ServerSettings.Instance.Database.Schema   = txtMySQL_DatabaseName.Text;
                    ServerSettings.Instance.Database.Password = txtMySQL_Password.Password;
                    ServerSettings.Instance.Database.Hostname = txtMySQL_ServerAddress.Text;
                    ServerSettings.Instance.Database.Username = txtMySQL_Username.Text;
                }

                logger.Info("Initializing DB...");

                ShokoServer.RunWorkSetupDB();
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
                MessageBox.Show(Commons.Properties.Resources.Server_FailedToStart + ex.Message,
                                Commons.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 12
0
        public MainWindow()
        {
            InitializeComponent();

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Instance.Culture);
            ShokoServer.Instance.OAuthProvider    = new AuthProvider(this);
            if (!ShokoServer.Instance.StartUpServer())
            {
                MessageBox.Show(Commons.Properties.Resources.Server_Running,
                                Commons.Properties.Resources.ShokoServer, MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }

            //Create an instance of the NotifyIcon Class
            TippuTrayNotify = new NotifyIcon();

            // This icon file needs to be in the bin folder of the application
            TippuTrayNotify = new NotifyIcon();
            Stream iconStream =
                Application.GetResourceStream(new Uri("pack://application:,,,/ShokoServer;component/db.ico")).Stream;

            TippuTrayNotify.Icon = new Icon(iconStream);
            iconStream.Dispose();

            //show the Tray Notify IconbtnRemoveMissingFiles.Click
            TippuTrayNotify.Visible = true;

            //-- for winforms applications
            System.Windows.Forms.Application.ThreadException -= UnhandledExceptionManager.ThreadExceptionHandler;
            System.Windows.Forms.Application.ThreadException += UnhandledExceptionManager.ThreadExceptionHandler;

            CreateMenus();

            ServerState.Instance.DatabaseAvailable = false;
            ServerState.Instance.ServerOnline      = false;
            ServerState.Instance.BaseImagePath     = ImageUtils.GetBaseImagesPath();

            Closing      += MainWindow_Closing;
            StateChanged += MainWindow_StateChanged;
            TippuTrayNotify.MouseDoubleClick += TippuTrayNotify_MouseDoubleClick;

            btnToolbarShutdown.Click += btnToolbarShutdown_Click;
            btnHasherPause.Click     += btnHasherPause_Click;
            btnHasherResume.Click    += btnHasherResume_Click;
            btnGeneralPause.Click    += btnGeneralPause_Click;
            btnGeneralResume.Click   += btnGeneralResume_Click;
            btnImagesPause.Click     += btnImagesPause_Click;
            btnImagesResume.Click    += btnImagesResume_Click;
            btnAdminMessages.Click   += btnAdminMessages_Click;

            btnRemoveMissingFiles.Click += btnRemoveMissingFiles_Click;
            btnRunImport.Click          += btnRunImport_Click;
            btnSyncHashes.Click         += BtnSyncHashes_Click;
            btnSyncMedias.Click         += BtnSyncMedias_Click;
            btnSyncMyList.Click         += btnSyncMyList_Click;
            btnSyncVotes.Click          += btnSyncVotes_Click;
            btnUpdateTvDBInfo.Click     += btnUpdateTvDBInfo_Click;
            btnUpdateAllStats.Click     += btnUpdateAllStats_Click;
            btnSyncTrakt.Click          += btnSyncTrakt_Click;
            btnImportManualLinks.Click  += btnImportManualLinks_Click;
            btnUpdateAniDBInfo.Click    += btnUpdateAniDBInfo_Click;
            btnLaunchWebUI.Click        += btnLaunchWebUI_Click;
            btnUpdateImages.Click       += btnUpdateImages_Click;
            btnUploadAzureCache.Click   += btnUploadAzureCache_Click;
            btnUpdateTraktInfo.Click    += BtnUpdateTraktInfo_Click;
            btnSyncPlex.Click           += BtnSyncPlexOn_Click;
            btnValidateImages.Click     += BtnValidateAllImages_Click;

            Loaded += MainWindow_Loaded;

            txtServerPort.Text = ServerSettings.Instance.ServerPort.ToString(CultureInfo.InvariantCulture);

            btnToolbarHelp.Click     += btnToolbarHelp_Click;
            btnApplyServerPort.Click += btnApplyServerPort_Click;
            btnUpdateMediaInfo.Click += btnUpdateMediaInfo_Click;

            //StartUp();

            cboDatabaseType.Items.Clear();
            ShokoServer.Instance.GetSupportedDatabases().ForEach(s => cboDatabaseType.Items.Add(s));
            cboDatabaseType.SelectionChanged +=
                cboDatabaseType_SelectionChanged;

            btnChooseImagesFolder.Click += btnChooseImagesFolder_Click;
            btnSetDefault.Click         += BtnSetDefault_Click;


            btnSaveDatabaseSettings.Click   += btnSaveDatabaseSettings_Click;
            btnRefreshMSSQLServerList.Click += btnRefreshMSSQLServerList_Click;
            // btnInstallMSSQLServer.Click += new RoutedEventHandler(btnInstallMSSQLServer_Click);
            btnMaxOnStartup.Click               += toggleMinimizeOnStartup;
            btnMinOnStartup.Click               += toggleMinimizeOnStartup;
            btnLogs.Click                       += btnLogs_Click;
            btnChooseVLCLocation.Click          += btnChooseVLCLocation_Click;
            btnJMMEnableStartWithWindows.Click  += btnJMMEnableStartWithWindows_Click;
            btnJMMDisableStartWithWindows.Click += btnJMMDisableStartWithWindows_Click;
            btnUpdateAniDBLogin.Click           += btnUpdateAniDBLogin_Click;

            btnHasherClear.Click  += btnHasherClear_Click;
            btnGeneralClear.Click += btnGeneralClear_Click;
            btnImagesClear.Click  += btnImagesClear_Click;

            //automaticUpdater.MenuItem = mnuCheckForUpdates;

            ServerState.Instance.LoadSettings();

            cboLanguages.SelectionChanged += cboLanguages_SelectionChanged;

            InitCulture();
            Instance = this;

            if (!ServerSettings.Instance.FirstRun && ShokoService.AnidbProcessor.ValidAniDBCredentials())
            {
                logger.Info("Already been set up... Initializing DB...");
                ShokoServer.RunWorkSetupDB();
                cboLanguages.IsEnabled = true;
            }

            SubscribeEvents();
        }
Exemplo n.º 13
0
        private void ButtonOk_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckValuesDCSBIOS();
                CheckValuesSRS();

                if (_generalChanged)
                {
                    if (RadioButtonKeyBd.IsChecked == true)
                    {
                        Settings.Default.APIMode = 0;
                        Common.APIMode           = APIModeEnum.keybd_event;
                        Settings.Default.Save();
                    }
                    if (RadioButtonSendInput.IsChecked == true)
                    {
                        Settings.Default.APIMode = 1;
                        Common.APIMode           = APIModeEnum.SendInput;
                        Settings.Default.Save();
                    }
                    if (RadioButtonBelowNormal.IsChecked == true)
                    {
                        Settings.Default.ProcessPriority = ProcessPriorityClass.BelowNormal;
                        Settings.Default.Save();
                        Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
                    }
                    if (RadioButtonNormal.IsChecked == true)
                    {
                        Settings.Default.ProcessPriority = ProcessPriorityClass.Normal;
                        Settings.Default.Save();
                        Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
                    }
                    if (RadioButtonAboveNormal.IsChecked == true)
                    {
                        Settings.Default.ProcessPriority = ProcessPriorityClass.AboveNormal;
                        Settings.Default.Save();
                        Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
                    }
                    if (RadioButtonHigh.IsChecked == true)
                    {
                        Settings.Default.ProcessPriority = ProcessPriorityClass.High;
                        Settings.Default.Save();
                        Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
                    }
                    if (RadioButtonRealtime.IsChecked == true)
                    {
                        Settings.Default.ProcessPriority = ProcessPriorityClass.RealTime;
                        Settings.Default.Save();
                        Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
                    }

                    Settings.Default.DebugOn     = CheckBoxDoDebug.IsChecked == true;
                    Settings.Default.DebugToFile = CheckBoxDebugToFile.IsChecked == true;
                    Settings.Default.Save();

                    Settings.Default.RunMinimized = CheckBoxMinimizeToTray.IsChecked == true;
                    Settings.Default.Save();
                }

                if (_dcsbiosChanged)
                {
                    Settings.Default.DCSBiosJSONLocation = TextBoxDcsBiosJSONLocation.Text;
                    Settings.Default.DCSBiosIPFrom       = IpAddressFromDCSBIOS;
                    Settings.Default.DCSBiosPortFrom     = PortFromDCSBIOS;
                    Settings.Default.DCSBiosIPTo         = IpAddressToDCSBIOS;
                    Settings.Default.DCSBiosPortTo       = PortToDCSBIOS;
                    Settings.Default.Save();
                }

                if (_srsChanged)
                {
                    Settings.Default.SRSIpFrom   = IpAddressFromSRS;
                    Settings.Default.SRSPortFrom = int.Parse(PortFromSRS);
                    Settings.Default.SRSIpTo     = IpAddressToSRS;
                    Settings.Default.SRSPortTo   = int.Parse(PortToSRS);
                    Settings.Default.Save();
                }
                DialogResult = true;
                Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message + Environment.NewLine + exception.StackTrace);
            }
        }
 public static MessageBoxViewModel GetInstance(MessageBox manager, MessageBoxConfiguration options)
 {
     _theInstance = new MessageBoxViewModel(manager, options);
     return _theInstance;
 }
Exemplo n.º 15
0
        private void InitApplication()
        {
            try
            {
                // prevent some application crash
                //WpfCommands.DisableWpfTabletSupport();

                Dispatcher.Invoke(new Action(ServiceProvider.Configure));


                ServiceProvider.Settings = new Settings();
                ServiceProvider.Settings = ServiceProvider.Settings.Load();
                ServiceProvider.Branding = Branding.LoadBranding();

                if (ServiceProvider.Settings.DisableNativeDrivers &&
                    MessageBox.Show(TranslationStrings.MsgDisabledDrivers, "", MessageBoxButton.YesNo) ==
                    MessageBoxResult.Yes)
                {
                    ServiceProvider.Settings.DisableNativeDrivers = false;
                }
                ServiceProvider.Settings.LoadSessionData();
                TranslationManager.LoadLanguage(ServiceProvider.Settings.SelectedLanguage);

                ServiceProvider.PluginManager.CopyPlugins();
                Dispatcher.Invoke(new Action(InitWindowManager));


                ServiceProvider.Trigger.Start();
                ServiceProvider.Analytics.Start();
                BitmapLoader.Instance.MetaDataUpdated += Instance_MetaDataUpdated;


                Dispatcher.Invoke(new Action(delegate
                {
                    try
                    {
                        // event handlers
                        ServiceProvider.Settings.SessionSelected += Settings_SessionSelected;

                        ServiceProvider.DeviceManager.CameraConnected    += DeviceManager_CameraConnected;
                        ServiceProvider.DeviceManager.CameraSelected     += DeviceManager_CameraSelected;
                        ServiceProvider.DeviceManager.CameraDisconnected += DeviceManager_CameraDisconnected;
                        //-------------------
                        ServiceProvider.DeviceManager.DisableNativeDrivers = ServiceProvider.Settings.DisableNativeDrivers;
                        if (ServiceProvider.Settings.AddFakeCamera)
                        {
                            ServiceProvider.DeviceManager.AddFakeCamera();
                        }
                        ServiceProvider.DeviceManager.LoadWiaDevices = ServiceProvider.Settings.WiaDeviceSupport;
                        ServiceProvider.DeviceManager.DetectWebcams  = ServiceProvider.Settings.WebcamSupport;
                        ServiceProvider.DeviceManager.ConnectToCamera();
                        if (ServiceProvider.Settings.DisableHardwareAccelerationNew)
                        {
                            OpenCL.IsEnabled = false;
                        }
                    }
                    catch (Exception exception)
                    {
                        Log.Error("Unable to initialize device manager", exception);
                        if (exception.Message.Contains("0AF10CEC-2ECD-4B92-9581-34F6AE0637F3"))
                        {
                            MessageBox.Show(
                                "Unable to initialize device manager !\nMissing some components! Please install latest Windows Media Player! ");
                            Application.Current.Shutdown(1);
                        }
                    }
                    StartApplication();
                    if (_startUpWindow != null)
                    {
                        _startUpWindow.Close();
                    }
                }));
                ServiceProvider.Database.StartEvent(EventType.App);
            }
            catch (Exception ex)
            {
                Log.Error("Fatal error ", ex);
            }
        }
Exemplo n.º 16
0
        private async void files_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //files.IsEnabled = false;
            e.Handled = true;
            try
            {
                var entry = files.SelectedItem as BarEntry;
                if (entry == null)
                {
                    ImageViewer.Visibility = Visibility.Collapsed;
                    XMLViewer.Visibility   = Visibility.Collapsed;
                    //files.IsEnabled = true;
                    return;
                }
                var entries = files.SelectedItems.Cast <BarEntry>().ToList();
                SelectedSize = entries.Sum(x => (long)x.FileSize2);
                await file.readFile(entry);

                if (outputDevice != null)
                {
                    outputDevice.Dispose();
                    outputDevice = null;
                }
                if (mp3File != null)
                {
                    mp3File.Dispose();
                    mp3File = null;
                }
                if (waveFile != null)
                {
                    waveFile.Dispose();
                    waveFile = null;
                }
                point      = new Point();
                validPoint = false;
                ImagePreview.RenderTransform = new TranslateTransform();

                if (file.Preview != null)
                {
                    XMLViewer.Text = file.Preview.Text;
                    if (foldingManager != null)
                    {
                        FoldingManager.Uninstall(foldingManager);
                        foldingManager = null;
                    }
                    foldingManager = FoldingManager.Install(XMLViewer.TextArea);
                    if (entry.Extension == ".XMB" || entry.Extension == ".XML" || entry.Extension == ".SHP" || entry.Extension == ".LGT" || entry.Extension == ".TXT" || entry.Extension == ".CFG" || entry.Extension == ".XAML" || entry.Extension == ".PY")
                    {
                        var foldingStrategy = new XmlFoldingStrategy();
                        foldingStrategy.UpdateFoldings(foldingManager, XMLViewer.Document);
                    }
                    else
                    if (entry.Extension == ".XS")
                    {
                        var foldingStrategy = new BraceFoldingStrategy();
                        foldingStrategy.UpdateFoldings(foldingManager, XMLViewer.Document);
                    }
                }

                if (entry.Extension == ".WAV")
                {
                    using (outputDevice = new WaveOutEvent())
                        using (waveFile = new WaveFileReader(file.audio))
                        {
                            outputDevice.Init(waveFile);
                            outputDevice.Play();
                            while (outputDevice.PlaybackState == PlaybackState.Playing)
                            {
                                await Task.Delay(500);
                            }
                        }
                    ImageViewer.Visibility = Visibility.Collapsed;
                    XMLViewer.Visibility   = Visibility.Collapsed;
                }
                if (entry.Extension == ".MP3")
                {
                    //var w = new WaveFormat(new BinaryReader(file.audio));
                    //MessageBox.Show(w.Encoding.ToString());
                    using (outputDevice = new WaveOutEvent())
                        using (mp3File = new Mp3FileReader(file.audio))
                        {
                            outputDevice.Init(mp3File);
                            outputDevice.Play();
                            while (outputDevice.PlaybackState == PlaybackState.Playing)
                            {
                                await Task.Delay(500);
                            }
                        }
                    ImageViewer.Visibility = Visibility.Collapsed;
                    XMLViewer.Visibility   = Visibility.Collapsed;
                }
                else
                if (entry.Extension == ".DDT")
                {
                    ImagePreview.Source    = file.PreviewDdt.Bitmap;
                    XMLViewer.Visibility   = Visibility.Collapsed;
                    ImageViewer.Visibility = Visibility.Visible;
                }
                else
                if (entry.Extension == ".TGA" || entry.Extension == ".BMP" || entry.Extension == ".PNG" || entry.Extension == ".CUR" || entry.Extension == ".JPG")
                {
                    ImagePreview.Source    = file.PreviewImage;
                    XMLViewer.Visibility   = Visibility.Collapsed;
                    ImageViewer.Visibility = Visibility.Visible;
                }
                else
                if (entry.Extension == ".XMB" || entry.Extension == ".XML" || entry.Extension == ".SHP" || entry.Extension == ".LGT" || entry.Extension == ".XS" || entry.Extension == ".TXT" || entry.Extension == ".CFG" || entry.Extension == ".XAML" || entry.Extension == ".PY")
                {
                    ImageViewer.Visibility = Visibility.Collapsed;
                    XMLViewer.Visibility   = Visibility.Visible;
                }
                else
                {
                    ImageViewer.Visibility = Visibility.Collapsed;
                    XMLViewer.Visibility   = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            //files.IsEnabled = true;
        }
Exemplo n.º 17
0
        private async void extractMenuItem(object sender, RoutedEventArgs e)
        {
            if (file == null)
            {
                return;
            }
            List <BarEntry> entries;

            if ((sender as MenuItem).Tag.ToString() == "Selected")
            {
                entries = files.SelectedItems.Cast <BarEntry>().ToList();
            }
            else
            {
                entries = file.barFile.BarFileEntrys.ToList();
            }


            if (entries.Count != 0)
            {
                string RootPath;


                ExtractDialog ExtractDialog = new ExtractDialog(file.barFilePath);
                if (ExtractDialog.ShowDialog() != true)
                {
                    return;
                }

                RootPath = ExtractDialog.Path;


                mainMenu.IsEnabled        = false;
                tbExtract.Text            = "Extracting";
                SpinnerExtract.Visibility = Visibility.Visible;
                bPause.IsEnabled          = true;
                bStop.IsEnabled           = true;
                bRun.IsEnabled            = false;
                bool decompress = ExtractDialog.AutoDecompress;

                file.extractingState = 0;
                CancelTokenSource    = new CancellationTokenSource();
                Token = CancelTokenSource.Token;
                try
                {
                    await Task.Run(async() =>
                    {
                        await file.saveFiles(entries, RootPath, decompress, Token, ExtractDialog.AutoDDTConversion, ExtractDialog.AutoXMBConversion);
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                bPause.IsEnabled          = false;
                bStop.IsEnabled           = false;
                bRun.IsEnabled            = false;
                tbExtract.Text            = "Extract";
                SpinnerExtract.Visibility = Visibility.Collapsed;
                mainMenu.IsEnabled        = true;
            }
        }
Exemplo n.º 18
0
        private void HandleCommandLineArguments(string[] commandArgs)
        {
            var arg0 = CommandArgs[0].ToLower().TrimStart('-');

            if (CommandArgs[0] == "-")
            {
                arg0 = "-";
            }

            switch (arg0)
            {
            case "version":
                // just display the header
                break;

            case "uninstall":
                _noStart = true;
                UninstallSettings();

                ConsoleHeader();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Markdown Monster Machine Wide Settings uninstalled.");
                ConsoleFooter();

                break;

            case "reset":
                // load old config and backup
                mmApp.Configuration.Backup();
                mmApp.Configuration.Reset();     // forces exit

                ConsoleHeader();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Markdown Monster Settings reset to defaults.");
                ConsoleFooter();

                break;

            case "setportable":
                ConsoleHeader();

                // Note: Startup logic to handle portable startup is in AppConfiguration::FindCommonFolder
                try
                {
                    string portableSettingsFolder = Path.Combine(InitialStartDirectory, "PortableSettings");
                    bool   exists          = Directory.Exists(portableSettingsFolder);
                    string oldCommonFolder = mmApp.Configuration.CommonFolder;

                    File.WriteAllText("_IsPortable",
                                      @"forces the settings to be read from .\PortableSettings rather than %appdata%");

                    if (!exists &&
                        Directory.Exists(oldCommonFolder) &&
                        MessageBox.Show(
                            "Portable mode set. Do you want to copy settings from:\r\n\r\n" +
                            oldCommonFolder + "\r\n\r\nto the PortableSettings folder?",
                            "Markdown MonsterPortable Mode",
                            MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        FileUtils.CopyDirectory(oldCommonFolder,
                                                portableSettingsFolder, deepCopy: true);

                        mmApp.Configuration.CommonFolder = portableSettingsFolder;
                        mmApp.Configuration.Read();
                    }


                    mmApp.Configuration.CommonFolder = portableSettingsFolder;
                    mmApp.Configuration.Write();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Unable to set portable mode: " + ex.Message);
                }

                ConsoleFooter();
                break;

            case "unsetportable":
                ConsoleHeader();
                try
                {
                    File.Delete("_IsPortable");
                    mmApp.Configuration.InternalCommonFolder = Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Markdown Monster");
                    mmApp.Configuration.CommonFolder = mmApp.Configuration.InternalCommonFolder;
                    mmApp.Configuration.Write();

                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Removed Portable settings for this installation. Use `mm SetPortable` to reenable.");
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Unable to delete portable settings switch file\r\n_IsPortable\r\n\r\n{ex.Message}");
                }

                break;

            case "register":
                ConsoleHeader();
                if (CommandArgs.Length < 2)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Missing registration code. Please pass a registration code.");
                }
                else
                {
                    if (!UnlockKey.Register(CommandArgs[1]))
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Invalid registration code. Please pass a valid registration code.");
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Registration succeeded. Thank your for playing fair.");
                    }
                }
                ConsoleFooter();
                break;

            // Standard In Re-Routing
            case "stdin":
                string stdin = null;
                if (Console.IsInputRedirected)
                {
                    using (Stream stream = Console.OpenStandardInput())
                    {
                        byte[]        buffer  = new byte[1000]; // Use whatever size you want
                        StringBuilder builder = new StringBuilder();
                        int           read    = -1;
                        while (true)
                        {
                            AutoResetEvent gotInput    = new AutoResetEvent(false);
                            Thread         inputThread = new Thread(() =>
                            {
                                try
                                {
                                    read = stream.Read(buffer, 0, buffer.Length);
                                    gotInput.Set();
                                }
                                catch (ThreadAbortException)
                                {
                                    Thread.ResetAbort();
                                }
                            })
                            {
                                IsBackground = true
                            };

                            inputThread.Start();

                            // Timeout expired?
                            if (!gotInput.WaitOne(100))
                            {
                                inputThread.Abort();
                                break;
                            }

                            // End of stream?
                            if (read == 0)
                            {
                                stdin = builder.ToString();
                                break;
                            }

                            // Got data
                            builder.Append(Console.InputEncoding.GetString(buffer, 0, read));
                        }

                        if (builder.Length > 0)
                        {
                            var tempFile = Path.ChangeExtension(Path.GetTempFileName(), "md");
                            File.WriteAllText(tempFile, builder.ToString());
                            CommandArgs[0] = tempFile;
                        }
                        else
                        {
                            CommandArgs[0] = null;
                        }
                    }
                }

                break;
            }
        }
Exemplo n.º 19
0
        private async void convertFiles(object sender, RoutedEventArgs e)
        {
            mainMenu.IsEnabled        = false;
            SpinnerConvert.Visibility = Visibility.Visible;
            tbConvert.Text            = "Converting";
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Multiselect = true;

            string operationType = (sender as MenuItem).Tag.ToString();

            //await DdtFileUtils.Ddt2PngAsync(@"D:\Development\Resource Manager\Resource Manager\bin\Release\netcoreapp3.1\Art\ui\alerts\alert_treatyend_bump.ddt");

            if (operationType == "topng")
            {
                openFileDialog.Filter = "Age of Empires 3 ddt files (*.ddt)|*.ddt";
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await DdtFileUtils.Ddt2PngAsync(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxml")
            {
                openFileDialog.Filter = "Age of Empires 3 xmb files (*.xmb)|*.xmb";

                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            var data = await File.ReadAllBytesAsync(file);


                            if (Alz4Utils.IsAlz4File(data))
                            {
                                data = await Alz4Utils.ExtractAlz4BytesAsync(data);
                            }
                            else
                            {
                                if (L33TZipUtils.IsL33TZipFile(data))
                                {
                                    data = await L33TZipUtils.ExtractL33TZippedBytesAsync(data);
                                }
                            }


                            using MemoryStream stream = new MemoryStream(data);
                            XMBFile xmb = await XMBFile.LoadXMBFile(stream);

                            var newName = Path.ChangeExtension(file, "");

                            xmb.file.Save(newName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxmbde")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.xml)|*.xml";

                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await XMBFile.CreateXMBFileALZ4(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            if (operationType == "toxmbcc")
            {
                openFileDialog.Filter = "Age of Empires 3 xml files (*.xml)|*.xml";
                if (openFileDialog.ShowDialog() == true)
                {
                    foreach (var file in openFileDialog.FileNames)
                    {
                        try
                        {
                            await XMBFile.CreateXMBFileL33T(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Conversion error - " + Path.GetFileName(file), MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }



            tbConvert.Text            = "Convert";
            SpinnerConvert.Visibility = Visibility.Collapsed;
            mainMenu.IsEnabled        = true;
        }
Exemplo n.º 20
0
 private void AboutButton_OnClick(object sender, RoutedEventArgs e)
 {
     MessageBox.Show(
         "goatmon reborn\n\nA FFXIV Packet analysis tool for Sapphire\nCapture backend(Machina) by Ravahn of ACT fame\n\nhttps://github.com/SapphireMordred\nhttps://github.com/ravahn/machina", "FFXIVMon Reborn", MessageBoxButton.OK, MessageBoxImage.Asterisk);
 }
Exemplo n.º 21
0
        private void ButtonClick1(object sender, RoutedEventArgs e)
        {
            _moviesInsertedSuccessfully = 0;
            MoviesToAdd            = listOfMovies.Text.Split(new[] { "\r\n", "\n", Environment.NewLine }, StringSplitOptions.None).ToList();
            progressBar.Minimum    = 0;
            progressBar.Maximum    = MoviesToAdd.Count;
            progressBar.Value      = 0;
            progressBar.Visibility = Visibility.Visible;

            Stopwatch timer = new Stopwatch();

            timer.Start();
            foreach (string movieToRetrieve in MoviesToAdd)
            {
                _movieCount++;

                if (!string.IsNullOrWhiteSpace(movieToRetrieve))
                {
                    IMDB Movie;
                    if (movieToRetrieve.Contains(@"http://www.imdb.com/title"))
                    {
                        Movie = new IMDB(movieToRetrieve, true);
                        AddMovie(Movie);
                    }
                    else
                    {
                        if (!MovieAppHelpers.CheckDBForMovie(movieToRetrieve))
                        {
                            try
                            {
                                Movie = new IMDB(movieToRetrieve);

                                if (Movie.Title.ToLower() != movieToRetrieve.ToLower())
                                {
                                    string message = string.Format(
                                        "Retrieved title [ {1} ] did not match entered title [ {2} ], add anyway?{0}{0}[ Title: {1}, Year: {3}, Lead: {4} ]",
                                        Environment.NewLine, Movie.Title, movieToRetrieve, Movie.Year ?? string.Empty,
                                        (Movie.Cast != null) ? Movie.Cast.ToArray().FirstOrDefault() : string.Empty);

                                    MessageBoxResult msgBoxResult = MessageBox.Show(message, "Ambiguous Match Found", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.DefaultDesktopOnly);

                                    if (msgBoxResult == MessageBoxResult.Yes)
                                    {
                                        AddMovie(Movie);
                                    }

                                    if (msgBoxResult == MessageBoxResult.No)
                                    {
                                        Log.Trace(
                                            "Retrieved Movie: [ Title: {0}, Year: {1}, Lead: {2} ] Entered Movie: [ Title: {3} ]",
                                            new object[]
                                        {
                                            Movie.Title, Movie.Year ?? string.Empty,
                                            (Movie.Cast != null)
                                                        ? Movie.Cast.ToArray().FirstOrDefault()
                                                        : string.Empty, movieToRetrieve
                                        });
                                        Dispatcher.Invoke(_updatePbDelegate,
                                                          System.Windows.Threading.DispatcherPriority.Background,
                                                          new object[]
                                        {
                                            RangeBase.ValueProperty, (double)_movieCount
                                        });
                                    }
                                }
                                else // Titles Match
                                {
                                    AddMovie(Movie);
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Trace("Could not complete movie retrieval and insert", ex, movieToRetrieve);
                                //Log.Error("Could not complete movie insert, exception: [ {0} ]", ex.ToString());
                            }
                        }
                    }
                }
            }

            //Switcher.Switch(new AddResults( processedMovies));
            timer.Stop();
            "Inserted {0} of {1} movies successfully, Total run time: {2}, (see log for any failures)".ShowMessage(new object[] { _moviesInsertedSuccessfully, MoviesToAdd.Count, timer.Elapsed.ToReadableString() });
        }
Exemplo n.º 22
0
 private void ReloadDBRelay(object sender, RoutedEventArgs e)
 {
     ((XivMonTab)MainTabControl.SelectedContent).ReloadDb();
     MessageBox.Show("Database reloaded.", "FFXIVMon Reborn", MessageBoxButton.OK, MessageBoxImage.Asterisk);
 }
Exemplo n.º 23
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!User.Settings.User.LICENSE_read)
            {
                if (MessageBoxResult.Yes == MessageBox.Show("By using the software in any way you are agreeing to the license located at " + AppDomain.CurrentDomain.BaseDirectory + @"LICENSE.md" + "\n\nContinue?", "Accept True Mining License", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.None, MessageBoxOptions.DefaultDesktopOnly))
                {
                    User.Settings.User.LICENSE_read = true;
                }
                else
                {
                    this.Close();
                }
            }

            try
            {
                this.CanvasSoftwareVersion.Text            = "v" + Tools.GetAssemblyVersion();
                this.CanvasSoftwareVersion.TextDecorations = null;
            }
            catch { }

            this.TaskbarItemInfo = new System.Windows.Shell.TaskbarItemInfo();

            Tools.TryChangeTaskbarIconAsSettingsOrder();
            nIcon.Visible    = true;
            nIcon.MouseDown += notifier_MouseDown;

            Core.NextStart.Actions.Load();

            if (Core.NextStart.Actions.loadedNextStartInstructions.useThisInstructions)
            {
                if (Core.NextStart.Actions.loadedNextStartInstructions.startHiden)
                {
                    Hide();
                }
                else
                {
                    this.ShowInTaskbar = true;
                    this.Activate();
                    this.Focus();
                }
            }
            else
            {
                if (User.Settings.User.StartHide)
                {
                    Hide();
                }
                else
                {
                    this.ShowInTaskbar = true;
                    this.Activate();
                    this.Focus();
                }
            }

            if (!Tools.HaveADM)
            {
                Janelas.Pages.Home.RestartAsAdministratorButton.Visibility = Visibility.Visible; Janelas.Pages.Home.WarningsTextBlock.Text += "You haven't opened True Mining as an administrator. Restart as ADM is recommended and generally results in a better hashrate";
            }
            else
            {
                Janelas.Pages.Home.RestartAsAdministratorButton.Visibility = Visibility.Collapsed;
            }

            if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Diebold\Warsaw\unins000.exe"))
            {
                Janelas.Pages.Home.UninstallWarsawDiebold.Visibility = Visibility.Visible; Janelas.Pages.Home.WarningsTextBlock.Text += "\nWarsaw Diebold found on your system. It is highly recommended to uninstall this agent. Click \"Remove Warsaw\"";
            }
            else
            {
                Janelas.Pages.Home.UninstallWarsawDiebold.Visibility = Visibility.Collapsed;
            }

            MenuMenu.SelectedIndex = 0; // mostra a tela Home

            Tools.CheckerPopup = new Janelas.CheckerPopup("TrueMining");
            Tools.CheckerPopup.ShowDialog();

            Tools.TryChangeTaskbarIconAsSettingsOrder();

            Task.Run(() => User.Settings.SettingsSaver());

            if (Core.NextStart.Actions.loadedNextStartInstructions.useThisInstructions)
            {
                if (Core.NextStart.Actions.loadedNextStartInstructions.startMining)
                {
                    if (!String.IsNullOrEmpty(User.Settings.User.Payment_Wallet))
                    {
                        if (!Miner.IsMining)
                        {
                            Miner.StartMiner();
                        }
                    }
                }
            }
            else
            {
                if (User.Settings.User.AutostartMining)
                {
                    if (!String.IsNullOrEmpty(User.Settings.User.Payment_Wallet))
                    {
                        if (!Miner.IsMining)
                        {
                            Miner.StartMiner();
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        public ConnectorCandlesUi(ConnectorCandles connectorBot)
        {
            try
            {
                InitializeComponent();

                List <IServer> servers = ServerMaster.GetServers();

                if (servers == null)
                {// if connection server to exhange hasn't been created yet / если сервер для подключения к бирже ещё не создан
                    Close();
                    return;
                }

                // save connectors
                // сохраняем коннекторы
                _connectorBot = connectorBot;

                // upload settings to controls
                // загружаем настройки в контролы
                for (int i = 0; i < servers.Count; i++)
                {
                    ComboBoxTypeServer.Items.Add(servers[i].ServerType);
                }

                if (connectorBot.ServerType != ServerType.None)
                {
                    ComboBoxTypeServer.SelectedItem = connectorBot.ServerType;
                    _selectedType = connectorBot.ServerType;
                }
                else
                {
                    ComboBoxTypeServer.SelectedItem = servers[0].ServerType;
                    _selectedType = servers[0].ServerType;
                }

                if (connectorBot.StartProgram == StartProgram.IsTester)
                {
                    ComboBoxTypeServer.IsEnabled    = false;
                    CheckBoxIsEmulator.IsEnabled    = false;
                    CheckBoxSetForeign.IsEnabled    = false;
                    ComboBoxTypeServer.SelectedItem = ServerType.Tester;
                    //ComboBoxClass.SelectedItem = ServerMaster.GetServers()[0].Securities[0].NameClass;
                    //ComboBoxPortfolio.SelectedItem = ServerMaster.GetServers()[0].Portfolios[0].Number;

                    connectorBot.ServerType = ServerType.Tester;
                    _selectedType           = ServerType.Tester;
                }

                LoadClassOnBox();

                LoadSecurityOnBox();

                LoadPortfolioOnBox();

                ComboBoxClass.SelectionChanged += ComboBoxClass_SelectionChanged;

                CheckBoxIsEmulator.IsChecked = _connectorBot.EmulatorIsOn;

                ComboBoxTypeServer.SelectionChanged += ComboBoxTypeServer_SelectionChanged;

                ComboBoxCandleMarketDataType.Items.Add(CandleMarketDataType.Tick);
                ComboBoxCandleMarketDataType.Items.Add(CandleMarketDataType.MarketDepth);
                ComboBoxCandleMarketDataType.SelectedItem = _connectorBot.CandleMarketDataType;

                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Simple);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Renko);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.HeikenAshi);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Delta);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Volume);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Ticks);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Range);
                ComboBoxCandleCreateMethodType.Items.Add(CandleCreateMethodType.Rеvers);

                ComboBoxCandleCreateMethodType.SelectedItem = _connectorBot.CandleCreateMethodType;

                CheckBoxSetForeign.IsChecked = _connectorBot.SetForeign;

                LoadTimeFrameBox();

                TextBoxCountTradesInCandle.Text         = _connectorBot.CountTradeInCandle.ToString();
                _countTradesInCandle                    = _connectorBot.CountTradeInCandle;
                TextBoxCountTradesInCandle.TextChanged += TextBoxCountTradesInCandle_TextChanged;

                TextBoxVolumeToClose.Text         = _connectorBot.VolumeToCloseCandleInVolumeType.ToString();
                _volumeToClose                    = _connectorBot.VolumeToCloseCandleInVolumeType;
                TextBoxVolumeToClose.TextChanged += TextBoxVolumeToClose_TextChanged;

                TextBoxRencoPunkts.Text         = _connectorBot.RencoPunktsToCloseCandleInRencoType.ToString();
                _rencoPuncts                    = _connectorBot.RencoPunktsToCloseCandleInRencoType;
                TextBoxRencoPunkts.TextChanged += TextBoxRencoPunkts_TextChanged;

                if (_connectorBot.RencoIsBuildShadows)
                {
                    CheckBoxRencoIsBuildShadows.IsChecked = true;
                }

                TextBoxDeltaPeriods.Text         = _connectorBot.DeltaPeriods.ToString();
                TextBoxDeltaPeriods.TextChanged += TextBoxDeltaPeriods_TextChanged;
                _deltaPeriods = _connectorBot.DeltaPeriods;

                TextBoxRangeCandlesPunkts.Text         = _connectorBot.RangeCandlesPunkts.ToString();
                TextBoxRangeCandlesPunkts.TextChanged += TextBoxRangeCandlesPunkts_TextChanged;
                _rangeCandlesPunkts = _connectorBot.RangeCandlesPunkts;

                TextBoxReversCandlesPunktsMinMove.Text         = _connectorBot.ReversCandlesPunktsMinMove.ToString();
                TextBoxReversCandlesPunktsMinMove.TextChanged += TextBoxReversCandlesPunktsMinMove_TextChanged;
                _reversCandlesPunktsBackMove = _connectorBot.ReversCandlesPunktsBackMove;

                TextBoxReversCandlesPunktsBackMove.Text         = _connectorBot.ReversCandlesPunktsBackMove.ToString();
                TextBoxReversCandlesPunktsBackMove.TextChanged += TextBoxReversCandlesPunktsBackMove_TextChanged;
                _reversCandlesPunktsMinMove = _connectorBot.ReversCandlesPunktsMinMove;

                ShowDopCandleSettings();

                ComboBoxCandleCreateMethodType.SelectionChanged += ComboBoxCandleCreateMethodType_SelectionChanged;
                ComboBoxSecurities.KeyDown += ComboBoxSecuritiesOnKeyDown;


                Title                                    = OsLocalization.Market.TitleConnectorCandle;
                Label1.Content                           = OsLocalization.Market.Label1;
                Label2.Content                           = OsLocalization.Market.Label2;
                Label3.Content                           = OsLocalization.Market.Label3;
                CheckBoxIsEmulator.Content               = OsLocalization.Market.Label4;
                Label5.Content                           = OsLocalization.Market.Label5;
                Label6.Content                           = OsLocalization.Market.Label6;
                Label7.Content                           = OsLocalization.Market.Label7;
                Label8.Content                           = OsLocalization.Market.Label8;
                Label9.Content                           = OsLocalization.Market.Label9;
                LabelTimeFrame.Content                   = OsLocalization.Market.Label10;
                LabelCountTradesInCandle.Content         = OsLocalization.Market.Label11;
                CheckBoxSetForeign.Content               = OsLocalization.Market.Label12;
                LabelDeltaPeriods.Content                = OsLocalization.Market.Label13;
                LabelVolumeToClose.Content               = OsLocalization.Market.Label14;
                LabelRencoPunkts.Content                 = OsLocalization.Market.Label15;
                CheckBoxRencoIsBuildShadows.Content      = OsLocalization.Market.Label16;
                LabelRangeCandlesPunkts.Content          = OsLocalization.Market.Label17;
                LabelReversCandlesPunktsMinMove.Content  = OsLocalization.Market.Label18;
                LabelReversCandlesPunktsBackMove.Content = OsLocalization.Market.Label19;
                ButtonAccept.Content                     = OsLocalization.Market.ButtonAccept;
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }
        private void InstallScripts(string path)
        {
            //if scripts folder doesnt exist, create it
            Directory.CreateDirectory(path);
            Directory.CreateDirectory(path + "\\Hooks");
            Thread.Sleep(100);

            var write = true;

            //does it contain an export.lua?
            if (File.Exists(path + "\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Export.lua");

                if (contents.Contains("SimpleRadioStandalone.lua"))
                {
//                    contents =
//                        contents.Replace(
//                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])",
//                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])");
//                    contents = contents.Trim();
//
//                    File.WriteAllText(path + "\\Export.lua", contents);

                    // do nothing
                }
                else
                {
                    var writer = File.AppendText(path + "\\Export.lua");

                    writer.WriteLine(
                        "\n  local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])\n");
                    writer.Close();
                }
            }
            else
            {
                var writer = File.CreateText(path + "\\Export.lua");

                writer.WriteLine(
                    "\n  local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])\n");
                writer.Close();
            }

            try
            {
                File.Copy(currentDirectory + "\\DCS-SimpleRadioStandalone.lua",
                          path + "\\DCS-SimpleRadioStandalone.lua", true);

                File.Copy(currentDirectory + "\\DCS-SRSGameGUI.lua",
                          path + "\\DCS-SRSGameGUI.lua", true);

                File.Copy(currentDirectory + "\\DCS-SRS-OverlayGameGUI.lua", path + "\\DCS-SRS-OverlayGameGUI.lua",
                          true);

                File.Copy(currentDirectory + "\\DCS-SRS-Overlay.dlg", path + "\\DCS-SRS-Overlay.dlg",
                          true);

                File.Copy(currentDirectory + "\\DCS-SRS-hook.lua", path + "\\Hooks\\DCS-SRS-hook.lua",
                          true);
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(
                    "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer",
                    "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }
        }
Exemplo n.º 26
0
        private bool SearchPixel(string hexcode)
        {
            Bitmap bitmap = new Bitmap(SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);

            Graphics graphics = Graphics.FromImage(bitmap as Image);

            graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

            Color desiredPixelColor = ColorTranslator.FromHtml(hexcode);

            for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
            {
                for (int y = 0; y < SystemInformation.VirtualScreen.Height; y++)
                {
                    Color currentPixelColor = bitmap.GetPixel(x, y);
                    if (desiredPixelColor == currentPixelColor)
                    {
                        DoubleClickAtPosition(x, y);
                        return(true);
                    }
                }
            }

            string endmin1       = textbox2.Text;
            int    endminutes1   = Convert.ToInt32(endmin1);
            int    endmilli1     = endminutes1 * 60000;
            int    endmillifinal = endmilli1 + 30000;

            new System.Threading.ManualResetEvent(false).WaitOne(120000);

            string joinbutton = "#C2C3DD";

            method(joinbutton);
            bool finalised1 = true;

            if (finalised1 == true)
            {
                new System.Threading.ManualResetEvent(false).WaitOne(1000);
                string secondjoin = "#62C4F1";
                method(secondjoin);
                bool secondstep = true;
                new System.Threading.ManualResetEvent(false).WaitOne(1);

                if (secondstep == true)
                {
                    string inputhexcolorcode5 = "#CF586D";
                    method(inputhexcolorcode5);
                    var window3 = new finished();
                    window3.Show();
                }
            }

            void method(string codehex)
            {
                Bitmap   bitmap1   = new Bitmap(SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);
                Graphics graphics1 = Graphics.FromImage(bitmap as Image);

                graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

                Color desiredPixelColor1 = ColorTranslator.FromHtml(codehex);

                for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
                {
                    for (int y = 0; y < SystemInformation.VirtualScreen.Height; y++)
                    {
                        Color currentPixelColor = bitmap.GetPixel(x, y);

                        if (desiredPixelColor == currentPixelColor)
                        {
                            DoubleClickAtPosition(x, y);
                        }
                    }
                }


                //space to add a feature so it tries 3 times in total



                string message45 = "join button not found, tried 2 times";

                MessageBox.Show(message45);
                // IF you want to try 3 times, write the code again here
            }

            string message = "Join button not found... Whoops....";

            MessageBox.Show(message);

            return(false);
        }
Exemplo n.º 27
0
        private void GameTimer_Tick(object sender, EventArgs e)
        {
            //
            //double xComponent = Ball;
            //double yComponent = 0;
            if (gameBallTop <= 0 || gameBallTop >= (myGameCanvas.Height - Ball.Height))
            {
                vertDirection *= -1;
            }
            if (gameBallLeft <= 0 || gameBallLeft >= myGameCanvas.Width - Ball.Width)
            {
                horizDirection *= -1;
            }
            if (gamePaddleLeft + Paddle.Width == gameBallLeft &&
                gameBallTop + Ball.Height / 2 >= gamePaddleTop && gameBallTop + Ball.Height / 2 <= gamePaddleTop + Paddle.Height)
            {
                hits++;
                horizDirection = 1;
            }
            //Difficulty Clause
            //paddle
            if (hits == 1 && PaddleChange == false)
            {
                Status.Content = "Looks like your paddle broke!";
                PaddleChange   = true;
                Paddle.Height  = 75;
            }
            //ball
            if (hits == 2 && BallChange == false)
            {
                Status.Content = "Do you need glasses or is the ball getting smaller?";
                Ball.Height    = 20;
                Ball.Width     = Ball.Height;
            }
            if (hits == 3 && BallChange == false)
            {
                Status.Content = "oof, ... good luck";
                Ball.Height    = 10;
                Ball.Width     = Ball.Height;
            }
            if (hits == 5 && BallChange == false)
            {
                Status.Content = "ouch";
                bSpeed         = 3;
                BallChange     = true;
            }

            //ending clause
            if (gameBallLeft <= 0)
            {
                Status.Content      = "get gud";
                gameTimer.IsEnabled = false;
                Paddle.Visibility   = Visibility.Hidden;
                MessageBox.Show($"You Lose\n your score is:{hits}");
                for (int i = 0; i < 5; i++)
                {
                    if (Highscore[i] < hits)
                    {
                        Highscore[i] = hits;
                        break;
                    }
                }
            }

            gameBallLeft += dx * horizDirection * bSpeed;
            gameBallTop  += dy * vertDirection * bSpeed;

            Canvas.SetTop(Ball, gameBallTop);
            Canvas.SetLeft(Ball, gameBallLeft);
            Score.Content = hits;
        }
        public void ExportServerList()
        {
            StreamReader  sr           = null;
            StreamWriter  sw           = null;
            List <string> settingsList = new List <string>();
            string        path         = _path + @"\Server List.txt";

            try
            {
                var dialog = new FolderBrowserDialog
                {
                    Description = Resources.ServerManager_ExportServerList_Description
                };
                dialog.ShowDialog();
                path = dialog.SelectedPath + @"\Server List.txt";
            }
            catch (IOException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }

            try
            {
                sr = new StreamReader(_serverListFile);
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    settingsList.Add(line);
                }
            }
            catch (IOException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            try
            {
                sw = new StreamWriter(path);

                for (int i = 0; i < settingsList.Count; i++)
                {
                    sw.WriteLine(settingsList[i]);
                }
            }
            catch (IOException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
        }
Exemplo n.º 29
0
 private void mnuHelpAbout(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("Lonely Persons Pong\n, A fun slow to fast pace game that get more difficult as you go along, \nBased on the .Net Core and developed using WPF \nConstructed by Ryan Cranston");
 }
        public void ImportServerList()
        {
            StreamReader  sr           = null;
            StreamWriter  sw           = null;
            List <string> settingsList = new List <string>();
            string        path         = null;

            try
            {
                var dialog = new OpenFileDialog();
                dialog.Filter      = Resources.ServerManager_ImportServerList_Filter;
                dialog.Multiselect = false;
                dialog.ShowDialog();
                path = dialog.FileName;
                Console.WriteLine(path);                 // Debug
            }
            catch (IOException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }

            try
            {
                if (path != null && path.Contains(".txt"))
                {
                    sr = new StreamReader(path);

                    string line;

                    while ((line = sr.ReadLine()) != null)
                    {
                        settingsList.Add(line);
                    }
                }
            }
            catch (IOException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            try
            {
                if (path != null && path.Contains(".txt"))
                {
                    sw = new StreamWriter(_serverListFile);

                    for (int i = 0; i < settingsList.Count; i++)
                    {
                        sw.WriteLine(settingsList[i]);
                    }
                }
            }
            catch (IOException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (UnauthorizedAccessException exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            catch (Exception exception)
            {
                MessageBox.Show($"ERROR\n\n{exception.Message}\n\n{exception.Source}\n\n{exception.StackTrace}", "ERROR",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                Console.WriteLine(exception);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
        }
Exemplo n.º 31
0
        private void BtSeleccionar_OnClick(object sender, RoutedEventArgs e)
        {
            var openFile = new OpenFileDialog {
                Filter      = @"*.csv|*.CSV",
                Multiselect = false
            };

            openFile.ShowDialog();
            _file = openFile.FileName;

            CsvLoader loader = new CsvTimes(new[] { _file });

            if (loader.Returned is IEnumerable <PartialTimesObjects> objects)
            {
                var dnis = new string[objects.Count()];
                for (var i = 0; i < objects.Count(); i++)
                {
                    dnis[i] = service.SelectDniFromDorsal(objects.ElementAt(i).Dorsal,
                                                          objects.ElementAt(i).CompetitionId);
                }

                var index = 0;
                IList <PartialTimesDto> noInserted    = new List <PartialTimesDto>();
                IList <string>          noInsertedDni = new List <string>();
                var countI = 0;
                var countU = 0;
                var notes  = string.Join("\n", loader.Errores);
                foreach (var times in objects)
                {
                    try {
                        _dto = new PartialTimesDto {
                            CompetitionDto = new CompetitionService().SearchCompetitionById(new CompetitionDto {
                                ID = times.CompetitionId
                            }),
                            Time = times.Times
                        };


                        var status = new EnrollService(_dto.CompetitionDto).SelectStatusEnroll(dnis[index]);

                        if (dnis[index] != null && status.Equals("REGISTERED"))
                        {
                            new EnrollService(_dto.CompetitionDto).InsertHasRegisteredTimes(dnis[index], _dto.Time[0],
                                                                                            _dto.Time[_dto.Time.Length - 1]);
                            timesService.InsertPartialTime(dnis[index], _dto);
                            countI++;
                        }
                        else
                        {
                            var s = $"El atleta {times.Dorsal} no esta registrado. \n";
                            if (notes.Contains(s))
                            {
                                notes += s;
                            }
                            else
                            {
                                notes += $"Linea {index + 1}: {s}";
                            }
                        }
                    }
                    catch (InvalidOperationException) {
                        if (_dto != null)
                        {
                            noInserted.Add(_dto);
                            noInsertedDni.Add(dnis[index]);
                        }
                    }

                    index++;
                }

                if (noInserted.Count > 0)
                {
                    var result  = MessageBoxResult.None;
                    var message = "¿Quiere sobreescribir los tiempos?";
                    result = MessageBox.Show(message, "Error", MessageBoxButton.YesNo);

                    if (result == MessageBoxResult.Yes)
                    {
                        index = 0;
                        foreach (var noInsert in noInserted)
                        {
                            timesService.UpdateAthleteRegisteredDorsal(noInsertedDni[index++], noInsert);
                            countU++;
                        }
                    }
                }

                PrintInsert(notes, countI, countU);
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Function to convert GHS SongNumber to WLG/LQ SongNumbers and back
        /// </summary>
        /// <param name="songNumber">The SongNumber</param>
        /// <param name="strippedDown">Returns the Result wihout additional Text</param>
        /// <param name="choosenSongBook"></param>
        /// <returns>Tuple: String1=WLG/LQ SongNumber String2=SongBook</returns>
        public static Tuple <string, string> ConvertSong(string songNumber, bool strippedDown, SongBook choosenSongBook)
        {
            try
            {
                int songNumberInt;
                int.TryParse(songNumber, out songNumberInt);

                if (songNumberInt > 694)
                {
                    MessageBox.Show(songNumber + " ist keine gültige Liednummer", "Fehler!", MessageBoxButton.OK,
                                    MessageBoxImage.Exclamation);
                    return(new Tuple <string, string>("big", ""));
                }


                object result   = "";
                string songBook = "";

                var database =
                    new SQLiteConnection("Data Source=songs.db;Version=3;");
                database.Open();

                var cmdGhsWlg = "SELECT wlg FROM wlg WHERE ghs=\"" + songNumber + "\";";
                var cmdGhsLq  = "SELECT lq FROM lq WHERE ghs=\"" + songNumber + "\";";
                var cmdWlgGhs = "SELECT ghs FROM wlg WHERE wlg=\"" + songNumber + "\";";
                var cmdLqGhs  = "SELECT ghs FROM lq WHERE lq=\"" + songNumber + "\";";


                switch (choosenSongBook)
                {
                case SongBook.Ghs:
                    SQLiteCommand    commandGhsWlg = new SQLiteCommand(cmdGhsWlg, database);
                    SQLiteDataReader readerGhsWlg  = commandGhsWlg.ExecuteReader();
                    while (readerGhsWlg.Read())
                    {
                        songBook = "WLG";
                        if (strippedDown)
                        {
                            result = readerGhsWlg["wlg"];
                        }
                        else
                        {
                            result = "WLG: " + readerGhsWlg["wlg"];
                        }
                    }


                    if (String.IsNullOrEmpty(result.ToString()))
                    {
                        SQLiteCommand    commandGhsLq = new SQLiteCommand(cmdGhsLq, database);
                        SQLiteDataReader readerGhsLq  = commandGhsLq.ExecuteReader();
                        while (readerGhsLq.Read())
                        {
                            songBook = "LQ";
                            if (strippedDown)
                            {
                                result = readerGhsLq["lq"];
                            }
                            else
                            {
                                result = "LQ: " + readerGhsLq["lq"];
                            }
                        }
                    }

                    break;

                case SongBook.Wlg:
                    SQLiteCommand    commandWlgGhs = new SQLiteCommand(cmdWlgGhs, database);
                    SQLiteDataReader readerWlgGhs  = commandWlgGhs.ExecuteReader();

                    while (readerWlgGhs.Read())
                    {
                        songBook = "WLG";
                        if (strippedDown)
                        {
                            result = readerWlgGhs["ghs"];
                        }
                        else
                        {
                            result = "GHS: " + readerWlgGhs["ghs"];
                        }
                    }

                    break;

                case SongBook.Lq:
                    SQLiteCommand    commandLqGhs = new SQLiteCommand(cmdLqGhs, database);
                    SQLiteDataReader readerLqGhs  = commandLqGhs.ExecuteReader();

                    while (readerLqGhs.Read())
                    {
                        songBook = "WLG";
                        if (strippedDown)
                        {
                            result = readerLqGhs["ghs"];
                        }
                        else
                        {
                            result = "GHS: " + readerLqGhs["ghs"];
                        }
                    }

                    break;
                }


                if (String.IsNullOrEmpty(result.ToString()))
                {
                    result = strippedDown ? "" : "Lied nicht in der Liste";
                }

                return(new Tuple <string, string>(result.ToString(), songBook));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                throw;
            }
        }
 //CBL  Added this. Trying to update how the view-model works.
 #region Init
 /// <summary>
 /// Initialize this object's properties from the given manager and options.
 /// Call this before the MessageBoxWindow is loaded (ie, the Loaded event gets raised).
 /// </summary>
 /// <param name="manager">the MessageBox object that serves as a manager of the message-box facility</param>
 /// <param name="options">a MessageBoxConfiguration to get the options from</param>
 internal void Init(MessageBox manager, MessageBoxConfiguration options)
 {
     Configuration = options;
     DetailText = options.DetailText;
     SummaryText = options.SummaryText;
     // If there is no caption, then just put the caption-prefix without the spacer.
     if (StringLib.HasNothing(options.CaptionAfterPrefix))
     {
         if (StringLib.HasNothing(options.CaptionPrefix))
         {
             Title = manager.CaptionPrefix;
         }
         else
         {
             Title = options.CaptionPrefix;
         }
     }
     else // the caption-suffix is not empty.
     {
         if (StringLib.HasNothing(options.CaptionPrefix))
         {
             Title = manager.CaptionPrefix + ": " + options.CaptionAfterPrefix;
         }
         else
         {
             Title = options.CaptionPrefix + ": " + options.CaptionAfterPrefix;
         }
     }
     // Cause all of the property binding values to be retrieved again
     // that depend upon the _configuration choices.
     Notify("BackgroundBrush");
     Notify("ButtonMargin");
     Notify("ButtonCount");
     Notify("ButtonWidth");
     Notify("ButtonPanelBackground");
     Notify("ButtonCancelVisibility");
     Notify("ButtonCloseVisibility");
     Notify("ButtonIgnoreVisibility");
     Notify("ButtonOkVisibility");
     Notify("ButtonRetryVisibility");
     Notify("ButtonYesVisibility");
     Notify("ButtonNoVisibility");
     Notify("Height");
     Notify("SummaryTextColor");
     Notify("SummaryTextBackground");
     Notify("SummaryTextHorizontalContentAlignment");
     Notify("SummaryTextMargin");
     Notify("SummaryTextRowSpan");
     Notify("DetailTextBackground");
     Notify("DetailTextHorizontalContentAlignment");
     Notify("DetailTextVerticalAlignment");
     Notify("DetailTextMargin");
     Notify("GradiantLeftColor");
     Notify("GradiantRightColor");
     Notify("IconImage");
     Notify("IconMargin");
     Notify("UpperRectangleRowSpan");
     Notify("UpperRectangleVisibility");
 }