Beispiel #1
0
        public void ForFullItemToStringIsMaximum()
        {
            var item = new XdtTransformationLogEntry();

            item.File                 = "File";
            item.LineNumber           = 10;
            item.LinePosition         = 20;
            item.Message              = "Message {0} {1}";
            item.MessageArgs          = new object[] { "arg0", 30 };
            item.MessageVerbosityType = MessageType.Verbose;
            item.MessageType          = "Type";
            item.Timestamp            = new DateTime(2000, 1, 2, 3, 4, 5);

            try {
                throw new Exception("Exception was thrown.");
            }
            catch (Exception ex) {
                item.Exception = ex;
            }

            var stringRepresentation = "";

            CultureUtil.UseGBCulture(() => { stringRepresentation = item.ToString(); });

            stringRepresentation.Should().StartWith(@"[02/01/2000 03:04:05] [MessageType:Type] [MessageVerbosityType:Verbose] [File:File] [LineNumber:10] [LinePosition:20] Exception: System.Exception: Exception was thrown.");

            stringRepresentation.Should().Contain("at Cake.XdtTransform.Tests.XdtTransformationLogEntryTests.ForFullItemToStringIsMaximum() in ");

            stringRepresentation.Should().Contain("Message arg0 30");
        }
        private void PopulateUser(PageSubscriptionUser userInfo, XDoc userDoc)
        {
            var email = userDoc["email"].AsText;

            if (string.IsNullOrEmpty(email))
            {
                throw new UserException("no email for user");
            }
            userInfo.Email    = email;
            userInfo.Username = userDoc["fullname"].AsText.IfNullOrEmpty(userDoc["username"].AsText);
            var language = userDoc["language"].AsText;

            if (!string.IsNullOrEmpty(language))
            {
                userInfo.Culture = CultureUtil.GetNonNeutralCulture(language);
            }
            var timezone = userDoc["timezone"].AsText;

            if (!string.IsNullOrEmpty(timezone))
            {
                // only update timezone if the user has it defined
                userInfo.Timezone = timezone;
            }
            var perms = (userDoc["permissions.effective/operations"].AsText ?? "").Split(',');

            userInfo.IsAdmin = false;
            foreach (var perm in perms)
            {
                if ("ADMIN".EqualsInvariantIgnoreCase(perm.Trim()))
                {
                    userInfo.IsAdmin = true;
                }
            }
        }
Beispiel #3
0
        public PromptBuilder ToPromptBuilder(String defaultVoice)
        {
            PromptBuilder builder = new PromptBuilder(CultureUtil.GetOriginalCulture());

            builder.StartVoice(defaultVoice);

            var tags = GetTagsInText();

            int startIndex = 0;

            foreach (ITag tag in tags)
            {
                String textBeforeCurrentTag = _contents.Substring(startIndex, tag.Start - startIndex);
                builder.AppendText(textBeforeCurrentTag);

                bool isCommandSuccessful = tag.Apply(builder);
                if (isCommandSuccessful)
                {
                    startIndex = tag.End + 1;
                }
            }

            String remaining = _contents.Substring(startIndex).Trim();

            builder.AppendText(remaining);
            builder.EndVoice();
            return(builder);
        }
Beispiel #4
0
        public DmdDevice()
        {
            _currentFrameFormat    = new BehaviorSubject <FrameFormat>(FrameFormat.Rgb24);
            _vpmGray2Source        = new VpmGray2Source(_currentFrameFormat);
            _vpmGray4Source        = new VpmGray4Source(_currentFrameFormat);
            _vpmRgb24Source        = new VpmRgb24Source(_currentFrameFormat);
            _vpmAlphaNumericSource = new VpmAlphaNumericSource(_currentFrameFormat);

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // setup logger
            var assembly      = Assembly.GetCallingAssembly();
            var assemblyPath  = Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath);
            var logConfigPath = Path.Combine(assemblyPath, "DmdDevice.log.config");

            if (File.Exists(logConfigPath))
            {
                LogManager.Configuration = new XmlLoggingConfiguration(logConfigPath, true);
#if !DEBUG
                LogManager.Configuration.AddTarget("memory", MemLogger);
                LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, MemLogger));
                LogManager.ReconfigExistingLoggers();
#endif
            }
#if !DEBUG
            else
            {
                SimpleConfigurator.ConfigureForTargetLogging(MemLogger, LogLevel.Debug);
            }
#endif
            CultureUtil.NormalizeUICulture();
            _config       = new Configuration();
            _altcolorPath = GetColorPath();

            // read versions from assembly
            var attr = assembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
            var fvi  = FileVersionInfo.GetVersionInfo(assembly.Location);
            _version = fvi.ProductVersion;
            if (attr.Length > 0)
            {
                var aca = (AssemblyConfigurationAttribute)attr[0];
                _sha = aca.Configuration;
                if (string.IsNullOrEmpty(_sha))
                {
                    _fullVersion = _version;
                }
                else
                {
                    _fullVersion = $"{_version} ({_sha})";
                }
            }
            else
            {
                _fullVersion = fvi.ProductVersion;
                _sha         = "";
            }

            Logger.Info("Starting VPinMAME API {0} through {1}.exe.", _fullVersion, Process.GetCurrentProcess().ProcessName);
            Logger.Info("Assembly located at {0}", assembly.Location);
        }
Beispiel #5
0
 public void Setup()
 {
     CultureUtil.SetDefaultCulture(CultureInfo.GetCultureInfo("en-US"));
     App  = new PowerPoint.Application();
     Pres = App.Presentations.Open(
         PathUtil.GetDocTestPath() + GetTestingSlideName(),
         WithWindow: MsoTriState.msoFalse);
     PpOperations = new UnitTestPpOperations(Pres, App);
 }
Beispiel #6
0
        public void SetUICultureWithInvalidCultureThrows()
        {
            // Arrange
            var    context = GetContextForSetCulture();
            Thread thread  = GetThread();

            // Act and Assert
            ExceptionAssert.Throws <CultureNotFoundException>(() => CultureUtil.SetUICulture(thread, context, "sans-culture"));
        }
    public void FromAcceptLanguageHeader(string header, string expectedCulture)
    {
        var acceptLanguage = new RequestHeaders(new HeaderDictionary {
            ["accept-language"] = header
        }).AcceptLanguage;

        var returnedCulture = CultureUtil.FromAcceptLanguageHeader(acceptLanguage, supportedCultures, new CultureInfo("de-AT"));

        returnedCulture.Should().Be(new CultureInfo(expectedCulture));
    }
Beispiel #8
0
        public void ForEmptyItemToStringIsMinimum()
        {
            var stringRepresentation = "";
            var item = new XdtTransformationLogEntry();

            item.Timestamp = new DateTime(2000, 1, 2, 3, 4, 5);

            CultureUtil.UseGBCulture(() => { stringRepresentation = item.ToString(); });

            stringRepresentation.Should().Equals("[02/01/2000 03:04:05] ");
        }
    public void GetFirstSupportedCulture(string culture, string?expectedCulture)
    {
        var returnedCulture = CultureUtil.GetFirstSupportedCulture(culture, supportedCultures);

        if (expectedCulture == null)
        {
            returnedCulture.Should().BeNull();
        }
        else
        {
            returnedCulture.Should().Be(new CultureInfo(expectedCulture));
        }
    }
Beispiel #10
0
        public void SetAutoUICultureWithEmptyUserLanguagesDoesNothing()
        {
            // Arrange
            var         context = GetContextForSetCulture(Enumerable.Empty <string>());
            Thread      thread  = GetThread();
            CultureInfo culture = thread.CurrentUICulture;

            // Act
            CultureUtil.SetUICulture(thread, context, "auto");

            // Assert
            Assert.AreEqual(culture, thread.CurrentUICulture);
        }
Beispiel #11
0
        public void SetAutoUICultureWithInvalidLanguageDoesNothing()
        {
            // Arrange
            var         context = GetContextForSetCulture(new[] { "aa-AA", "bb-BB", "cc-CC" });
            Thread      thread  = GetThread();
            CultureInfo culture = thread.CurrentUICulture;

            // Act
            CultureUtil.SetUICulture(thread, context, "auto");

            // Assert
            Assert.AreEqual(culture, thread.CurrentUICulture);
        }
Beispiel #12
0
        public void SetUICultureWithValidCulture()
        {
            // Arrange
            var    context = GetContextForSetCulture();
            Thread thread  = GetThread();

            // Act
            CultureUtil.SetUICulture(thread, context, "en-GB");

            // Assert
            Assert.AreEqual(CultureInfo.GetCultureInfo("en-GB"), thread.CurrentUICulture);
            Assert.AreEqual("05/01/1979", new DateTime(1979, 1, 5).ToString("d", thread.CurrentUICulture));
        }
Beispiel #13
0
        public void SetAutoUICultureDetectsUserLanguageWithQParameterCulture()
        {
            // Arrange
            var    context = GetContextForSetCulture(new[] { "en-GB;q=0.3", "en-US", "ar-eg;q=0.5" });
            Thread thread  = GetThread();

            // Act
            CultureUtil.SetUICulture(thread, context, "auto");

            // Assert
            Assert.AreEqual(CultureInfo.GetCultureInfo("en-GB"), thread.CurrentUICulture);
            Assert.AreEqual("05/01/1979", new DateTime(1979, 1, 5).ToString("d", thread.CurrentUICulture));
        }
        public void SetAutoUICultureWithNoUserLanguagesDoesNothing()
        {
            // Arrange
            var         context = GetContextForSetCulture(null);
            Thread      thread  = Thread.CurrentThread;
            CultureInfo culture = thread.CurrentUICulture;

            // Act
            CultureUtil.SetUICulture(thread, context, "auto");

            // Assert
            Assert.Equal(culture, thread.CurrentUICulture);
        }
        public void SetAutoCultureDetectsUserLanguageCulture()
        {
            // Arrange
            var    context = GetContextForSetCulture(new[] { "en-GB", "en-US", "ar-eg" });
            Thread thread  = Thread.CurrentThread;

            // Act
            CultureUtil.SetCulture(thread, context, "auto");

            // Assert
            Assert.Equal(CultureInfo.GetCultureInfo("en-GB"), thread.CurrentCulture);
            Assert.Equal("05/01/1979", new DateTime(1979, 1, 5).ToString("d", thread.CurrentCulture));
        }
Beispiel #16
0
        public void SetAutoUICultureWithBlankUserLanguagesDoesNothing()
        {
            // Arrange
            var         context = GetContextForSetCulture(new[] { " " });
            Thread      thread  = GetThread();
            CultureInfo culture = thread.CurrentUICulture;

            // Act
            CultureUtil.SetUICulture(thread, context, "auto");

            // Assert
            Assert.AreEqual(culture, thread.CurrentUICulture);
        }
Beispiel #17
0
        /// <summary>
        /// Extract <see cref="CultureInfo"/> from a header value.
        /// </summary>
        /// <param name="header">Header value to be parsed.</param>
        /// <param name="def">Default <see cref="CultureInfo"/> to return in case no culture can be parsed from the header.</param>
        /// <returns>Parsed or default culture.</returns>
        public static CultureInfo GetCultureInfoFromHeader(string header, CultureInfo def)
        {
            if (!string.IsNullOrEmpty(header))
            {
                // NOTE: we attempt to find the best acceptable language; format is: da, en-gb;q=0.8, en;q=0.7, *

                // convert language header into sorted list of languages
                List <Tuplet <string, double> > choices = new List <Tuplet <string, double> >();
                foreach (string choice in header.Split(','))
                {
                    string[] parts = choice.Split(';');
                    string   name  = parts[0].Trim();

                    // parse optional quality parameter
                    double quality = (name == "*") ? 0.0 : 1.0;
                    if ((parts.Length == 2))
                    {
                        string value = parts[1].Trim();
                        if (value.StartsWith("q="))
                        {
                            double.TryParse(value.Substring(2), out quality);
                        }
                    }

                    // add language option
                    choices.Add(new Tuplet <string, double>(name, quality));
                }
                choices.Sort(delegate(Tuplet <string, double> left, Tuplet <string, double> right) {
                    // reverse order sort based on quality
                    return(Math.Sign(right.Item2 - left.Item2));
                });

                // find the first acceptable language
                for (int i = 0; i < choices.Count; ++i)
                {
                    // check for wildcard
                    if (choices[0].Item1 == "*")
                    {
                        return(def);
                    }

                    // expand language to full culture
                    CultureInfo culture = CultureUtil.GetNonNeutralCulture(choices[i].Item1);
                    if (culture != null)
                    {
                        return(culture);
                    }
                }
            }
            return(def);
        }
        public void SetAutoUICultureWithInvalidLanguageDoesNothing()
        {
            // Arrange
            // "sans-culture" is an invalid culture name everywhere -- even on Windows 10.
            var         context = GetContextForSetCulture(new[] { "sans-culture", "bb-BB", "cc-CC" });
            Thread      thread  = Thread.CurrentThread;
            CultureInfo culture = thread.CurrentUICulture;

            // Act
            CultureUtil.SetUICulture(thread, context, "auto");

            // Assert
            Assert.Equal(culture, thread.CurrentUICulture);
        }
        public Yield GetLocalizedString(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            string      resource = context.GetParam("resource");
            string      language = context.GetParam("lang", null);
            CultureInfo culture  = CultureUtil.GetNonNeutralCulture(language) ?? DreamContext.Current.Culture;
            string      value    = ResourceManager.GetString(resource, culture, null);

            if (value == null)
            {
                throw new SiteNoSuchLocalizationResourceNotFoundException(resource);
            }
            response.Return(DreamMessage.Ok(MimeType.TEXT_UTF8, value));
            yield break;
        }
Beispiel #20
0
 public void Setup()
 {
     CultureUtil.SetDefaultCulture(CultureInfo.GetCultureInfo("en-US"));
     try
     {
         App = new PowerPoint.Application();
     }
     catch (COMException)
     {
         // in case a warm-up is needed
         App = new PowerPoint.Application();
     }
     Pres = App.Presentations.Open(
         PathUtil.GetDocTestPath() + GetTestingSlideName(),
         WithWindow: MsoTriState.msoFalse);
     PpOperations = new UnitTestPpOperations(Pres, App);
 }
Beispiel #21
0
        private CultureInfo GetCulture(DataRow row)
        {
            string cultureString = "";

            if (!string.IsNullOrEmpty(this.CountryColumnName) &&
                this.CountryColumnName == this.LanguageColumnName)
            {
                cultureString = row[this.CountryColumnName].ToStringOrEmpty();
            }
            else
            {
                // Is the country "US" in a column?
                string countryString = "";
                if (!string.IsNullOrEmpty(this.CountryColumnName))
                {
                    countryString = row[this.CountryColumnName].ToStringOrEmpty();
                }

                // Is the language "en" in a column?
                string languageString = "";
                if (!string.IsNullOrEmpty(this.LanguageColumnName))
                {
                    languageString = row[this.LanguageColumnName].ToStringOrEmpty();
                }

                // language an country? -> build "en-US"
                if (!string.IsNullOrEmpty(languageString) && !string.IsNullOrEmpty(countryString))
                {
                    cultureString = languageString.ToLower() + "-" + countryString;
                }
                else
                {
                    // otherwise just take "US"
                    cultureString = countryString;
                }
            }

            var culture = CultureUtil.GetCultureFromString(cultureString);

            if (culture == null)
            {
                culture = this.DefaultCulture;
            }

            return(culture);
        }
Beispiel #22
0
        public void TestDisplayLanguage()
        {
            var languagesToTest = new[] { LocalizationHelper.CurrentUICulture }
            .Concat(CultureUtil.AvailableDisplayLanguages());

            foreach (var language in languagesToTest)
            {
                var oldLanguage = LocalizationHelper.CurrentUICulture;
                try
                {
                    LocalizationHelper.CurrentUICulture = language;
                    _language = language;
                    RunFunctionalTest();
                }
                finally
                {
                    LocalizationHelper.CurrentUICulture = oldLanguage;
                }
            }
        }
        public void Setup()
        {
            CultureUtil.SetDefaultCulture(CultureInfo.GetCultureInfo("en-US"));
            try
            {
                App = new PowerPoint.Application();
            }
            catch (COMException)
            {
                // in case a warm-up is needed
                App = new PowerPoint.Application();
            }
            Pres = App.Presentations.Open(
                PathUtil.GetDocTestPath() + GetTestingSlideName(),
                WithWindow: MsoTriState.msoFalse);
            PpOperations = new UnitTestPpOperations(Pres, App);
            PPLClipboard.Init(PpOperations.Window, true);
            int processId = Process.GetCurrentProcess().Id;

            WindowWatcher.HeadlessSetup(processId);
        }
Beispiel #24
0
        public ToolOptionsUI()
        {
            InitializeComponent();
            checkBoxShowWizard.Checked = Settings.Default.ShowStartupForm;
            powerOfTenCheckBox.Checked = Settings.Default.UsePowerOfTen;
            Icon = Resources.Skyline;

            _driverServers = new SettingsListBoxDriver <Server>(listboxServers, Settings.Default.ServerList);
            _driverServers.LoadList();
            _driverChorusAccounts = new SettingsListBoxDriver <RemoteAccount>(listBoxRemoteAccounts, Settings.Default.RemoteAccountList);
            _driverChorusAccounts.LoadList();
            _driverColorSchemes = new SettingsListComboDriver <ColorScheme>(comboColorScheme, Settings.Default.ColorSchemes, true);
            _driverColorSchemes.LoadList(Settings.Default.CurrentColorScheme);

            // Hide ability to turn off live reports
            //tabControl.TabPages.Remove(tabMisc);

            // Populate the languages list with the languages that Skyline has been localized to
            string defaultDisplayName = string.Format(Resources.ToolOptionsUI_ToolOptionsUI_Default___0__,
                                                      CultureUtil.GetDisplayLanguage(CultureInfo.InstalledUICulture).DisplayName);

            listBoxLanguages.Items.Add(new DisplayLanguageItem(string.Empty, defaultDisplayName));
            foreach (var culture in CultureUtil.AvailableDisplayLanguages())
            {
                listBoxLanguages.Items.Add(new DisplayLanguageItem(culture.Name, culture.DisplayName));
            }
            for (int i = 0; i < listBoxLanguages.Items.Count; i++)
            {
                var displayLanguageItem = (DisplayLanguageItem)listBoxLanguages.Items[i];
                if (Equals(displayLanguageItem.Key, Settings.Default.DisplayLanguage))
                {
                    listBoxLanguages.SelectedIndex = i;
                }
            }
            comboCompactFormatOption.Items.AddRange(CompactFormatOption.ALL_VALUES.ToArray());
            comboCompactFormatOption.SelectedItem = CompactFormatOption.FromSettings();
        }
Beispiel #25
0
        //--- Constructors ---
        public PageSubscriptionInstance(string wikiId, XDoc config, IContainer container)
        {
            _log.DebugFormat("created PageSubscriptionInstance for wikiid '{0}'", wikiId);
            _wikiId = wikiId;
            _pageSubscriptionSessionFactory = container.Resolve <IPageSubscriptionDataSessionFactory>(new NamedParameter("config", config));

            // derive siteinfo
            _sitename = config["ui/sitename"].AsText;
            if (string.IsNullOrEmpty(_sitename))
            {
                _log.WarnFormat("missing ui/sitename for instance {0}", _wikiId);
            }
            _timezone = config["ui/timezone"].AsText;
            var emailFromAddress = config["page-subscription/from-address"].AsText;

            if (string.IsNullOrEmpty(emailFromAddress))
            {
                emailFromAddress = config["admin/email"].AsText;
            }
            if (string.IsNullOrEmpty(emailFromAddress))
            {
                _log.WarnFormat("missing page-subscription/from-address and admin/email for instance {0}", _wikiId);
            }
            else
            {
                var address = new MailAddress(emailFromAddress);
                if (string.IsNullOrEmpty(address.DisplayName))
                {
                    address = new MailAddress(emailFromAddress, emailFromAddress);
                }
                _emailFromAddress = address.ToString();
            }
            _emailFormat          = config["page-subscription/email-format"].AsText;
            _useShortEmailAddress = config["page-subscription/use-short-email-address"].AsBool ?? false;
            _culture = CultureUtil.GetNonNeutralCulture(config["ui/language"].AsText) ?? CultureInfo.GetCultureInfo("en-us");
        }
Beispiel #26
0
 public void Should_get_en_us_from_en()
 {
     Assert.AreEqual(CultureInfo.GetCultureInfo("en-us"), CultureUtil.GetNonNeutralCulture(CultureInfo.GetCultureInfo("en"), _default));
 }
Beispiel #27
0
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var attr     = assembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
            var fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);

            _version = fvi.ProductVersion;
            if (attr.Length > 0)
            {
                var aca = (AssemblyConfigurationAttribute)attr[0];
                _sha         = aca.Configuration;
                _fullVersion = $"{_version} ({_sha})";
            }
            else
            {
                _fullVersion = fvi.ProductVersion;
                _sha         = "";
            }

            CultureUtil.NormalizeUICulture();
            _commandLineArgs = args;

            // setup logger
            var assemblyPath  = Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath);
            var logConfigPath = Path.Combine(assemblyPath, "dmdext.log.config");

            if (File.Exists(logConfigPath))
            {
                LogManager.Configuration = new XmlLoggingConfiguration(logConfigPath, true);
#if !DEBUG
                LogManager.Configuration.AddTarget("memory", MemLogger);
                LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, MemLogger));
                LogManager.ReconfigExistingLoggers();
#endif
            }
#if !DEBUG
            else
            {
                SimpleConfigurator.ConfigureForTargetLogging(MemLogger, LogLevel.Debug);
            }
#endif
            AssertDotNetVersion();
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // enable exit handler
            _handler += ExitHandler;
            SetConsoleCtrlHandler(_handler, true);

            var    invokedVerb         = "";
            object invokedVerbInstance = null;
            var    options             = new Options();
            if (!CommandLine.Parser.Default.ParseArgumentsStrict(args, options, (verb, subOptions) => {
                // if parsing succeeds the verb name and correct instance
                // will be passed to onVerbCommand delegate (string,object)
                invokedVerb = verb;
                invokedVerbInstance = subOptions;
            }))
            {
                Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
            }

            try {
                Logger.Info("Launching console tool v{0}", _fullVersion);
                options.Validate();
                var cmdLineOptions = (BaseOptions)invokedVerbInstance;
                var config         = cmdLineOptions.DmdDeviceIni == null
                                        ? (IConfiguration)cmdLineOptions
                                        : new Configuration(cmdLineOptions.DmdDeviceIni);

                //BaseOptions baseOptions;
                switch (invokedVerb)
                {
                case "mirror":
                    _command = new MirrorCommand(config, (MirrorOptions)cmdLineOptions);
                    break;

                case "play":
                    _command = new PlayCommand(config, (PlayOptions)cmdLineOptions);
                    break;

                case "test":
                    _command = new TestCommand(config, (TestOptions)cmdLineOptions);
                    break;

                case "server":
                    _command = new ServerCommand(config, (ServerOptions)cmdLineOptions);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                var renderGraphs = _command.GetRenderGraphs();

                if (config.Bitmap.Enabled)
                {
                    renderGraphs.AddDestination(new BitmapOutput(config.Bitmap.Path));
                }

                if (config.PinUp.Enabled)
                {
                    try {
                        renderGraphs.AddDestination(new PinUpOutput(config.PinUp.GameName));
                    } catch (Exception e) {
                        Logger.Warn("Error opening PinUP output: {0}", e.Message);
                    }
                }

                _command.Execute(() => {
                    if (config != null && config.Global.QuitWhenDone)
                    {
                        Logger.Info("Exiting.");
                        _command?.Dispose();
                        Environment.Exit(0);
                    }
                }, ex => {
                    Logger.Error("Error: {0}", ex.Message);
                    _command?.Dispose();
                    Environment.Exit(0);
                });

                if (config.Global.QuitAfter > -1)
                {
                    Logger.Info("Quitting in {0}ms...", config.Global.QuitAfter);
                    Observable
                    .Return(Unit.Default)
                    .Delay(TimeSpan.FromMilliseconds(config.Global.QuitAfter))
                    .Subscribe(_ => WinApp.Dispatcher.Invoke(() => WinApp.Shutdown()));
                }
                else
                {
                    Logger.Info("Press CTRL+C to close.");
                }

                WinApp.Run();
            } catch (DeviceNotAvailableException e) {
                Logger.Error("Device {0} is not available.", e.Message);
            } catch (NoRenderersAvailableException) {
                Logger.Error("No output devices available.");
            } catch (InvalidOptionException e) {
                Logger.Error("Invalid option: {0}", e.Message);
            } catch (FileNotFoundException e) {
                Logger.Error(e.Message);
                Logger.Info("Try installing the Visual C++ Redistributable for Visual Studio 2015 if you haven't so already:");
                Logger.Info("    https://www.microsoft.com/en-us/download/details.aspx?id=48145");
            } catch (UnknownFormatException e) {
                Logger.Error(e.Message);
            } catch (WrongFormatException e) {
                Logger.Error(e.Message);
            } catch (UnsupportedResolutionException e) {
                Logger.Error(e.Message);
            } catch (InvalidFolderException e) {
                Logger.Error(e.Message);
            } catch (RenderException e) {
                Logger.Error(e.Message);
            } catch (NoRawDestinationException e) {
                Logger.Error(e.Message);
            } catch (MultipleRawSourcesException e) {
                Logger.Error(e.Message);
            } catch (ProPinballSlaveException e) {
                Logger.Error(e.Message);
            } catch (IncompatibleRenderer e) {
                Logger.Error(e.Message);
            } catch (IncompatibleSourceException e) {
                Logger.Error(e.Message);
            } catch (IniNotFoundException e) {
                Logger.Error(e.Message);
            } catch (CropRectangleOutOfRangeException e) {
                Logger.Error(e.Message);
                Logger.Error("Are you running PinballFX2 in cabinet mode with the DMD at 1040x272?");
            } finally {
                Process.GetCurrentProcess().Kill();
            }
        }
        public void ImplementsEveryInterfaceMethodAndSavesAllLogEntries()
        {
            CultureUtil.UseGBCulture(() => {
                var log = new XdtTransformationLog();

                log.HasError.Should().BeFalse();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeFalse();
                log.Log.Count().Should().Equals(0);

                log.LogMessage("Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeFalse();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeFalse();
                log.Log.Count().Should().Equals(1);
                log.Log.ElementAt(0).ToString().Should().Contain("[MessageType:Message] Message 1 2");

                log.LogMessage(MessageType.Verbose, "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeFalse();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeFalse();
                log.Log.Count().Should().Equals(2);
                log.Log.ElementAt(1).ToString().Should().Contain("[MessageType:Message] [MessageVerbosityType:Verbose] Message 1 2");

                log.LogWarning("File", "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeFalse();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(3);
                log.Log.ElementAt(2).ToString().Should().Contain("[MessageType:Warning] [File:File] Message 1 2");

                log.LogWarning("File", 30, 40, "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeFalse();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(4);
                log.Log.ElementAt(3).ToString().Should().Contain("[MessageType:Warning] [File:File] [LineNumber:30] [LinePosition:40] Message 1 2");

                log.LogError("Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(5);
                log.Log.ElementAt(4).ToString().Should().Contain("[MessageType:Error] Message 1 2");

                log.LogError("File", "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(6);
                log.Log.ElementAt(5).ToString().Should().Contain("[MessageType:Error] [File:File] Message 1 2");

                log.LogError("File", 30, 40, "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeFalse();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(7);
                log.Log.ElementAt(6).ToString().Should().Contain("[MessageType:Error] [File:File] [LineNumber:30] [LinePosition:40] Message 1 2");

                Exception exception = null;
                try {
                    throw new Exception("Exception was thrown");
                }
                catch (Exception ex) {
                    exception = ex;
                }

                log.LogErrorFromException(exception);
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(8);
                log.Log.ElementAt(7).ToString().Should().Contain("[MessageType:Exception] Exception: System.Exception: Exception was thrown");

                log.LogErrorFromException(exception, "File");
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(9);
                log.Log.ElementAt(8).ToString().Should().Contain("[MessageType:Exception] [File:File] Exception: System.Exception: Exception was thrown");

                log.LogErrorFromException(exception, "File", 30, 40);
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(10);
                log.Log.ElementAt(9).ToString().Should().Contain("[MessageType:Exception] [File:File] [LineNumber:30] [LinePosition:40] Exception: System.Exception: Exception was thrown");

                log.StartSection("Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(11);
                log.Log.ElementAt(10).ToString().Should().Contain("[MessageType:Section] Message 1 2");

                log.StartSection(MessageType.Verbose, "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(12);
                log.Log.ElementAt(11).ToString().Should().Contain("[MessageType:Section] [MessageVerbosityType:Verbose] Message 1 2");

                log.EndSection("Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(13);
                log.Log.ElementAt(12).ToString().Should().Contain("[MessageType:Section] Message 1 2");

                log.EndSection(MessageType.Verbose, "Message {0} {1}", new object[] { "1", 2 });
                log.HasError.Should().BeTrue();
                log.HasException.Should().BeTrue();
                log.HasWarning.Should().BeTrue();
                log.Log.Count().Should().Equals(14);
                log.Log.ElementAt(13).ToString().Should().Contain("[MessageType:Section] [MessageVerbosityType:Verbose] Message 1 2");
            });
        }
    public void GetFirstSupportedCulture_FallsBackToDefault()
    {
        var returnedCulture = CultureUtil.GetFirstSupportedCulture("Invalid", supportedCultures, new CultureInfo("de-AT"));

        returnedCulture.Should().Be(new CultureInfo("de-AT"));
    }
Beispiel #30
0
        public ToolOptionsUI(SrmSettings settings)
        {
            InitializeComponent();
            checkBoxShowWizard.Checked = Settings.Default.ShowStartupForm;
            powerOfTenCheckBox.Checked = Settings.Default.UsePowerOfTen;
            Icon = Resources.Skyline;

            _driverServers = new SettingsListBoxDriver <Server>(listboxServers, Settings.Default.ServerList);
            _driverServers.LoadList();
            _driverRemoteAccounts = new SettingsListBoxDriver <RemoteAccount>(listBoxRemoteAccounts, Settings.Default.RemoteAccountList);
            _driverRemoteAccounts.LoadList();
            _driverColorSchemes = new SettingsListComboDriver <ColorScheme>(comboColorScheme, Settings.Default.ColorSchemes, true);
            _driverColorSchemes.LoadList(Settings.Default.CurrentColorScheme);

            var pingPep   = new Peptide(@"PING");
            var peptide   = new PeptideDocNode(pingPep);
            var precursor = new TransitionGroupDocNode(new TransitionGroup(pingPep, Adduct.SINGLY_PROTONATED, IsotopeLabelType.light),
                                                       new TransitionDocNode[0]);

            _pingInput     = new PrositIntensityModel.PeptidePrecursorNCE(peptide, precursor, IsotopeLabelType.light, 32);
            _settingsNoMod = settings.ChangePeptideModifications(
                pm => new PeptideModifications(new StaticMod[0], new TypedModifications[0]));

            // Hide ability to turn off live reports
            //tabControl.TabPages.Remove(tabMisc);

            // Populate the languages list with the languages that Skyline has been localized to
            string defaultDisplayName = string.Format(Resources.ToolOptionsUI_ToolOptionsUI_Default___0__,
                                                      CultureUtil.GetDisplayLanguage(CultureInfo.InstalledUICulture).DisplayName);

            listBoxLanguages.Items.Add(new DisplayLanguageItem(string.Empty, defaultDisplayName));
            foreach (var culture in CultureUtil.AvailableDisplayLanguages())
            {
                listBoxLanguages.Items.Add(new DisplayLanguageItem(culture.Name, culture.DisplayName));
            }
            for (int i = 0; i < listBoxLanguages.Items.Count; i++)
            {
                var displayLanguageItem = (DisplayLanguageItem)listBoxLanguages.Items[i];
                if (Equals(displayLanguageItem.Key, Settings.Default.DisplayLanguage))
                {
                    listBoxLanguages.SelectedIndex = i;
                }
            }
            comboCompactFormatOption.Items.AddRange(CompactFormatOption.ALL_VALUES.ToArray());
            comboCompactFormatOption.SelectedItem = CompactFormatOption.FromSettings();

            var iModels = PrositIntensityModel.Models.ToList();

            iModels.Insert(0, string.Empty);
            var rtModels = PrositRetentionTimeModel.Models.ToList();

            rtModels.Insert(0, string.Empty);

            tbxPrositServer.Text = PrositConfig.GetPrositConfig().Server;
            intensityModelCombo.Items.AddRange(iModels.ToArray());
            iRTModelCombo.Items.AddRange(rtModels.ToArray());

            prositServerStatusLabel.Text = string.Empty;
            if (iModels.Contains(Settings.Default.PrositIntensityModel))
            {
                intensityModelCombo.SelectedItem = Settings.Default.PrositIntensityModel;
            }
            if (rtModels.Contains(Settings.Default.PrositRetentionTimeModel))
            {
                iRTModelCombo.SelectedItem = Settings.Default.PrositRetentionTimeModel;
            }

            ceCombo.Items.AddRange(
                Enumerable.Range(PrositConstants.MIN_NCE, PrositConstants.MAX_NCE - PrositConstants.MIN_NCE + 1).Select(c => (object)c)
                .ToArray());
            ceCombo.SelectedItem = Settings.Default.PrositNCE;
        }