public void ModelWithDuplicateCustomAttribute_DoesNotThrowException() { ConfigurationContext.Current.CustomAttributes = new[] { new CustomAttributeDescriptor(typeof(FancyHelpTextAttribute)) }; var sut = new TypeDiscoveryHelper(); var resources = sut.ScanResources(typeof(ModelWithCustomAttributesDuplicates)); Assert.NotNull(resources); }
public LocalizedModelsDiscoveryTests() { var types = new[] { typeof(SampleViewModel), typeof(SubViewModel) }; var sut = new TypeDiscoveryHelper(); Assert.NotEmpty(types); _properties = types.SelectMany(t => sut.ScanResources(t)); }
public void ModelWithCustomAttribute_NullTranslation_DiscoversResource() { ConfigurationContext.Current.CustomAttributes = new[] { new CustomAttributeDescriptor(typeof(HelpTextAttribute), false) }; var sut = new TypeDiscoveryHelper(); var resources = sut.ScanResources(typeof(ModelWithCustomAttributes)); var helpTextResource = resources.First(r => r.PropertyName == "UserName-HelpText"); Assert.Equal(string.Empty, helpTextResource.Translation); }
public void SameModel_MultipleDefinitions_DoesNotThrowException() { var sut = new TypeDiscoveryHelper(); var resources = sut.ScanResources(typeof(ViewModelWithDuplicateSubModels)); Assert.NotNull(resources); var count = resources.Count(r => r.Key == "DbLocalizationProvider.Tests.SubModel.MyProperty-StringLength"); Assert.Equal(1, count); }
public void SingleLevel_ScalarProperties() { var sut = new TypeDiscoveryHelper(); var type = _types.First(t => t.FullName == "DbLocalizationProvider.Tests.ResourceKeys"); var properties = sut.ScanResources(type); var staticField = properties.First(p => p.Key == "DbLocalizationProvider.Tests.ResourceKeys.ThisIsConstant"); Assert.True(LocalizedTypeScannerBase.IsStringProperty(staticField.ReturnType)); Assert.Equal("Default value for constant", staticField.Translation); }
public void Test() { var sut = new TypeDiscoveryHelper(); var properties = new[] { typeof(SampleViewModelWithBaseNotInherit), typeof(BaseLocalizedViewModel) } .Select(t => sut.ScanResources(t)) .ToList(); var childModel = new SampleViewModelWithBaseNotInherit(); var basePropertyKey = ExpressionHelper.GetFullMemberName(() => childModel.BaseProperty); Assert.Equal("DbLocalizationProvider.Tests.InheritedModels.BaseLocalizedViewModel.BaseProperty", basePropertyKey); }
public void DiscoverForeignResourceNestedClass() { var sut = new TypeDiscoveryHelper(); var resources = sut.ScanResources(typeof(ResourceWithNoAttribute.NestedResource)); Assert.True(resources.Any()); var resource = resources.First(); Assert.Equal("NestedProperty", resource.Translations.DefaultTranslation()); Assert.Equal("DbLocalizationProvider.Tests.ForeignKnownResources.ResourceWithNoAttribute+NestedResource.NestedProperty", resource.Key); }
public void DiscoverForeignResourceClass_SingleProperty() { var sut = new TypeDiscoveryHelper(); var resources = sut.ScanResources(typeof(ResourceWithNoAttribute)); Assert.True(resources.Any()); var resource = resources.First(); Assert.Equal("Default resource value", resource.Translation); Assert.Equal("DbLocalizationProvider.Tests.ForeignKnownResources.ResourceWithNoAttribute.SampleProperty", resource.Key); }
public void DiscoverClassField_RespectsResourceKeyAttribute() { var sut = new TypeDiscoveryHelper(); var discoveredModels = sut.ScanResources(typeof(LocalizedModelWithFieldResourceKeys)); // check return Assert.NotEmpty(discoveredModels); // check discovered translation Assert.Equal("/this/is/key", discoveredModels.First().Key); Assert.Equal("/this/is/key", ResourceKeyBuilder.BuildResourceKey(typeof(LocalizedModelWithFieldResourceKeys), nameof(LocalizedModelWithFieldResourceKeys.AnotherField))); }
public void ProperRenameDiscoveryTests(Type target, string resourceKey, string oldTypeName, string typeOldNamespace, string oldResourceKey) { var sut = new TypeDiscoveryHelper(); var result = sut.ScanResources(target); Assert.NotEmpty(result); var discoveredResource = result.First(); Assert.Equal(resourceKey, discoveredResource.Key); Assert.Equal(oldTypeName, discoveredResource.TypeOldName); Assert.Equal(typeOldNamespace, discoveredResource.TypeOldNamespace); Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey); }
public void Test() { var sut = new TypeDiscoveryHelper(); var properties = new[] { typeof(SampleViewModelWithBaseNotInherit), typeof(BaseLocalizedViewModel) } .Select(t => sut.ScanResources(t)) .ToList(); var childModel = new SampleViewModelWithBaseNotInherit(); var basePropertyKey = ExpressionHelper.GetFullMemberName(() => childModel.BaseProperty); Assert.Equal("DbLocalizationProvider.Tests.InheritedModels.BaseLocalizedViewModel.BaseProperty", basePropertyKey); }
private void RegisterDiscoveredResources(IEnumerable<Type> types) { var helper = new TypeDiscoveryHelper(); var properties = types.SelectMany(type => helper.ScanResources(type)).DistinctBy(r => r.Key); using (var db = new LanguageEntities()) { foreach (var property in properties) RegisterIfNotExist(db, property.Key, property.Translation); db.SaveChanges(); } }
public void DiscoverClassField_ChildClassWithNoInherit_FieldIsNotInChildClassNamespace() { var discoveredModels = new[] { typeof(LocalizedChildModelWithFields), typeof(LocalizedBaseModelWithFields) } .SelectMany(t => _sut.ScanResources(t)).ToList(); // check return Assert.NotEmpty(discoveredModels); }
public void DiscoverEnumValue_NameAsTranslation() { var properties = _sut.ScanResources(typeof(SampleStatus)); var openStatus = properties.First(p => p.Key == "DbLocalizationProvider.Tests.EnumTests.SampleStatus.Open"); Assert.Equal("Open", openStatus.Translations.DefaultTranslation()); }
public void NotInheritedModel_ContainsOnlyDeclaredProperties() { var sut = new TypeDiscoveryHelper(); var properties = sut.ScanResources(typeof(SampleViewModelWithBase)).ToList(); var keys = properties.Select(p => p.Key).ToList(); var stringLengthResource = properties.FirstOrDefault(r => r.Key == "DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.ChildProperty-StringLength"); Assert.Contains("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.ChildProperty-Description", keys); Assert.NotNull(stringLengthResource); Assert.Contains("StringLength", stringLengthResource.Translation); Assert.DoesNotContain("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.BaseProperty", keys); Assert.DoesNotContain("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.BaseProperty-Required", keys); Assert.DoesNotContain("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.ChildProperty-Description-Required", keys); }
public void ModelAdditionalResourceProperRenameDiscoveryTests(Type target, string resourceKey, string secondResourceKey, string oldResourceKey, string oldSecondResourceKey) { var sut = new TypeDiscoveryHelper(); var result = sut.ScanResources(target); Assert.NotEmpty(result); var discoveredResource = result.First(); var secondDiscoveredResource = result.Skip(1).First(); Assert.Equal(resourceKey, discoveredResource.Key); Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey); Assert.Equal(secondResourceKey, secondDiscoveredResource.Key); Assert.Equal(oldSecondResourceKey, secondDiscoveredResource.OldResourceKey); }
public void DiscoverForeignResource_Enum() { var sut = new TypeDiscoveryHelper(); var resources = sut.ScanResources(typeof(SomeEnum)); Assert.True(resources.Any()); Assert.Equal(3, resources.Count()); var resource = resources.First(); Assert.Equal("None", resource.Translations.DefaultTranslation()); Assert.Equal("DbLocalizationProvider.Tests.ForeignKnownResources.SomeEnum.None", resource.Key); }
public void ModelWith2ChildModelAsProperties_ReturnsDuplicates() { var sut = new TypeDiscoveryHelper(); var types = new[] { typeof(ModelWithTwoChildModelPropertiesCustomAttributes), typeof(AnotherModelWithTwoChildModelPropertiesCustomAttributes) }; var resources = types.SelectMany(t => sut.ScanResources(t)).DistinctBy(r => r.Key); var containsDuplicates = resources.GroupBy(r => r.Key).Any(g => g.Count() > 1); Assert.False(containsDuplicates); }
public void NotInheritedModel_ContainsOnlyDeclaredProperties() { var sut = new TypeDiscoveryHelper(); var properties = sut.ScanResources(typeof(SampleViewModelWithBase)).ToList(); var keys = properties.Select(p => p.Key).ToList(); var stringLengthResource = properties.FirstOrDefault(r => r.Key == "DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.ChildProperty-StringLength"); Assert.Contains("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.ChildProperty-Description", keys); Assert.NotNull(stringLengthResource); Assert.Contains("StringLength", stringLengthResource.Translation); Assert.DoesNotContain("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.BaseProperty", keys); Assert.DoesNotContain("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.BaseProperty-Required", keys); Assert.DoesNotContain("DbLocalizationProvider.Tests.DataAnnotations.SampleViewModelWithBase.ChildProperty-Description-Required", keys); }
public void DiscoverHiddenEnumProperties() { var sut = new TypeDiscoveryHelper(); var result = sut.ScanResources(typeof(SomeEnumWithHiddenResources)); Assert.NotEmpty(result); var firstResource = result.First(); Assert.False(firstResource.IsHidden); var middleResource = result.First(r => r.Key == "DbLocalizationProvider.Tests.HiddenResourcesTests.SomeEnumWithHiddenResources.Some"); Assert.True(middleResource.IsHidden); }
public void DiscoverClassInstanceField() { var sut = new TypeDiscoveryHelper(); var t = new LocalizedModelWithInstanceField(); var discoveredModels = sut.ScanResources(t.GetType()); // check return Assert.NotEmpty(discoveredModels); // check discovered translation Assert.Equal("instance field value", discoveredModels.First().Translations.DefaultTranslation()); Assert.Equal("DbLocalizationProvider.Tests.ClassFieldsTests.LocalizedModelWithInstanceField.ThisIsInstanceField", ExpressionHelper.GetFullMemberName(() => t.ThisIsInstanceField)); }
public void DiscoverClassField_WithDefaultValue() { var sut = new TypeDiscoveryHelper(); var discoveredModels = sut.ScanResources(typeof(LocalizedModelWithFields)); // check return Assert.NotEmpty(discoveredModels); // check discovered translation Assert.Equal("other value", discoveredModels.First().Translations.DefaultTranslation()); //// check generated key from expression Assert.Equal("DbLocalizationProvider.Tests.ClassFieldsTests.LocalizedModelWithFields.AnotherField", ExpressionHelper.GetFullMemberName(() => LocalizedModelWithFields.AnotherField)); }
public void ModelCustomAttributesResourceProperRenameDiscoveryTests( Type target, string resourceKey, string secondResourceKey, string oldResourceKey, string oldSecondResourceKey) { var sut = new TypeDiscoveryHelper(); var result = sut.ScanResources(target); Assert.NotEmpty(result); Assert.Equal(2, result.Count()); var discoveredResource = result.First(dr => dr.Key.EndsWith("NewResourceKey")); var secondDiscoveredResource = result.First(dr => dr.Key.EndsWith("AdditionalData")); Assert.Equal(resourceKey, discoveredResource.Key); Assert.Equal(oldResourceKey, discoveredResource.OldResourceKey); Assert.Equal(secondResourceKey, secondDiscoveredResource.Key); Assert.Equal(oldSecondResourceKey, secondDiscoveredResource.OldResourceKey); }
public void ModelWith2ChildModelAsProperties_ReturnsDuplicates() { ConfigurationContext.Current.CustomAttributes = new[] { new CustomAttributeDescriptor(typeof(HelpTextAttribute), false), new CustomAttributeDescriptor(typeof(FancyHelpTextAttribute), false) }; var sut = new TypeDiscoveryHelper(); var types = new[] { typeof(ModelWithTwoChildModelPropertiesCustomAttributes), typeof(AnotherModelWithTwoChildModelPropertiesCustomAttributes) }; var resources = types.SelectMany(t => sut.ScanResources(t)).DistinctBy(r => r.Key); var containsDuplicates = resources.GroupBy(r => r.Key).Any(g => g.Count() > 1); Assert.False(containsDuplicates); }
public void ModelWith2ChildModelAsProperties_ReturnsDuplicates() { ConfigurationContext.Current.CustomAttributes = new[] { new CustomAttributeDescriptor(typeof(HelpTextAttribute), false), new CustomAttributeDescriptor(typeof(FancyHelpTextAttribute), false) }; var sut = new TypeDiscoveryHelper(); var types = new[] { typeof(ModelWithTwoChildModelPropertiesCustomAttributes), typeof(AnotherModelWithTwoChildModelPropertiesCustomAttributes) }; var resources = types.SelectMany(t => sut.ScanResources(t)).DistinctBy(r => r.Key); var containsDuplicates = resources.GroupBy(r => r.Key).Any(g => g.Count() > 1); Assert.False(containsDuplicates); }
public void ModelWithResourceKeysOnValidationAttributes_GetsCorrectCustomKey() { var sut = new TypeDiscoveryHelper(); var container = typeof(ModelWithDataAnnotationsAndResourceKey); var properties = sut.ScanResources(container); Assert.NotEmpty(properties); Assert.Equal(2, properties.Count()); Assert.NotNull(properties.First(r => r.Key == "the-key")); var requiredResource = properties.First(r => r.Key == "the-key-Required"); Assert.NotNull(requiredResource); Assert.Equal("User name is required!", requiredResource.Translations.DefaultTranslation()); var resourceKey = ResourceKeyBuilder.BuildResourceKey(container, nameof(ModelWithDataAnnotationsAndResourceKey.UserName)); Assert.Equal("the-key", resourceKey); var requiredResourceKey = ResourceKeyBuilder.BuildResourceKey(container, nameof(ModelWithDataAnnotationsAndResourceKey.UserName), new RequiredAttribute()); Assert.Equal("the-key-Required", requiredResourceKey); }
public LocalizedModelsDiscoveryTests() { var types = new[] { typeof(SampleViewModel), typeof(SubViewModel) }; var state = new ScanState(); var keyBuilder = new ResourceKeyBuilder(state); var oldKeyBuilder = new OldResourceKeyBuilder(keyBuilder); var ctx = new ConfigurationContext(); ctx.TypeFactory.ForQuery <DetermineDefaultCulture.Query>().SetHandler <DetermineDefaultCulture.Handler>(); var queryExecutor = new QueryExecutor(ctx.TypeFactory); var translationBuilder = new DiscoveredTranslationBuilder(queryExecutor); var sut = new TypeDiscoveryHelper(new List <IResourceTypeScanner> { new LocalizedModelTypeScanner(keyBuilder, oldKeyBuilder, state, ctx, translationBuilder), new LocalizedResourceTypeScanner(keyBuilder, oldKeyBuilder, state, ctx, translationBuilder), new LocalizedEnumTypeScanner(keyBuilder, translationBuilder), new LocalizedForeignResourceTypeScanner(keyBuilder, oldKeyBuilder, state, ctx, translationBuilder) }, ctx); _properties = types.SelectMany(t => sut.ScanResources(t)); }
public void ResourceWithBaseClass_NoInheritance_ScannedOnlyDirectProperties() { var result = _sut.ScanResources(typeof(ResourceWithBaseClassNoInheritance)); Assert.Equal(1, result.Count()); }
/// <summary>Registers the discovered resources.</summary> /// <param name="types"> The types. </param> /// <param name="allResources"> all resources. </param> private void RegisterDiscoveredResources(IEnumerable <Type> types, IList <LocalizationResource> allResources) { var helper = new TypeDiscoveryHelper(); var props = types.SelectMany(type => helper.ScanResources(type)).DistinctBy(r => r.Key); // split work queue by 400 resources each var groupedProperties = props.SplitByCount(400); // loop through all groups foreach (var group in groupedProperties) { using (var uow = _dataService.StartUnitOfWork()) { var resourceRepository = uow.ResourceRepository; var translationRepository = uow.TranslationRepository; // enumerate beforehand var properties = group.ToList(); // loop through all refactored properties and change their key foreach (var refactoredResource in properties.Where(r => !string.IsNullOrEmpty(r.OldResourceKey))) { if (resourceRepository.RefactorKey(refactoredResource.OldResourceKey, refactoredResource.Key)) { allResources.Single(r => r.ResourceKey == refactoredResource.OldResourceKey).ResourceKey = refactoredResource.Key; } } // loop through all properties foreach (var property in properties) { var existingResource = allResources.FirstOrDefault(r => r.ResourceKey == property.Key); if (existingResource == null) { // add the new resource var newResource = resourceRepository.Add(new ResourceEntity { Author = "Code", FromCode = true, IsHidden = property.IsHidden, IsModified = false, ResourceKey = property.Key, ModificationDate = DateTime.Now }); //we don't have to respect existing translations - just insert them all translationRepository.AddRange(property.Translations.Select(t => new TranslationEntity { ResourceId = newResource.Id, Language = t.Culture, Value = t.Translation })); } else { // update the existing resource var resourceEntity = resourceRepository.GetByKey(existingResource.ResourceKey); resourceEntity.FromCode = true; resourceEntity.IsHidden = property.IsHidden; resourceRepository.Update(resourceEntity); // add/update languages var byResource = translationRepository.ByResource(resourceEntity); var existingTranslations = byResource.ToDictionary(t => t.Language ?? string.Empty); foreach (var translation in property.Translations) { // if it exists - update it if it was modified or the invariant translations if (existingTranslations.ContainsKey(translation.Culture)) { // skip if modified - or culture isnt invariant if (translation.Culture != string.Empty && (!existingResource.IsModified.HasValue || existingResource.IsModified.Value)) { continue; } var entity = existingTranslations[translation.Culture]; entity.Value = translation.Translation; translationRepository.Update(entity); } // if it doesnt - add it else { translationRepository.Add(new TranslationEntity { Language = translation.Culture, ResourceId = existingResource.Id, Value = translation.Translation }); } } } } uow.Commit(); } } }
public void ScanResourceWillScalarEnumerables_ShouldDiscover() { var properties = _sut.ScanResources(typeof(ResourceClassWithScalarCollection)); Assert.Equal(2, properties.Count()); }
public void ThrowOnDuplicateCultures() { var sut = new TypeDiscoveryHelper(); Assert.Throws <DuplicateResourceTranslationsException>(() => sut.ScanResources(typeof(SomeResourcesWithDuplicateCultures))); }
public void UseResourceAttribute_NoResourceRegistered() { var results = _sut.ScanResources(typeof(ModelWithOtherResourceUsage)); Assert.Empty(results); }
private void RegisterDiscoveredResources(IEnumerable <Type> types, IEnumerable <LocalizationResource> allResources) { var helper = new TypeDiscoveryHelper(); var properties = types.SelectMany(type => helper.ScanResources(type)).DistinctBy(r => r.Key); // split work queue by 400 resources each var groupedProperties = properties.SplitByCount(400); Parallel.ForEach(groupedProperties, group => { var sb = new StringBuilder(); sb.AppendLine("declare @resourceId int"); var refactoredResources = group.Where(r => !string.IsNullOrEmpty(r.OldResourceKey)); foreach (var refactoredResource in refactoredResources) { sb.Append($@" if exists(select 1 from localizationresources with(nolock) where resourcekey = '{refactoredResource.OldResourceKey}') begin update dbo.localizationresources set resourcekey = '{refactoredResource.Key}', fromcode = 1 where resourcekey = '{refactoredResource.OldResourceKey}' end "); } foreach (var property in group) { var existingResource = allResources.FirstOrDefault(r => r.ResourceKey == property.Key); if (existingResource == null) { sb.Append($@" set @resourceId = isnull((select id from localizationresources where [resourcekey] = '{property.Key}'), -1) if (@resourceId = -1) begin insert into localizationresources ([resourcekey], modificationdate, author, fromcode, ismodified, ishidden) values ('{property.Key}', getutcdate(), 'type-scanner', 1, 0, {Convert.ToInt32(property.IsHidden)}) set @resourceId = SCOPE_IDENTITY()"); // add all translations foreach (var propertyTranslation in property.Translations) { sb.Append($@" insert into localizationresourcetranslations (resourceid, [language], [value]) values (@resourceId, '{propertyTranslation.Culture}', N'{ propertyTranslation.Translation.Replace("'", "''") }') "); } sb.Append(@" end "); } if (existingResource != null) { sb.AppendLine($"update localizationresources set fromcode = 1, ishidden = {Convert.ToInt32(property.IsHidden)} where [id] = {existingResource.Id}"); var invariantTranslation = property.Translations.First(t => t.Culture == string.Empty); sb.AppendLine($"update localizationresourcetranslations set [value] = N'{invariantTranslation.Translation.Replace("'", "''")}' where resourceid={existingResource.Id} and [language]='{invariantTranslation.Culture}'"); if (existingResource.IsModified.HasValue && !existingResource.IsModified.Value) { foreach (var propertyTranslation in property.Translations) { AddTranslationScript(existingResource, sb, propertyTranslation); } } } } using (var conn = new SqlConnection(ConfigurationContext.Current.DbContextConnectionString)) { var cmd = new SqlCommand(sb.ToString(), conn) { CommandTimeout = 60 }; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } }); }
public void TestGenericProperty() { var properties = _sut.ScanResources(typeof(OpenGenericModel <>)); Assert.NotEmpty(properties); }
public void DuplicateAttributes_DiffProperties_SameKey_ThrowsException() { var model = new[] { typeof(BadResourceWithDuplicateKeysWithinClass) }; Assert.Throws <DuplicateResourceKeyException>(() => model.SelectMany(t => _sut.ScanResources(t)).ToList()); }
public void ScanResource_BadTranslationLanguage() { var sut = new TypeDiscoveryHelper(); Assert.Throws <ArgumentException>(() => sut.ScanResources(typeof(BadResourceWithNoExistingLanguageCode))); }
public void Test1() { _sut.ScanResources(typeof(ResourceClassWithRecursiveProperty)); Assert.True(TypeDiscoveryHelper.DiscoveredResourceCache.ContainsKey("DbLocalizationProvider.Tests.RecursiveModelsTests.ResourceClassWithRecursiveProperty")); }