/// <summary>
    /// Adds new row into result table.
    /// </summary>
    private TableRow GetRow(string cultureName, string cultureCode)
    {
        bool isDefaultCulture = cultureCode.EqualsCSafe(CultureHelper.DefaultUICultureCode, true);
        bool isCurrentCulture = cultureCode.EqualsCSafe(selectedCultureCode);

        if (isDefaultCulture)
        {
            cultureName = String.Format("{0} ({1})", cultureName, GetString("general.default").ToLowerCSafe());
        }
        else if (isCurrentCulture)
        {
            cultureName = String.Format("{0} ({1})", cultureName, GetString("general.current").ToLowerCSafe());
        }

        Image flag = new Image();

        flag.ImageUrl = GetFlagIconUrl(cultureCode, "16x16");
        flag.CssClass = "cms-icon-80";
        flag.Style.Add("vertical-align", "middle");
        flag.ToolTip       = String.Format("{0} ({1})", cultureName, cultureCode);
        flag.AlternateText = flag.ToolTip;

        var label = new Label();

        label.Text = " " + cultureName;

        TableCell cultureCell = new TableCell();

        cultureCell.Width = new Unit("250px");
        cultureCell.Controls.Add(flag);
        cultureCell.Controls.Add(label);

        var textArea = (FormEngineUserControl)LoadControl("~/CMSFormControls/Inputs/LargeTextArea.ascx");

        textArea.ID      = cultureCode;
        textArea.Enabled = EnableTranslations;
        textArea.SetValue("ProcessMacroSecurity", false);

        if (!String.IsNullOrEmpty(mResourceStringInfo.StringKey))
        {
            textArea.Text = ResourceStringInfoProvider.GetStringFromDB(mResourceStringInfo.StringKey, cultureCode);
            if (string.IsNullOrEmpty(textArea.Text))
            {
                // If translation not found in database try to load it from resource file
                textArea.Text = LocalizationHelper.GetFileString(mResourceStringInfo.StringKey, cultureCode, string.Empty, false);
            }
        }

        if (!isDefaultCulture && EnableTranslations)
        {
            textArea.SetValue("AllowTranslationServices", true);
            textArea.SetValue("TranslationSourceLanguage", CultureHelper.DefaultUICultureCode);
            textArea.SetValue("TranslationTargetLanguage", cultureCode);
        }

        TableCell resStringCell = new TableCell();

        resStringCell.Controls.Add(textArea);

        TableRow row = new TableRow();

        row.Cells.Add(cultureCell);
        row.Cells.Add(resStringCell);

        mTranslations.Add(cultureCode.ToLowerCSafe(), textArea);

        return(row);
    }
예제 #2
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="UpdateManager" /> class.
        /// </summary>
        /// <param name="updateConfigurationFileUri">The URI of the update configuration file.</param>
        /// <param name="publicKey">The public key for the validity check of the update packages.</param>
        /// <param name="languageCulture">
        ///     The language culture to use. If no value is provided, the default one ("en") will be
        ///     used.
        /// </param>
        /// <param name="currentVersion">
        ///     The current version of that should be used for the update checks. This parameter has a
        ///     higher priority than the <see cref="nUpdateVersionAttribute" /> and will replace it, if specified.
        /// </param>
        /// <param name="applicationName">
        ///     The application's name.
        ///     By default, this will be derived from the entry assembly. Set this manually, if this results in a wrong application name.
        /// </param>
        /// <param name="applicationExecutablePath">
        ///     The path of the application's executable file (.exe) that should be (re)started after the update installation.
        ///     By default, this will be derived from the entry assembly. Set this manually, if this results in the wrong application being opened.
        /// </param>
        /// <remarks>
        ///     The public key can be found in the overview of your project when you're opening it in nUpdate Administration.
        ///     If you have problems inserting the data (or if you want to save time) you can scroll down there and follow the
        ///     steps of the category "Copy data" which will automatically generate the necessary code for you.
        /// </remarks>
        public UpdateManager(Uri updateConfigurationFileUri, string publicKey,
                             CultureInfo languageCulture = null, UpdateVersion currentVersion = null, string applicationName = null, string applicationExecutablePath = null)
        {
            UpdateConfigurationFileUri = updateConfigurationFileUri ??
                                         throw new ArgumentNullException(nameof(updateConfigurationFileUri));

            if (string.IsNullOrEmpty(publicKey))
            {
                throw new ArgumentNullException(nameof(publicKey));
            }
            PublicKey = publicKey;

            CultureFilePaths = new Dictionary <CultureInfo, string>();
            Arguments        = new List <UpdateArgument>();

            var projectAssembly = Assembly.GetEntryAssembly();

            if (projectAssembly == null)
            {
                throw new Exception("The entry assembly could not be determined.");
            }

            var nUpdateVersionAttribute =
                projectAssembly.GetCustomAttributes(false).OfType <nUpdateVersionAttribute>().SingleOrDefault();

            _productName = applicationName ?? projectAssembly.GetName().Name;

            if (applicationExecutablePath != null)
            {
                _executablePath = applicationExecutablePath;
            }
            else
            {
                _executablePath = projectAssembly.Location;

                // It may happen that the calling assembly is not the .exe, but another library. This is the case in .NET Core 6, for example.
                // We try to fix the path automatically. If this still does not work, the user can use the ExecutableFilePath property to set the path manually.
                if (!_executablePath.EndsWith(".exe"))
                {
                    _executablePath = Path.Combine(Path.GetDirectoryName(_executablePath) ?? string.Empty, $"{_productName}.exe");
                }
            }

            _startupPath = Path.GetDirectoryName(_executablePath);
            _applicationUpdateDirectory = Path.Combine(Path.GetTempPath(), "nUpdate",
                                                       _productName);

            // TODO: This is just there to make sure we don't create an API-change that would require a new Major version. This will be changed/removed in v5.0.
            // Before v3.0-beta8 it was not possible to provide the current version except using the nUpdateVersionAttribute.
            // In order to allow specific features, e.g. updating another application and not the current one (as it's done by a launcher), there must be a way to provide this version separately.
            // So, if an argument is specified for the "currentVersion" parameter, we will use this one instead of the nUpdateVersionAttribute.
            if (currentVersion != null)
            {
                CurrentVersion = currentVersion;
            }
            else
            {
                // Neither the nUpdateVersionAttribute nor the additional parameter argument was provided.
                if (nUpdateVersionAttribute == null)
                {
                    throw new ArgumentException(
                              "The version string couldn't be loaded because the nUpdateVersionAttribute isn't implemented in the executing assembly and no version was provided explicitly.");
                }

                CurrentVersion = new UpdateVersion(nUpdateVersionAttribute.VersionString);
            }

            // TODO: This is just there to make sure we don't create an API-change that would require a new Major version. This will be changed/removed in v4.0.
            // Before v3.0-beta5 it was not possible to use custom languages due to a mistake in the architecture. So we can be pretty sure that nobody specifies a custom CultureInfo in the constructor.
            // We only need these two lines for those who specified one of the implemented CultureInfos here as they shouldn't have to change anything when updating to v3.0-beta5.
            // Nevertheless, it's therefore possible to use custom CultureInfos just by leaving the optional parameter "null" and specifying the culture using the corresponding properties. So, both cases are covered with that solution.
            if (languageCulture != null && LocalizationHelper.IsIntegratedCulture(languageCulture, CultureFilePaths))
            {
                LanguageCulture = languageCulture;
            }
            else
            {
                throw new ArgumentException($"The culture \"{languageCulture}\" is not defined.");
            }

            if (UseCustomInstallerUserInterface && string.IsNullOrEmpty(CustomInstallerUiAssemblyPath))
            {
                throw new ArgumentException(
                          "The property \"CustomInstallerUiAssemblyPath\" is not initialized although \"UseCustomInstallerUserInterface\" is set to \"true\"");
            }
            Initialize();
        }
예제 #3
0
 /// <summary>
 /// Gets localized string from given source  for given key name and current language with formatting strings.
 /// </summary>
 /// <param name="sourceName">Source name</param>
 /// <param name="name">Key name</param>
 /// <param name="culture">culture information</param>
 /// <param name="args">Format arguments</param>
 /// <returns>Localized string</returns>
 protected virtual string Ls(string sourceName, string name, CultureInfo culture, params object[] args)
 {
     return(LocalizationHelper.GetSource(sourceName).GetString(name, culture, args));
 }
    /// <summary>
    /// Returns the content of results column. Results column contains message "failed" with link to error message when search task execution has failed.
    /// </summary>
    /// <param name="row">Grid row</param>
    /// <returns>Content of result column</returns>
    private object RenderResult(DataRowView row)
    {
        if (row == null)
        {
            return(String.Empty);
        }

        // Check if task has error status
        string status = ValidationHelper.GetString(row["SearchTaskStatus"], "");

        if (String.IsNullOrEmpty(status) || status.ToEnum <SearchTaskStatusEnum>() != SearchTaskStatusEnum.Error)
        {
            return(String.Empty);
        }

        // Check task ID, render failed message if task id cannot be obtained
        int taskID = ValidationHelper.GetInteger(row["SearchTaskID"], 0);

        if (taskID == 0)
        {
            return(LocalizationHelper.GetString("smartsearch.resultfailed"));
        }

        // Render failed message with link to modal dialog with full report
        string resultUrl = URLHelper.ResolveUrl("~/CMSModules/SmartSearch/SearchTask_Report.aspx?taskid=") + taskID;

        return(String.Format("<a target=\"_blank\" href=\"{0}\" onclick=\"modalDialog('{0}', 'taskresult', 700, 500); return false;\">{1}</a>", resultUrl, LocalizationHelper.GetString("smartsearch.resultfailed")));
    }
예제 #5
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            #region Validation

            if (Global.UpdateAvailable == null)
            {
                WhatsNewParagraph.Inlines.Add("Something wrong happened. No update was found.");
                return;
            }

            #endregion

            try
            {
                //Detect if this is portable or installed. Download the proper file.
                IsChocolatey = AppDomain.CurrentDomain.BaseDirectory.EndsWith(@"Chocolatey\lib\screentogif\content\");
                IsInstaller  = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory).Any(x => x.ToLowerInvariant().EndsWith("screentogif.visualelementsmanifest.xml"));

                VersionRun.Text = $"{LocalizationHelper.Get("S.Updater.Version")} {Global.UpdateAvailable.Version}";
                SizeRun.Text    = !UserSettings.All.PortableUpdate ? (Global.UpdateAvailable.InstallerSize > 0 ? Humanizer.BytesToString(Global.UpdateAvailable.InstallerSize) : "") :
                                  (Global.UpdateAvailable.PortableSize > 0 ? Humanizer.BytesToString(Global.UpdateAvailable.PortableSize) : "");
                TypeRun.Text = IsInstaller ? LocalizationHelper.Get("S.Updater.Installer") : LocalizationHelper.Get("S.Updater.Portable");

                //Details.
                if (Global.UpdateAvailable.IsFromGithub)
                {
                    //From Github, the description is available.
                    var splited = Global.UpdateAvailable.Description.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

                    WhatsNewParagraph.Inlines.Add(splited[0].Replace(" What's new?\r\n\r\n", ""));
                    FixesParagraph.Inlines.Add(splited.Length > 1 ? splited[1].Replace(" Bug fixes:\r\n\r\n", "").Replace(" Fixed:\r\n\r\n", "") : "Aparently nothing.");
                }
                else
                {
                    //If the release detail was obtained by querying Fosshub, no release note is available.
                    MainFlowDocument.Blocks.Remove(WhatsNewParagraphTitle);
                    MainFlowDocument.Blocks.Remove(FixesParagraphTitle);
                    MainFlowDocument.Blocks.Remove(FixesParagraph);

                    var run = new Run();
                    run.SetResourceReference(Run.TextProperty, "S.Updater.Info.NewVersionAvailable");
                    WhatsNewParagraph.Inlines.Add(run);
                }

                DocumentViewer.UpdateLayout();

                //If set to force the download the portable version of the app, check if it was downloaded.
                if (UserSettings.All.PortableUpdate)
                {
                    //If the update was already downloaded.
                    if (File.Exists(Global.UpdateAvailable.PortablePath))
                    {
                        //If it's still downloading, wait for it to finish before displaying "Open".
                        if (Global.UpdateAvailable.IsDownloading)
                        {
                            Global.UpdateAvailable.TaskCompletionSource = new TaskCompletionSource <bool>();
                            await Global.UpdateAvailable.TaskCompletionSource.Task;

                            if (!IsLoaded)
                            {
                                return;
                            }
                        }

                        DownloadButton.SetResourceReference(ExtendedButton.TextProperty, "S.Updater.InstallManually");
                    }

                    return;
                }

                //If set to download automatically, check if the installer was downloaded.
                if (UserSettings.All.InstallUpdates)
                {
                    //If the update was already downloaded.
                    if (File.Exists(Global.UpdateAvailable.InstallerPath))
                    {
                        //If it's still downloading, wait for it to finish before displaying "Install".
                        if (Global.UpdateAvailable.IsDownloading)
                        {
                            Global.UpdateAvailable.TaskCompletionSource = new TaskCompletionSource <bool>();
                            await Global.UpdateAvailable.TaskCompletionSource.Task;

                            if (!IsLoaded)
                            {
                                return;
                            }
                        }

                        DownloadButton.SetResourceReference(ExtendedButton.TextProperty, "S.Updater.Install");

                        //When the update was prompted manually, the user can set the installer to run the app afterwards.
                        if (WasPromptedManually)
                        {
                            RunAfterwardsCheckBox.Visibility = Visibility.Visible;
                            RunAfterwardsCheckBox.IsChecked  = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to load the download details");
                StatusBand.Error(LocalizationHelper.Get("S.Updater.Warning.Show"));
            }
            finally
            {
                Height        = ActualHeight;
                SizeToContent = SizeToContent.Width;
                Width         = ActualWidth;
                SizeToContent = SizeToContent.Manual;

                MaxHeight = double.PositiveInfinity;
                MaxWidth  = double.PositiveInfinity;

                CenterOnScreen();
            }
        }
        protected static WorkflowAction LoadMethodCallAction(XPathNavigator actionNav)
        {
            string         id              = null;
            string         name            = null;
            string         displayTitle    = null;
            string         displayCategory = null;
            string         sortOrder       = null;
            string         sourceStates    = null;
            string         modelId         = null;
            string         methodName      = null;
            XPathNavigator attrNav         = actionNav.Clone();

            if (attrNav.MoveToFirstAttribute())
            {
                do
                {
                    switch (attrNav.Name)
                    {
                    case "Id":
                        id = attrNav.Value;
                        break;

                    case "Name":
                        name = attrNav.Value;
                        break;

                    case "DisplayTitle":
                        displayTitle = attrNav.Value;
                        break;

                    case "DisplayCategory":
                        displayCategory = attrNav.Value;
                        break;

                    case "SortOrder":
                        sortOrder = attrNav.Value;
                        break;

                    case "SourceStates":
                        sourceStates = attrNav.Value;
                        break;

                    case "ModelId":
                        modelId = attrNav.Value;
                        break;

                    case "MethodName":
                        methodName = attrNav.Value;
                        break;

                    default:
                        throw new ArgumentException("'" + actionNav.Name + "' element doesn't support an attribute '" + attrNav.Name + "'");
                    }
                } while (attrNav.MoveToNextAttribute());
            }
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(string.Format("{0} '{1}': Id attribute is missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(string.Format("{0} with id '{1}': 'Name' attribute missing", actionNav.Name, id));
            }
            if (string.IsNullOrEmpty(sourceStates))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'SourceStates' attribute missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(modelId))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'ModelId' attribute missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(methodName))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'MethodName' attribute missing", actionNav.Name, name));
            }
            MethodCallAction result = new MethodCallAction(new Guid(id), name, ParseActionSourceStates(sourceStates),
                                                           LocalizationHelper.CreateResourceString(displayTitle), new Guid(modelId), methodName)
            {
                DisplayCategory = displayCategory,
                SortOrder       = sortOrder
            };

            return(result);
        }
예제 #7
0
        internal void CheckDiskSpace()
        {
            if (string.IsNullOrWhiteSpace(UserSettings.All.TemporaryFolderResolved))
            {
                return;
            }

            try
            {
                var isRelative = !string.IsNullOrWhiteSpace(UserSettings.All.TemporaryFolderResolved) && !Path.IsPathRooted(UserSettings.All.TemporaryFolderResolved);
                var drive      = new DriveInfo((isRelative ? Path.GetFullPath(UserSettings.All.TemporaryFolderResolved) : UserSettings.All.TemporaryFolderResolved).Substring(0, 1));

                Global.AvailableDiskSpacePercentage = drive.AvailableFreeSpace * 100d / drive.TotalSize; //Get the percentage of space left.
                Global.AvailableDiskSpace           = drive.AvailableFreeSpace;

                //If there's less than 2GB left.
                if (drive.AvailableFreeSpace < 2_000_000_000)
                {
                    Application.Current.Dispatcher?.Invoke(() => NotificationManager.AddNotification(LocalizationHelper.GetWithFormat("S.Editor.Warning.LowSpace", Math.Round(Global.AvailableDiskSpacePercentage, 2)),
                                                                                                     StatusType.Warning, "disk", () => App.MainViewModel.OpenOptions.Execute(Options.TempFilesIndex)));
                }
                else
                {
                    Application.Current.Dispatcher?.Invoke(() => NotificationManager.RemoveNotification(r => r.Tag == "disk"));
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Error while checking the space left in disk");
            }
        }
예제 #8
0
 /// <summary>
 /// Gets localized string for given key name and specified culture information.
 /// </summary>
 /// <param name="name">Key name</param>
 /// <param name="culture">culture information</param>
 /// <returns>Localized string</returns>
 protected virtual string L(string name, CultureInfo culture)
 {
     return(LocalizationHelper.GetString(LocalizationSourceName, name, culture));
 }
예제 #9
0
        public static string ValidateSeName <T>(this T entity,
                                                string seName,
                                                string name,
                                                bool ensureNotEmpty,
                                                IUrlRecordService urlRecordService,
                                                SeoSettings seoSettings,
                                                int?languageId = null,
                                                Func <string, UrlRecord> extraSlugLookup = null)
            where T : BaseEntity, ISlugSupported
        {
            Guard.NotNull(urlRecordService, nameof(urlRecordService));
            Guard.NotNull(seoSettings, nameof(seoSettings));

            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            // use name if sename is not specified
            if (String.IsNullOrWhiteSpace(seName) && !String.IsNullOrWhiteSpace(name))
            {
                seName = name;
            }

            // validation
            seName = GetSeName(seName, seoSettings);

            // max length
            seName = seName.Truncate(400);

            if (String.IsNullOrWhiteSpace(seName))
            {
                if (ensureNotEmpty)
                {
                    // use entity identifier as sename if empty
                    seName = entity.Id.ToString();
                }
                else
                {
                    // return. no need for further processing
                    return(seName);
                }
            }

            // validate and alter SeName if it could be interpreted as SEO code
            if (LocalizationHelper.IsValidCultureCode(seName))
            {
                if (seName.Length == 2)
                {
                    seName = seName + "-0";
                }
            }

            // ensure this sename is not reserved yet
            string entityName = typeof(T).Name;
            int    i          = 2;
            var    tempSeName = seName;

            extraSlugLookup = extraSlugLookup ?? ((s) => null);

            while (true)
            {
                // check whether such slug already exists (and that it's not the current entity)
                var urlRecord = urlRecordService.GetBySlug(tempSeName) ?? extraSlugLookup(tempSeName);
                var reserved1 = urlRecord != null && !(urlRecord.EntityId == entity.Id && urlRecord.EntityName.Equals(entityName, StringComparison.InvariantCultureIgnoreCase));

                if (!reserved1 && urlRecord != null && languageId.HasValue)
                {
                    reserved1 = (urlRecord.LanguageId != languageId.Value);
                }

                // and it's not in the list of reserved slugs
                var reserved2 = seoSettings.ReservedUrlRecordSlugs.Contains(tempSeName, StringComparer.InvariantCultureIgnoreCase);
                if (!reserved1 && !reserved2)
                {
                    break;
                }

                tempSeName = string.Format("{0}-{1}", seName, i);
                i++;
            }
            seName = tempSeName;

            return(seName);
        }
예제 #10
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            #region Size check

            var left  = NewList[0].Path.SourceFrom();
            var right = CurrentList[0].Path.SourceFrom();

            //Left: New, Right: Current
            LeftImage.Source  = left;
            RightImage.Source = right;

            //The image should be displayed based on the scale of the screen.
            var scaleLeft  = Math.Round(left.DpiX / 96d, 2);
            var scaleRight = Math.Round(right.DpiX / 96d, 2);
            var scale      = this.Scale();

            var scaleDiffLeft  = Math.Round(scale / scaleLeft, 2);
            var scaleDiffRight = Math.Round(scale / scaleRight, 2);

            LeftImage.Width  = _leftWidth = left.Width / scaleDiffLeft;
            LeftImage.Height = _leftHeight = left.Height / scaleDiffLeft;

            RightImage.Width  = _rightWidth = right.Width / scaleDiffRight;
            RightImage.Height = _rightHeight = right.Height / scaleDiffRight;

            #endregion

            #region Initial sizing

            LeftImage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            LeftImage.Arrange(new Rect(new Point(0, 0), LeftImage.DesiredSize));
            RightImage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            RightImage.Arrange(new Rect(new Point(0, 0), RightImage.DesiredSize));

            if (Math.Abs(LeftImage.ActualWidth - RightImage.ActualWidth) > 0.01 || Math.Abs(LeftImage.ActualHeight - RightImage.ActualHeight) > 0.01)
            {
                StatusBand.Warning(LocalizationHelper.Get("S.InsertFrames.DifferentSizes"));
            }

            LeftCanvas.Width  = LeftImage.ActualWidth;
            LeftCanvas.Height = LeftImage.ActualHeight;

            RightCanvas.Width  = RightImage.ActualWidth;
            RightCanvas.Height = RightImage.ActualHeight;

            EqualizeSizes();

            #endregion

            MouseLeftButtonDown += Unselect_MouseLeftButtonDown;

            LeftImage.MouseLeftButtonDown  += Select_PreviewMouseLeftButtonDown;
            LeftCanvas.MouseLeftButtonDown += Select_PreviewMouseLeftButtonDown;

            RightImage.MouseLeftButtonDown  += Select_PreviewMouseLeftButtonDown;
            RightCanvas.MouseLeftButtonDown += Select_PreviewMouseLeftButtonDown;

            LeftCanvas.SizeChanged  += Canvas_SizeChanged;
            RightCanvas.SizeChanged += Canvas_SizeChanged;

            UpdateLayout();
        }
예제 #11
0
        public bool Run(TestInfo test, int pass, int testNumber)
        {
            if (_showStatus)
            {
                Log("#@ Running {0} ({1})...\n", test.TestMethod.Name, Language.TwoLetterISOLanguageName);
            }

            if (_buildMode)
            {
                Log("{0,3}. {1,-46} ",
                    testNumber,
                    test.TestMethod.Name);
            }
            else
            {
                var time = DateTime.Now;
                Log("[{0}:{1}] {2,3}.{3,-3} {4,-46} ({5}) ",
                    time.Hour.ToString("D2"),
                    time.Minute.ToString("D2"),
                    pass,
                    testNumber,
                    test.TestMethod.Name,
                    Language.TwoLetterISOLanguageName);
            }

            Exception exception = null;
            var       stopwatch = new Stopwatch();

            stopwatch.Start();
            var  saveCulture    = Thread.CurrentThread.CurrentCulture;
            var  saveUICulture  = Thread.CurrentThread.CurrentUICulture;
            long crtLeakedBytes = 0;

            try
            {
                // Create test class.
                var testObject = Activator.CreateInstance(test.TestClassType);

                // Set the TestContext.
                TestContext.Properties["AccessInternet"]               = AccessInternet.ToString();
                TestContext.Properties["RunPerfTests"]                 = RunPerfTests.ToString();
                TestContext.Properties["TestSmallMolecules"]           = AddSmallMoleculeNodes.ToString();     // Add the magic small molecule test node to every document?
                TestContext.Properties["RunSmallMoleculeTestVersions"] = RunsSmallMoleculeVersions.ToString(); // Run the AsSmallMolecule version of tests when available?
                TestContext.Properties["LiveReports"]             = LiveReports.ToString();
                TestContext.Properties["TestName"]                = test.TestMethod.Name;
                TestContext.Properties["TestRunResultsDirectory"] =
                    Path.Combine(TestContext.TestDir, test.TestClassType.Name);

                if (test.SetTestContext != null)
                {
                    var context = new object[] { TestContext };
                    test.SetTestContext.Invoke(testObject, context);
                }

                // Switch to selected culture.
                LocalizationHelper.CurrentCulture = LocalizationHelper.CurrentUICulture = Language;
                LocalizationHelper.InitThread();

                // Run the test and time it.
                if (test.TestInitialize != null)
                {
                    test.TestInitialize.Invoke(testObject, null);
                }

                if (CheckCrtLeaks > 0)
                {
                    // TODO: CrtDebugHeap class used to be provided by Crawdad.dll
                    // If we ever want to enable this funcationality again, we need to find another .dll
                    // to put this in.
                    //CrtDebugHeap.Checkpoint();
                }
                test.TestMethod.Invoke(testObject, null);
                if (CheckCrtLeaks > 0)
                {
                    //crtLeakedBytes = CrtDebugHeap.DumpLeaks(true);
                }

                if (test.TestCleanup != null)
                {
                    test.TestCleanup.Invoke(testObject, null);
                }
            }
            catch (Exception e)
            {
                exception = e;
            }
            stopwatch.Stop();
            LastTestDuration = (int)(stopwatch.ElapsedMilliseconds / 1000);

            // Restore culture.
            Thread.CurrentThread.CurrentCulture   = saveCulture;
            Thread.CurrentThread.CurrentUICulture = saveUICulture;

            MemoryManagement.FlushMemory();
            _process.Refresh();
//            long[] heapCounts = MemoryManagement.GetProcessHeapSizes();
//            ManagedMemoryBytes = heapCounts[0]; // Process heap
            ManagedMemoryBytes   = GC.GetTotalMemory(true); // Managed heap
            TotalMemoryBytes     = _process.PrivateMemorySize64;
            LastTotalHandleCount = GetHandleCount(HandleType.total);
            LastUserHandleCount  = GetHandleCount(HandleType.user);
            LastGdiHandleCount   = GetHandleCount(HandleType.gdi);

            if (exception == null)
            {
                // Test succeeded.
                Log("{0,3} failures, {1:F2}/{2:F1} MB, {3}/{4} handles, {5} sec.\r\n",
                    FailureCount,
                    ManagedMemory,
                    TotalMemory,
                    LastUserHandleCount + LastGdiHandleCount,
                    LastTotalHandleCount,
                    LastTestDuration);
//                Log("# Heaps " + string.Join("\t", heapCounts.Select(s => string.Format("{0:F2}", s / (double) MB))) + "\r\n");
                if (crtLeakedBytes > CheckCrtLeaks)
                {
                    Log("!!! {0} CRT-LEAKED {1} bytes\r\n", test.TestMethod.Name, crtLeakedBytes);
                }

                using (var writer = new FileStream("TestRunnerMemory.log", FileMode.Append, FileAccess.Write, FileShare.Read))
                    using (var stringWriter = new StreamWriter(writer))
                    {
                        stringWriter.WriteLine(TotalMemory.ToString("F1"));
                    }
                return(true);
            }

            // Save failure information.
            FailureCount++;
            if (FailureCounts.ContainsKey(test.TestMethod.Name))
            {
                FailureCounts[test.TestMethod.Name]++;
            }
            else
            {
                FailureCounts[test.TestMethod.Name] = 1;
            }
            var message     = exception.InnerException == null ? exception.Message : exception.InnerException.Message;
            var stackTrace  = exception.InnerException == null ? exception.StackTrace : exception.InnerException.StackTrace;
            var failureInfo = "# " + test.TestMethod.Name + "FAILED:\n" +
                              message + "\n" +
                              stackTrace;

            if (ErrorCounts.ContainsKey(failureInfo))
            {
                ErrorCounts[failureInfo]++;
            }
            else
            {
                ErrorCounts[failureInfo] = 1;
            }

            Log("{0,3} failures, {1:F2}/{2:F1} MB, {3}/{4} handles, {5} sec.\r\n\r\n!!! {6} FAILED\r\n{7}\r\n{8}\r\n!!!\r\n\r\n",
                FailureCount,
                ManagedMemory,
                TotalMemory,
                LastUserHandleCount + LastGdiHandleCount,
                LastTotalHandleCount,
                LastTestDuration,
                test.TestMethod.Name,
                message,
                exception);
            return(false);
        }
예제 #12
0
    private async void Localization_Loaded(object sender, RoutedEventArgs e)
    {
        AddButton.IsEnabled    = false;
        SaveButton.IsEnabled   = false;
        RemoveButton.IsEnabled = false;
        DownButton.IsEnabled   = false;
        UpButton.IsEnabled     = false;
        OkButton.IsEnabled     = false;

        var actualIndex = 0;

        foreach (var resourceDictionary in Application.Current.Resources.MergedDictionaries)
        {
            //If it's not a localization resource, ignore it.
            if (resourceDictionary.Source?.OriginalString.Contains("StringResources") != true)
            {
                actualIndex++;
                continue;
            }

            var imageItem = new ExtendedListBoxItem
            {
                Content             = resourceDictionary.Source.OriginalString,
                Icon                = FindResource("Vector.Translate") as Brush,
                Index               = actualIndex++,
                ShowMarkOnSelection = false
            };

            #region Language code

            var pieces = resourceDictionary.Source.OriginalString.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            if (pieces.Length == 3 || pieces.Length == 4)
            {
                imageItem.Author = LocalizationHelper.GetWithFormat("S.Localization.Recognized", "Recognized as {0}", pieces[1]);
            }
            else
            {
                imageItem.Author = LocalizationHelper.Get("S.Localization.NotRecognized");
            }

            #endregion

            ResourceListBox.Items.Add(imageItem);
        }

        //Selects the last item on the list.
        ResourceListBox.SelectedItem = ResourceListBox.Items.Cast <ExtendedListBoxItem>().LastOrDefault(w => w.IsEnabled);

        if (ResourceListBox.SelectedItem != null)
        {
            ResourceListBox.ScrollIntoView(ResourceListBox.SelectedItem);
        }

        StatusBand.Info(LocalizationHelper.Get("S.Localization.GettingCodes"));

        _cultures = await GetProperCulturesAsync();

        AddButton.IsEnabled    = true;
        SaveButton.IsEnabled   = true;
        RemoveButton.IsEnabled = true;
        DownButton.IsEnabled   = true;
        UpButton.IsEnabled     = true;
        OkButton.IsEnabled     = true;

        StatusBand.Hide();
        SizeToContent = SizeToContent.Width;
        MaxHeight     = double.PositiveInfinity;

        CommandManager.InvalidateRequerySuggested();
    }
예제 #13
0
    private async void Add_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        var ofd = new OpenFileDialog
        {
            AddExtension    = true,
            CheckFileExists = true,
            Title           = LocalizationHelper.Get("S.Localization.OpenResource"),
            Filter          = LocalizationHelper.Get("S.Localization.File.Resource") + " (*.xaml)|*.xaml;"
        };

        var result = ofd.ShowDialog();

        if (!result.HasValue || !result.Value)
        {
            return;
        }

        #region Validations

        var position = ofd.FileName.IndexOf("StringResources", StringComparison.InvariantCulture);
        var subs     = position > -1 ? ofd.FileName.Substring(position) : "";
        var pieces   = subs.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

        //Wrong filename format.
        if (position < 0 || pieces.Length != 3)
        {
            Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Name"), LocalizationHelper.Get("S.Localization.Warning.Name.Info"));
            StatusBand.Hide();
            return;
        }

        //Repeated language code.
        if (Application.Current.Resources.MergedDictionaries.Any(x => x.Source != null && x.Source.OriginalString.Contains(subs)))
        {
            Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Repeated"), LocalizationHelper.Get("S.Localization.Warning.Repeated.Info"));
            StatusBand.Hide();
            return;
        }

        try
        {
            var properCulture = await Task.Factory.StartNew(() => CheckSupportedCulture(pieces[1]));

            if (properCulture != pieces[1])
            {
                Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Redundant"), LocalizationHelper.GetWithFormat("S.Localization.Warning.Redundant.Info",
                                                                                                                              "The \"{0}\" code is redundant. Try using \"{1}\" instead.", pieces[1], properCulture));
                StatusBand.Hide();
                return;
            }
        }
        catch (CultureNotFoundException cn)
        {
            LogWriter.Log(cn, "Impossible to validade the resource name, culture not found");
            Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.Unknown"), LocalizationHelper.GetWithFormat("S.Localization.Warning.Unknown.Info",
                                                                                                                        "The \"{0}\" and its family were not recognized as valid language codes.", pieces[1]));
            StatusBand.Hide();
            return;
        }
        catch (Exception ex)
        {
            LogWriter.Log(ex, "Impossible to validade the resource name");
            Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.NotPossible"), ex.Message);
            StatusBand.Hide();
            return;
        }

        #endregion

        StatusBand.Info(LocalizationHelper.Get("S.Localization.Importing"));

        try
        {
            var fileName = ofd.FileName;

            await Task.Factory.StartNew(() => LocalizationHelper.ImportStringResource(fileName));
        }
        catch (Exception ex)
        {
            LogWriter.Log(ex, "Impossible to import the resource");
            Dialog.Ok(Title, LocalizationHelper.Get("S.Localization.Warning.NotPossible"), ex.Message);
            StatusBand.Hide();
            return;
        }

        var resourceDictionary = Application.Current.Resources.MergedDictionaries.LastOrDefault();

        var imageItem = new ExtendedListBoxItem
        {
            Content             = resourceDictionary?.Source.OriginalString ?? "...",
            Icon                = FindResource("Vector.Translate") as Brush,
            Author              = LocalizationHelper.GetWithFormat("S.Localization.Recognized", "Recognized as {0}", pieces[1]),
            Index               = Application.Current.Resources.MergedDictionaries.Count - 1,
            ShowMarkOnSelection = false
        };

        StatusBand.Hide();

        ResourceListBox.Items.Add(imageItem);
        ResourceListBox.ScrollIntoView(imageItem);

        UpdateIndexes();

        CommandManager.InvalidateRequerySuggested();
    }
예제 #14
0
        /// <summary>
        /// Method that starts or pauses the recording
        /// </summary>
        private void RecordPause()
        {
            switch (Stage)
            {
            case Stage.Stopped:

                #region To Record

                _capture = new Timer {
                    Interval = 1000 / FpsNumericUpDown.Value
                };

                Project?.Clear();
                Project = new ProjectInfo().CreateProjectFolder(ProjectByType.BoardRecorder);

                HeightIntegerBox.IsEnabled = false;
                WidthIntegerBox.IsEnabled  = false;
                FpsNumericUpDown.IsEnabled = false;

                IsRecording = true;
                Topmost     = true;

                FrameRate.Start(_capture.Interval);

                #region Start

                //if (!Settings.Default.Snapshot)
                //{
                #region Normal Recording

                _capture.Tick += Normal_Elapsed;
                //Normal_Elapsed(null, null);
                _capture.Start();

                Stage = Stage.Recording;

                AutoFitButtons();

                #endregion
                //}
                //else
                //{
                //    #region SnapShot Recording

                //    Stage = Stage.Snapping;
                //    //Title = "Board Recorder - " + Properties.Resources.Con_SnapshotMode;

                //    AutoFitButtons();

                //    #endregion
                //}

                break;

                #endregion

                #endregion

            case Stage.Recording:

                #region To Pause

                Stage = Stage.Paused;
                Title = LocalizationHelper.Get("S.Recorder.Paused");

                AutoFitButtons();

                _capture.Stop();

                FrameRate.Stop();
                break;

                #endregion

            case Stage.Paused:

                #region To Record Again

                Stage = Stage.Recording;
                Title = LocalizationHelper.Get("S.Board.Title");

                AutoFitButtons();

                FrameRate.Start(_capture.Interval);

                _capture.Start();
                break;

                #endregion

            case Stage.Snapping:

                #region Take Screenshot (All possibles types)

                Normal_Elapsed(null, null);

                break;

                #endregion
            }
        }
예제 #15
0
        public override object GetObject()
        {
            var generalSettings      = DependencyResolver.Resolve <GeneralSettings>();
            var catalogSettings      = DependencyResolver.Resolve <CatalogSettings>();
            var orderSettings        = DependencyResolver.Resolve <OrderSettings>();
            var urlSettings          = DependencyResolver.Resolve <UrlSettings>();
            var gdprSettings         = DependencyResolver.Resolve <GdprSettings>();
            var localizationSettings = DependencyResolver.Resolve <LocalizationSettings>();
            var securitySettings     = DependencyResolver.Resolve <SecuritySettings>();
            var vendorSettings       = DependencyResolver.Resolve <VendorSettings>();
            var affiliateSettings    = DependencyResolver.Resolve <AffiliateSettings>();

            var mediaAccountant = DependencyResolver.Resolve <IMediaAccountant>();
            var categoryService = DependencyResolver.Resolve <ICategoryService>();
            var antiforgery     = DependencyResolver.Resolve <IAntiforgery>();
            var currencyService = DependencyResolver.Resolve <ICurrencyService>();

            var categories = categoryService.Get(x => x.ParentId == 0).ToList();
            var logoUrl    = generalSettings.LogoId > 0
                ? mediaAccountant.GetPictureUrl(generalSettings.LogoId)
                : ApplicationEngine.MapUrl(ApplicationConfig.DefaultLogoUrl, true);
            var faviconUrl = generalSettings.LogoId > 0
                ? mediaAccountant.GetPictureUrl(generalSettings.FaviconId)
                : ApplicationEngine.MapUrl(ApplicationConfig.DefaultFaviconUrl, true);
            var categoryDefaultName =
                LocalizationHelper.Localize("All Categories", ApplicationEngine.CurrentLanguageCultureCode);
            var store = new StoreImplementation()
            {
                Url   = WebHelper.GetUrlFromPath("/", generalSettings.StoreDomain, urlSettings.GetUrlProtocol()),
                Name  = generalSettings.StoreName,
                Theme = new ThemeImplementation()
                {
                    Name = generalSettings.ActiveTheme,
                    Url  = WebHelper.GetUrlFromPath("/default", generalSettings.StoreDomain, urlSettings.GetUrlProtocol()),
                },
                LogoUrl                   = logoUrl,
                FaviconUrl                = faviconUrl,
                CurrentPage               = ApplicationEngine.GetActiveRouteName(),
                CurrentUrl                = ApplicationEngine.CurrentHttpContext.Request.GetDisplayUrl(),
                Categories                = SelectListHelper.GetSelectItemList(categories, x => x.Id, x => x.Name, categoryDefaultName),
                WishlistEnabled           = orderSettings.EnableWishlist,
                RepeatOrdersEnabled       = orderSettings.AllowReorder,
                ReviewsEnabled            = catalogSettings.EnableReviews,
                ReviewModificationAllowed = catalogSettings.AllowReviewModification,
                ActiveCurrencyCode        = ApplicationEngine.CurrentCurrency.IsoCode,
                PrimaryCurrencyCode       = currencyService.Get(localizationSettings.BaseCurrencyId)?.IsoCode,
                ActiveCurrencySymbol      = ApplicationEngine.CurrentCurrency.GetSymbol(),
                XsrfToken                 = antiforgery.GetToken(),
                SoftwareVersion           = AppVersionEvaluator.Version,
                SoftwareTitle             = ApplicationConfig.AppName,
                HoneypotFieldName         = securitySettings.HoneypotFieldName,
                VendorSignupEnabled       = vendorSettings.EnableVendorSignup,
                VendorsEnabled            = vendorSettings.EnableVendorSignup
            };

            var currentUser = ApplicationEngine.CurrentUser;

            if (affiliateSettings.EnableAffiliates && currentUser.IsActiveAffiliate())
            {
                store.AffiliateUrl = store.CurrentPage == RouteNames.SingleProduct ? currentUser.GetAffiliateUrl(store.CurrentUrl) : currentUser.GetAffiliateUrl();
            }
            if (!ApplicationEngine.CurrentHttpContext.IsTokenAuthenticated() && gdprSettings.ShowCookiePopup && !currentUser.IsAdministrator())
            {
                store.CookiePopupText = gdprSettings.CookiePopupText;
                store.UseConsentGroup = gdprSettings.UseConsentGroup;
                //if there was no consent provided, we show the popup
                store.ShowCookieConsent = CookieHelper.GetRequestCookie(ApplicationConfig.ConsentCookieName).IsNullEmptyOrWhiteSpace();
                if (gdprSettings.ConsentGroupId > 0 && gdprSettings.UseConsentGroup)
                {
                    var consentGroupService = DependencyResolver.Resolve <IConsentGroupService>();
                    var gdprService         = DependencyResolver.Resolve <IGdprService>();
                    var consentGroup        = consentGroupService.GetWithConsents(gdprSettings.ConsentGroupId);
                    if (consentGroup != null)
                    {
                        //has user already consented?
                        var consented = currentUser != null && gdprService.AreConsentsActedUpon(currentUser.Id,
                                                                                                consentGroup.Consents.Select(x => x.Id).ToArray());
                        store.ShowCookieConsent = store.ShowCookieConsent && !consented;
                        if (store.ShowCookieConsent)
                        {
                            store.ConsentGroup = new ConsentGroupImplementation()
                            {
                                Name        = consentGroup.Name,
                                Description = consentGroup.Description,
                                Consents    = new List <ConsentImplementation>()
                            };
                            foreach (var consent in consentGroup.Consents)
                            {
                                store.ConsentGroup.Consents.Add(new ConsentImplementation()
                                {
                                    Description = consent.Description,
                                    Title       = consent.Title,
                                    IsRequired  = consent.IsRequired,
                                    Id          = consent.Id
                                });
                            }
                        }
                    }
                    else
                    {
                        //no need to use consent group..it's null anyways
                        store.UseConsentGroup = false;
                    }
                }
            }

            return(store);
        }
        protected void UpdatePlayerConfigurationMenu()
        {
            // Some updates could be avoided if we tracked a "dirty" flag and break execution if !dirty
            lock (_syncObj)
            {
                IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
                IPlayerManager        playerManager        = ServiceRegistration.Get <IPlayerManager>();
                int numActivePlayers = playerContextManager.NumActivePlayerContexts;
                int slotNo           = 0;
                IList <IPlayerContext> playerContexts = playerContextManager.PlayerContexts;
                IList <string>         playerNames    = new List <string>(playerContexts.Select(pc => GetNameForPlayerContext(pc, slotNo++)));

                _playerConfigurationMenu.Clear();
                // Change player focus
                if (numActivePlayers > 1)
                {
                    // Set player focus
                    int    newCurrentPlayer = 1 - playerContextManager.CurrentPlayerIndex;
                    string name             = playerNames[newCurrentPlayer];
                    if (name != null)
                    {
                        ListItem item = new ListItem(Consts.KEY_NAME, LocalizationHelper.CreateResourceString(Consts.RES_FOCUS_PLAYER).Evaluate(name))
                        {
                            Command = new MethodDelegateCommand(() => SetCurrentPlayer(newCurrentPlayer))
                        };
                        item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                        _playerConfigurationMenu.Add(item);
                    }
                }
                // Switch players
                if (numActivePlayers > 1 && playerContextManager.IsPipActive)
                {
                    ListItem item = new ListItem(Consts.KEY_NAME, Consts.RES_SWITCH_PIP_PLAYERS)
                    {
                        Command = new MethodDelegateCommand(SwitchPrimarySecondaryPlayer)
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                    _playerConfigurationMenu.Add(item);
                }
                // Change geometry
                IList <IPlayerContext> videoPCs = new List <IPlayerContext>();
                for (int i = 0; i < numActivePlayers; i++)
                {
                    IPlayerContext pc = playerContextManager.GetPlayerContext(i);
                    if (pc != null && pc.CurrentPlayer is IVideoPlayer)
                    {
                        videoPCs.Add(pc);
                    }
                }
                for (int i = 0; i < videoPCs.Count; i++)
                {
                    IPlayerContext pc        = videoPCs[i];
                    string         geometry  = LocalizationHelper.CreateResourceString(Consts.RES_CHOOSE_PLAYER_GEOMETRY).Evaluate();
                    string         entryName = videoPCs.Count > 1 ?
                                               string.Format("{0} ({1})", geometry, GetNameForPlayerContext(pc, i)) : geometry;
                    ListItem item = new ListItem(Consts.KEY_NAME, entryName)
                    {
                        Command = new MethodDelegateCommand(() => OpenChooseGeometryDialog(pc))
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.SuccessorDialog;
                    _playerConfigurationMenu.Add(item);
                }
                // Change rendering effect
                for (int i = 0; i < videoPCs.Count; i++)
                {
                    IPlayerContext pc        = videoPCs[i];
                    string         effect    = LocalizationHelper.CreateResourceString(Consts.RES_CHOOSE_PLAYER_EFFECT).Evaluate();
                    string         entryName = videoPCs.Count > 1 ?
                                               string.Format("{0} ({1})", effect, GetNameForPlayerContext(pc, i)) : effect;
                    ListItem item = new ListItem(Consts.KEY_NAME, entryName)
                    {
                        Command = new MethodDelegateCommand(() => OpenChooseEffectDialog(pc))
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.SuccessorDialog;
                    _playerConfigurationMenu.Add(item);
                }
                // Audio streams
                AudioStreamDescriptor currentAudioStream;
                ICollection <AudioStreamDescriptor> audioStreams = playerContextManager.GetAvailableAudioStreams(out currentAudioStream);
                if (audioStreams.Count > 1)
                {
                    ListItem item = new ListItem(Consts.KEY_NAME, Consts.RES_CHOOSE_AUDIO_STREAM)
                    {
                        Command = new MethodDelegateCommand(OpenChooseAudioStreamDialog)
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.SuccessorDialog;
                    _playerConfigurationMenu.Add(item);
                }
                // Mute
                if (numActivePlayers > 0)
                {
                    ListItem item;
                    if (playerManager.Muted)
                    {
                        item = new ListItem(Consts.KEY_NAME, Consts.RES_MUTE_OFF)
                        {
                            Command = new MethodDelegateCommand(PlayersResetMute)
                        }
                    }
                    ;
                    else
                    {
                        item = new ListItem(Consts.KEY_NAME, Consts.RES_MUTE)
                        {
                            Command = new MethodDelegateCommand(PlayersMute)
                        }
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                    _playerConfigurationMenu.Add(item);
                }
                // Close player
                for (int i = 0; i < numActivePlayers; i++)
                {
                    string         name = playerNames[i];
                    IPlayerContext pc   = playerContexts[i];
                    if (name != null)
                    {
                        ListItem item = new ListItem(Consts.KEY_NAME, LocalizationHelper.CreateResourceString(Consts.RES_CLOSE_PLAYER_CONTEXT).Evaluate(name))
                        {
                            Command = new MethodDelegateCommand(pc.Close)
                        };
                        _playerConfigurationMenu.Add(item);
                    }
                }
                _playerConfigurationMenu.FireChange();
            }
        }
        protected static WorkflowAction LoadPopNavigationTransition(XPathNavigator actionNav)
        {
            string         id              = null;
            string         name            = null;
            string         displayTitle    = null;
            string         displayCategory = null;
            string         sortOrder       = null;
            string         sourceStates    = null;
            int            numPop          = -1;
            XPathNavigator attrNav         = actionNav.Clone();

            if (attrNav.MoveToFirstAttribute())
            {
                do
                {
                    switch (attrNav.Name)
                    {
                    case "Id":
                        id = attrNav.Value;
                        break;

                    case "Name":
                        name = attrNav.Value;
                        break;

                    case "DisplayCategory":
                        displayCategory = attrNav.Value;
                        break;

                    case "SortOrder":
                        sortOrder = attrNav.Value;
                        break;

                    case "SourceStates":
                        sourceStates = attrNav.Value;
                        break;

                    case "NumPop":
                        if (!Int32.TryParse(attrNav.Value, out numPop))
                        {
                            throw new ArgumentException("'NumPop' attribute value must be a positive integer");
                        }
                        break;

                    case "DisplayTitle":
                        displayTitle = attrNav.Value;
                        break;

                    default:
                        throw new ArgumentException("'" + actionNav.Name + "' element doesn't support an attribute '" + attrNav.Name + "'");
                    }
                } while (attrNav.MoveToNextAttribute());
            }
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(string.Format("{0} '{1}': Id attribute is missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(string.Format("{0} with id '{1}': 'Name' attribute missing", actionNav.Name, id));
            }
            if (string.IsNullOrEmpty(sourceStates))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'SourceStates' attribute missing", actionNav.Name, name));
            }
            if (numPop == -1)
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'NumPop' attribute missing", actionNav.Name, name));
            }
            PopNavigationTransition result = new PopNavigationTransition(new Guid(id), name, ParseActionSourceStates(sourceStates),
                                                                         LocalizationHelper.CreateResourceString(displayTitle), numPop)
            {
                DisplayCategory = displayCategory,
                SortOrder       = sortOrder
            };

            return(result);
        }
        protected void UpdatePlayerSlotAudioMenu()
        {
            // Some updates could be avoided if we tracked a "dirty" flag and break execution if !dirty
            lock (_syncObj)
            {
                IPlayerManager        playerManager        = ServiceRegistration.Get <IPlayerManager>();
                IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();

                _playerSlotAudioMenu.Clear();
                IPlayerContext pc = _playerAudioMenuPlayerContext;
                if (pc == null || !pc.IsActive)
                {
                    LeaveAudioMenuWorkflow();
                    return;
                }
                IPlayer player = pc.CurrentPlayer;
                AudioStreamDescriptor         currentAudioStream;
                IList <AudioStreamDescriptor> asds = new List <AudioStreamDescriptor>(pc.GetAudioStreamDescriptors(out currentAudioStream));
                foreach (AudioStreamDescriptor asd in asds)
                {
                    string playedItem = player == null ? null : player.MediaItemTitle ?? pc.Name;
                    string choiceItemName;
                    if (asds.Count > 1)
                    {
                        // Only display the audio stream name if the player has more than one audio stream
                        choiceItemName = playedItem + ": " + asd.AudioStreamName;
                    }
                    else
                    {
                        choiceItemName = playedItem;
                    }
                    AudioStreamDescriptor asdClosureCopy = asd;
                    ListItem item = new ListItem(Consts.KEY_NAME, choiceItemName)
                    {
                        Command  = new MethodDelegateCommand(() => ChooseAudioStream(asdClosureCopy)),
                        Selected = asd == currentAudioStream,
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                    _playerSlotAudioMenu.Add(item);
                }
                if (_showToggleMute)
                {
                    ListItem item;
                    if (playerManager.Muted)
                    {
                        item = new ListItem(Consts.KEY_NAME, Consts.RES_MUTE_OFF)
                        {
                            Command  = new MethodDelegateCommand(PlayersResetMute),
                            Selected = true,
                        }
                    }
                    ;
                    else
                    {
                        item = new ListItem(Consts.KEY_NAME, Consts.RES_MUTE)
                        {
                            Command = new MethodDelegateCommand(PlayersMute)
                        }
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                    _playerSlotAudioMenu.Add(item);
                }

                IList <IPlayerContext> playerContexts = playerContextManager.PlayerContexts.ToList();
                _playerSlotAudioMenu.FireChange();
                _playerSlotAudioMenuHeader = LocalizationHelper.CreateResourceString(Consts.RES_PLAYER_SLOT_AUDIO_MENU).Evaluate(
                    GetNameForPlayerContext(_playerAudioMenuPlayerContext, playerContexts.IndexOf(_playerAudioMenuPlayerContext)));
            }
        }
예제 #19
0
        private async Task CheckOnFosshub()
        {
            try
            {
                var proxy   = WebHelper.GetProxy();
                var handler = new HttpClientHandler
                {
                    Proxy    = proxy,
                    UseProxy = proxy != null,
                };

                using (var client = new HttpClient(handler)
                {
                    BaseAddress = new Uri("https://www.fosshub.com")
                })
                {
                    using (var response = await client.GetAsync("/feed/5bfc6fce8c9fe8186f809d24.json"))
                    {
                        var result = await response.Content.ReadAsStringAsync();

                        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(result)))
                        {
                            var ser = new DataContractJsonSerializer(typeof(FosshubResponse));
                            var obj = ser.ReadObject(ms) as FosshubResponse;

                            if (obj?.Release == null)
                            {
                                return;
                            }

                            var version = Version.Parse(obj.Release.Items[0].Version ?? "0.1");

                            if (version.Major == 0 || version <= Assembly.GetExecutingAssembly().GetName().Version)
                            {
                                return;
                            }

                            Global.UpdateAvailable = new UpdateAvailable
                            {
                                IsFromGithub         = false,
                                Version              = version,
                                PortableDownloadUrl  = obj.Release.Items.FirstOrDefault(f => f.Title.EndsWith(".zip"))?.Link,
                                InstallerDownloadUrl = obj.Release.Items.FirstOrDefault(f => f.Title.EndsWith(".msi"))?.Link,
                            };

                            //With Fosshub, the download must be manual.
                            Application.Current.Dispatcher?.BeginInvoke(new Action(() => NotificationManager.AddNotification(string.Format(LocalizationHelper.Get("S.Updater.NewRelease.Info"), Global.UpdateAvailable.Version), StatusType.Update, "update", PromptUpdate)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to check for updates on Fosshub");
            }
            finally
            {
                GC.Collect();
            }
        }
예제 #20
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            #region Unhandled Exceptions

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            #endregion

            #region Arguments

            try
            {
                if (e.Args.Length > 0)
                {
                    Argument.Prepare(e.Args);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Generic Exception - Arguments");

                ErrorDialog.Ok("ScreenToGif", "Generic error - arguments", ex.Message, ex);
            }

            #endregion

            #region Language

            try
            {
                LocalizationHelper.SelectCulture(UserSettings.All.LanguageCode);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Language Settings Exception.");

                ErrorDialog.Ok("ScreenToGif", "Generic error - language", ex.Message, ex);
            }

            #endregion

            #region Net Framework

            var array  = Type.GetType("System.Array");
            var method = array?.GetMethod("Empty");

            if (array == null || method == null)
            {
                var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the web page to download?");

                if (ask)
                {
                    Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
                    return;
                }
            }

            //try
            //{
            //    //If there's no Array.Empty, means that there's no .Net Framework 4.6.1
            //    //This is not the best way...
            //    Array.Empty<int>();
            //}
            //catch (MissingMethodException ex)
            //{
            //    var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the web page to download?");

            //    if (ask)
            //    {
            //        Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
            //        return;
            //    }

            //    LogWriter.Log(ex, "Missing .Net Framework 4.6.1");
            //}

            //if (Environment.Version.Build < 30319 && Environment.Version.Revision < 42000)
            //{
            //    var ask = Dialog.Ask("Missing Dependency", "Net Framework 4.6.1 is not present", "In order to properly use this app, you need to download the correct version of the .Net Framework. Open the page to download?");

            //    if (ask)
            //    {
            //        Process.Start("https://www.microsoft.com/en-us/download/details.aspx?id=49981");
            //        return;
            //    }
            //}

            #endregion

            //var select = new RecorderNew();
            //var select = new SelectFolderDialog();
            //var select = new TestField();
            //var select = new Encoder();
            //select.ShowDialog(); return;

            try
            {
                #region Startup

                if (UserSettings.All.StartUp == 0)
                {
                    var startup = new Startup();
                    Current.MainWindow = startup;
                    startup.ShowDialog();
                }
                else if (UserSettings.All.StartUp == 4 || Argument.FileNames.Any())
                {
                    var edit = new Editor();
                    Current.MainWindow = edit;
                    edit.ShowDialog();
                }
                else
                {
                    var         editor  = new Editor();
                    ProjectInfo project = null;
                    var         exitArg = ExitAction.Exit;
                    bool?       result  = null;

                    #region Recorder, Webcam or Border

                    switch (UserSettings.All.StartUp)
                    {
                    case 1:
                        if (UserSettings.All.NewRecorder)
                        {
                            var recNew = new RecorderNew(true);
                            Current.MainWindow = recNew;

                            result  = recNew.ShowDialog();
                            exitArg = recNew.ExitArg;
                            project = recNew.Project;
                            break;
                        }

                        var rec = new Recorder(true);
                        Current.MainWindow = rec;

                        result  = rec.ShowDialog();
                        exitArg = rec.ExitArg;
                        project = rec.Project;
                        break;

                    case 2:
                        var web = new Windows.Webcam(true);
                        Current.MainWindow = web;

                        result  = web.ShowDialog();
                        exitArg = web.ExitArg;
                        project = web.Project;
                        break;

                    case 3:
                        var board = new Board();
                        Current.MainWindow = board;

                        result  = board.ShowDialog();
                        exitArg = board.ExitArg;
                        project = board.Project;
                        break;
                    }

                    #endregion

                    if (result.HasValue && result.Value)
                    {
                        #region If Close

                        Environment.Exit(0);

                        #endregion
                    }
                    else if (result.HasValue)
                    {
                        #region If Backbutton or Stop Clicked

                        if (exitArg == ExitAction.Recorded)
                        {
                            editor.Project     = project;
                            Current.MainWindow = editor;
                            editor.ShowDialog();
                        }

                        #endregion
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Generic Exception - Root");

                ErrorDialog.Ok("ScreenToGif", "Generic error", ex.Message, ex);
            }
        }
예제 #21
0
        private async Task <bool> CheckOnGithub()
        {
            try
            {
                //If the app was installed by Chocolatey, avoid this.
                if (AppDomain.CurrentDomain.BaseDirectory.EndsWith(@"Chocolatey\lib\screentogif\content\"))
                {
                    return(true);
                }

                #region GraphQL equivalent

                //query {
                //    repository(owner: "NickeManarin", name: "ScreenToGif") {
                //        releases(first: 1, orderBy: { field: CREATED_AT, direction: DESC}) {
                //            nodes {
                //                name
                //                tagName
                //                createdAt
                //                url
                //                isPrerelease
                //                description
                //                releaseAssets(last: 2) {
                //                    nodes {
                //                        name
                //                        downloadCount
                //                        downloadUrl
                //                        size
                //                    }
                //                }
                //            }
                //        }
                //    }
                //}

                #endregion

                var request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/NickeManarin/ScreenToGif/releases/latest");
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393";
                request.Proxy     = WebHelper.GetProxy();

                var response = (HttpWebResponse)await request.GetResponseAsync();

                using (var resultStream = response.GetResponseStream())
                {
                    if (resultStream == null)
                    {
                        return(false);
                    }

                    using (var reader = new StreamReader(resultStream))
                    {
                        var result = await reader.ReadToEndAsync();

                        var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(result), new System.Xml.XmlDictionaryReaderQuotas());
                        var release    = XElement.Load(jsonReader);

                        var version = Version.Parse(release.XPathSelectElement("tag_name")?.Value ?? "0.1");

                        if (version.Major == 0 || version <= Assembly.GetExecutingAssembly().GetName().Version)
                        {
                            return(true);
                        }

                        Global.UpdateAvailable = new UpdateAvailable
                        {
                            Version              = version,
                            Description          = release.XPathSelectElement("body")?.Value ?? "",
                            PortableDownloadUrl  = release.XPathSelectElement("assets/item[1]/browser_download_url")?.Value ?? "",
                            PortableSize         = Convert.ToInt64(release.XPathSelectElement("assets/item[1]/size")?.Value ?? "0"),
                            InstallerDownloadUrl = release.XPathSelectElement("assets/item[2]/browser_download_url")?.Value ?? "",
                            InstallerSize        = Convert.ToInt64(release.XPathSelectElement("assets/item[2]/size")?.Value ?? "0"),
                            InstallerName        = release.XPathSelectElement("assets/item[2]/name")?.Value ?? "ScreenToGif.Setup.msi",
                        };

                        Application.Current.Dispatcher?.BeginInvoke(new Action(() => NotificationManager.AddNotification(string.Format(LocalizationHelper.Get("S.Updater.NewRelease.Info"),
                                                                                                                                       Global.UpdateAvailable.Version), StatusType.Update, "update", PromptUpdate)));

                        //Download update to be installed when the app closes.
                        if (UserSettings.All.InstallUpdates && !string.IsNullOrEmpty(Global.UpdateAvailable.InstallerDownloadUrl))
                        {
                            await DownloadUpdate();
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to check for updates on Github");
                return(false);
            }
            finally
            {
                GC.Collect();
            }
        }
예제 #22
0
 public virtual void SetMetadata(ConfigBaseMetadata metadata)
 {
     _metadata        = metadata;
     _text            = LocalizationHelper.CreateResourceString(_metadata.Text);
     RestrictionGroup = metadata.RestrictionGroup;
 }
예제 #23
0
        private async void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            StatusBand.Hide();

            if (EncodingManager.Encodings.Any(a => a.Status == Status.Processing))
            {
                StatusBand.Warning(LocalizationHelper.Get("S.Updater.Warning.Encoding"));
                return;
            }

            DownloadButton.IsEnabled = false;
            StatusBand.Info(LocalizationHelper.Get("S.Updater.Downloading"));

            //If it's still downloading, wait for it to finish.
            if (Global.UpdateAvailable.IsDownloading)
            {
                Global.UpdateAvailable.TaskCompletionSource = new TaskCompletionSource <bool>();
                await Global.UpdateAvailable.TaskCompletionSource.Task;

                if (!IsLoaded)
                {
                    return;
                }
            }

            //If update already downloaded, simply close this window. The installation will happen afterwards.
            if (File.Exists(Global.UpdateAvailable.ActivePath))
            {
                GC.Collect();
                DialogResult = true;
                return;
            }

            //When the update was not queried from Github, the download must be done by browser.
            if (!Global.UpdateAvailable.IsFromGithub)
            {
                try
                {
                    Process.Start(Global.UpdateAvailable.ActiveDownloadUrl);
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Impossible to open the browser to download the update.", Global.UpdateAvailable?.ActiveDownloadUrl);
                }

                GC.Collect();
                DialogResult = true;
                return;
            }

            DownloadProgressBar.Visibility   = Visibility.Visible;
            RunAfterwardsCheckBox.Visibility = Visibility.Collapsed;

            var result = await Task.Run(async() => await App.MainViewModel.DownloadUpdate());

            //If cancelled.
            if (!IsLoaded)
            {
                return;
            }

            if (!result)
            {
                DownloadButton.IsEnabled       = true;
                DownloadProgressBar.Visibility = Visibility.Hidden;
                StatusBand.Error(LocalizationHelper.Get("S.Updater.Warning.Download"));
                return;
            }

            //If the update was downloaded successfully, close this window to run.
            if (File.Exists(Global.UpdateAvailable.ActivePath))
            {
                GC.Collect();
                StatusBand.Hide();
                DialogResult = true;
                return;
            }

            StatusBand.Error(LocalizationHelper.Get("S.Updater.Warning.Download"));
        }
 public static void SetItemName(this ItemMaster itemMaster, string newIdentifier, string name)
 {
     LocalizationHelper.AddTermData(newIdentifier, name);
     itemMaster.name    = name;
     itemMaster.nameKey = newIdentifier;
 }
예제 #25
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Global.StartupDateTime = DateTime.Now;

            //Unhandled Exceptions.
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.AssemblyResolve    += CurrentDomain_AssemblyResolve;

            //Increases the duration of the tooltip display.
            ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(int.MaxValue));

            if (UserSettings.All.WorkaroundQuota)
            {
                BaseCompatibilityPreferences.HandleDispatcherRequestProcessingFailure = BaseCompatibilityPreferences.HandleDispatcherRequestProcessingFailureOptions.Reset;
            }

            #region Set network connection properties

            try
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to set the network properties");
            }

            #endregion

            //Parse arguments.
            if (e.Args.Length > 0)
            {
                Argument.Prepare(e.Args);
            }

            LocalizationHelper.SelectCulture(UserSettings.All.LanguageCode);
            ThemeHelper.SelectTheme(UserSettings.All.MainTheme.ToString());

            #region If set, it allows only one instance per user

            //The singleton works on a per-user and per-executable mode.
            //Meaning that a different user and/or a different executable intances can co-exist.
            //Part of this code wont work on debug mode, since the SetForegroundWindow() needs focus on the foreground window calling the method.
            if (UserSettings.All.SingleInstance)
            {
                try
                {
                    using (var thisProcess = Process.GetCurrentProcess())
                    {
                        var user      = System.Security.Principal.WindowsIdentity.GetCurrent().User;
                        var name      = thisProcess.MainModule?.FileName ?? Assembly.GetEntryAssembly()?.Location ?? "ScreenToGif";
                        var location  = Convert.ToBase64String(Encoding.UTF8.GetBytes(name));
                        var mutexName = (user?.Value ?? Environment.UserName) + "_" + location;

                        _mutex = new Mutex(true, mutexName, out _accepted);

                        //If the mutext failed to be accepted, it means that another process already openned it.
                        if (!_accepted)
                        {
                            var warning = true;

                            //Switch to the other app (get only one, if multiple available). Use name of assembly.
                            using (var process = Process.GetProcessesByName(thisProcess.ProcessName).FirstOrDefault(f => f.MainWindowHandle != thisProcess.MainWindowHandle))
                            {
                                if (process != null)
                                {
                                    var handles = Native.GetWindowHandlesFromProcess(process);

                                    //Show the window before setting focus.
                                    Native.ShowWindow(handles.Count > 0 ? handles[0] : process.Handle, Native.ShowWindowEnum.Show);

                                    //Set user the focus to the window.
                                    Native.SetForegroundWindow(handles.Count > 0 ? handles[0] : process.Handle);
                                    warning = false;
                                }
                            }

                            //If no window available (app is in the system tray), display a warning.
                            if (warning)
                            {
                                Dialog.Ok(LocalizationHelper.Get("S.Warning.Single.Title"), LocalizationHelper.Get("S.Warning.Single.Header"), LocalizationHelper.Get("S.Warning.Single.Message"), Icons.Info);
                            }

                            Environment.Exit(0);
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log(ex, "Impossible to check if another instance is running");
                }
            }

            #endregion

            //Render mode.
            RenderOptions.ProcessRenderMode = UserSettings.All.DisableHardwareAcceleration ? RenderMode.SoftwareOnly : RenderMode.Default;

            #region Net Framework

            if (!FrameworkHelper.HasFramework())
            {
                var ask = Dialog.Ask(LocalizationHelper.Get("S.Warning.Net.Title"), LocalizationHelper.Get("S.Warning.Net.Header"), LocalizationHelper.Get("S.Warning.Net.Message"));

                if (ask)
                {
                    Process.Start("http://go.microsoft.com/fwlink/?LinkId=2085155");
                    return;
                }
            }

            #endregion

            #region Net Framework HotFixes

            //Only runs on Windows 7 SP1.
            if (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        var search = new ManagementObjectSearcher("SELECT HotFixID FROM Win32_QuickFixEngineering WHERE HotFixID = 'KB4055002'").Get();
                        Global.IsHotFix4055002Installed = search.Count > 0;
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Log(ex, "Error while trying to know if a hot fix was installed.");
                    }
                });
            }

            #endregion

            #region Tray icon and view model

            NotifyIcon = (NotifyIcon)FindResource("NotifyIcon");

            if (NotifyIcon != null)
            {
                NotifyIcon.Visibility = UserSettings.All.ShowNotificationIcon || UserSettings.All.StartMinimized || UserSettings.All.StartUp == 5 ? Visibility.Visible : Visibility.Collapsed;

                //Replace the old option with the new setting.
                if (UserSettings.All.StartUp == 5)
                {
                    UserSettings.All.StartMinimized       = true;
                    UserSettings.All.ShowNotificationIcon = true;
                    UserSettings.All.StartUp = 0;
                }

                //using (var iconStream = GetResourceStream(new Uri("pack://application:,,,/Resources/Logo.ico"))?.Stream)
                //{
                //    if (iconStream != null)
                //        NotifyIcon.Icon = new System.Drawing.Icon(iconStream);
                //}
            }

            MainViewModel = (ApplicationViewModel)FindResource("AppViewModel") ?? new ApplicationViewModel();

            RegisterShortcuts();

            #endregion

            //var select = new SelectFolderDialog(); select.ShowDialog(); return;
            //var select = new TestField(); select.ShowDialog(); return;
            //var select = new Encoder(); select.ShowDialog(); return;
            //var select = new EditorEx(); select.ShowDialog(); return;

            #region Tasks

            Task.Factory.StartNew(MainViewModel.ClearTemporaryFiles, TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(MainViewModel.CheckForUpdates, TaskCreationOptions.LongRunning);
            Task.Factory.StartNew(MainViewModel.SendFeedback, TaskCreationOptions.LongRunning);

            #endregion

            #region Startup

            //When starting minimized, the
            if (UserSettings.All.StartMinimized)
            {
                return;
            }

            if (UserSettings.All.StartUp == 4 || Argument.FileNames.Any())
            {
                MainViewModel.OpenEditor.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp < 1 || UserSettings.All.StartUp > 4)
            {
                MainViewModel.OpenLauncher.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp == 1)
            {
                MainViewModel.OpenRecorder.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp == 2)
            {
                MainViewModel.OpenWebcamRecorder.Execute(null);
                return;
            }

            if (UserSettings.All.StartUp == 3)
            {
                MainViewModel.OpenBoardRecorder.Execute(null);
            }

            #endregion
        }
 public static void SetItemDescription(this ItemMaster itemMaster, string newIdentifier, string description)
 {
     LocalizationHelper.AddTermData(newIdentifier, description);
     itemMaster.description    = description;
     itemMaster.descriptionKey = newIdentifier;
 }
예제 #27
0
 private void loadLocales()
 {
     Resources.MergedDictionaries.Add(LocalizationHelper.getLocale());
 }
예제 #28
0
 public string GetDescription(Colony colony, Players.Player player)
 {
     return(LocalizationHelper.LocalizeOrDefault("BedsClose", player));
 }
예제 #29
0
 /// <summary>
 /// Gets localized string from given source for given key name and current language.
 /// </summary>
 /// <param name="sourceName">Source name</param>
 /// <param name="name">Key name</param>
 /// <returns>Localized string</returns>
 protected virtual string Ls(string sourceName, string name)
 {
     return(LocalizationHelper.GetSource(sourceName).GetString(name));
 }
예제 #30
0
        public override void OnSetComponentDefaults()
        {
            LocalizationHelper rp = (LocalizationHelper)Component;

            rp.Parent = (Control)Component.Site.Container.Components[0];
        }