コード例 #1
0
        /// <summary>
        /// Конструктор. Запускает форму выбора размера
        /// </summary>
        /// <param name="InterfaceLanguage">Язык интерфейса</param>
        /// <param name="MaxHeight">Максимальная высота окна</param>
        /// <param name="MaxWidth">Максимальная ширина окна</param>
        public WindowSizeForm(uint MaxWidth, uint MaxHeight, SupportedLanguages InterfaceLanguage)
        {
            // Инициализация
            InitializeComponent();
            this.AcceptButton = BOK;
            this.CancelButton = BCancel;

            this.Text    = Localization.GetText("CDP_WindowSize", InterfaceLanguage);
            BOK.Text     = Localization.GetText("ConcurrentDrawParameters_BOK", InterfaceLanguage);
            BCancel.Text = Localization.GetText("ConcurrentDrawParameters_BCancel", InterfaceLanguage);

            availableSizes.Add(new Point(640, 360));
            availableSizes.Add(new Point(640, 480));
            availableSizes.Add(new Point(800, 450));
            availableSizes.Add(new Point(800, 600));
            availableSizes.Add(new Point(960, 540));
            availableSizes.Add(new Point(960, 720));
            availableSizes.Add(new Point(1280, 720));
            availableSizes.Add(new Point(1024, 768));
            availableSizes.Add(new Point((int)MaxWidth, 128));
            availableSizes.Add(new Point((int)MaxWidth, (int)MaxHeight));

            for (int i = 0; i < availableSizes.Count; i++)
            {
                SizesCombo.Items.Add(availableSizes[i].X.ToString() + " x " + availableSizes[i].Y.ToString() + " px");
            }
            SizesCombo.SelectedIndex = 0;

            // Запуск
            this.ShowDialog();
        }
コード例 #2
0
        /// <summary>
        /// Метод отображает справочное окно приложения
        /// </summary>
        /// <param name="InterfaceLanguage">Язык интерфейса</param>
        /// <param name="Description">Описание программы и/или справочная информация</param>
        /// <param name="StartupMode">Флаг, указывающий, что справка не должна отображаться, если
        /// она уже была показана для данной версии приложения</param>
        /// <returns>Возвращает 1, если справка уже отображалась для данной версии (при StartupMode == true);
        /// Другое значение, если окно справки было отображено</returns>
        public int ShowAbout(SupportedLanguages InterfaceLanguage, string Description, bool StartupMode)
        {
            al          = InterfaceLanguage;
            description = Description;

            return(LaunchForm(StartupMode, false));
        }
コード例 #3
0
        public string this[SupportedLanguages sl]
        {
            get
            {
                MultiLangueValue text = Labels.SingleOrDefault(p => p.Language == sl);

                if (text != null)
                {
                    return(text.Text);
                }
                else
                {
                    return(String.Empty);
                }
            }

            set
            {
                Labels.RemoveAll(p => p.Language == sl);
                Labels.Add(new MultiLangueValue()
                {
                    Language = sl, Text = value
                });
            }
        }
コード例 #4
0
        public async Task GetSupportedLanguagesAsync()
        {
            Mock <TranslationService.TranslationServiceClient> mockGrpcClient = new Mock <TranslationService.TranslationServiceClient>(MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient())
            .Returns(new Mock <Operations.OperationsClient>().Object);
            GetSupportedLanguagesRequest expectedRequest = new GetSupportedLanguagesRequest
            {
                ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
                DisplayLanguageCode  = "displayLanguageCode30710199",
                Model = "model104069929",
            };
            SupportedLanguages expectedResponse = new SupportedLanguages();

            mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(expectedRequest, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <SupportedLanguages>(Task.FromResult(expectedResponse), null, null, null, null));
            TranslationServiceClient client        = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
            LocationName             parent        = new LocationName("[PROJECT]", "[LOCATION]");
            string             displayLanguageCode = "displayLanguageCode30710199";
            string             model    = "model104069929";
            SupportedLanguages response = await client.GetSupportedLanguagesAsync(parent, displayLanguageCode, model);

            Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
コード例 #5
0
        public GettingStartedViewModel(SupportedLanguages userLanguage, string main_video_code = null)
        {
            UserLanguage = userLanguage;
            LoadLanguageContext(userLanguage, main_video_code);

            ActiveTab = "tab_video";
        }
コード例 #6
0
        private async Task LoadSupportedLanguagesAsync()
        {
            try
            {
                SupportedLanguages supportedLanguages = await this.translatorTextService?.GetSupportedLanguagesAsync();

                if (supportedLanguages != null)
                {
                    List <LanguageDictionary> languageDictionaryList = supportedLanguages.Dictionary
                                                                       .Select(v =>
                    {
                        LanguageDictionary languageDict = v.Value;
                        languageDict.Code = v.Key;
                        return(languageDict);
                    })
                                                                       .OrderBy(v => v.Name)
                                                                       .ToList();
                    InputLanguageCollection.Clear();
                    InputLanguageCollection.AddRange(languageDictionaryList);
                }
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure loading languages.");
            }
        }
コード例 #7
0
        public Dictionary <string, string> GetLangs(string language = "en")
        {
            url = string.Format(AppCache.UrlGetAvailableLanguages, AppCache.Key, language);
            SupportedLanguages supportedLanguages = GetObjectFromAPI <SupportedLanguages>(url);

            return(supportedLanguages.Langs);
        }
コード例 #8
0
 protected TranslationPreviewEditor(SupportedLanguages supportedLanguages, string keyLabel, string valueLabel)
 {
     // Setup member variables
     SupportedLanguages = supportedLanguages;
     this.keyLabel      = keyLabel;
     this.valueLabel    = valueLabel;
 }
コード例 #9
0
 public CreateCourseCommandValidator()
 {
     RuleFor(x => x.Name).NotEmpty().Length(10, 30).WithMessage("Name validation failed");
     RuleFor(x => x.Description).Length(10, 260).WithMessage("Description validation failed");
     RuleFor(x => x.Languages).Must(x => x.All(l => SupportedLanguages.GetAll().Contains(l))).NotNull();
     RuleFor(x => x.Avatar).NotNull();
 }
コード例 #10
0
        public static void Main()
        {
            // Инициализация
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Запрос языка приложения
            SupportedLanguages al = Localization.CurrentLanguage;

            // Проверка запуска единственной копии
            bool  result;
            Mutex instance = new Mutex(true, ProgramDescription.AssemblyTitle, out result);

            if (!result)
            {
                MessageBox.Show(string.Format(Localization.GetText("AlreadyStarted", al), ProgramDescription.AssemblyTitle),
                                ProgramDescription.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Отображение справки и запроса на принятие Политики
            if (!ProgramDescription.AcceptEULA())
            {
                return;
            }
            ProgramDescription.ShowAbout(true);

            // Запуск
            Application.Run(new FileExtensionsManagerForm());
        }
コード例 #11
0
        /// <summary>
        /// Конструктор. Запускает форму
        /// </summary>
        /// <param name="ExpectedColumnsCount">Ожидаемое количество столбцов, полученное из конфигурации программы</param>
        /// <param name="Language">Язык локализации</param>
        /// <param name="SelectAbscissas">Флаг, указывающий, следует ли запрашивать номер столбца абсцисс</param>
        public UnknownFileParametersSelector(uint ExpectedColumnsCount, SupportedLanguages Language, bool SelectAbscissas)
        {
            // Инициализация и локализация формы
            InitializeComponent();
            Localization.SetControlsText(this, Language);
            ApplyButton.Text = Localization.GetText("ApplyButton", Language);
            AbortButton.Text = Localization.GetText("AbortButton", Language);
            this.Text        = Localization.GetControlText(this.Name, "T", Language);

            // Настройка контролов
            ColumnsCount.Maximum = ConfigAccessor.MaxExpectedColumnsCount;
            try
            {
                ColumnsCount.Value = dataColumnsCount = ExpectedColumnsCount;
                Abscissas.Maximum  = ColumnsCount.Value + 1;
                Abscissas.Value    = abscissasColumn = 1;
            }
            catch
            {
            }

            Label03.Visible = Abscissas.Visible = SelectAbscissas;

            // Запуск
            this.ShowDialog();
        }
コード例 #12
0
 public void ApplyLocalization()
 {
     if (!SupportedLanguages.ContainsKey(Application.systemLanguage))
     {
         if (_dataManager.UserSave.AppLanguage == Enumerators.Language.NONE)
         {
             SetLanguage(_defaultLanguage);
         }
         else
         {
             SetLanguage(_dataManager.UserSave.AppLanguage);
         }
     }
     else
     {
         if (_dataManager.UserSave.AppLanguage == Enumerators.Language.NONE)
         {
             SetLanguage(SupportedLanguages[Application.systemLanguage]);
         }
         else
         {
             SetLanguage(_dataManager.UserSave.AppLanguage);
         }
     }
 }
コード例 #13
0
        public async Task <ActionResult <IList <SupportedLanguage> > > GetGoogleTranslateLanguages()
        {
            TranslationServiceClient service = await translateServiceAccessor.InitializeServiceAsync();

            string[] displayLanguageCodeList = { "en" };

            #region Accept Header
            if (Request.Headers.TryGetValue("Accept-Language", out StringValues value))
            {
                string[] accept_language_values = value.ToString().Split(',');
            }
            #endregion

            int i = 0;             // iterate over display language code list
            IList <SupportedLanguage> response = null;
            while (response == null && i < displayLanguageCodeList.Length)
            {
                string displayLanguageCode = displayLanguageCodeList[i];

                try {
                    SupportedLanguages temp = await service.GetSupportedLanguagesAsync(new GetSupportedLanguagesRequest {
                        Parent = ApplicationValues.GOOGLE_PROJECT_NAME.ToString(),
                        DisplayLanguageCode = displayLanguageCode,
                    });

                    response = temp.Languages;
                } catch (Grpc.Core.RpcException) {
                    i++;
                }
            }

            return(new ActionResult <IList <SupportedLanguage> >(response));
        }
コード例 #14
0
        /// <summary>
        /// Adds a family of class names to the specified languages.
        /// </summary>
        /// <param name="family">The family identifier.</param>
        /// <param name="names">The names included in the family.</param>
        /// <param name="languages">The languages which
        /// the family must be associated with.</param>
        /// <returns>
        /// A value equal to <c>0</c> for successful operations; nonzero otherwise.
        /// </returns>
        /// <remarks>
        /// <para>
        /// If a family already exists having the given identifier
        /// for the specified languages,
        /// its current class names will be deleted before starting
        /// the addition of the new
        /// ones.
        /// </para>
        /// <para>
        /// Identifiers of supported languages are as follows.
        /// <list type="table">
        /// <item>
        /// <description><c>"c"</c></description>
        /// <description><c>"cs"</c></description>
        /// <description><c>"cpp"</c></description>
        /// <description><c>"fs"</c></description>
        /// </item>
        /// <item>
        /// <description><c>"jsharp"</c></description>
        /// <description><c>"javascript"</c></description>
        /// <description><c>"jscriptnet"</c></description>
        /// <description><c>"vbnet"</c></description>
        /// </item>
        /// <item>
        /// <description><c>"vbscript"</c></description>
        /// <description><c>"sql"</c></description>
        /// <description><c>"pshell"</c></description>
        /// <description><c>"python"</c></description>
        /// </item>
        /// </list>
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="family"/> is <b>null</b>.<br/>
        /// -or-<br/>
        /// <paramref name="names"/> is <b>null</b>.<br/>
        /// -or-<br/>
        /// <paramref name="languages"/> is <b>null</b>.<br/>
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="family"/> is an empty string,
        /// or a string consisting only of white-space characters.<br/>
        /// -or-<br/>
        /// <paramref name="names"/> contain empty strings,
        /// or strings consisting only of white-space characters.<br/>
        /// -or-<br/>
        /// <paramref name="languages"/> contain strings
        /// that are not supported language identifiers.<br/>
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The environmental variable <c>SHFBROOT</c> cannot be found.<br />
        /// -or-<br />
        /// The environmental variable <c>SHFBROOT</c> exists but points to
        /// a SHFB installation which is corrupted or has a version different from the
        /// target one.</exception>
        public static int AddClassNamesFamily(
            string family,
            IEnumerable <string> names,
            IEnumerable <string> languages)
        {
            #region INPUT VALIDATION

            if (family is null)
            {
                throw new ArgumentNullException(nameof(family));
            }

            if (String.IsNullOrWhiteSpace(family))
            {
                throw new ArgumentException(
                          "The parameter cannot be an empty string, " +
                          "or a string consisting only of white-space characters.",
                          nameof(family));
            }

            if (names is null)
            {
                throw new ArgumentNullException(nameof(names));
            }

            foreach (var name in names)
            {
                if (String.IsNullOrWhiteSpace(name))
                {
                    throw new ArgumentException(
                              "The parameter cannot contain empty strings, " +
                              "or strings consisting only of white-space characters.",
                              nameof(names));
                }
            }

            if (languages is null)
            {
                throw new ArgumentNullException(nameof(languages));
            }

            SupportedLanguages.Validate(languages);

            #endregion

            if (Shfb.SHFBROOT is null)
            {
                throw new InvalidOperationException(
                          "The environmental variable SHFBROOT cannot be found. " +
                          String.Format(
                              "Please, install SHFB version {0} and try again.",
                              Shfb.TargetVersion));
            }

            return(AddClassNamesFamily(
                       family,
                       names.Distinct(),
                       languages,
                       Shfb.SHFBROOT));
        }
コード例 #15
0
        public bool IsSupportedLanguage(CultureInfo sourceLanguage, CultureInfo targetLanguage)
        {
            if (!SupportedLanguages.Any())
            {
                SetGoogleAvailableLanguages();
            }

            var suportsSource  = false;
            var supportsTarget = false;

            var searchedSource =
                SupportedLanguages?.FirstOrDefault(l => l.CultureInfo.Name.Equals(sourceLanguage.TwoLetterISOLanguageName));
            var searchedTarget =
                SupportedLanguages?.FirstOrDefault(l => l.CultureInfo.Name.Equals(targetLanguage.TwoLetterISOLanguageName));

            if (searchedSource != null)
            {
                suportsSource = searchedSource.SupportSource;
            }
            if (searchedTarget != null)
            {
                supportsTarget = searchedTarget.SupportTarget;
            }
            return(suportsSource && supportsTarget);
        }
コード例 #16
0
        public void SetGoogleAvailableLanguages()
        {
            try
            {
                var request = new GetSupportedLanguagesRequest
                {
                    ParentAsLocationName = new LocationName(_options.ProjectName, "global"),
                };
                var response = _translationServiceClient.GetSupportedLanguages(request);

                foreach (var language in response.Languages)
                {
                    var languageModel = new GoogleV3LanguageModel
                    {
                        GoogleLanguageCode = language.LanguageCode,
                        SupportSource      = language.SupportSource,
                        SupportTarget      = language.SupportTarget,
                        CultureInfo        = new CultureInfo(language.LanguageCode)
                    };
                    SupportedLanguages.Add(languageModel);
                }
            }
            catch (Exception e)
            {
                _logger.Error($"{MethodBase.GetCurrentMethod().Name}: {e}");
            }
        }
コード例 #17
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="Word"></param>
 /// <param name="Lang"></param>
 /// <returns></returns>
 public string[] GetSuggestions(string Word, SupportedLanguages Lang)
 {
     List<string> result = new List<string>();
     SpellingProxy spellingproxy = SpellingProxy.SpellingProxyInstance;
     result = spellingproxy.GetSuggestion(Word, Lang);
     return result.ToArray();
 }
コード例 #18
0
ファイル: Loca.cs プロジェクト: merlinsaw/VRInterface.main
    public static void CreateMissingTranslationFilesForSupportedLanguages()
    {
        log.Info(_Logger.User.Msaw, "Creating missing translation files for supported languages...");

        // default language is always English
        SystemLanguage defaultLanguage     = SystemLanguage.English;
        string         locaPath            = Application.dataPath + "/Resources/" + locaFileBasePath;
        string         defaultLanguageFile = locaPath + defaultLanguage.ToString().ToLower() + locaFileExtension;

        // if the default translation file does not exist, create an empty one
        if (System.IO.File.Exists(defaultLanguageFile) == false)
        {
            log.Warn(_Logger.User.Msaw, "Default translation file does not exist - creating an empty one: " + defaultLanguageFile);
            System.IO.File.Create(defaultLanguageFile);
        }

        if (SupportedLanguages != null)
        {
            SupportedLanguages.ForEach(language =>
            {
                if (language != defaultLanguage)
                {
                    // if the translation file does not exist, copy the default language file
                    string languageFile = locaPath + language.ToString().ToLower() + locaFileExtension;
                    if (System.IO.File.Exists(languageFile) == false)
                    {
                        log.Info(_Logger.User.Msaw, "Creating a translation file for " + language.ToString());
                        System.IO.File.Copy(defaultLanguageFile, languageFile);
                    }
                }
            });
        }
    }
コード例 #19
0
        public async Task ValidParameter_Should_ChangeChatConfig_And_ReplyMessage(SupportedLanguages languageParameter)
        {
            // Arrange
            var          channelConfigurationServiceMock = new Mock <IDiscordChannelConfigService>();
            var          command      = new LanguageCommand(channelConfigurationServiceMock.Object);
            const string replyMessage = "Language updated";

            var chatConfig = new DiscordChannelConfig
            {
                SelectedLanguage = SupportedLanguages.Auto
            };

            var channelMock = new Mock <IMessageChannel>();
            var user        = new Mock <IGuildUser>();

            user.Setup(v => v.GuildPermissions).Returns(GuildPermissions.All);
            var message = new Mock <IMessage>();

            message.Setup(v => v.Content).Returns($"{DiscordBotCommands.Language} {(int)languageParameter}");
            message.Setup(v => v.Author).Returns(user.Object);
            message.Setup(v => v.Channel).Returns(channelMock.Object);

            channelConfigurationServiceMock.Setup(v => v.GetConfigurationByChannelId(message.Object.Channel.Id))
            .ReturnsAsync(chatConfig);

            // Act
            await command.Handle(message.Object);

            // Assert

            // Verify SendMessageAsync was called with the reply message "Language updated"
            channelMock.Verify(v => v.SendMessageAsync(null, false, It.Is <Embed>(e => e.Description.Contains(replyMessage)), null, null, null, null, null, null, MessageFlags.None));
            Assert.Equal(languageParameter, chatConfig.SelectedLanguage);
        }
        private async Task LoadSupportedLanguagesAsync()
        {
            try
            {
                SupportedLanguages supportedLanguages = await this.translatorTextService.GetSupportedLanguagesAsync();

                this.alternativeTranslationDict = supportedLanguages.Dictionary.ToDictionary(l => l.Key, l => l.Value.Translations);
                List <Language> translationLanguageList = supportedLanguages.Translation
                                                          .Select(v =>
                {
                    Language translationLang = v.Value;
                    translationLang.Code     = v.Key;
                    return(translationLang);
                })
                                                          .OrderBy(v => v.Name).ToList();

                InputLanguageCollection.AddRange(translationLanguageList);
                OutputLanguageCollection.AddRange(translationLanguageList);
                OutputLanguage = OutputLanguageCollection.FirstOrDefault(l => l.Code.Equals(DefaultLanguage.Code, StringComparison.OrdinalIgnoreCase));
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure loading languages.");
            }
        }
コード例 #21
0
 public XmlClient(SupportedLanguages language,
                  string token)
 {
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
     _language = language;
     Token = token;
 }
コード例 #22
0
        private string CompileNotDocumented(Document document, string strippedSlug, string fullPath, ClientType currentLanguage)
        {
            var builder = new StringBuilder();

            builder.Append("<ul>");

            foreach (var language in SupportedLanguages.Where(x => x != currentLanguage))
            {
                var path = Path.Combine(fullPath, strippedSlug + "." + language + ".markdown");
                if (File.Exists(path))
                {
                    var url =
                        (Output.RootUrl.EndsWith("/") ? string.Empty : "/")
                        + document.VirtualTrail
                        .Replace(currentLanguage.ToString(), language.ToString().ToLower())
                        .Replace("\\", "/")
                        + "/" + strippedSlug;

                    builder.AppendFormat("<li><a href='{0}'>{1}</a></li>", new Uri(Output.RootUrl + url).AbsoluteUri, language.GetDescription());
                }
            }
            builder.Append("</ul>");

            var pathToNotDocumented = Path.Combine(destinationFullPath, "not-documented.markdown");

            document.Content = DocumentationParser.Parse(this, null, document, pathToNotDocumented, document.Trail);
            document.Content = string.Format(document.Content, currentLanguage.GetDescription(), builder);
            document.Slug    = strippedSlug;

            Output.SaveDocItem(document);

            return(document.Content);
        }
コード例 #23
0
        /// <summary>
        /// Deserializes JSON data contained within the passed filename
        /// </summary>
        /// <param name="filename"></param>
        public void LoadLocalizedText(string fileName)
        {
            localizedText = new Dictionary <string, string> ();

            string filePath = Path.Combine(Path.Combine(Application.streamingAssetsPath, "lang"), fileName);

            if (File.Exists(filePath))
            {
                string dataAsJson = File.ReadAllText(filePath);
                LocalizedLanguageData loadedData = JsonUtility.FromJson <LocalizedLanguageData> (dataAsJson);
                for (int i = 0; i < loadedData.items.Length; i++)
                {
                    localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
                }

                selectedLanguage = loadedData.Language;

                foreach (KeyValuePair <string, string> pair in unlocalizedText)
                {
                    if (!localizedText.ContainsKey(pair.Key))
                    {
                        localizedText.Add(pair.Key, pair.Value);
                    }
                }

                Debug.Log("Data loaded, dictionary contains: " + localizedText.Count + " entries");
            }
            else
            {
                Debug.LogError("Cannot find file! Defaulting to unlocalized text");
                LoadUnlocalizedText();
            }

            isReady = true;
        }
 internal static void FixStandardNamespacesAndRootNamespace(CodeNamespaceCollection codeNamespaces, string rootNS, SupportedLanguages language)
 {
     if (language == SupportedLanguages.VB)
     {
         foreach (CodeNamespace namespace2 in codeNamespaces)
         {
             if (namespace2.Name == rootNS)
             {
                 namespace2.Name = string.Empty;
                 namespace2.UserData.Add("TruncatedNamespace", null);
             }
             else if (namespace2.Name.StartsWith(rootNS + ".", StringComparison.Ordinal))
             {
                 namespace2.Name = namespace2.Name.Substring(rootNS.Length + 1);
                 namespace2.UserData.Add("TruncatedNamespace", null);
             }
         }
     }
     foreach (CodeNamespace namespace3 in codeNamespaces)
     {
         Hashtable hashtable = new Hashtable();
         foreach (CodeNamespaceImport import in namespace3.Imports)
         {
             hashtable.Add(import.Namespace, import);
         }
         foreach (string str in standardNamespaces)
         {
             if (!hashtable.Contains(str))
             {
                 namespace3.Imports.Add(new CodeNamespaceImport(str));
             }
         }
     }
 }
コード例 #25
0
        /// <summary>
        /// Метод формирует сообщение об ошибке
        /// </summary>
        /// <param name="Result">Результат инициализации класса</param>
        /// <param name="Language">Язык локализации</param>
        /// <returns>Сообщение об ошибке</returns>
        public static string ErrorMessage(DiagramDataInitResults Result, SupportedLanguages Language)
        {
            switch (Result)
            {
            case DiagramDataInitResults.NotInited:
                return(Localization.GetText("NotInitedError", Language));

            case DiagramDataInitResults.FileNotAvailable:
                return(Localization.GetText("FileNotAvailableError", Language));

            case DiagramDataInitResults.BrokenFile:
                return(Localization.GetText("BrokenFileError", Language));

            case DiagramDataInitResults.NotEnoughData:
                return(Localization.GetText("NotEnoughDataError", Language));

            case DiagramDataInitResults.BrokenTable:
                return(Localization.GetText("BrokenTableError", Language));

            case DiagramDataInitResults.ExcelNotAvailable:
                return(Localization.GetText("ExcelNotAvailableError", Language));

            default:                            // В том числе - OK
                return("");
            }
        }
コード例 #26
0
        internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            ValidationError error = null;

            if (identifier == null || identifier.Length == 0)
            {
                error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
            }
            else
            {
                SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(context);
                CodeDomProvider    provider = CompilerHelpers.GetCodeDomProvider(language);

                if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
                    language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
                    !provider.IsValidIdentifier(provider.CreateEscapedIdentifier(identifier)))
                {
                    error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier)), ErrorNumbers.Error_InvalidIdentifier);
                }
            }
            if (error != null)
            {
                error.PropertyName = propName;
            }
            return(error);
        }
コード例 #27
0
        public FeaturesViewModel(SupportedLanguages userLanguage)
        {
            UserLanguage = userLanguage;

            if (UserLanguage == SupportedLanguages.English)
            {
                Title           = "Features";
                ScriptGen       = "Script Generation";
                ScriptGenParag1 = "DBBroker does not change database structures, because it believes in the principle of <a href='https://en.wikipedia.org/wiki/Separation_of_concerns' target='_blank'>Separation of Concerns</a>.";
                ScriptGenParag2 = "Gennerally the greatest responsibility of an application is manipulate data, a human should think an then change data structure. To give DBBroker this power, it would require the user given to it other privileges than reading and writing data. That would not be good.";
                ScriptGenParag3 = "The good news is DBBroker can deliver you the script to generate the database that reflects the classes of the mapped domain. Just access the methods of the class:";
                ScriptGenParag4 = "DBBroker.Engine.SqlScriptMaker";

                ConnStrEncryption       = "Connection String Encryption";
                ConnStrEncryptionParag1 = "Security should be a constant concern in software development. To garantee that only the appropriated persons will have access to the sensitive information of the Connection String some additional and, sometimes, hard work is necessary.";
                ConnStrEncryptionParag2 = "To simplify that, DBBroker provides a method that encrypts the DBBroker.config file contents, just call the static method:";
                ConnStrEncryptionParag3 = "DBBroker.Engine.Configuration.EncryptConfigFile()";
            }
            else if (UserLanguage == SupportedLanguages.Português)
            {
                Title           = "Funções";
                ScriptGen       = "Geração de Script";
                ScriptGenParag1 = "O DBBroker não altera a estrutura de sua base de dados, isso porque ele acredita no princípio da <a href='https://en.wikipedia.org/wiki/Separation_of_concerns' target='_blank'>Separação de Responsabilidades</a> (em inglês, Separation of Concerns).";
                ScriptGenParag2 = "Geralmente a maior responsabilidade de uma aplicação é a manipulação de dados, um ser humano deve pensar e então mudar a estrutura dos dados. Para dar ao DBBroker este poder, seria necessário que o usuário dado a ele tivesse outros privilégios além de ler e escrever dados. Isso não seria bom.";
                ScriptGenParag3 = "A boa notícia é que o DBBroker pode disponibilizar o script de criação da base de dados que reflita as classes do domínio mapeado. Basta acessar os métodos da classe:";
                ScriptGenParag4 = "DBBroker.Engine.SqlScriptMaker";

                ConnStrEncryption       = "Encriptação da String de Conexão";
                ConnStrEncryptionParag1 = "Segurança deve ser uma preocupação constante no desenvolvimento de software. Para garantir que apenas as pessoas apropriadas irão ter acesso ao conteúdo sensível da String de Conexão algum esforço adicional, e algumas vezes, trabalho duro é necessário.";
                ConnStrEncryptionParag2 = "Para simplificar isso, o DBBroker possui um método que encripta o conteúdo do arquivo DBBroker.config, basta acessar o método estático:";
                ConnStrEncryptionParag3 = "DBBroker.Engine.Configuration.EncryptConfigFile()";
            }
        }
コード例 #28
0
ファイル: XmlClient.cs プロジェクト: kleopatra999/CIV
 public XmlClient(SupportedLanguages language,
                  string token)
 {
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
     _language = language;
     Token     = token;
 }
コード例 #29
0
        /// <summary>
        /// Given a channel, will parse out the primary language code based on the channel name.
        /// </summary>
        public static Language Language(this SocketGuildChannel channel)
        {
            var supportedLanguages = SupportedLanguages.GetInstance()
                                     .GetLanguages();

            var name  = channel.Name;
            var split = name.Split('-');

            if (split.Length > 1)
            {
                var language = supportedLanguages.FirstOrDefault(l =>
                                                                 string.Compare(l.Code, split.Last(), StringComparison.OrdinalIgnoreCase) == 0);

                if (language.IsNotNull())
                {
                    return(language);
                }
            }

            return(new Language
            {
                Code = "en",
                Name = "English"
            });
        }
コード例 #30
0
        public void ThrowIfNotSupported_Unrecognised_Throws()
        {
            Action action = () => SupportedLanguages.ThrowIfNotSupported("");

            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("123");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("Visual Basic");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("CSharp");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("Cs");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("CS");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("vB");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();

            action = () => SupportedLanguages.ThrowIfNotSupported("VB");
            action.Should().ThrowExactly <ArgumentOutOfRangeException>();
        }
コード例 #31
0
        private void LoadLanguageContext(SupportedLanguages lang, string token)
        {
            try
            {
                Issue = DB_DBBrokerIssue.GetByToken(token);
            }
            catch (Exception ex)
            {
                AppLog.Log(ex);
            }

            if (Issue == null)
            {
                Issue = new DBBrokerIssue();
            }

            if (lang == SupportedLanguages.Português)
            {
                Title         = "Ativação do relato";
                TxSubtitle    = Issue.Id == 0 ? ":( Nenhuma interação encontrada" : "O seu feedback ou relato de um bug foi ativado. Entraremos em contato o mais breve possível.";
                TxTitle       = "Título";
                TxDescription = "Descrição";
            }
            else
            {
                Title         = "Issue activation";
                TxSubtitle    = Issue.Id == 0 ? ":( Nothing found" :  "Your feedback or issue has been activated. We will respond as soon as possible.";
                TxTitle       = "Title";
                TxDescription = "Description";
            }
        }
コード例 #32
0
        /// <summary>
        /// Конструктор. Запускает форму
        /// </summary>
        /// <param name="InterfaceLanguage">Язык интерфейса</param>
        public IconsExtractor(SupportedLanguages InterfaceLanguage)
        {
            // Инициализация
            InitializeComponent();
            al = InterfaceLanguage;
            this.AcceptButton = SelectButton;
            this.CancelButton = AbortButton;

            // Настройка контролов
            OFDialog.Title  = Localization.GetText("IE_OFDialogTitle", al);
            OFDialog.Filter = Localization.GetText("IE_OFDialogFilter", al);

            MainPicture.Width  = (int)(iconPositionWidth * iconsHorizontalCount + 4);
            MainPicture.Height = (int)(iconPositionHeight * iconsVerticalCount + 4);

            this.Width  = MainPicture.Width + 30;
            this.Height = MainPicture.Height + 80;

            PageNumber.Top  = PageLabel.Top = TotalLabel.Top = SelectButton.Top = AbortButton.Top = this.Height - 60;
            TotalLabel.Left = MainPicture.Left + MainPicture.Width - TotalLabel.Width;

            SelectButton.Left = this.Width / 2 - SelectButton.Width - 6;
            AbortButton.Left  = this.Width / 2 + 6;

            AbortButton.Text = Localization.GetText("AbortButton", al);
            PageLabel.Text   = Localization.GetText("IE_PageLabel", al);

            // Запуск
            this.Text = ProgramDescription.AssemblyTitle + Localization.GetText("IE_Title", al);
            this.ShowDialog();
        }
コード例 #33
0
        internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            ValidationError error = null;

            if ((identifier == null) || (identifier.Length == 0))
            {
                error = new ValidationError(SR.GetString("Error_PropertyNotSet", new object[] { propName }), 0x116);
            }
            else
            {
                SupportedLanguages supportedLanguage = CompilerHelpers.GetSupportedLanguage(context);
                CodeDomProvider    codeDomProvider   = CompilerHelpers.GetCodeDomProvider(supportedLanguage);
                if ((((supportedLanguage == SupportedLanguages.CSharp) && identifier.StartsWith("@", StringComparison.Ordinal)) || (((supportedLanguage == SupportedLanguages.VB) && identifier.StartsWith("[", StringComparison.Ordinal)) && identifier.EndsWith("]", StringComparison.Ordinal))) || !codeDomProvider.IsValidIdentifier(codeDomProvider.CreateEscapedIdentifier(identifier)))
                {
                    error = new ValidationError(SR.GetString("Error_InvalidIdentifier", new object[] { propName, SR.GetString("Error_InvalidLanguageIdentifier", new object[] { identifier }) }), 0x119);
                }
            }
            if (error != null)
            {
                error.PropertyName = propName;
            }
            return(error);
        }
コード例 #34
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="TextItems"></param>
        /// <param name="Lang"></param>
        /// <returns></returns>
        public string[] GetMisspelledWords(string CheckText, SupportedLanguages Lang)
        {
            List<string> result = new List<string>();
            SpellingProxy spellingproxy = SpellingProxy.SpellingProxyInstance;
            result.AddRange(spellingproxy.GetMisspelledWords(CheckText, Lang));

            return result.ToArray();
        }
コード例 #35
0
 internal static CodeDomProvider GetCodeDomProvider(SupportedLanguages language, string compilerVersion)
 {
     if (language == SupportedLanguages.CSharp)
     {
         return GetCodeProviderInstance(typeof(CSharpCodeProvider), compilerVersion);
     }
     return GetCodeProviderInstance(typeof(VBCodeProvider), compilerVersion);
 }
コード例 #36
0
        public static FormattingType GetFormattingType(SupportedLanguages language) {
            if (languageFeatures == null) {
                languageFeatures = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(GetLanguageFeaturesJson());
            }

            // TODO: implement better defaults handling, decouple
            var formattingType = (FormattingType)Enum.Parse(typeof(FormattingType), languageFeatures[language.ToString().ToLower()]["formatting"].ToUpper());

            return formattingType;
        }
コード例 #37
0
        public string[] GetMisspelledWords(string CheckText, SupportedLanguages Lang)
        {
            string xml;
            List<string> result;
            SetSwitches(HttpContext.Current);

            xml = GetSpellCheckRequest(CheckText, Enum.GetName(typeof(SupportedLanguages), Lang));
            result = GetListOfMisspelledWords(xml, CheckText);
            
            return result.ToArray();
        }
コード例 #38
0
        public string[] GetSuggestions(string Word, SupportedLanguages Lang)
        {
            string xml;
            List<string> result;
            SetSwitches(HttpContext.Current);

            xml = GetSpellCheckRequest(Word, Enum.GetName(typeof(SupportedLanguages), Lang));
            result = GetListOfSuggestWords(xml);

            return result.ToArray();
        }
コード例 #39
0
        public static IFoldingAlgorithm CreateAlgorithm(SupportedLanguages language) {
            var formattingType = LanguageFeatureInfo.GetFormattingType(language);

            switch (formattingType) {
                case FormattingType.BRACKETS:
                    return new BracketsFoldingAlgorithm();
                case FormattingType.MARKUP:
                    return new MarkupFoldingAlgorithm();
                case FormattingType.WHITESPACE:
                    return new WhitespaceFoldingAlgorithm();
            }

            throw new ArgumentException("Unsupported formatting type");
        }
コード例 #40
0
        /// <summary>
        /// Returns a list of misspelled words based on the passed input
        /// </summary>
        /// <param name="Text">
        /// The Text to be checked for misspelled words
        /// </param>
        /// <param name="Language">
        /// The language in which the check will be performed
        /// </param>
        /// <returns>
        /// A list of misspelled words
        /// </returns>
        public List<string> GetMisspelledWords(string Text, SupportedLanguages Language)
        {
            string[] words = Text.Split(' ');
            Hunspell spellEngine = this.getDictionary(Language);
            List<string> misspelledWords = new List<string>();
            foreach (string word in words)
            {
                string trimmedword = word.Trim(IGNORED_MARKS.ToCharArray());
                if (!spellEngine.Spell(trimmedword)) misspelledWords.Add(trimmedword);

            }
            return misspelledWords;

        }
コード例 #41
0
        public string this[SupportedLanguages sl]
        {
            get
            {
                MultiLangueValue text = Labels.SingleOrDefault(p => p.Language == sl);

                if (text != null)
                    return text.Text;
                else
                    return String.Empty;
            }

            set
            {
                Labels.RemoveAll(p => p.Language == sl);
                Labels.Add(new MultiLangueValue() {Language = sl, Text = value});
            }
        }
コード例 #42
0
        //ListBox dragSource = null;
        public GeneralSettings()
        {
            InitializeComponent();
            this.Title = CIV.strings.GeneralSettings_Title;

            _settings = ProgramSettings.Load();

            defaultLanguage = _settings.UserLanguage;

            DisplayInfoList = new ObservableCollection<DisplayInfoTypes>();
            DisplayInfoListSystray = new ObservableCollection<DisplayInfoTypes>();
            lbDisplayList.DataContext = DisplayInfoList;
            lbDisplayListSystray.DataContext = DisplayInfoListSystray;

            GenerateDisplayList();
            GenerateDisplaySystrayList();

            try
            {
                RegistryKey rkAutorun = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");

                if (rkAutorun != null)
                {
                    _settings.LaunchAtStartup = rkAutorun.GetValueNames().Contains("CIV");
                    rkAutorun.Close();
                }
                else
                    _settings.LaunchAtStartup = false;
            }
            catch (Exception e)
            {
                LogFactory.LogEngine.Instance.Add(e);
            }

            _launchAtStartup = _settings.LaunchAtStartup;

            this.DataContext = _settings;

            // Windows XP et moins
            if (Environment.OSVersion.Version.Major < 6)
                tabSystray.Visibility = System.Windows.Visibility.Collapsed;
        }
コード例 #43
0
 internal static CodeDomProvider GetCodeDomProvider(SupportedLanguages language)
 {
     return CompilerHelpers.GetCodeDomProvider(language, string.Empty);
 }
コード例 #44
0
 internal static string FormatType(Type type, SupportedLanguages language)
 {
     string fullName = string.Empty;
     if (type.IsArray)
     {
         fullName = FormatType(type.GetElementType(), language);
         if (language == SupportedLanguages.CSharp)
         {
             fullName = fullName + '[';
         }
         else
         {
             fullName = fullName + '(';
         }
         fullName = fullName + new string(',', type.GetArrayRank() - 1);
         if (language == SupportedLanguages.CSharp)
         {
             return (fullName + ']');
         }
         return (fullName + ')');
     }
     fullName = type.FullName;
     int index = fullName.IndexOf('`');
     if (index != -1)
     {
         fullName = fullName.Substring(0, index);
     }
     fullName = fullName.Replace('+', '.');
     if (!type.ContainsGenericParameters && !type.IsGenericType)
     {
         return fullName;
     }
     Type[] genericArguments = type.GetGenericArguments();
     if (language == SupportedLanguages.CSharp)
     {
         fullName = fullName + '<';
     }
     else
     {
         fullName = fullName + '(';
     }
     bool flag = true;
     foreach (Type type2 in genericArguments)
     {
         if (!flag)
         {
             fullName = fullName + ", ";
         }
         else
         {
             if (language == SupportedLanguages.VB)
             {
                 fullName = fullName + "Of ";
             }
             flag = false;
         }
         fullName = fullName + FormatType(type2, language);
     }
     if (language == SupportedLanguages.CSharp)
     {
         return (fullName + '>');
     }
     return (fullName + ')');
 }
コード例 #45
0
 internal static string FormatType(string type, SupportedLanguages language)
 {
     string str = string.Empty;
     string[] parameters = null;
     string typeName = string.Empty;
     string elemantDecorator = string.Empty;
     if (ParseTypeName(type, ParseTypeNameLanguage.NetFramework, out typeName, out parameters, out elemantDecorator))
     {
         if (elemantDecorator.Length > 0)
         {
             if (language == SupportedLanguages.VB)
             {
                 elemantDecorator = elemantDecorator.Replace('[', '(').Replace(']', ')');
             }
             return (FormatType(typeName, language) + elemantDecorator);
         }
         if ((parameters != null) && (parameters.Length > 0))
         {
             str = FormatType(typeName, language);
             if (language == SupportedLanguages.CSharp)
             {
                 str = str + '<';
             }
             else
             {
                 str = str + '(';
             }
             bool flag = true;
             foreach (string str4 in parameters)
             {
                 if (!flag)
                 {
                     str = str + ", ";
                 }
                 else
                 {
                     if (language == SupportedLanguages.VB)
                     {
                         str = str + "Of ";
                     }
                     flag = false;
                 }
                 str = str + FormatType(str4, language);
             }
             if (language == SupportedLanguages.CSharp)
             {
                 return (str + '>');
             }
             return (str + ')');
         }
         str = typeName.Replace('+', '.');
         int index = str.IndexOf('`');
         if (index != -1)
         {
             str = str.Substring(0, index);
         }
         index = str.IndexOf(',');
         if (index != -1)
         {
             str = str.Substring(0, index);
         }
     }
     return str;
 }
コード例 #46
0
        internal static Type ParseTypeName(ITypeProvider typeProvider, SupportedLanguages language, string typeName)
        {
            Type returnType = null;

            returnType = typeProvider.GetType(typeName, false);
            if (returnType == null)
            {
                string simpleTypeName = String.Empty;
                string decoratorString = String.Empty;
                string[] parameters = null;
                if (ParseTypeName(typeName, language == SupportedLanguages.CSharp ? ParseTypeNameLanguage.CSharp : ParseTypeNameLanguage.VB, out simpleTypeName, out parameters, out decoratorString))
                {
                    returnType = typeProvider.GetType(simpleTypeName + decoratorString, false);
                }
            }

            return returnType;
        }
コード例 #47
0
 internal static Type ParseTypeName(ITypeProvider typeProvider, SupportedLanguages language, string typeName)
 {
     Type type = null;
     type = typeProvider.GetType(typeName, false);
     if (type == null)
     {
         string str = string.Empty;
         string elemantDecorator = string.Empty;
         string[] parameters = null;
         if (ParseTypeName(typeName, (language == SupportedLanguages.CSharp) ? ParseTypeNameLanguage.CSharp : ParseTypeNameLanguage.VB, out str, out parameters, out elemantDecorator))
         {
             type = typeProvider.GetType(str + elemantDecorator, false);
         }
     }
     return type;
 }
コード例 #48
0
        internal static string FormatType(Type type, SupportedLanguages language)
        {
            string typeName = string.Empty;
            if (type.IsArray)
            {
                typeName = FormatType(type.GetElementType(), language);
                if (language == SupportedLanguages.CSharp)
                    typeName += '[';
                else
                    typeName += '(';

                typeName += new string(',', type.GetArrayRank() - 1);
                if (language == SupportedLanguages.CSharp)
                    typeName += ']';
                else
                    typeName += ')';
            }
            else
            {
                typeName = type.FullName;
                int indexOfSpecialChar = typeName.IndexOf('`');
                if (indexOfSpecialChar != -1)
                    typeName = typeName.Substring(0, indexOfSpecialChar);
                typeName = typeName.Replace('+', '.');

                if (type.ContainsGenericParameters || type.IsGenericType)
                {
                    Type[] genericArguments = type.GetGenericArguments();
                    if (language == SupportedLanguages.CSharp)
                        typeName += '<';
                    else
                        typeName += '(';

                    bool first = true;
                    foreach (Type genericArgument in genericArguments)
                    {
                        if (!first)
                            typeName += ", ";
                        else
                        {
                            if (language == SupportedLanguages.VB)
                                typeName += "Of ";
                            first = false;
                        }
                        typeName += FormatType(genericArgument, language);
                    }

                    if (language == SupportedLanguages.CSharp)
                        typeName += '>';
                    else
                        typeName += ')';
                }
            }
            return typeName;
        }
コード例 #49
0
        internal static string FormatType(string type, SupportedLanguages language)
        {
            string formattedType = string.Empty;
            string[] genericParamTypeNames = null;
            string baseTypeName = string.Empty;
            string elementDecorators = string.Empty;
            if (ParseHelpers.ParseTypeName(type, ParseHelpers.ParseTypeNameLanguage.NetFramework, out baseTypeName, out genericParamTypeNames, out elementDecorators))
            {
                if (elementDecorators.Length > 0)
                {
                    // VB uses '()' for arrays
                    if (language == SupportedLanguages.VB)
                        elementDecorators = elementDecorators.Replace('[', '(').Replace(']', ')');

                    formattedType = FormatType(baseTypeName, language) + elementDecorators;
                }
                else if (genericParamTypeNames != null && genericParamTypeNames.Length > 0)
                {
                    // add generic type
                    formattedType = FormatType(baseTypeName, language);

                    // add generic arguments
                    if (language == SupportedLanguages.CSharp)
                        formattedType += '<';
                    else
                        formattedType += '(';

                    bool first = true;
                    foreach (string genericArgument in genericParamTypeNames)
                    {
                        if (!first)
                            formattedType += ", ";
                        else
                        {
                            if (language == SupportedLanguages.VB)
                                formattedType += "Of ";
                            first = false;
                        }

                        formattedType += FormatType(genericArgument, language);
                    }

                    if (language == SupportedLanguages.CSharp)
                        formattedType += '>';
                    else
                        formattedType += ')';
                }
                else
                {
                    // non generic, non decorated type - simple cleanup
                    formattedType = baseTypeName.Replace('+', '.');

                    int indexOfSpecialChar = formattedType.IndexOf('`');
                    if (indexOfSpecialChar != -1)
                        formattedType = formattedType.Substring(0, indexOfSpecialChar);

                    indexOfSpecialChar = formattedType.IndexOf(',');
                    if (indexOfSpecialChar != -1)
                        formattedType = formattedType.Substring(0, indexOfSpecialChar);

                }
            }

            return formattedType;
        }
コード例 #50
0
        internal static void FixStandardNamespacesAndRootNamespace(CodeNamespaceCollection codeNamespaces, string rootNS, SupportedLanguages language)
        {
            // add the standard imports to all the namespaces.
            if (language == SupportedLanguages.VB)
            {
                foreach (CodeNamespace codeNamespace in codeNamespaces)
                {
                    if (codeNamespace.Name == rootNS)
                    {
                        codeNamespace.Name = string.Empty;
                        codeNamespace.UserData.Add("TruncatedNamespace", null);
                    }
                    else if (codeNamespace.Name.StartsWith(rootNS + ".", StringComparison.Ordinal))
                    {
                        codeNamespace.Name = codeNamespace.Name.Substring(rootNS.Length + 1);
                        codeNamespace.UserData.Add("TruncatedNamespace", null);
                    }
                }
            }

            foreach (CodeNamespace codeNamespace in codeNamespaces)
            {
                Hashtable definedNamespaces = new Hashtable();
                foreach (CodeNamespaceImport codeNamespaceImport in codeNamespace.Imports)
                    definedNamespaces.Add(codeNamespaceImport.Namespace, codeNamespaceImport);

                foreach (string standardNS in standardNamespaces)
                    if (!definedNamespaces.Contains(standardNS))//add only new imports
                        codeNamespace.Imports.Add(new CodeNamespaceImport(standardNS));
            }
        }
コード例 #51
0
        internal static void ReapplyRootNamespace(CodeNamespaceCollection codeNamespaces, string rootNS, SupportedLanguages language)
        {
            if (language == SupportedLanguages.VB)
            {
                foreach (CodeNamespace codeNamespace in codeNamespaces)
                {
                    if (codeNamespace.UserData.Contains("TruncatedNamespace"))
                    {
                        if (codeNamespace.Name == null || codeNamespace.Name.Length == 0)
                            codeNamespace.Name = rootNS;
                        else if (codeNamespace.Name.StartsWith(rootNS + ".", StringComparison.Ordinal))
                            codeNamespace.Name = rootNS + "." + codeNamespace.Name;

                        codeNamespace.UserData.Remove("TruncatedNamespace");
                    }
                }
            }
        }
 internal static CodeNamespaceCollection GenerateCodeFromXomlDocument(Activity rootActivity, string filePath, string rootNamespace, SupportedLanguages language, IServiceProvider serviceProvider)
 {
     CodeNamespaceCollection namespaces = new CodeNamespaceCollection();
     CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language);
     string str = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
     CodeTypeDeclaration declaration = null;
     if ((codeDomProvider != null) && !string.IsNullOrEmpty(str))
     {
         string str2;
         string str3;
         Helpers.GetNamespaceAndClassName(str, out str2, out str3);
         if (codeDomProvider.IsValidIdentifier(str3))
         {
             DesignerSerializationManager manager = new DesignerSerializationManager(serviceProvider);
             using (manager.CreateSession())
             {
                 ActivityCodeDomSerializationManager manager2 = new ActivityCodeDomSerializationManager(manager);
                 TypeCodeDomSerializer serializer = manager2.GetSerializer(rootActivity.GetType(), typeof(TypeCodeDomSerializer)) as TypeCodeDomSerializer;
                 bool flag = true;
                 ArrayList list = new ArrayList();
                 list.Add(rootActivity);
                 if (rootActivity is CompositeActivity)
                 {
                     foreach (Activity activity in Helpers.GetNestedActivities((CompositeActivity) rootActivity))
                     {
                         if (!Helpers.IsActivityLocked(activity))
                         {
                             if (codeDomProvider.IsValidIdentifier(manager2.GetName(activity)))
                             {
                                 list.Insert(0, activity);
                             }
                             else
                             {
                                 flag = false;
                                 break;
                             }
                         }
                     }
                 }
                 if (flag)
                 {
                     DummySite site = new DummySite();
                     foreach (Activity activity2 in list)
                     {
                         activity2.Site = site;
                     }
                     rootActivity.Site = site;
                     declaration = serializer.Serialize(manager2, rootActivity, list);
                     declaration.IsPartial = true;
                     if ((filePath != null) && (filePath.Length > 0))
                     {
                         MD5 md = new MD5CryptoServiceProvider();
                         byte[] buffer = null;
                         using (StreamReader reader = new StreamReader(filePath))
                         {
                             buffer = md.ComputeHash(reader.BaseStream);
                         }
                         string str4 = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}", new object[] { buffer[0].ToString("X2", CultureInfo.InvariantCulture), buffer[1].ToString("X2", CultureInfo.InvariantCulture), buffer[2].ToString("X2", CultureInfo.InvariantCulture), buffer[3].ToString("X2", CultureInfo.InvariantCulture), buffer[4].ToString("X2", CultureInfo.InvariantCulture), buffer[5].ToString("X2", CultureInfo.InvariantCulture), buffer[6].ToString("X2", CultureInfo.InvariantCulture), buffer[7].ToString("X2", CultureInfo.InvariantCulture), buffer[8].ToString("X2", CultureInfo.InvariantCulture), buffer[9].ToString("X2", CultureInfo.InvariantCulture), buffer[10].ToString("X2", CultureInfo.InvariantCulture), buffer[11].ToString("X2", CultureInfo.InvariantCulture), buffer[12].ToString("X2", CultureInfo.InvariantCulture), buffer[13].ToString("X2", CultureInfo.InvariantCulture), buffer[14].ToString("X2", CultureInfo.InvariantCulture), buffer[15].ToString("X2", CultureInfo.InvariantCulture) });
                         CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration(typeof(WorkflowMarkupSourceAttribute).FullName);
                         declaration2.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(filePath)));
                         declaration2.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(str4)));
                         declaration.CustomAttributes.Add(declaration2);
                     }
                     CodeNamespace namespace2 = new CodeNamespace(str2);
                     namespace2.Types.Add(declaration);
                     namespaces.Add(namespace2);
                 }
             }
         }
     }
     if (declaration != null)
     {
         Queue queue = new Queue(new object[] { rootActivity });
         while (queue.Count > 0)
         {
             Activity activity3 = (Activity) queue.Dequeue();
             if (!Helpers.IsActivityLocked(activity3))
             {
                 Queue queue2 = new Queue(new object[] { activity3 });
                 while (queue2.Count > 0)
                 {
                     Activity activity4 = (Activity) queue2.Dequeue();
                     if (activity4 is CompositeActivity)
                     {
                         foreach (Activity activity5 in ((CompositeActivity) activity4).Activities)
                         {
                             queue2.Enqueue(activity5);
                         }
                     }
                     CodeTypeMemberCollection members = activity4.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection;
                     if (members != null)
                     {
                         foreach (CodeSnippetTypeMember member in members)
                         {
                             declaration.Members.Add(member);
                         }
                     }
                 }
             }
         }
         if (language == SupportedLanguages.CSharp)
         {
             declaration.LinePragma = new CodeLinePragma((string) rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int) rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
         }
         CodeConstructor constructor = null;
         CodeMemberMethod method = null;
         foreach (CodeTypeMember member2 in declaration.Members)
         {
             if ((constructor == null) && (member2 is CodeConstructor))
             {
                 constructor = member2 as CodeConstructor;
             }
             if (((method == null) && (member2 is CodeMemberMethod)) && member2.Name.Equals("InitializeComponent", StringComparison.Ordinal))
             {
                 method = member2 as CodeMemberMethod;
             }
             if ((constructor != null) && (method != null))
             {
                 break;
             }
         }
         if (constructor != null)
         {
             constructor.LinePragma = new CodeLinePragma((string) rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int) rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
         }
         if ((method != null) && (language == SupportedLanguages.CSharp))
         {
             method.LinePragma = new CodeLinePragma((string) rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int) rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
         }
     }
     List<string> list2 = rootActivity.GetValue(WorkflowMarkupSerializer.ClrNamespacesProperty) as List<string>;
     if (list2 != null)
     {
         foreach (CodeNamespace namespace3 in namespaces)
         {
             foreach (string str5 in list2)
             {
                 if (!string.IsNullOrEmpty(str5))
                 {
                     CodeNamespaceImport import = new CodeNamespaceImport(str5) {
                         LinePragma = new CodeLinePragma((string) rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int) rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1))
                     };
                     namespace3.Imports.Add(import);
                 }
             }
         }
     }
     return namespaces;
 }
コード例 #53
0
        internal static CodeNamespaceCollection GenerateCodeFromXomlDocument(Activity rootActivity, string filePath, string rootNamespace, SupportedLanguages language, IServiceProvider serviceProvider)
        {
            CodeNamespaceCollection codeNamespaces = new CodeNamespaceCollection();
            CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language);

            // generate activity class
            string activityFullClassName = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
            CodeTypeDeclaration activityTypeDeclaration = null;
            if (codeDomProvider != null && !string.IsNullOrEmpty(activityFullClassName))
            {
                // get class and namespace names
                string activityNamespaceName, activityClassName;
                Helpers.GetNamespaceAndClassName(activityFullClassName, out activityNamespaceName, out activityClassName);
                if (codeDomProvider.IsValidIdentifier(activityClassName))
                {
                    DesignerSerializationManager designerSerializationManager = new DesignerSerializationManager(serviceProvider);
                    using (designerSerializationManager.CreateSession())
                    {
                        ActivityCodeDomSerializationManager codeDomSerializationManager = new ActivityCodeDomSerializationManager(designerSerializationManager);
                        TypeCodeDomSerializer typeCodeDomSerializer = codeDomSerializationManager.GetSerializer(rootActivity.GetType(), typeof(TypeCodeDomSerializer)) as TypeCodeDomSerializer;

                        // get all activities
                        bool generateCode = true;

                        ArrayList allActivities = new ArrayList();
                        allActivities.Add(rootActivity);
                        if (rootActivity is CompositeActivity)
                        {
                            foreach (Activity activity in Helpers.GetNestedActivities((CompositeActivity)rootActivity))
                            {
                                if (Helpers.IsActivityLocked(activity))
                                    continue;
                                if (codeDomProvider.IsValidIdentifier(codeDomSerializationManager.GetName(activity)))
                                {
                                    // WinOE Bug 14561.  This is to fix a performance problem.  When an activity is added to the activity
                                    // tree at the runtime, it's much faster if the ID of the activity is already set.  The code that
                                    // the CodeDomSerializer generates will add the activity first before it sets the ID for the child
                                    // activity.  We can change that order by always serializing the children first.  Therefore, we 
                                    // construct a list where we guarantee that the child will be serialized before its parent.
                                    allActivities.Insert(0, activity);
                                }
                                else
                                {
                                    generateCode = false;
                                    break;
                                }
                            }
                        }

                        if (generateCode)
                        {
                            // Work around!! TypeCodeDomSerializer checks that root component has a site or not, otherwise it
                            // does not serialize it look at ComponentTypeCodeDomSerializer.cs
                            DummySite dummySite = new DummySite();
                            foreach (Activity nestedActivity in allActivities)
                                ((IComponent)nestedActivity).Site = dummySite;
                            ((IComponent)rootActivity).Site = dummySite;

                            // create activity partial class
                            activityTypeDeclaration = typeCodeDomSerializer.Serialize(codeDomSerializationManager, rootActivity, allActivities);
                            activityTypeDeclaration.IsPartial = true;

                            // add checksum attribute
                            if (filePath != null && filePath.Length > 0)
                            {
                                MD5 md5 = new MD5CryptoServiceProvider();
                                byte[] checksumBytes = null;
                                using (StreamReader streamReader = new StreamReader(filePath))
                                    checksumBytes = md5.ComputeHash(streamReader.BaseStream);
                                string checksum = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}", new object[] { checksumBytes[0].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[1].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[2].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[3].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[4].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[5].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[6].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[7].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[8].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[9].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[10].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[11].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[12].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[13].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[14].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[15].ToString("X2", CultureInfo.InvariantCulture) });
                                CodeAttributeDeclaration xomlSourceAttribute = new CodeAttributeDeclaration(typeof(WorkflowMarkupSourceAttribute).FullName);
                                xomlSourceAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(filePath)));
                                xomlSourceAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(checksum)));
                                activityTypeDeclaration.CustomAttributes.Add(xomlSourceAttribute);
                            }

                            // create a new namespace and add activity class into that
                            CodeNamespace activityCodeNamespace = new CodeNamespace(activityNamespaceName);
                            activityCodeNamespace.Types.Add(activityTypeDeclaration);
                            codeNamespaces.Add(activityCodeNamespace);
                        }
                    }
                }
            }

            // generate code for x:Code
            if (activityTypeDeclaration != null)
            {
                Queue activitiesQueue = new Queue(new object[] { rootActivity });
                while (activitiesQueue.Count > 0)
                {
                    Activity activity = (Activity)activitiesQueue.Dequeue();
                    if (Helpers.IsActivityLocked(activity))
                        continue;

                    Queue childActivities = new Queue(new object[] { activity });
                    while (childActivities.Count > 0)
                    {
                        Activity childActivity = (Activity)childActivities.Dequeue();
                        if (childActivity is CompositeActivity)
                        {
                            foreach (Activity nestedChildActivity in ((CompositeActivity)childActivity).Activities)
                            {
                                childActivities.Enqueue(nestedChildActivity);
                            }
                        }

                        // generate x:Code
                        CodeTypeMemberCollection codeSegments = childActivity.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection;
                        if (codeSegments != null)
                        {
                            foreach (CodeSnippetTypeMember codeSegmentMember in codeSegments)
                                activityTypeDeclaration.Members.Add(codeSegmentMember);
                        }
                    }
                }

                if (language == SupportedLanguages.CSharp)
                    activityTypeDeclaration.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));

                //Now make sure we that we also emit line pragma around the constructor
                CodeConstructor constructor = null;
                CodeMemberMethod method = null;
                foreach (CodeTypeMember typeMember in activityTypeDeclaration.Members)
                {
                    if (constructor == null && typeMember is CodeConstructor)
                        constructor = typeMember as CodeConstructor;

                    if (method == null && typeMember is CodeMemberMethod && typeMember.Name.Equals("InitializeComponent", StringComparison.Ordinal))
                        method = typeMember as CodeMemberMethod;

                    if (constructor != null && method != null)
                        break;
                }

                if (constructor != null)
                    constructor.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));

                if (method != null && language == SupportedLanguages.CSharp)
                    method.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
            }

            // generate mappings
            List<String> clrNamespaces = rootActivity.GetValue(WorkflowMarkupSerializer.ClrNamespacesProperty) as List<String>;
            if (clrNamespaces != null)
            {
                // foreach namespace add these mappings
                foreach (CodeNamespace codeNamespace in codeNamespaces)
                {
                    foreach (string clrNamespace in clrNamespaces)
                    {
                        if (!String.IsNullOrEmpty(clrNamespace))
                        {
                            CodeNamespaceImport codeNamespaceImport = new CodeNamespaceImport(clrNamespace);
                            codeNamespaceImport.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
                            codeNamespace.Imports.Add(codeNamespaceImport);
                        }
                    }
                }
            }
            // return namespaces
            return codeNamespaces;
        }
コード例 #54
0
 /// <summary>
 /// Returns a list of suggestions for a given misspelled word
 /// </summary>
 /// <param name="Word">
 /// The misspelled word
 /// </param>
 /// <param name="Language">
 /// The Language to retrieve the suggestions in
 /// </param>
 /// <returns></returns>
 public List<string> GetSuggestion(string Word, SupportedLanguages Language)
 {
     Hunspell spellEngine = this.getDictionary(Language);
     return spellEngine.Suggest(Word);
 }
コード例 #55
0
ファイル: Program.cs プロジェクト: BioRoboticsUNAM/Robotics
        public static bool ParseArgs(string[] args, out string[] files, out SupportedLanguages[] langs, out string defaultNamespace)
        {
            int i;
            Regex rxNameSpaceValidator = new Regex(@"[A-Za-z_][0-9A-Za-z_]*(\.[A-Za-z_][0-9A-Za-z_]*)*");
            List<SupportedLanguages> languages = new List<SupportedLanguages>();
            List<string> sourceFiles =  new List<string>();

            files = null;
            langs = null;
            defaultNamespace = null;

            for (i = 0; i < args.Length; ++i)
            {
                switch (args[i])
                {
                    case "/?":
                    case "/h":
                    case "/help":
                    case "-?":
                    case "-h":
                    case "-help":
                    case "--h":
                    case "--help":
                        Help();
                        return false;

                    case "/l":
                    case "/lang":
                    case "/language":
                    case "-l":
                    case "-lang":
                    case "-language":
                    case "--l":
                    case "--lang":
                    case "--language":
                        if (args.Length <= ++i)
                        {
                            Console.WriteLine("\t" + args[i - 1] + " error. No output language specified.");
                            return false;
                        }
                        ParseLanguages(languages, args[i]);
                        break;

                    case "/ns":
                    case "-ns":
                    case "--ns":
                    case "/package":
                    case "-package":
                    case "--package":
                        if (args.Length <= ++i)
                        {
                            Console.WriteLine("\t" + args[i - 1] + " error. No namespace/package specified.");
                            return false;
                        }
                        if (String.IsNullOrEmpty(defaultNamespace) && !rxNameSpaceValidator.IsMatch(args[i]))
                        {
                            Console.WriteLine("\t" + args[i - 1] + " " + args[i] + " error. Invalid namespace/package specified.");
                            return false;
                        }
                        if (!String.IsNullOrEmpty(defaultNamespace))
                            Console.WriteLine("\tWarning. namespace/package already defined will be overwrited");
                        defaultNamespace = args[i];
                        break;

                    default:
                        if (File.Exists(args[i]))
                            sourceFiles.Add(args[i]);
                        else if (args[i].StartsWith("-") || args[i].StartsWith("/"))
                            Console.WriteLine("\tInvalid flag: " + args[i]);
                        else
                            Console.WriteLine("\tInvalid file: '" + args[i] + "'. File does not exist.");
                        break;
                }
            }

            if ((languages.Count < 1) || (sourceFiles.Count < 1))
            {
                Console.WriteLine("Invalid input.");
                Console.WriteLine("Usage: tdcm -lang <language> <source files>");
                Console.WriteLine("use -help for a list of possible options");
                Console.WriteLine();
                return false;
            }
            langs = languages.ToArray();
            files = sourceFiles.ToArray();
            return true;
        }
コード例 #56
0
 /// <summary>
 /// Returns a dictionary from the factory
 /// </summary>
 /// <param name="Language">
 /// One of the supported Langauges.  Currently only english is supported, but this can be expanded 
 /// to support and of the Open Office Languages
 /// </param>
 /// <returns>
 /// This singleton instance of the dictionary
 /// </returns>
 private Hunspell getDictionary(SupportedLanguages Language)
 {
    //ensure thread safety
     lock (_lockObject)
     {
         switch (Language)
         {
             case SupportedLanguages.en:
                 return _englishDictionary.Value;
             default:
                 throw new NotSupportedException("This Language is not supported.");
         }
     }
 }