public NamingServiceViewModel(NamingService namingService)
        {
            _namingService = namingService;

            ViewModelHelper.BindNotifyChanged(
                _namingService, this, (sender, e) => RaisePropertyChanged(e.PropertyName));
        }
        /// <summary>
        /// Returns true if the word is spelled correctly.
        /// </summary>
        /// <param name="namingService">
        /// The naming service to use.
        /// </param>
        /// <param name="word">
        /// The word to check.
        /// </param>
        /// <param name="hint">
        /// A message indicating why the word isn't spelled correctly, or <see langword="null"/> if there is none.
        /// </param>
        /// <returns>
        /// True if spelled correctly; otherwise, False.
        /// </returns>
        private static bool IsSpelledCorrectly(NamingService namingService, string word, out string hint)
        {
            string alternate;

            alternate = namingService.GetPreferredAlternateForDeprecatedWord(word);
            if (alternate != null)
            {
                // Deprecated word, preferred alternate should be used.
                hint = (alternate.Length > 0)
                        ? string.Format(CultureInfo.InvariantCulture, Strings.SpellingPreferredAlternate, alternate)
                        : null;
                return(false);
            }

            alternate = namingService.GetCompoundAlternateForDiscreteWord(word);
            if (alternate != null)
            {
                // Compound alternate should be used.
                hint = (alternate.Length > 0)
                        ? string.Format(CultureInfo.InvariantCulture, Strings.SpellingUseCompoundWord, alternate)
                        : null;
                return(false);
            }

            if (namingService.CheckSpelling(word) == WordSpelling.Unrecognized)
            {
                // Spelling error.
                hint = null;
                return(false);
            }

            // No error.
            hint = null;
            return(true);
        }
        public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
        {
            NamingService = new NamingService((INamingService)services.GetService(typeof(INamingService)));
            Services = services;
            InitializeMappings();
            var types = codeUnit.Namespaces[0].Types;
            foreach (CodeTypeDeclaration type in types)
            {
                if (!type.IsClass || type.IsContextType() || type.IsBaseEntityType()) { continue; }

                var logicalName = type.GetFieldInitalizedValue("EntityLogicalName");
                var propertiesToAdd = new List<CodeMemberProperty>();
                foreach (var member in type.Members)
                {
                    var property = member as CodeMemberProperty;
                    if (SkipProperty(property, type, logicalName))
                    {
                        continue;
                    }
                    propertiesToAdd.Add(GetOptionSetEnumType(property, logicalName));
                }

                foreach (var enumProp in propertiesToAdd.Where(p => p != null))
                {
                    type.Members.Add(enumProp);
                }
            }

            if (!CreateBaseClasses)
            {
                // If creating Base Classes, this will be included in the base class
                types.Add(GetEntityOptionSetEnumDeclaration());
            }
        }
        private EnumPropertyInfo GetOptionSetEnumInfo(CodeMemberProperty prop, string entityLogicalName)
        {
            var propertyLogicalName = prop.GetLogicalName();
            if (propertyLogicalName == null) { throw new Exception("Unable to determine property Logical Name"); }

            var data = CodeWriterFilterService.EntityMetadata[entityLogicalName];
            var attribute = data.Attributes.FirstOrDefault(a => a.LogicalName == propertyLogicalName);
            var picklist = attribute as EnumAttributeMetadata;
            if (picklist == null) { return null; }

            var enumName = NamingService.GetNameForOptionSet(data, picklist.OptionSet, Services);
            if (SpecifiedMappings.TryGetValue(entityLogicalName.ToLower() + "." + prop.Name.ToLower(), out var specifiedEnum))
            {
                enumName = specifiedEnum;
            }
            else if (CodeWriterFilterService.EntityMetadata.ContainsKey(enumName) && CodeWriterFilterService.EntityMetadata[enumName].SchemaName == enumName)
            {
                enumName += "Enum";
            }

            return new EnumPropertyInfo
            {
                OptionSetType = enumName,
                IsMultSelect = picklist is MultiSelectPicklistAttributeMetadata,
                PropertyName = prop.Name + "Enum",
                LogicalName = propertyLogicalName
            };
        }
Exemple #5
0
        public static void Initialize()
        {
            FdoConnectionManager manager = ServiceManager.Instance.GetService <FdoConnectionManager>();
            NamingService        namer   = ServiceManager.Instance.GetService <NamingService>();

            manager.ConnectionAdded += delegate(object sender, EventArgs <string> e)
            {
                LoggingService.InfoFormatted("Connection added: {0}", e.Data);
            };
            manager.ConnectionRemoved += delegate(object sender, EventArgs <string> e)
            {
                LoggingService.InfoFormatted("Connection removed: {0}", e.Data);
                if (manager.GetConnectionNames().Count == 0)
                {
                    namer.ResetCounter();
                }
            };
            manager.ConnectionRenamed += delegate(object sender, ConnectionRenameEventArgs e)
            {
                LoggingService.InfoFormatted("Connection {0} renamed to {1}", e.OldName, e.NewName);
            };
            manager.ConnectionRefreshed += delegate(object sender, EventArgs <string> e)
            {
                LoggingService.InfoFormatted("Connection {0} refreshed", e.Data);
            };
        }
 public static void SetContext(NamingService namingService)
 {
     lock (instanceLock) {
         Conditions.AssertArgument(namingService != null);
         Conditions.AssertState(instance == null);
         instance = new SimpleKVSMessageLayer(namingService);
     }
 }
Exemple #7
0
        /// <summary>
        /// Does not mark the OptionSet for generation if it has already been generated.
        /// This could get called for the same Global Option Set multiple times because it's on multiple Entities
        /// </summary>
        public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
        {
            PopulateUsedEntityGlobalOptionSetOnInitialCall(services);

            // Skip the state optionsets unless the XrmClient is used
            if (!Entity.CustomizeCodeDomService.UseXrmClient && optionSetMetadata.OptionSetType == OptionSetType.State)
            {
                return(false);
            }

            if (optionSetMetadata.IsGlobal.GetValueOrDefault() &&
                GenerateOnlyReferencedOptionSets &&
                !UsedEntityGlobalOptionSets.Contains(optionSetMetadata.Name.ToLower()))
            {
                return(false);
            }


            if (!IsOptionSetGenerated(optionSetMetadata.Name))
            {
                return(false);
            }

            bool generate = false;

            if (optionSetMetadata.IsGlobal.GetValueOrDefault())
            {
                if (!GeneratedOptionSets.Contains(optionSetMetadata.Name))
                {
                    GeneratedOptionSets.Add(optionSetMetadata.Name);
                    generate = true;
                }
            }
            else
            {
                generate = true;
            }

            // Remove Dups
            var metadataOptionSet = optionSetMetadata as OptionSetMetadata;

            if (generate && metadataOptionSet != null)
            {
                var namingService = new NamingService((INamingService)services.GetService(typeof(INamingService)));
                var names         = new HashSet <string>();
                foreach (var option in metadataOptionSet.Options.ToList())
                {
                    var name = namingService.GetNameForOption(optionSetMetadata, option, services);
                    if (names.Contains(name))
                    {
                        metadataOptionSet.Options.Remove(option);
                    }
                    names.Add(name);
                }
            }

            return(generate);
        }
        public void Infer_SuccessfullyAccountsForReservedNames()
        {
            var validators = new List <Validator> {
                new ReservedNamesValidator(new string[] { "Page" })
            };
            var result = NamingService.Infer("Page", validators);

            Assert.Equal("Page1", result);
        }
        /// <summary>
        /// Does not mark the OptionSet for generation if it has already been generated.
        /// This could get called for the same Global Option Set multiple times because it's on multiple Entites
        /// </summary>
        public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
        {
#if SKIP_STATE_OPTIONSETS
            // Only skip the state optionsets if the user of the extension wishes to.
            if (optionSetMetadata.OptionSetType == OptionSetType.State)
            {
                return(false);
            }
#endif
            if (Skip(optionSetMetadata.Name))
            {
                return(false);
            }

            bool generate = false;

            if (optionSetMetadata.IsGlobal.GetValueOrDefault())
            {
                if (!GeneratedOptionSets.Contains(optionSetMetadata.Name))
                {
                    GeneratedOptionSets.Add(optionSetMetadata.Name);
                    generate = true;
                }
            }
            else
            {
                generate = true;
            }

            if (generate && optionSetMetadata.Name != null)
            {
                string name = optionSetMetadata.Name;
                if (name.ToLower().EndsWith("set"))
                {
                    optionSetMetadata.Name = name + "Enum";
                }
            }

            // Remove Dups
            var metadataOptionSet = optionSetMetadata as OptionSetMetadata;
            if (generate && metadataOptionSet != null)
            {
                var namingService = new NamingService((INamingService)services.GetService(typeof(INamingService)));
                var names         = new HashSet <string>();
                foreach (var option in metadataOptionSet.Options.ToList())
                {
                    var name = namingService.GetNameForOption(optionSetMetadata, option, services);
                    if (names.Contains(name))
                    {
                        metadataOptionSet.Options.Remove(option);
                    }
                    names.Add(name);
                }
            }

            return(generate);
        }
        /// <summary>
        /// Does not mark the OptionSet for generation if it has already been generated.
        /// This could get called for the same Global Option Set multiple times because it's on multiple Entities
        /// </summary>
        public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
        {
            PopulateUsedEntityGlobalOptionSetOnInitialCall(services);

            // Skip the state optionSets
            if (optionSetMetadata.OptionSetType == OptionSetType.State)
            {
                return(false);
            }

            if (optionSetMetadata.IsGlobal.GetValueOrDefault() &&
                GenerateOnlyReferencedOptionSets &&
                !UsedEntityGlobalOptionSets.Contains(optionSetMetadata.Name.ToLower()))
            {
                return(false);
            }


            if (!Approver.IsAllowed(optionSetMetadata.Name.ToLower()))
            {
                return(false);
            }

            var generate = false;

            if (optionSetMetadata.IsGlobal.GetValueOrDefault())
            {
                if (!GeneratedOptionSets.Contains(optionSetMetadata.Name))
                {
                    GeneratedOptionSets.Add(optionSetMetadata.Name);
                    generate = true;
                }
            }
            else
            {
                generate = true;
            }

            // Remove Dups
            if (generate && optionSetMetadata is OptionSetMetadata metadataOptionSet)
            {
                var namingService = new NamingService((INamingService)services.GetService(typeof(INamingService)));
                var names         = new HashSet <string>();
                foreach (var option in metadataOptionSet.Options.ToList())
                {
                    var name = namingService.GetNameForOption(optionSetMetadata, option, services);
                    if (names.Contains(name))
                    {
                        metadataOptionSet.Options.Remove(option);
                    }
                    names.Add(name);
                }
            }

            return(generate);
        }
        public void Infer_SuccessfullyAccountsForExistingNames()
        {
            Func <IEnumerable <string> > getExistingNames = () => { return(new string[] { "App" }); };
            var validators = new List <Validator> {
                new ExistingNamesValidator(getExistingNames)
            };
            var result = NamingService.Infer("App", validators);

            Assert.Equal("App1", result);
        }
        public void Infer_SuccessfullyAccountsForDefaultNames(string language)
        {
            SetUpFixtureForTesting(language);

            var validators = new List <Validator> {
                new DefaultNamesValidator()
            };
            var result = NamingService.Infer("LiveTile", validators);

            Assert.Equal("LiveTile1", result);
        }
        public void Validate_SuccessfullyIdentifies_ReservedProjectName()
        {
            var validators = new List <Validator>()
            {
                new ReservedNamesValidator(new string[] { "Prism" }),
            };
            var result = NamingService.Validate("Prism", validators);

            Assert.False(result.IsValid);
            Assert.Equal(ValidationErrorType.ReservedName, result.Errors.FirstOrDefault()?.ErrorType);
        }
        private static void PopulateUniqueNames()
        {
            var adoClientService = new AdoClientService();
            var namingService    = new NamingService(adoClientService);

            var countryCodes = adoClientService.GetCountryCodes();

            foreach (var countryCode in countryCodes)
            {
                namingService.SetUniqueNames("en", countryCode);
            }
        }
        public void Infer_SuccessfullyHandles_SuggestedDirectoryNameValidator()
        {
            var testDirectory = Path.GetTempPath();

            Directory.CreateDirectory(Path.Combine(testDirectory, "TestDir"));
            var result = NamingService.Infer("TestDir", new List <Validator>()
            {
                new FolderNameValidator(testDirectory)
            });

            Assert.Equal("TestDir1", result);
        }
        public void Infer_SuccessfullyHandles_FileExistsValidator()
        {
            var testDirectory = Path.GetTempPath();

            File.Create(Path.Combine(testDirectory, "TestFile"));
            var result = NamingService.Infer("TestFile", new List <Validator>()
            {
                new FileNameValidator(testDirectory)
            });

            Assert.Equal("TestFile1", result);
        }
Exemple #17
0
        public void CsAnalyzerDocumentationTest()
        {
            using (var namingService = NamingService.GetNamingService(CultureInfo.CurrentCulture))
            {
                if (!namingService.SupportsSpelling)
                {
                    Assert.Inconclusive(
                        "Spell checking is not available, most likely because Word 2010 is not installed.");
                }
            }

            this.RunTest("Documentation");
        }
        public static string GetTempGenerationPath(string projectName)
        {
            string projectGuid       = ToolBox.Shell.GetProjectGuidByName(GenContext.Current.ProjectName).ToString();
            var    projectTempFolder = Path.Combine(_tempGenerationFolder, projectGuid);

            Fs.EnsureFolder(projectTempFolder);
            var tempGenerationName = $"{projectName}_{DateTime.Now.FormatAsShortDateTime()}";
            var inferredName       = NamingService.Infer(tempGenerationName, new List <Validator> {
                new FolderNameValidator(projectTempFolder)
            }, "_");

            return(Path.Combine(projectTempFolder, inferredName, projectName));
        }
        public void Validate_SuccessfullyIdentifies_ValidProjectName()
        {
            var validators = new List <Validator>()
            {
                new ReservedNamesValidator(new string[] { "Prism" }),
                new RegExValidator(new RegExConfig()
                {
                    Name = "projectStartWith$", Pattern = "^[^\\$]"
                }),
            };
            var result = NamingService.Validate("App", validators);

            Assert.True(result.IsValid);
            Assert.Empty(result.Errors);
        }
        public void Validate_SuccessfullyIdentifies_ProjectStartsWith()
        {
            var validators = new List <Validator>()
            {
                new RegExValidator(new RegExConfig()
                {
                    Name = "projectStartWith$", Pattern = "^[^\\$]"
                }),
            };
            var result = NamingService.Validate("$App", validators);

            Assert.False(result.IsValid);
            Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType);
            Assert.Equal("projectStartWith$", result.Errors.FirstOrDefault()?.ValidatorName);
        }
Exemple #21
0
        private string GetMappingColumnName(PropertyInfo property, Type modelType)
        {
            string mappingColumnName = "";
            object attribute         = property.GetCustomAttributes(false)
                                       .Where(a => a is DBColumnAttribute)
                                       .First();

            mappingColumnName = ((DBColumnAttribute)attribute).ColumnName;
            if (mappingColumnName.Equals("Id"))
            {
                mappingColumnName = NamingService.GetIdName(modelType);
            }

            return(mappingColumnName);
        }
        public void Validate_RecognizesValidNameAsValid(string language)
        {
            SetUpFixtureForTesting(language);
            var validators = new List <Validator>()
            {
                new EmptyNameValidator(),
                new RegExValidator(new RegExConfig()
                {
                    Name = "badFormat", Pattern = "^((?!\\d)\\w+)$"
                }),
            };
            var result = NamingService.Validate("Blank1", validators);

            Assert.True(result.IsValid);
        }
        public void Validate_SuccessfullyIdentifies_NamesThatStartWithNumbers()
        {
            var validators = new List <Validator>()
            {
                new EmptyNameValidator(),
                new RegExValidator(new RegExConfig()
                {
                    Name = "badFormat", Pattern = "^((?!\\d)\\w+)$"
                }),
            };
            var result = NamingService.Validate("1Blank", validators);

            Assert.False(result.IsValid);
            Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType);
            Assert.Equal("badFormat", result.Errors.FirstOrDefault()?.ValidatorName);
        }
        public void Validate_SuccessfullyIdentifiesReservedNames()
        {
            var validators = new List <Validator>()
            {
                new EmptyNameValidator(),
                new RegExValidator(new RegExConfig()
                {
                    Name = "badFormat", Pattern = "^((?!\\d)\\w+)$"
                }),
                new ReservedNamesValidator(new string[] { "Page" }),
            };
            var result = NamingService.Validate("Page", validators);

            Assert.False(result.IsValid);
            Assert.Equal(ValidationErrorType.ReservedName, result.Errors.FirstOrDefault()?.ErrorType);
        }
Exemple #25
0
        public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
        {
            NamingService = new NamingService((INamingService)services.GetService(typeof(INamingService)));
            Services      = services;
            InitializeMappings();
            var types = codeUnit.Namespaces[0].Types;

            foreach (CodeTypeDeclaration type in types)
            {
                if (!type.IsClass || type.IsContextType() || type.IsBaseEntityType())
                {
                    continue;
                }

                var logicalName         = type.GetFieldInitalizedValue("EntityLogicalName");
                var propertiesToReplace = new Dictionary <int, CodeMemberProperty>();
                foreach (var member in type.Members)
                {
                    var property = member as CodeMemberProperty;
                    if (SkipProperty(property, type, logicalName))
                    {
                        continue;
                    }

                    // ReSharper disable once AssignNullToNotNullAttribute
                    propertiesToReplace[type.Members.IndexOf(property)] = GetOptionSetEnumType(property, logicalName);
                }

                foreach (var enumProp in propertiesToReplace.Where(p => p.Value != null).OrderByDescending(p => p.Key))
                {
                    if (ReplaceOptionSetProperties)
                    {
                        type.Members[enumProp.Key] = enumProp.Value;
                    }
                    else
                    {
                        type.Members.Insert(enumProp.Key + 1, enumProp.Value);
                    }
                }
            }

            if (!CreateBaseClasses)
            {
                // If creating Base Classes, this will be included in the base class
                types.Add(GetEntityOptionSetEnumDeclaration());
            }
        }
Exemple #26
0
        /// <summary>
        /// Handles the file drop
        /// </summary>
        /// <param name="file">The file being dropped</param>
        public void HandleDrop(string file)
        {
            IFdoConnectionManager connMgr = ServiceManager.Instance.GetService<IFdoConnectionManager>();
            NamingService namer = ServiceManager.Instance.GetService<NamingService>();
            FdoConnection conn = null;
            try
            {
                conn = ExpressUtility.CreateFlatFileConnection(file);
            }
            catch (Exception ex)
            {
                LoggingService.Error("Failed to load connection", ex);
                return;
            }

            string name = namer.GetDefaultConnectionName(conn.Provider, System.IO.Path.GetFileNameWithoutExtension(file));
            connMgr.AddConnection(name, conn);
        }
Exemple #27
0
        /// <summary>
        /// Returns True if the text has incorrect spelling.
        /// </summary>
        /// <param name="element">
        /// The element containing the text we're checking.
        /// </param>
        /// <param name="text">
        /// The text to check.
        /// </param>
        /// <param name="spellingError">
        /// Returns a comma separated list of words encountered as spelling errors.
        /// </param>
        /// <returns>
        /// True if the text contains an incorrect spelling.
        /// </returns>
        private static bool TextContainsIncorectSpelling(CsElement element, string text, out string spellingError)
        {
            NamingService namingService = NamingService.GetNamingService(element.Document.SourceCode.Project.Culture);

            spellingError = string.Empty;

            if (namingService.SupportsSpelling)
            {
                ICollection <string> recognizedWords = element.Document.SourceCode.Project.RecognizedWords;

                WordParser parser = new WordParser(text, WordParserOptions.SplitCompoundWords, recognizedWords);
                if (parser.PeekWord() != null)
                {
                    string word = parser.NextWord();
                    do
                    {
                        // Ignore words starting and ending with '$'.
                        // Ignore if in our recognized words list or correct spelling
                        string hint = null;
                        if ((word.StartsWith("$") && word.EndsWith("$")) || (recognizedWords.Contains(word) || IsSpelledCorrectly(namingService, word, out hint)))
                        {
                            continue;
                        }

                        // If we already have a spelling error for this element, add a comma to separate them.
                        if (!string.IsNullOrEmpty(spellingError))
                        {
                            spellingError += ", ";
                        }

                        spellingError += "'" + word + "'";

                        // Append a hint message to this spelling error if we have one.
                        if (hint != null && hint.Trim().Length > 0)
                        {
                            spellingError += " " + hint;
                        }
                    }while ((word = parser.NextWord()) != null);
                }
            }

            return(!string.IsNullOrEmpty(spellingError));
        }
Exemple #28
0
        private static void RunAdvancedVersion(ClientConfiguration clientConfig)
        {
            Console.WriteLine(
                "[{0}] Client {1} executing script {2} at {3} with advanced version",
                DateTime.Now.ToString("HH:mm:ss"),
                clientConfig.Username,
                clientConfig.Script,
                clientConfig.Url);

            NamingService namingService = new NamingService(
                clientConfig.NamingServersUrls,
                AdvancedGrpcMessageLayer.Instance);

            AdvancedKVSMessageLayer.SetContext(namingService);

            AdvancedClientController controller = new AdvancedClientController(namingService);

            RunMainLoop(controller, clientConfig);
        }
        public void Validate_SuccessfullyIdentifies_ValidPageSuffix()
        {
            var validators = new List <Validator>()
            {
                new EmptyNameValidator(),
                new RegExValidator(new RegExConfig()
                {
                    Name = "badFormat", Pattern = "^((?!\\d)\\w+)$"
                }),
                new RegExValidator(new RegExConfig()
                {
                    Name = "itemEndsWithPage", Pattern = ".*(?<!page)$"
                }),
            };
            var result = NamingService.Validate("BlankView", validators);

            Assert.True(result.IsValid);
            Assert.Empty(result.Errors);
        }
        public void Validate_SuccessfullyIdentifies_InvalidPageSuffix()
        {
            var validators = new List <Validator>()
            {
                new EmptyNameValidator(),
                new RegExValidator(new RegExConfig()
                {
                    Name = "badFormat", Pattern = "^((?!\\d)\\w+)$"
                }),
                new RegExValidator(new RegExConfig()
                {
                    Name = "itemEndsWithPage", Pattern = ".*(?<!page)$"
                }),
            };
            var result = NamingService.Validate("BlankPage", validators);

            Assert.False(result.IsValid);
            Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType);
            Assert.Equal("itemEndsWithPage", result.Errors.FirstOrDefault()?.ValidatorName);
        }