Owner
stringclasses
774 values
Repo
stringclasses
979 values
SolutionFilePath
stringlengths
32
160
ProjectFilePath
stringlengths
47
196
FilePath
stringlengths
43
230
Namespace
stringlengths
5
182
ClassDeclaration
stringlengths
2
78
ClassFields
stringlengths
2
458k
UsingStatements
stringlengths
9
3.14k
TestFramework
stringclasses
4 values
LanguageFramework
stringclasses
236 values
ClassBody
stringlengths
100
627k
ClassBodyStartPos
int64
16
176k
ClassBodyEndPos
int64
179
636k
SourceBody
stringlengths
32
3.67M
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\TokenAllocatorTest.cs
AsmResolver.DotNet.Tests
TokenAllocatorTest
[]
['System', 'System.Linq', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit']
xUnit
net8.0
public class TokenAllocatorTest { [Fact] public void AssigningAvailableTokenShouldSetMetadataToken() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var typeRef = new TypeReference(module, "", ""); var nextToken = module.TokenAllocator.GetNextAvailableToken(TableIndex.TypeRef); module.TokenAllocator.AssignNextAvailableToken(typeRef); Assert.NotEqual((uint)0,nextToken.Rid); Assert.Equal(nextToken, typeRef.MetadataToken); } [Theory] [InlineData(TableIndex.TypeRef)] [InlineData(TableIndex.TypeDef)] [InlineData(TableIndex.Field)] [InlineData(TableIndex.MemberRef)] [InlineData(TableIndex.Property)] [InlineData(TableIndex.Method)] [InlineData(TableIndex.AssemblyRef)] public void GetNextAvailableTokenShouldReturnTableSize(TableIndex index) { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var tableStream = module.DotNetDirectory.Metadata.GetStream<TablesStream>(); var table = tableStream.GetTable(index); var count = (uint)table.Count; var nextToken = module.TokenAllocator.GetNextAvailableToken(index); Assert.Equal(count + 1, nextToken.Rid); } [Fact] public void NextAvailableTokenShouldChangeAfterAssigning() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var typeRef = new TypeReference(module, "", ""); var nextToken = module.TokenAllocator.GetNextAvailableToken(TableIndex.TypeRef); module.TokenAllocator.AssignNextAvailableToken(typeRef); var typeRef2 = new TypeReference(module, "", ""); module.TokenAllocator.AssignNextAvailableToken(typeRef2); Assert.Equal(nextToken.Rid + 1, typeRef2.MetadataToken.Rid); } [Fact] public void AssignTokenToNewUnusedTypeReferenceShouldPreserveAfterBuild() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var reference = new TypeReference(module, module, "SomeNamespace", "SomeType"); module.TokenAllocator.AssignNextAvailableToken(reference); var image = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveTypeReferenceIndices)); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var newReference = (TypeReference) newModule.LookupMember(reference.MetadataToken); Assert.Equal(reference.Namespace, newReference.Namespace); Assert.Equal(reference.Name, newReference.Name); } [Fact] public void AssignTokenToNewUnusedMemberReferenceShouldPreserveAfterBuild() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var reference = new MemberReference( new TypeReference(module, module, "SomeNamespace", "SomeType"), "SomeMethod", MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)); module.TokenAllocator.AssignNextAvailableToken(reference); var image = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveMemberReferenceIndices)); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var newReference = (MemberReference) newModule.LookupMember(reference.MetadataToken); Assert.Equal(reference.Name, newReference.Name); } [Fact] public void AssignTokenOfNextMemberShouldPreserve() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); // Create two dummy fields. var fieldType = module.CorLibTypeFactory.Object; var field1 = new FieldDefinition("NonAssignedField", FieldAttributes.Static, fieldType); var field2 = new FieldDefinition("AssignedField", FieldAttributes.Static, fieldType); // Add both. var moduleType = module.GetOrCreateModuleType(); moduleType.Fields.Add(field1); moduleType.Fields.Add(field2); // Only assign token to the second one, but leave the first one floating. module.TokenAllocator.AssignNextAvailableToken(field2); // Rebuild. var image = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveAll)); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); // Verify. Assert.Equal(field2.Name, ((FieldDefinition) newModule.LookupMember(field2.MetadataToken)).Name); } [Fact] public void Issue187() { // https://github.com/Washi1337/AsmResolver/issues/187 var targetModule = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var method = new MethodDefinition("test", MethodAttributes.Public | MethodAttributes.Static, MethodSignature.CreateStatic(targetModule.CorLibTypeFactory.Boolean)); var body = new CilMethodBody(method); body.Instructions.Add(CilOpCodes.Ldc_I4, 0); body.Instructions.Add(CilOpCodes.Ret); method.CilMethodBody = body; targetModule.TopLevelTypes.First().Methods.Add(method); var allocator = targetModule.TokenAllocator; allocator.AssignNextAvailableToken(method); targetModule.GetOrCreateModuleConstructor(); _ = targetModule.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveAll)); } [Fact] public void Issue252() { // https://github.com/Washi1337/AsmResolver/issues/252 var module = ModuleDefinition.FromFile(typeof(TokenAllocatorTest).Assembly.Location, TestReaderParameters); var asmResRef = module.AssemblyReferences.First(a => a.Name == "AsmResolver.DotNet"); var reference = new TypeReference(module, asmResRef, "AsmResolver.DotNet", "MethodDefinition"); var reference2 = new TypeReference(module, asmResRef, "AsmResolver.DotNet", "ModuleDefinition"); module.TokenAllocator.AssignNextAvailableToken(reference); module.TokenAllocator.AssignNextAvailableToken(reference2); var image = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveAll)); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var newReference = (TypeReference) newModule.LookupMember(reference.MetadataToken); var newReference2 = (TypeReference) newModule.LookupMember(reference2.MetadataToken); Assert.Equal(reference.Namespace, newReference.Namespace); Assert.Equal(reference.Name, newReference.Name); Assert.Equal(reference2.Namespace, newReference2.Namespace); Assert.Equal(reference2.Name, newReference2.Name); } }
322
7,823
using System; using System.Collections.Generic; using AsmResolver.PE.DotNet; using AsmResolver.PE.DotNet.Metadata; using AsmResolver.PE.DotNet.Metadata.Tables; namespace AsmResolver.DotNet { /// <summary> /// Provides a mechanism to assign metadata tokens /// </summary> public sealed class TokenAllocator { private readonly TokenBucket[] _buckets = new TokenBucket[(int) TableIndex.Max]; internal TokenAllocator(ModuleDefinition module) { if (module is null) throw new ArgumentNullException(nameof(module)); Initialize(module.DotNetDirectory); } private void Initialize(DotNetDirectory? netDirectory) { if (netDirectory is null) InitializeDefault(); else InitializeTable(netDirectory); } private void InitializeDefault() { for (TableIndex index = 0; index < TableIndex.Max; index++) _buckets[(int) index] = new TokenBucket(new MetadataToken(index, 1)); } private void InitializeTable(DotNetDirectory netDirectory) { var tableStream = netDirectory.Metadata!.GetStream<TablesStream>(); for (TableIndex index = 0; index < TableIndex.Max; index++) { if (!index.IsValidTableIndex()) continue; var table = tableStream.GetTable(index); _buckets[(int) index] = new TokenBucket(new MetadataToken(index, (uint) table.Count + 1)); } } /// <summary> /// Obtains the next unused <see cref="MetadataToken"/> for the provided table. /// </summary> /// <param name="index">Type of <see cref="MetadataToken"/></param> /// <remarks> /// This method is pure. That is, it only returns the next available metadata token and does not claim /// any metadata token. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// Occurs when an invalid <see cref="TableIndex"/> is provided. /// </exception> /// <returns>The next unused <see cref="MetadataToken"/>.</returns> public MetadataToken GetNextAvailableToken(TableIndex index) { return _buckets[(int) index].GetNextAvailableToken(); } /// <summary> /// Determines the next metadata token for provided member and assigns it. /// </summary> /// <remarks>This method only succeeds when new or copied member is provided</remarks> /// <exception cref="ArgumentNullException">Occurs when <paramref name="member"/> is null</exception> /// <exception cref="ArgumentException"> /// Occurs when <paramref name="member"/> is already assigned a <see cref="MetadataToken"/> /// </exception> /// <param name="member">The member to assign a new metadata token.</param> public void AssignNextAvailableToken(MetadataMember member) { if (member is null) throw new ArgumentNullException(nameof(member)); if (member.MetadataToken.Rid != 0) throw new ArgumentException("Only new members can be assigned a new metadata token"); var index = member.MetadataToken.Table; member.MetadataToken = GetNextAvailableToken(index); _buckets[(int) index].AssignedMembers.Add(member); } /// <summary> /// Obtains the members that were manually assigned a new metadata token using this token allocator. /// </summary> /// <param name="table">The table for which to get the assignees from.</param> /// <returns>The assignees.</returns> public IEnumerable<IMetadataMember> GetAssignees(TableIndex table) => _buckets[(int) table].AssignedMembers; private readonly struct TokenBucket { public TokenBucket(MetadataToken baseToken) { BaseToken = baseToken; AssignedMembers = new List<IMetadataMember>(); } public MetadataToken BaseToken { get; } public List<IMetadataMember> AssignedMembers { get; } public MetadataToken GetNextAvailableToken() => new(BaseToken.Table, (uint) (BaseToken.Rid + AssignedMembers.Count)); } } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\TypeDefinitionTest.cs
AsmResolver.DotNet.Tests
TypeDefinitionTest
['private static readonly SignatureComparer Comparer = new();']
['System', 'System.Collections.Generic', 'System.IO', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.CustomAttributes', 'AsmResolver.DotNet.TestCases.Events', 'AsmResolver.DotNet.TestCases.Fields', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.DotNet.TestCases.NestedClasses', 'AsmResolver.DotNet.TestCases.Properties', 'AsmResolver.DotNet.TestCases.Types', 'AsmResolver.DotNet.TestCases.Types.Structs', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit']
xUnit
net8.0
public class TypeDefinitionTest { private static readonly SignatureComparer Comparer = new(); private TypeDefinition RebuildAndLookup(TypeDefinition type) { var stream = new MemoryStream(); type.Module!.Write(stream); var newModule = ModuleDefinition.FromBytes(stream.ToArray(), TestReaderParameters); return newModule.TopLevelTypes.FirstOrDefault(t => t.FullName == type.FullName); } private void AssertNamesEqual(IEnumerable<INameProvider> expected, IEnumerable<INameProvider> actual) { Assert.Equal(expected.Select(n => n.Name), actual.Select(n => n.Name)); } [Fact] public void LinkedToModule() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); foreach (var type in module.TopLevelTypes) Assert.Same(module, type.Module); } [Fact] public void ReadName() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); Assert.Equal("<Module>", module.TopLevelTypes[0].Name); Assert.Equal("Program", module.TopLevelTypes[1].Name); } [Fact] public void ReadNameFromNormalMetadata() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_DoubleStringsStream, TestReaderParameters); Assert.Equal("Class_2", module.TopLevelTypes[1].Name); } [Fact] public void ReadNameFromEnCMetadata() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_DoubleStringsStream_EnC, TestReaderParameters); Assert.Equal("Class_1", module.TopLevelTypes[1].Name); } [Fact] public void NameIsPersistentAfterRebuild() { const string newName = "SomeType"; var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == "Program"); type.Name = newName; var newType = RebuildAndLookup(type); Assert.Equal(newName, newType.Name); } [Fact] public void ReadNamespace() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); Assert.Null(module.TopLevelTypes[0].Namespace); Assert.Equal("HelloWorld", module.TopLevelTypes[1].Namespace); } [Fact] public void ReadTopLevelTypeFullName() { var module = ModuleDefinition.FromFile(typeof(Class).Assembly.Location, TestReaderParameters); var type = (TypeDefinition) module.LookupMember(typeof(Class).MetadataToken); Assert.Equal("AsmResolver.DotNet.TestCases.Types.Class", type.FullName); } [Fact] public void NonNullNamespaceIsPersistentAfterRebuild() { const string newNameSpace = "SomeNamespace"; var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == "Program"); type.Namespace = newNameSpace; var newType = RebuildAndLookup(type); Assert.Equal(newNameSpace, newType.Namespace); } [Fact] public void NullNamespaceIsPersistentAfterRebuild() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == "Program"); type.Namespace = null; var newType = RebuildAndLookup(type); Assert.Null(newType.Namespace); } [Fact] public void ReadBaseType() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); Assert.Null(module.TopLevelTypes[0].BaseType); Assert.NotNull(module.TopLevelTypes[1].BaseType); Assert.Equal("System.Object", module.TopLevelTypes[1].BaseType.FullName); } [Fact] public void ReadNestedTypes() { var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters); var class1 = module.TopLevelTypes.First(t => t.Name == nameof(TopLevelClass1)); Assert.Equal(new Utf8String[] { nameof(TopLevelClass1.Nested1), nameof(TopLevelClass1.Nested2) }, class1.NestedTypes.Select(t => t.Name)); var nested1 = class1.NestedTypes.First(t => t.Name == nameof(TopLevelClass1.Nested1)); Assert.Equal(new Utf8String[] { nameof(TopLevelClass1.Nested1.Nested1Nested1), nameof(TopLevelClass1.Nested1.Nested1Nested2) }, nested1.NestedTypes.Select(t => t.Name)); var nested2 = class1.NestedTypes.First(t => t.Name == nameof(TopLevelClass1.Nested2)); Assert.Equal(new Utf8String[] { nameof(TopLevelClass1.Nested2.Nested2Nested1), nameof(TopLevelClass1.Nested2.Nested2Nested2) }, nested2.NestedTypes.Select(t => t.Name)); var class2 = module.TopLevelTypes.First(t => t.Name == nameof(TopLevelClass2)); Assert.Equal(new Utf8String[] { nameof(TopLevelClass2.Nested3), nameof(TopLevelClass2.Nested4) }, class2.NestedTypes.Select(t => t.Name)); var nested3 = class2.NestedTypes.First(t => t.Name == nameof(TopLevelClass2.Nested3)); Assert.Equal(new Utf8String[] { nameof(TopLevelClass2.Nested3.Nested3Nested1), nameof(TopLevelClass2.Nested3.Nested3Nested2) }, nested3.NestedTypes.Select(t => t.Name)); var nested4 = class2.NestedTypes.First(t => t.Name == nameof(TopLevelClass2.Nested4)); Assert.Equal(new Utf8String[] { nameof(TopLevelClass2.Nested4.Nested4Nested1), nameof(TopLevelClass2.Nested4.Nested4Nested2) }, nested4.NestedTypes.Select(t => t.Name)); Assert.Same(class1, nested1.DeclaringType); Assert.Same(class1, nested2.DeclaringType); Assert.Same(class2, nested3.DeclaringType); Assert.Same(class2, nested4.DeclaringType); Assert.Same(module, nested1.Module); Assert.Same(module, nested2.Module); Assert.Same(module, nested3.Module); Assert.Same(module, nested4.Module); } [Fact] public void ReadNestedFullName() { var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters); var type = (TypeDefinition) module.LookupMember(typeof(TopLevelClass1.Nested1).MetadataToken); Assert.Equal("AsmResolver.DotNet.TestCases.NestedClasses.TopLevelClass1+Nested1", type.FullName); } [Fact] public void ReadNestedNestedFullName() { var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters); var type = (TypeDefinition) module.LookupMember(typeof(TopLevelClass1.Nested1.Nested1Nested2) .MetadataToken); Assert.Equal("AsmResolver.DotNet.TestCases.NestedClasses.TopLevelClass1+Nested1+Nested1Nested2", type.FullName); } [Fact] public void ResolveNestedType() { var module = ModuleDefinition.FromFile(typeof(TopLevelClass1).Assembly.Location, TestReaderParameters); var member = (TypeDefinition) module.LookupMember(new MetadataToken(TableIndex.TypeDef, 4)); Assert.NotNull(member.DeclaringType); Assert.Equal(nameof(TopLevelClass1), member.DeclaringType.Name); } [Fact] public void ReadEmptyFields() { var module = ModuleDefinition.FromFile(typeof(NoFields).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoFields)); Assert.Empty(type.Fields); } [Fact] public void PersistentEmptyFields() { var module = ModuleDefinition.FromFile(typeof(NoFields).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoFields)); var newType = RebuildAndLookup(type); AssertNamesEqual(type.Fields, newType.Fields); } [Fact] public void ReadSingleField() { var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleField)); Assert.Equal(new Utf8String[] { nameof(SingleField.IntField), }, type.Fields.Select(p => p.Name)); } [Fact] public void PersistentSingleField() { var module = ModuleDefinition.FromFile(typeof(SingleField).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleField)); var newType = RebuildAndLookup(type); AssertNamesEqual(type.Fields, newType.Fields); } [Fact] public void ReadMultipleFields() { var module = ModuleDefinition.FromFile(typeof(MultipleFields).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleFields)); Assert.Equal(new Utf8String[] { nameof(MultipleFields.IntField), nameof(MultipleFields.StringField), nameof(MultipleFields.TypeDefOrRefFieldType), }, type.Fields.Select(p => p.Name)); } [Fact] public void PersistentMultipleFields() { var module = ModuleDefinition.FromFile(typeof(MultipleFields).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleFields)); var newType = RebuildAndLookup(type); AssertNamesEqual(type.Fields, newType.Fields); } [Fact] public void ReadEmptyMethods() { var module = ModuleDefinition.FromFile(typeof(NoMethods).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoMethods)); Assert.Empty(type.Methods); } [Fact] public void PersistentEmptyMethods() { var module = ModuleDefinition.FromFile(typeof(NoMethods).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoMethods)); var newType = RebuildAndLookup(type); Assert.Empty(newType.Methods); } [Fact] public void ReadSingleMethod() { var module = ModuleDefinition.FromFile(typeof(SingleMethod).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleMethod)); Assert.Equal(new Utf8String[] { nameof(SingleMethod.VoidParameterlessMethod), }, type.Methods.Select(p => p.Name)); } [Fact] public void PersistentSingleMethod() { var module = ModuleDefinition.FromFile(typeof(SingleMethod).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleMethod)); var newType = RebuildAndLookup(type); AssertNamesEqual(type.Methods, newType.Methods); } [Fact] public void ReadMultipleMethods() { var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleMethods)); Assert.Equal(new Utf8String[] { ".ctor", nameof(MultipleMethods.VoidParameterlessMethod), nameof(MultipleMethods.IntParameterlessMethod), nameof(MultipleMethods.TypeDefOrRefParameterlessMethod), nameof(MultipleMethods.SingleParameterMethod), nameof(MultipleMethods.MultipleParameterMethod), }, type.Methods.Select(p => p.Name)); } [Fact] public void PersistentMultipleMethods() { var module = ModuleDefinition.FromFile(typeof(MultipleMethods).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleMethods)); var newType = RebuildAndLookup(type); AssertNamesEqual(type.Methods, newType.Methods); } [Fact] public void ReadEmptyProperties() { var module = ModuleDefinition.FromFile(typeof(NoProperties).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoProperties)); Assert.Empty(type.Properties); } [Fact] public void PersistentEmptyProperties() { var module = ModuleDefinition.FromFile(typeof(NoProperties).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoProperties)); var newType = RebuildAndLookup(type); Assert.Empty(newType.Properties); } [Fact] public void ReadSingleProperty() { var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleProperty)); Assert.Equal(new Utf8String[] { nameof(SingleProperty.IntProperty) }, type.Properties.Select(p => p.Name)); } [Fact] public void PersistentSingleProperty() { var module = ModuleDefinition.FromFile(typeof(SingleProperty).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleProperty)); var newType = RebuildAndLookup(type); Assert.Equal(new Utf8String[] { nameof(SingleProperty.IntProperty) }, newType.Properties.Select(p => p.Name)); } [Fact] public void ReadMultipleProperties() { var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleProperties)); Assert.Equal(new Utf8String[] { nameof(MultipleProperties.ReadOnlyProperty), nameof(MultipleProperties.WriteOnlyProperty), nameof(MultipleProperties.ReadWriteProperty), "Item", }, type.Properties.Select(p => p.Name)); } [Fact] public void PersistentMultipleProperties() { var module = ModuleDefinition.FromFile(typeof(MultipleProperties).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleProperties)); var newType = RebuildAndLookup(type); Assert.Equal(new Utf8String[] { nameof(MultipleProperties.ReadOnlyProperty), nameof(MultipleProperties.WriteOnlyProperty), nameof(MultipleProperties.ReadWriteProperty), "Item", }, newType.Properties.Select(p => p.Name)); } [Fact] public void ReadEmptyEvents() { var module = ModuleDefinition.FromFile(typeof(NoEvents).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoEvents)); Assert.Empty(type.Events); } [Fact] public void PersistentEmptyEvent() { var module = ModuleDefinition.FromFile(typeof(NoEvents).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(NoEvents)); var newType = RebuildAndLookup(type); Assert.Empty(newType.Events); } [Fact] public void ReadSingleEvent() { var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleEvent)); Assert.Equal(new Utf8String[] { nameof(SingleEvent.SimpleEvent) }, type.Events.Select(p => p.Name)); } [Fact] public void PersistentSingleEvent() { var module = ModuleDefinition.FromFile(typeof(SingleEvent).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(SingleEvent)); var newType = RebuildAndLookup(type); Assert.Equal(new Utf8String[] { nameof(SingleEvent.SimpleEvent) }, newType.Events.Select(p => p.Name)); } [Fact] public void ReadMultipleEvents() { var module = ModuleDefinition.FromFile(typeof(MultipleEvents).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleEvents)); Assert.Equal(new Utf8String[] { nameof(MultipleEvents.Event1), nameof(MultipleEvents.Event2), nameof(MultipleEvents.Event3), }, type.Events.Select(p => p.Name)); } [Fact] public void PersistentMultipleEvents() { var module = ModuleDefinition.FromFile(typeof(MultipleEvents).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(MultipleEvents)); var newType = RebuildAndLookup(type); Assert.Equal(new Utf8String[] { nameof(MultipleEvents.Event1), nameof(MultipleEvents.Event2), nameof(MultipleEvents.Event3), }, newType.Events.Select(p => p.Name)); } [Fact] public void ReadCustomAttributes() { var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass)); Assert.Single(type.CustomAttributes); } [Fact] public void ReadGenericParameters() { var module = ModuleDefinition.FromFile(typeof(GenericType<,,>).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == typeof(GenericType<,,>).Name); Assert.Equal(3, type.GenericParameters.Count); } [Fact] public void ReadInterfaces() { var module = ModuleDefinition.FromFile(typeof(InterfaceImplementations).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(InterfaceImplementations)); Assert.Equal(new HashSet<Utf8String>(new Utf8String[] { nameof(IInterface1), nameof(IInterface2), }), new HashSet<Utf8String>(type.Interfaces.Select(i => i.Interface?.Name))); } [Fact] public void PersistentInterfaces() { var module = ModuleDefinition.FromFile(typeof(InterfaceImplementations).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(InterfaceImplementations)); var newType = RebuildAndLookup(type); Assert.Equal(new HashSet<Utf8String>(new Utf8String[] { nameof(IInterface1), nameof(IInterface2), }), new HashSet<Utf8String>(newType.Interfaces.Select(i => i.Interface?.Name))); } [Fact] public void ReadMethodImplementations() { var module = ModuleDefinition.FromFile(typeof(InterfaceImplementations).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(InterfaceImplementations)); Assert.Contains(type.MethodImplementations, i => i.Declaration!.Name == "Interface2Method"); } [Fact] public void PersistentMethodImplementations() { var module = ModuleDefinition.FromFile(typeof(InterfaceImplementations).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(InterfaceImplementations)); var newType = RebuildAndLookup(type); Assert.Contains(newType.MethodImplementations, i => i.Declaration!.Name == "Interface2Method"); } [Fact] public void ReadClassLayout() { var module = ModuleDefinition.FromFile(typeof(ExplicitSizeStruct).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(ExplicitSizeStruct)); Assert.NotNull(type.ClassLayout); Assert.Equal(100u, type.ClassLayout.ClassSize); } [Fact] public void PersistentClassLayout() { var module = ModuleDefinition.FromFile(typeof(ExplicitSizeStruct).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(ExplicitSizeStruct)); var newType = RebuildAndLookup(type); Assert.NotNull(newType.ClassLayout); Assert.Equal(100u, newType.ClassLayout.ClassSize); } [Fact] public void InheritanceMultipleLevels() { var module = ModuleDefinition.FromFile(typeof(DerivedDerivedClass).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(DerivedDerivedClass)); Assert.True(type.InheritsFrom(typeof(AbstractClass).FullName!)); Assert.False(type.InheritsFrom(typeof(Class).FullName!)); } [Fact] public void InheritanceMultipleLevelsTypeOf() { var module = ModuleDefinition.FromFile(typeof(DerivedDerivedClass).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(DerivedDerivedClass)); Assert.True(type.InheritsFrom(typeof(AbstractClass).Namespace, nameof(AbstractClass))); Assert.False(type.InheritsFrom(typeof(Class).Namespace, nameof(Class))); } [Fact] public void InterfaceImplementedFromInheritanceHierarchy() { var module = ModuleDefinition.FromFile(typeof(DerivedInterfaceImplementations).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(DerivedInterfaceImplementations)); Assert.True(type.Implements(typeof(IInterface1).FullName!)); Assert.True(type.Implements(typeof(IInterface2).FullName!)); Assert.True(type.Implements(typeof(IInterface3).FullName!)); Assert.False(type.Implements(typeof(IInterface4).FullName!)); } [Fact] public void InterfaceImplementedFromInheritanceHierarchyTypeOf() { var module = ModuleDefinition.FromFile(typeof(DerivedInterfaceImplementations).Assembly.Location, TestReaderParameters); var type = module.TopLevelTypes.First(t => t.Name == nameof(DerivedInterfaceImplementations)); Assert.True(type.Implements(typeof(IInterface1).Namespace, nameof(IInterface1))); Assert.True(type.Implements(typeof(IInterface2).Namespace, nameof(IInterface2))); Assert.True(type.Implements(typeof(IInterface3).Namespace, nameof(IInterface3))); Assert.False(type.Implements(typeof(IInterface4).Namespace, nameof(IInterface4))); } [Fact] public void CorLibTypeDefinitionToSignatureShouldResultInCorLibTypeSignature() { var module = new ModuleDefinition("Test"); var type = module.CorLibTypeFactory.Object.Resolve()!; var signature = type.ToTypeSignature(); var corlibType = Assert.IsAssignableFrom<CorLibTypeSignature>(signature); Assert.Equal(ElementType.Object, corlibType.ElementType); } [Fact] public void InvalidMetadataLoopInBaseTypeShouldNotCrashIsValueType() { var module = new ModuleDefinition("Test"); var typeA = new TypeDefinition(null, "A", TypeAttributes.Public); var typeB = new TypeDefinition(null, "B", TypeAttributes.Public, typeA); typeA.BaseType = typeB; module.TopLevelTypes.Add(typeA); module.TopLevelTypes.Add(typeB); Assert.False(typeB.IsValueType); Assert.False(typeB.IsEnum); } [Fact] public void AddTypeWithCorLibBaseTypeToAssemblyWithCorLibTypeReferenceInAttribute() { // https://github.com/Washi1337/AsmResolver/issues/263 var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_WithAttribute, TestReaderParameters); var corlib = module.CorLibTypeFactory; var type = new TypeDefinition(null, "Test", TypeAttributes.Class, corlib.Object.Type); module.TopLevelTypes.Add(type); var scope = corlib.Object.Scope; var newType = RebuildAndLookup(type); Assert.Equal(newType.BaseType, type.BaseType, Comparer); Assert.Same(scope, corlib.Object.Scope); var reference = Assert.IsAssignableFrom<AssemblyReference>(corlib.Object.Scope!.GetAssembly()); Assert.Same(module, reference.Module); } [Fact] public void ReadIsByRefLike() { var resolver = new DotNetCoreAssemblyResolver(new Version(5, 0)); var corLib = resolver.Resolve(KnownCorLibs.SystemPrivateCoreLib_v5_0_0_0)!; var intType = corLib.ManifestModule!.TopLevelTypes.First(t => t.Name == "Int32"); var spanType = corLib.ManifestModule.TopLevelTypes.First(t => t.Name == "Span`1"); Assert.False(intType.IsByRefLike); Assert.True(spanType.IsByRefLike); } [Fact] public void GetStaticConstructor() { var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters); var type1 = module.LookupMember<TypeDefinition>(typeof(Constructors).MetadataToken); var cctor = type1.GetStaticConstructor(); Assert.NotNull(cctor); Assert.True(cctor.IsStatic); Assert.True(cctor.IsConstructor); var type2 = module.LookupMember<TypeDefinition>(typeof(NoStaticConstructor).MetadataToken); Assert.Null(type2.GetStaticConstructor()); } [Fact] public void GetOrCreateStaticConstructor() { var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters); var type1 = module.LookupMember<TypeDefinition>(typeof(Constructors).MetadataToken); // If cctor already exists, we expect this to be returned. var cctor = type1.GetStaticConstructor(); Assert.NotNull(cctor); Assert.Same(cctor, type1.GetOrCreateStaticConstructor()); var type2 = module.LookupMember<TypeDefinition>(typeof(NoStaticConstructor).MetadataToken); Assert.Null(type2.GetStaticConstructor()); // If cctor doesn't exist yet, it should be added. cctor = type2.GetOrCreateStaticConstructor(); Assert.NotNull(cctor); Assert.Same(type2, cctor.DeclaringType); Assert.Same(cctor, type2.GetOrCreateStaticConstructor()); Assert.True(cctor.IsStatic); Assert.True(cctor.IsConstructor); } [Fact] public void GetParameterlessConstructor() { var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters); var type = module.LookupMember<TypeDefinition>(typeof(Constructors).MetadataToken); var ctor = type.GetConstructor(); Assert.NotNull(ctor); Assert.False(ctor.IsStatic); Assert.True(ctor.IsConstructor); Assert.Empty(ctor.Parameters); } [Theory] [InlineData(new[] {ElementType.I4, ElementType.I4})] [InlineData(new[] {ElementType.I4, ElementType.String})] [InlineData(new[] {ElementType.I4, ElementType.String, ElementType.R8})] public void GetParametersConstructor(ElementType[] types) { var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters); var type = module.LookupMember<TypeDefinition>(typeof(Constructors).MetadataToken); var signatures = types.Select(x => (TypeSignature) module.CorLibTypeFactory.FromElementType(x)).ToArray(); var ctor = type.GetConstructor(signatures); Assert.NotNull(ctor); Assert.False(ctor.IsStatic); Assert.True(ctor.IsConstructor); Assert.Equal(signatures, ctor.Signature!.ParameterTypes); } [Fact] public void GetNonExistingConstructorShouldReturnNull() { var module = ModuleDefinition.FromFile(typeof(Constructors).Assembly.Location, TestReaderParameters); var type = module.LookupMember<TypeDefinition>(typeof(Constructors).MetadataToken); var factory = module.CorLibTypeFactory; Assert.Null(type.GetConstructor(factory.String)); Assert.Null(type.GetConstructor(factory.String, factory.String)); } [Fact] public void AddTypeToModuleShouldSetOwner() { var module = new ModuleDefinition("Dummy"); var type = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public); module.TopLevelTypes.Add(type); Assert.Same(module, type.Module); } [Fact] public void AddNestedTypeToModuleShouldSetOwner() { var module = new ModuleDefinition("Dummy"); var type1 = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public); var type2 = new TypeDefinition(null, "NestedType", TypeAttributes.NestedPublic); module.TopLevelTypes.Add(type1); type1.NestedTypes.Add(type2); Assert.Same(type1, type2.DeclaringType); Assert.Same(module, type2.Module); } [Fact] public void AddSameTypeTwiceToModuleShouldThrow() { var module = new ModuleDefinition("Dummy"); var type = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public); module.TopLevelTypes.Add(type); Assert.Throws<ArgumentException>(() => module.TopLevelTypes.Add(type)); } [Fact] public void AddSameTypeTwiceToNestedTypeShouldThrow() { var type = new TypeDefinition("SomeNamespace", "SomeType", TypeAttributes.Public); var nestedType = new TypeDefinition(null, "SomeType", TypeAttributes.NestedPublic); type.NestedTypes.Add(nestedType); Assert.Throws<ArgumentException>(() => type.NestedTypes.Add(nestedType)); } [Fact] public void AddSameNestedTypeToDifferentTypesShouldThrow() { var type1 = new TypeDefinition("SomeNamespace", "SomeType1", TypeAttributes.Public); var type2 = new TypeDefinition("SomeNamespace", "SomeType2", TypeAttributes.Public); var nestedType = new TypeDefinition(null, "SomeType", TypeAttributes.NestedPublic); type1.NestedTypes.Add(nestedType); Assert.Throws<ArgumentException>(() => type2.NestedTypes.Add(nestedType)); } }
657
34,296
using System; using System.Collections.Generic; using AsmResolver.Collections; using AsmResolver.DotNet.Collections; using AsmResolver.PE.DotNet.Metadata.Tables; namespace AsmResolver.DotNet.Serialized { /// <summary> /// Represents a lazily initialized implementation of <see cref="TypeDefinition"/> that is read from a /// .NET metadata image. /// </summary> public class SerializedTypeDefinition : TypeDefinition { private readonly ModuleReaderContext _context; private readonly TypeDefinitionRow _row; /// <summary> /// Creates a type definition from a type metadata row. /// </summary> /// <param name="context">The reader context.</param> /// <param name="token">The token to initialize the type for.</param> /// <param name="row">The metadata table row to base the type definition on.</param> public SerializedTypeDefinition(ModuleReaderContext context, MetadataToken token, in TypeDefinitionRow row) : base(token) { _context = context ?? throw new ArgumentNullException(nameof(context)); _row = row; Attributes = row.Attributes; ((IOwnedCollectionElement<ModuleDefinition>) this).Owner = context.ParentModule; } /// <inheritdoc /> protected override Utf8String? GetNamespace() => _context.StringsStream?.GetStringByIndex(_row.Namespace); /// <inheritdoc /> protected override Utf8String? GetName() => _context.StringsStream?.GetStringByIndex(_row.Name); /// <inheritdoc /> protected override ITypeDefOrRef? GetBaseType() { if (_row.Extends == 0) return null; var token = _context.TablesStream .GetIndexEncoder(CodedIndex.TypeDefOrRef) .DecodeIndex(_row.Extends); return (ITypeDefOrRef) _context.ParentModule.LookupMember(token); } /// <inheritdoc /> protected override IList<TypeDefinition> GetNestedTypes() { var rids = _context.ParentModule.GetNestedTypeRids(MetadataToken.Rid); var result = new MemberCollection<TypeDefinition, TypeDefinition>(this, rids.Count); foreach (uint rid in rids) { var nestedType = (TypeDefinition) _context.ParentModule.LookupMember(new MetadataToken(TableIndex.TypeDef, rid)); result.AddNoOwnerCheck(nestedType); } return result; } /// <inheritdoc /> protected override TypeDefinition? GetDeclaringType() { uint parentTypeRid = _context.ParentModule.GetParentTypeRid(MetadataToken.Rid); return _context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.TypeDef, parentTypeRid), out var member) ? member as TypeDefinition : null; } /// <inheritdoc /> protected override IList<FieldDefinition> GetFields() => CreateMemberCollection<FieldDefinition>(_context.ParentModule.GetFieldRange(MetadataToken.Rid)); /// <inheritdoc /> protected override IList<MethodDefinition> GetMethods() => CreateMemberCollection<MethodDefinition>(_context.ParentModule.GetMethodRange(MetadataToken.Rid)); /// <inheritdoc /> protected override IList<PropertyDefinition> GetProperties() => CreateMemberCollection<PropertyDefinition>(_context.ParentModule.GetPropertyRange(MetadataToken.Rid)); /// <inheritdoc /> protected override IList<EventDefinition> GetEvents() => CreateMemberCollection<EventDefinition>(_context.ParentModule.GetEventRange(MetadataToken.Rid)); private IList<TMember> CreateMemberCollection<TMember>(MetadataRange range) where TMember : class, IMetadataMember, IOwnedCollectionElement<TypeDefinition> { var result = new MemberCollection<TypeDefinition, TMember>(this, range.Count); foreach (var token in range) result.AddNoOwnerCheck((TMember) _context.ParentModule.LookupMember(token)); return result; } /// <inheritdoc /> protected override IList<CustomAttribute> GetCustomAttributes() => _context.ParentModule.GetCustomAttributeCollection(this); /// <inheritdoc /> protected override IList<SecurityDeclaration> GetSecurityDeclarations() => _context.ParentModule.GetSecurityDeclarationCollection(this); /// <inheritdoc /> protected override IList<GenericParameter> GetGenericParameters() { var rids = _context.ParentModule.GetGenericParameters(MetadataToken); var result = new MemberCollection<IHasGenericParameters, GenericParameter>(this, rids.Count); foreach (uint rid in rids) { if (_context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.GenericParam, rid), out var member) && member is GenericParameter genericParameter) { result.AddNoOwnerCheck(genericParameter); } } return result; } /// <inheritdoc /> protected override IList<InterfaceImplementation> GetInterfaces() { var rids = _context.ParentModule.GetInterfaceImplementationRids(MetadataToken); var result = new MemberCollection<TypeDefinition, InterfaceImplementation>(this, rids.Count); foreach (uint rid in rids) { if (_context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.InterfaceImpl, rid), out var member) && member is InterfaceImplementation type) { result.AddNoOwnerCheck(type); } } return result; } /// <inheritdoc /> protected override IList<MethodImplementation> GetMethodImplementations() { var tablesStream = _context.TablesStream; var table = tablesStream.GetTable<MethodImplementationRow>(TableIndex.MethodImpl); var encoder = tablesStream.GetIndexEncoder(CodedIndex.MethodDefOrRef); var rids = _context.ParentModule.GetMethodImplementationRids(MetadataToken); var result = new List<MethodImplementation>(rids.Count); foreach (uint rid in rids) { var row = table.GetByRid(rid); _context.ParentModule.TryLookupMember(encoder.DecodeIndex(row.MethodBody), out var body); _context.ParentModule.TryLookupMember(encoder.DecodeIndex(row.MethodDeclaration), out var declaration); result.Add(new MethodImplementation( declaration as IMethodDefOrRef, body as IMethodDefOrRef)); } return result; } /// <inheritdoc /> protected override ClassLayout? GetClassLayout() { uint rid = _context.ParentModule.GetClassLayoutRid(MetadataToken); if (_context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.ClassLayout, rid), out var member) && member is ClassLayout layout) { layout.Parent = this; return layout; } return null; } } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\TypeReferenceTest.cs
AsmResolver.DotNet.Tests
TypeReferenceTest
['private static readonly SignatureComparer Comparer = new();']
['System', 'System.Linq', 'AsmResolver.DotNet.Signatures', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit']
xUnit
net8.0
public class TypeReferenceTest { private static readonly SignatureComparer Comparer = new(); [Fact] public void ReadAssemblyRefScope() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 13)); var scope = Assert.IsAssignableFrom<AssemblyReference>(typeRef.Scope); Assert.Equal("mscorlib", scope.Name); } [Fact] public void WriteAssemblyRefScope() { var module = new ModuleDefinition("SomeModule"); module.GetOrCreateModuleType().Fields.Add(new FieldDefinition( "SomeField", FieldAttributes.Static, new TypeDefOrRefSignature(new TypeReference( new AssemblyReference("SomeAssembly", new Version(1, 0, 0, 0)), "SomeNamespace", "SomeName") ).ImportWith(module.DefaultImporter) )); var image = module.ToPEImage(); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var typeRef = newModule.GetOrCreateModuleType().Fields.First().Signature!.FieldType.GetUnderlyingTypeDefOrRef()!; var scope = Assert.IsAssignableFrom<AssemblyReference>(typeRef.Scope); Assert.Equal("SomeAssembly", scope.Name); } [Fact] public void ReadTypeRefScope() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 4)); var scope = Assert.IsAssignableFrom<TypeReference>(typeRef.Scope); Assert.Equal("DebuggableAttribute", scope.Name); } [Fact] public void WriteTypeRefScope() { var module = new ModuleDefinition("SomeModule"); module.GetOrCreateModuleType().Fields.Add(new FieldDefinition( "SomeField", FieldAttributes.Static, new TypeDefOrRefSignature(new TypeReference( new TypeReference( new AssemblyReference("SomeAssembly", new Version(1, 0, 0, 0)), "SomeNamespace", "SomeName"), null, "SomeNestedType" )).ImportWith(module.DefaultImporter) )); var image = module.ToPEImage(); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var typeRef = newModule.GetOrCreateModuleType().Fields.First().Signature!.FieldType.GetUnderlyingTypeDefOrRef()!; var scope = Assert.IsAssignableFrom<TypeReference>(typeRef.Scope); Assert.Equal("SomeName", scope.Name); } [Fact] public void ReadModuleScope() { var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefModuleScope, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 2)); var scope = Assert.IsAssignableFrom<ModuleDefinition>(typeRef.Scope); Assert.Same(module, scope); } [Fact] public void WriteModuleScope() { var module = new ModuleDefinition("SomeModule"); module.GetOrCreateModuleType().Fields.Add(new FieldDefinition( "SomeField", FieldAttributes.Static, new TypeDefOrRefSignature(new TypeReference( module, "SomeNamepace", "SomeName") ).ImportWith(module.DefaultImporter) )); var image = module.ToPEImage(); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var typeRef = newModule.GetOrCreateModuleType().Fields.First().Signature!.FieldType.GetUnderlyingTypeDefOrRef()!; var scope = Assert.IsAssignableFrom<ModuleDefinition>(typeRef.Scope); Assert.Equal(module.Name, scope.Name); } [Fact] public void WriteNullScope() { var module = new ModuleDefinition("SomeModule"); module.GetOrCreateModuleType().Fields.Add(new FieldDefinition( "SomeField", FieldAttributes.Static, new TypeDefOrRefSignature(new TypeReference( null, "SomeNamespace", "SomeName") ).ImportWith(module.DefaultImporter) )); var image = module.ToPEImage(); var newModule = ModuleDefinition.FromImage(image, TestReaderParameters); var typeRef = newModule.GetOrCreateModuleType().Fields.First().Signature!.FieldType.GetUnderlyingTypeDefOrRef()!; Assert.Null(typeRef.Scope); } [Fact] public void ReadNullScopeCurrentModule() { var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefNullScope_CurrentModule, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 2)); Assert.Null(typeRef.Scope); } [Fact] public void ReadNullScopeExportedType() { var module = ModuleDefinition.FromBytes(Properties.Resources.TypeRefNullScope_ExportedType, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 1)); Assert.Null(typeRef.Scope); } [Fact] public void ReadName() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 13)); Assert.Equal("Console", typeRef.Name); } [Fact] public void ReadNamespace() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld, TestReaderParameters); var typeRef = module.LookupMember<TypeReference>(new MetadataToken(TableIndex.TypeRef, 13)); Assert.Equal("System", typeRef.Namespace); } [Fact] public void CorLibTypeToTypeSignatureShouldReturnCorLibTypeSignature() { var module = new ModuleDefinition("SomeModule"); var reference = new TypeReference(module, module.CorLibTypeFactory.CorLibScope, "System", "Object"); var signature = Assert.IsAssignableFrom<CorLibTypeSignature>(reference.ToTypeSignature()); Assert.Equal(ElementType.Object, signature.ElementType); } [Fact] public void NonCorLibTypeToTypeSignatureShouldReturnTypeDefOrRef() { var module = new ModuleDefinition("SomeModule"); var reference = new TypeReference(module, module.CorLibTypeFactory.CorLibScope, "System", "Array"); var signature = Assert.IsAssignableFrom<TypeDefOrRefSignature>(reference.ToTypeSignature()); Assert.Equal(signature.Type, reference, Comparer); } }
178
7,772
using System; using System.Collections.Generic; using AsmResolver.PE.DotNet.Metadata.Tables; namespace AsmResolver.DotNet.Serialized { /// <summary> /// Represents a lazily initialized implementation of <see cref="TypeReference"/> that is read from a /// .NET metadata image. /// </summary> public class SerializedTypeReference : TypeReference { private readonly ModuleReaderContext _context; private readonly TypeReferenceRow _row; /// <summary> /// Creates a type reference from a type metadata row. /// </summary> /// <param name="context">The reader context.</param> /// <param name="token">The token to initialize the type for.</param> /// <param name="row">The metadata table row to base the type definition on.</param> public SerializedTypeReference(ModuleReaderContext context, MetadataToken token, in TypeReferenceRow row) : base(token) { _context = context ?? throw new ArgumentNullException(nameof(context)); _row = row; Module = context.ParentModule; } /// <inheritdoc /> protected override Utf8String? GetNamespace() => _context.StringsStream?.GetStringByIndex(_row.Namespace); /// <inheritdoc /> protected override Utf8String? GetName() => _context.StringsStream?.GetStringByIndex(_row.Name); /// <inheritdoc /> protected override IResolutionScope? GetScope() { if (_row.ResolutionScope == 0) return null; var tablesStream = _context.TablesStream; var decoder = tablesStream.GetIndexEncoder(CodedIndex.ResolutionScope); var token = decoder.DecodeIndex(_row.ResolutionScope); return !_context.ParentModule.TryLookupMember(token, out var scope) ? _context.BadImageAndReturn<IResolutionScope>($"Invalid resolution scope in type reference {MetadataToken}.") : scope as IResolutionScope; } /// <inheritdoc /> protected override IList<CustomAttribute> GetCustomAttributes() => _context.ParentModule.GetCustomAttributeCollection(this); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\AsmResolver.DotNet.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Tests\TypeSpecificationTest.cs
AsmResolver.DotNet.Tests
TypeSpecificationTest
[]
['System.IO', 'System.Linq', 'AsmResolver.DotNet.Builder', 'AsmResolver.DotNet.Serialized', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit']
xUnit
net8.0
public class TypeSpecificationTest { [Fact] public void ReadGenericTypeInstantiation() { var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters); var fieldType = module .TopLevelTypes.First(t => t.Name == nameof(GenericsTestClass)) .Fields.First(f => f.Name == nameof(GenericsTestClass.GenericField)) .Signature.FieldType; Assert.IsAssignableFrom<GenericInstanceTypeSignature>(fieldType); var genericType = (GenericInstanceTypeSignature) fieldType; Assert.Equal("GenericType`3", genericType.GenericType.Name); Assert.Equal(new[] { "System.String", "System.Int32", "System.Object" }, genericType.TypeArguments.Select(a => a.FullName)); } [Fact] public void PersistentGenericTypeInstantiation() { var module = ModuleDefinition.FromFile(typeof(GenericsTestClass).Assembly.Location, TestReaderParameters); using var tempStream = new MemoryStream(); module.Write(tempStream); module = ModuleDefinition.FromBytes(tempStream.ToArray(), TestReaderParameters); var fieldType = module .TopLevelTypes.First(t => t.Name == nameof(GenericsTestClass))! .Fields.First(f => f.Name == nameof(GenericsTestClass.GenericField))! .Signature!.FieldType; Assert.IsAssignableFrom<GenericInstanceTypeSignature>(fieldType); var genericType = (GenericInstanceTypeSignature) fieldType; Assert.Equal("GenericType`3", genericType.GenericType.Name); Assert.Equal(new[] { "System.String", "System.Int32", "System.Object" }, genericType.TypeArguments.Select(a => a.FullName)); } [Fact] public void IllegalTypeSpecInTypeDefOrRef() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_IllegalTypeSpecInTypeDefOrRefSig, TestReaderParameters); var typeSpec = (TypeSpecification) module.LookupMember(new MetadataToken(TableIndex.TypeSpec, 1)); Assert.NotNull(typeSpec); } [Fact] public void MaliciousTypeSpecLoop() { var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld_MaliciousTypeSpecLoop, new ModuleReaderParameters(EmptyErrorListener.Instance)); var typeSpec = (TypeSpecification) module.LookupMember(new MetadataToken(TableIndex.TypeSpec, 1)); Assert.NotNull(typeSpec.Signature); } }
300
3,093
using System; using System.Collections.Generic; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Metadata.Tables; namespace AsmResolver.DotNet.Serialized { /// <summary> /// Represents a lazily initialized implementation of <see cref="TypeSpecification"/> that is read from a /// .NET metadata image. /// </summary> public class SerializedTypeSpecification : TypeSpecification { private readonly ModuleReaderContext _context; private readonly TypeSpecificationRow _row; /// <summary> /// Creates a type specification from a type metadata row. /// </summary> /// <param name="context">The reader context.</param> /// <param name="token">The token to initialize the type for.</param> /// <param name="row">The metadata table row to base the type specification on.</param> public SerializedTypeSpecification(ModuleReaderContext context, MetadataToken token, in TypeSpecificationRow row) : base(token) { _context = context ?? throw new ArgumentNullException(nameof(context)); _row = row; } /// <inheritdoc /> protected override TypeSignature? GetSignature() { if (_context.BlobStream is not { } blobStream || !blobStream.TryGetBlobReaderByIndex(_row.Signature, out var reader)) { return _context.BadImageAndReturn<TypeSignature>( $"Invalid blob signature for type specification {MetadataToken.ToString()}"); } var context = new BlobReaderContext(_context); context.StepInToken(MetadataToken); return TypeSignature.FromReader(ref context, ref reader); } /// <inheritdoc /> protected override IList<CustomAttribute> GetCustomAttributes() => _context.ParentModule.GetCustomAttributeCollection(this); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Win32Resources.Tests\AsmResolver.PE.Win32Resources.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Win32Resources.Tests\Icon\IconResourceTest.cs
AsmResolver.PE.Win32Resources.Tests.Icon
IconResourceTest
['private readonly TemporaryDirectoryFixture _fixture;']
['System.Linq', 'AsmResolver.PE.Builder', 'AsmResolver.PE.Win32Resources.Icon', 'AsmResolver.Tests.Runners', 'Xunit']
xUnit
net8.0
public class IconResourceTest : IClassFixture<TemporaryDirectoryFixture> { private readonly TemporaryDirectoryFixture _fixture; public IconResourceTest(TemporaryDirectoryFixture fixture) { _fixture = fixture; } private static IconResource GetTestIconResource(bool rebuild) { // Load dummy. var image = PEImage.FromBytes(Properties.Resources.HelloWorld); // Read icon resources. var iconResource = IconResource.FromDirectory(image.Resources!, IconType.Icon); Assert.NotNull(iconResource); if (rebuild) { iconResource.InsertIntoDirectory(image.Resources!); iconResource = IconResource.FromDirectory(image.Resources!, IconType.Icon); } return iconResource; } [Theory] [InlineData(false)] [InlineData(true)] public void IconGroup(bool rebuild) { var iconResource = GetTestIconResource(rebuild); // Verify. var group = Assert.Single(iconResource.Groups); Assert.Equal(32512u, group.Id); Assert.Equal(0u, group.Lcid); Assert.Equal(IconType.Icon, group.Type); } [Theory] [InlineData(false)] [InlineData(true)] public void IconEntries(bool rebuild) { var iconResource = GetTestIconResource(rebuild); // Verify. var icons = iconResource.GetGroup(32512).Icons; Assert.Equal([1, 2, 3, 4], icons.Select(x => x.Id)); Assert.Equal([16, 32, 48, 64], icons.Select(x => x.Width)); Assert.Equal([16, 32, 48, 64], icons.Select(x => x.Height)); Assert.All(icons, icon => Assert.Equal(32, icon.BitsPerPixel)); } [Theory] [InlineData(false)] [InlineData(true)] public void IconData(bool rebuild) { var iconResource = GetTestIconResource(rebuild); // Verify. var icons = iconResource.GetGroup(32512).Icons; Assert.All(icons, icon => Assert.NotNull(icon.PixelData)); } [Fact] public void AddNewIcons() { var image = PEImage.FromBytes(Properties.Resources.HelloWorld); var iconResource = IconResource.FromDirectory(image.Resources!, IconType.Icon)!; var iconGroup = new IconGroup(1337, 1033); iconGroup.Icons.Add(new IconEntry(100, 1033) { Width = 10, Height = 10, BitsPerPixel = 32, PixelData = new DataSegment([1, 2, 3, 4]), }); iconResource.Groups.Add(iconGroup); iconResource.InsertIntoDirectory(image.Resources!); var newIconResource = IconResource.FromDirectory(image.Resources!, IconType.Icon); Assert.NotNull(newIconResource); Assert.Equal([32512, 1337], newIconResource.Groups.Select(x => x.Id)); } [Fact] public void RebuildPEWithIconResource() { // Load dummy. var image = PEImage.FromBytes(Properties.Resources.HelloWorld); // Rebuild icon resources. var iconResource = IconResource.FromDirectory(image.Resources!, IconType.Icon)!; iconResource.InsertIntoDirectory(image.Resources!); var file = image.ToPEFile(new ManagedPEFileBuilder()); _fixture .GetRunner<FrameworkPERunner>() .RebuildAndRun(file, "HelloWorld.exe", "Hello World!\n"); } }
199
3,641
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using AsmResolver.IO; namespace AsmResolver.PE.Win32Resources.Icon; /// <summary> /// Provides a high level view on icon and cursor resources stored in a PE image. /// </summary> public class IconResource : IWin32Resource { /// <summary> /// Creates a new icon resource of the provided icon type. /// </summary> /// <param name="type">The icon type.</param> public IconResource(IconType type) { Type = type; } /// <summary> /// Gets the icon type the resource is storing. /// </summary> public IconType Type { get; } /// <summary> /// Gets the icon groups stored in the resource. /// </summary> public IList<IconGroup> Groups { get; } = new List<IconGroup>(); /// <summary> /// Reads icons from the provided root resource directory of a PE image. /// </summary> /// <param name="rootDirectory">The root resource directory.</param> /// <param name="type">The icon type.</param> /// <returns>The resource, or <c>null</c> if no resource of the provided type was present.</returns> public static IconResource? FromDirectory(ResourceDirectory rootDirectory, IconType type) { var (groupType, entryType) = GetResourceDirectoryTypes(type); if (!rootDirectory.TryGetDirectory(groupType, out var groupDirectory)) return null; if (!rootDirectory.TryGetDirectory(entryType, out var iconsDirectory)) return null; var result = new IconResource(type); foreach (var group in groupDirectory.Entries.OfType<ResourceDirectory>()) { foreach (var language in group.Entries.OfType<ResourceData>()) { result.Groups.Add(new SerializedIconGroup( group.Id, language.Id, iconsDirectory, language.CreateReader() )); } } return result; } private static (ResourceType Group, ResourceType Entry) GetResourceDirectoryTypes(IconType type) { return type switch { IconType.Icon => (ResourceType.GroupIcon, ResourceType.Icon), IconType.Cursor => (ResourceType.GroupCursor, ResourceType.Cursor), _ => throw new ArgumentOutOfRangeException(nameof(type)), }; } /// <summary> /// Gets an icon group by its numeric identifier. /// </summary> /// <param name="id">The identifier.</param> /// <returns>The group.</returns> /// <exception cref="ArgumentOutOfRangeException">Occurs when the group was not present.</exception> public IconGroup GetGroup(uint id) { return TryGetGroup(id, out var group) ? group : throw new ArgumentOutOfRangeException($"Icon group {id} does not exist."); } /// <summary> /// Gets an icon group by its string identifier. /// </summary> /// <param name="name">The identifier.</param> /// <returns>The group.</returns> /// <exception cref="ArgumentOutOfRangeException">Occurs when the group was not present.</exception> public IconGroup GetGroup(string name) { return TryGetGroup(name, out var group) ? group : throw new ArgumentOutOfRangeException($"Icon group '{name}' does not exist."); } /// <summary> /// Gets an icon group by its numeric identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="lcid">The language identifier.</param> /// <returns>The group.</returns> /// <exception cref="ArgumentOutOfRangeException">Occurs when the group was not present.</exception> public IconGroup GetGroup(uint id, uint lcid) { return TryGetGroup(id, lcid, out var group) ? group : throw new ArgumentOutOfRangeException($"Icon group {id} (language: {lcid}) does not exist."); } /// <summary> /// Gets an icon group by its string identifier. /// </summary> /// <param name="name">The identifier.</param> /// <param name="lcid">The language identifier.</param> /// <returns>The group.</returns> /// <exception cref="ArgumentOutOfRangeException">Occurs when the group was not present.</exception> public IconGroup GetGroup(string name, uint lcid) { return TryGetGroup(name, lcid, out var group) ? group : throw new ArgumentOutOfRangeException($"Icon group {name} (language: {lcid}) does not exist."); } /// <summary> /// Attempts to get an icon group by its numeric identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="group">The group, or <c>null</c> if none was found.</param> /// <returns><c>true</c> if the group was found, <c>false</c> otherwise.</returns> public bool TryGetGroup(uint id, [NotNullWhen(true)] out IconGroup? group) { foreach (var g in Groups) { if (g.Id == id) { group = g; return true; } } group = null; return false; } /// <summary> /// Attempts to get an icon group by its numeric identifier and language specifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="lcid">The language identifier.</param> /// <param name="group">The group, or <c>null</c> if none was found.</param> /// <returns><c>true</c> if the group was found, <c>false</c> otherwise.</returns> public bool TryGetGroup(uint id, uint lcid, [NotNullWhen(true)] out IconGroup? group) { foreach (var g in Groups) { if (g.Id == id && g.Lcid == lcid) { group = g; return true; } } group = null; return false; } /// <summary> /// Attempts to get an icon group by its string identifier. /// </summary> /// <param name="name">The identifier.</param> /// <param name="group">The group, or <c>null</c> if none was found.</param> /// <returns><c>true</c> if the group was found, <c>false</c> otherwise.</returns> public bool TryGetGroup(string name, [NotNullWhen(true)] out IconGroup? group) { foreach (var g in Groups) { if (g.Name == name) { group = g; return true; } } group = null; return false; } /// <summary> /// Attempts to get an icon group by its string identifier and language specifier. /// </summary> /// <param name="name">The identifier.</param> /// <param name="lcid">The language identifier.</param> /// <param name="group">The group, or <c>null</c> if none was found.</param> /// <returns><c>true</c> if the group was found, <c>false</c> otherwise.</returns> public bool TryGetGroup(string name, uint lcid, [NotNullWhen(true)] out IconGroup? group) { foreach (var g in Groups) { if (g.Name == name && g.Lcid == lcid) { group = g; return true; } } group = null; return false; } /// <inheritdoc /> public void InsertIntoDirectory(ResourceDirectory rootDirectory) { var (groupType, entryType) = GetResourceDirectoryTypes(Type); // We're always replacing the existing directories with new ones. var groupDirectory = new ResourceDirectory(groupType); var entryDirectory = new ResourceDirectory(entryType); var groupDirectories = new Dictionary<object, ResourceDirectory>(); foreach (var group in Groups) { // Create the group dir if it doesn't exist. object groupId = (object?) group.Name ?? group.Id; if (!groupDirectories.TryGetValue(groupId, out var directory)) { directory = group.Name is not null ? new ResourceDirectory(group.Name) : new ResourceDirectory(group.Id); groupDirectories.Add(groupId, directory); groupDirectory.Entries.Add(directory); } // Serialize the group. using var stream = new MemoryStream(); var writer = new BinaryStreamWriter(stream); group.Write(entryDirectory, writer); // Add the group. directory.Entries.Add(new ResourceData(group.Lcid, new DataSegment(stream.ToArray()))); } // Insert into the root win32 dir of the PE image. rootDirectory.InsertOrReplaceEntry(groupDirectory); rootDirectory.InsertOrReplaceEntry(entryDirectory); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Win32Resources.Tests\AsmResolver.PE.Win32Resources.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.PE.Win32Resources.Tests\Version\VersionInfoResourceTest.cs
AsmResolver.PE.Win32Resources.Tests.Version
VersionInfoResourceTest
['private readonly TemporaryDirectoryFixture _fixture;']
['System.Diagnostics', 'System.IO', 'AsmResolver.IO', 'AsmResolver.PE.Builder', 'AsmResolver.PE.File', 'AsmResolver.PE.Win32Resources.Builder', 'AsmResolver.PE.Win32Resources.Version', 'AsmResolver.Tests.Runners', 'Xunit']
xUnit
net8.0
public class VersionInfoResourceTest : IClassFixture<TemporaryDirectoryFixture> { private readonly TemporaryDirectoryFixture _fixture; public VersionInfoResourceTest(TemporaryDirectoryFixture fixture) { _fixture = fixture; } [Fact] public void ReadFixedVersion() { var image = PEImage.FromBytes(Properties.Resources.HelloWorld); var versionInfo = VersionInfoResource.FromDirectory(image.Resources!); Assert.NotNull(versionInfo); var fixedVersionInfo = versionInfo!.FixedVersionInfo; Assert.Equal(new System.Version(1,0,0,0), fixedVersionInfo.FileVersion); Assert.Equal(new System.Version(1,0,0,0), fixedVersionInfo.ProductVersion); } [Fact] public void PersistentFixedVersionInfo() { // Prepare mock data. var versionInfo = new VersionInfoResource(); var fixedVersionInfo = new FixedVersionInfo { FileVersion = new System.Version(1, 2, 3, 4), ProductVersion = new System.Version(1, 2, 3, 4), FileDate = 0x12345678_9ABCDEF, FileFlags = FileFlags.SpecialBuild, FileFlagsMask = FileFlags.ValidBitMask, FileType = FileType.App, FileOS = FileOS.NT, FileSubType = FileSubType.DriverInstallable, }; versionInfo.FixedVersionInfo = fixedVersionInfo; // Serialize. var tempStream = new MemoryStream(); versionInfo.Write(new BinaryStreamWriter(tempStream)); // Reload. var infoReader = new BinaryStreamReader(tempStream.ToArray()); var newVersionInfo = VersionInfoResource.FromReader(ref infoReader); var newFixedVersionInfo = newVersionInfo.FixedVersionInfo; // Verify. Assert.Equal(fixedVersionInfo.FileVersion, newFixedVersionInfo.FileVersion); Assert.Equal(fixedVersionInfo.ProductVersion, newFixedVersionInfo.ProductVersion); Assert.Equal(fixedVersionInfo.FileDate, newFixedVersionInfo.FileDate); Assert.Equal(fixedVersionInfo.FileFlags, newFixedVersionInfo.FileFlags); Assert.Equal(fixedVersionInfo.FileFlagsMask, newFixedVersionInfo.FileFlagsMask); Assert.Equal(fixedVersionInfo.FileType, newFixedVersionInfo.FileType); Assert.Equal(fixedVersionInfo.FileOS, newFixedVersionInfo.FileOS); Assert.Equal(fixedVersionInfo.FileSubType, newFixedVersionInfo.FileSubType); } [Fact] public void ReadStringFileInfo() { string path = typeof(PEImage).Assembly.Location; var image = PEImage.FromFile(path); var versionInfo = VersionInfoResource.FromDirectory(image.Resources!)!; Assert.NotNull(versionInfo); var expectedInfo = FileVersionInfo.GetVersionInfo(path); var actualInfo = versionInfo.GetChild<StringFileInfo>(StringFileInfo.StringFileInfoKey); foreach ((string key, string value) in actualInfo.Tables[0]) { string expected = key switch { StringTable.CommentsKey => expectedInfo.Comments, StringTable.CompanyNameKey => expectedInfo.CompanyName, StringTable.FileDescriptionKey => expectedInfo.FileDescription, StringTable.FileVersionKey => expectedInfo.FileVersion, StringTable.InternalNameKey => expectedInfo.InternalName, StringTable.LegalCopyrightKey => expectedInfo.LegalCopyright, StringTable.LegalTrademarksKey => expectedInfo.LegalTrademarks, StringTable.OriginalFilenameKey => expectedInfo.OriginalFilename, StringTable.PrivateBuildKey => expectedInfo.PrivateBuild, StringTable.ProductNameKey => expectedInfo.ProductName, StringTable.ProductVersionKey => expectedInfo.ProductVersion, StringTable.SpecialBuildKey => expectedInfo.SpecialBuild, _ => null, }; if (expected is null) continue; Assert.Equal(expected, value); } } [Fact] public void PersistentVarFileInfo() { // Prepare mock data. var versionInfo = new VersionInfoResource(); var varFileInfo = new VarFileInfo(); var table = new VarTable(); for (ushort i = 0; i < 10; i++) table.Values.Add(i); varFileInfo.Tables.Add(table); versionInfo.AddEntry(varFileInfo); // Serialize. var tempStream = new MemoryStream(); versionInfo.Write(new BinaryStreamWriter(tempStream)); // Reload. var infoReader = new BinaryStreamReader(tempStream.ToArray()); var newVersionInfo = VersionInfoResource.FromReader(ref infoReader); // Verify. var newVarFileInfo = newVersionInfo.GetChild<VarFileInfo>(VarFileInfo.VarFileInfoKey); Assert.NotNull(newVarFileInfo); Assert.Single(newVarFileInfo.Tables); var newTable = newVarFileInfo.Tables[0]; Assert.Equal(table.Values, newTable.Values); } [Fact] public void PersistentStringFileInfo() { // Prepare mock data. var versionInfo = new VersionInfoResource(); var stringFileInfo = new StringFileInfo(); var table = new StringTable(0, 0x4b0) { [StringTable.ProductNameKey] = "Sample product", [StringTable.FileVersionKey] = "1.2.3.4", [StringTable.ProductVersionKey] = "1.0.0.0", [StringTable.FileDescriptionKey] = "This is a sample description" }; stringFileInfo.Tables.Add(table); versionInfo.AddEntry(stringFileInfo); // Serialize. var tempStream = new MemoryStream(); versionInfo.Write(new BinaryStreamWriter(tempStream)); // Reload. var infoReader = new BinaryStreamReader(tempStream.ToArray()); var newVersionInfo = VersionInfoResource.FromReader(ref infoReader); // Verify. var newStringFileInfo = newVersionInfo.GetChild<StringFileInfo>(StringFileInfo.StringFileInfoKey); Assert.NotNull(newStringFileInfo); Assert.Single(newStringFileInfo.Tables); var newTable = newStringFileInfo.Tables[0]; foreach ((string key, string value) in table) Assert.Equal(value, newTable[key]); } [Fact] public void PersistentVersionResource() { // Load dummy var image = PEImage.FromBytes(Properties.Resources.HelloWorld); var resources = image.Resources!; // Update version info. var versionInfo = VersionInfoResource.FromDirectory(resources)!; Assert.NotNull(versionInfo); versionInfo.FixedVersionInfo.ProductVersion = new System.Version(1, 2, 3, 4); versionInfo.InsertIntoDirectory(resources); // Rebuild using var stream = new MemoryStream(); new ManagedPEFileBuilder().CreateFile(image).Write(new BinaryStreamWriter(stream)); // Reload version info. var newImage = PEImage.FromBytes(stream.ToArray()); var newVersionInfo = VersionInfoResource.FromDirectory(newImage.Resources!)!; Assert.NotNull(newVersionInfo); // Verify. Assert.Equal(versionInfo.FixedVersionInfo.ProductVersion, newVersionInfo.FixedVersionInfo.ProductVersion); } [Fact] public void VersionInfoAlignment() { // https://github.com/Washi1337/AsmResolver/issues/202 // Open dummy var file = PEFile.FromBytes(Properties.Resources.HelloWorld_PaddedVersionInfo); var image = PEImage.FromFile(file); // Update version info. var versionInfo = VersionInfoResource.FromDirectory(image.Resources!)!; var info = versionInfo.GetChild<StringFileInfo>(StringFileInfo.StringFileInfoKey); info.Tables[0][StringTable.FileDescriptionKey] = "This is a test application"; versionInfo.InsertIntoDirectory(image.Resources!); // Replace section. var resourceBuffer = new ResourceDirectoryBuffer(); resourceBuffer.AddDirectory(image.Resources!); var section = file.GetSectionContainingRva(file.OptionalHeader.GetDataDirectory(DataDirectoryIndex.ResourceDirectory).VirtualAddress); section.Contents = resourceBuffer; file.UpdateHeaders(); file.OptionalHeader.SetDataDirectory(DataDirectoryIndex.ResourceDirectory, new DataDirectory(resourceBuffer.Rva, resourceBuffer.GetPhysicalSize())); // Rebuild using var stream = new MemoryStream(); file.Write(stream); // Reopen and verify. var newImage = PEImage.FromBytes(stream.ToArray()); var newVersionInfo = VersionInfoResource.FromDirectory(newImage.Resources!)!; var newInfo = newVersionInfo.GetChild<StringFileInfo>(StringFileInfo.StringFileInfoKey); Assert.Equal("This is a test application", newInfo.Tables[0][StringTable.FileDescriptionKey]); Assert.Equal(versionInfo.Lcid, newVersionInfo.Lcid); } }
331
10,355
using System; using System.Collections.Generic; using System.Linq; using AsmResolver.IO; namespace AsmResolver.PE.Win32Resources.Version { /// <summary> /// Represents a native version resource file. /// </summary> public class VersionInfoResource : VersionTableEntry, IWin32Resource { /// <summary> /// The name of the root object of the native version resource file. /// </summary> public const string VsVersionInfoKey = "VS_VERSION_INFO"; private FixedVersionInfo _fixedVersionInfo = new(); private readonly Dictionary<string, VersionTableEntry> _entries = new(); /// <summary> /// Creates a new empty version info resource targeting the English (United States) language identifier. /// </summary> public VersionInfoResource() : this(0) { } /// <summary> /// Creates a new empty version info resource. /// </summary> /// <param name="lcid">The language identifier the resource version info is targeting.</param> public VersionInfoResource(int lcid) { Lcid = lcid; } /// <summary> /// Gets the language identifier the resource version info is targeting. /// </summary> public int Lcid { get; } /// <inheritdoc /> public override string Key => VsVersionInfoKey; /// <inheritdoc /> protected override VersionTableValueType ValueType => VersionTableValueType.Binary; /// <summary> /// Gets the fixed version info stored in this version resource. /// </summary> public FixedVersionInfo FixedVersionInfo { get => _fixedVersionInfo; set => _fixedVersionInfo = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Gets or sets a version table entry by its name. /// </summary> /// <param name="name">The name of the child.</param> public VersionTableEntry this[string name] { get => _entries[name]; set => _entries[name] = value; } /// <summary> /// Obtains all version info resources from the provided root win32 resources directory. /// </summary> /// <param name="rootDirectory">The root resources directory to extract the version info from.</param> /// <returns>The version info resource, or <c>null</c> if none was found.</returns> public static IEnumerable<VersionInfoResource?> FindAllFromDirectory(ResourceDirectory rootDirectory) { if (!rootDirectory.TryGetDirectory(ResourceType.Version, out var versionDirectory)) return Enumerable.Empty<VersionInfoResource?>(); var categoryDirectory = versionDirectory .Entries .OfType<ResourceDirectory>() .FirstOrDefault(); if (categoryDirectory is null) return Enumerable.Empty<VersionInfoResource?>(); return categoryDirectory.Entries .OfType<ResourceData>() .Select(FromResourceData)!; } /// <summary> /// Obtains the first version info resource from the provided root win32 resources directory. /// </summary> /// <param name="rootDirectory">The root resources directory to extract the version info from.</param> /// <returns>The version info resource, or <c>null</c> if none was found.</returns> public static VersionInfoResource? FromDirectory(ResourceDirectory rootDirectory) { return FindAllFromDirectory(rootDirectory).FirstOrDefault(); } /// <summary> /// Obtains the version info resource from the provided root win32 resources directory. /// </summary> /// <param name="rootDirectory">The root resources directory to extract the version info from.</param> /// <param name="lcid">The language identifier to get the version info from.</param> /// <returns>The version info resource, or <c>null</c> if none was found.</returns> public static VersionInfoResource? FromDirectory(ResourceDirectory rootDirectory, int lcid) { if (!rootDirectory.TryGetDirectory(ResourceType.Version, out var versionDirectory)) return null; var categoryDirectory = versionDirectory .Entries .OfType<ResourceDirectory>() .FirstOrDefault(); var dataEntry = categoryDirectory ?.Entries .OfType<ResourceData>() .FirstOrDefault(x => x.Id == lcid); if (dataEntry is null) return null; return FromResourceData(dataEntry); } /// <summary> /// Obtains the version info resource from the provided resource data entry. /// </summary> /// <param name="dataEntry">The data entry to extract the version info from.</param> /// <returns>The extracted version info resource.</returns> public static VersionInfoResource FromResourceData(ResourceData dataEntry) { if (dataEntry.CanRead) { var dataReader = dataEntry.CreateReader(); return FromReader((int) dataEntry.Id, ref dataReader); } if (dataEntry.Contents is VersionInfoResource resource) return resource; throw new ArgumentException("Version resource data is not readable."); } /// <summary> /// Reads a version resource from an input stream. /// </summary> /// <param name="reader">The input stream.</param> /// <returns>The parsed version resource.</returns> /// <exception cref="FormatException"> /// Occurs when the input stream does not point to a valid version resource. /// </exception> public static VersionInfoResource FromReader(ref BinaryStreamReader reader) => FromReader(0, ref reader); /// <summary> /// Reads a version resource from an input stream. /// </summary> /// <param name="lcid">The language identifier to get the version info from.</param> /// <param name="reader">The input stream.</param> /// <returns>The parsed version resource.</returns> /// <exception cref="FormatException"> /// Occurs when the input stream does not point to a valid version resource. /// </exception> public static VersionInfoResource FromReader(int lcid, ref BinaryStreamReader reader) { ulong start = reader.Offset; // Read header. var header = VersionTableEntryHeader.FromReader(ref reader); if (header.Key != VsVersionInfoKey) throw new FormatException($"Input stream does not point to a {VsVersionInfoKey} entry."); var result = new VersionInfoResource(lcid); // Read fixed version info. reader.Align(4); result.FixedVersionInfo = FixedVersionInfo.FromReader(ref reader); // Read children. while (reader.Offset - start < header.Length) { reader.Align(4); result.AddEntry(ReadNextEntry(ref reader)); } return result; } private static VersionTableEntry ReadNextEntry(ref BinaryStreamReader reader) { ulong start = reader.Offset; var header = VersionTableEntryHeader.FromReader(ref reader); reader.Align(4); return header.Key switch { VarFileInfo.VarFileInfoKey => VarFileInfo.FromReader(start, header, ref reader), StringFileInfo.StringFileInfoKey => StringFileInfo.FromReader(start, header, ref reader), _ => throw new FormatException($"Invalid or unsupported entry {header.Key}.") }; } /// <summary> /// Gets a collection of entries stored in the version resource. /// </summary> public IEnumerable<VersionTableEntry> GetChildren() => _entries.Values; /// <summary> /// Gets a version table entry by its name. /// </summary> /// <param name="name">The name of the child.</param> /// <typeparam name="TEntry">The type of the version table entry to lookup.</typeparam> /// <returns>The entry.</returns> public TEntry GetChild<TEntry>(string name) where TEntry : VersionTableEntry { return (TEntry) this[name]; } /// <summary> /// Adds (or overrides the existing entry with the same name) to the version resource. /// </summary> /// <param name="entry">The entry to add.</param> public void AddEntry(VersionTableEntry entry) => _entries[entry.Key] = entry; /// <summary> /// Remove an entry by its name. /// </summary> /// <param name="name">The name of the child to remove..</param> /// <returns> /// <c>true</c> if the name existed in the table and was removed successfully, <c>false</c> otherwise. /// </returns> public bool RemoveEntry(string name) => _entries.Remove(name); /// <inheritdoc /> public override uint GetPhysicalSize() { uint size = VersionTableEntryHeader.GetHeaderSize(Key); size = size.Align(4); size += _fixedVersionInfo.GetPhysicalSize(); size = size.Align(4); foreach (var entry in _entries) { size = size.Align(4); size += entry.Value.GetPhysicalSize(); } return size; } /// <inheritdoc /> protected override uint GetValueLength() => FixedVersionInfo.GetPhysicalSize(); /// <inheritdoc /> protected override void WriteValue(BinaryStreamWriter writer) { FixedVersionInfo.Write(writer); foreach (var entry in _entries.Values) { writer.Align(4); entry.Write(writer); } } /// <inheritdoc /> public void InsertIntoDirectory(ResourceDirectory rootDirectory) { // Add version directory if it doesn't exist yet. if (!rootDirectory.TryGetDirectory(ResourceType.Version, out var versionDirectory)) { versionDirectory = new ResourceDirectory(ResourceType.Version); rootDirectory.InsertOrReplaceEntry(versionDirectory); } // Add category directory if it doesn't exist yet. if (!versionDirectory.TryGetDirectory(1, out var categoryDirectory)) { categoryDirectory = new ResourceDirectory(1); versionDirectory.InsertOrReplaceEntry(categoryDirectory); } // Insert / replace data entry. categoryDirectory.InsertOrReplaceEntry(new ResourceData((uint) Lcid, this)); } } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\ArgumentListLeafTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
ArgumentListLeafTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class ArgumentListLeafTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ArgumentListLeafTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadMultipleTypes() { var list = (ArgumentListLeaf) _fixture.SimplePdb.GetLeafRecord(0x2391); Assert.IsAssignableFrom<PointerTypeRecord>(list.Types[0]); Assert.IsAssignableFrom<SimpleTypeRecord>(list.Types[1]); } }
126
627
using System.Collections.Generic; using System.Threading; using AsmResolver.Shims; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a leaf containing a list of type arguments for a function or method. /// </summary> public class ArgumentListLeaf : CodeViewLeaf, ITpiLeaf { private IList<CodeViewTypeRecord>? _types; /// <summary> /// Initializes an empty argument list. /// </summary> /// <param name="typeIndex">The type index to assign to the list.</param> protected ArgumentListLeaf(uint typeIndex) : base(typeIndex) { } /// <summary> /// Creates a new empty argument list. /// </summary> public ArgumentListLeaf() : base(0) { } /// <summary> /// Creates a new argument list. /// </summary> public ArgumentListLeaf(params CodeViewTypeRecord[] argumentTypes) : base(0) { _types = new List<CodeViewTypeRecord>(argumentTypes); } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.ArgList; /// <summary> /// Gets an ordered collection of types that correspond to the types of each parameter. /// </summary> public IList<CodeViewTypeRecord> Types { get { if (_types is null) Interlocked.CompareExchange(ref _types, GetArgumentTypes(), null); return _types; } } /// <summary> /// Obtains the argument types stored in the list. /// </summary> /// <returns>The types.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Types"/> property. /// </remarks> protected virtual IList<CodeViewTypeRecord> GetArgumentTypes() => new List<CodeViewTypeRecord>(); /// <inheritdoc /> public override string ToString() => StringShim.Join(", ", Types); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\ArrayTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
ArrayTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class ArrayTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ArrayTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadElementType() { var type = (ArrayTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1905); Assert.Equal(SimpleTypeKind.Void, Assert.IsAssignableFrom<SimpleTypeRecord>(type.ElementType).Kind); } [Fact] public void ReadIndexType() { var type = (ArrayTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1905); Assert.Equal(SimpleTypeKind.UInt32Long, Assert.IsAssignableFrom<SimpleTypeRecord>(type.IndexType).Kind); } [Fact] public void ReadLength() { var type = (ArrayTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1905); Assert.Equal(4u, type.Length); } [Fact] public void ReadEmptyName() { var type = (ArrayTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1905); Assert.True(Utf8String.IsNullOrEmpty(type.Name)); } }
106
1,210
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a type describing an array of elements. /// </summary> public class ArrayTypeRecord : CodeViewTypeRecord { private readonly LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?> _elementType; private readonly LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?> _indexType; private readonly LazyVariable<ArrayTypeRecord, Utf8String> _name; /// <summary> /// Initializes a new empty array type. /// </summary> /// <param name="typeIndex">The type index to assign to the type.</param> protected ArrayTypeRecord(uint typeIndex) : base(typeIndex) { _elementType = new LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?>(x => x.GetElementType()); _indexType = new LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?>(x => x.GetIndexType()); _name = new LazyVariable<ArrayTypeRecord, Utf8String>(x => x.GetName()); } /// <summary> /// Creates a new array type. /// </summary> /// <param name="elementType">The type of each element in the array.</param> /// <param name="indexType">The type to use for indexing into the array.</param> /// <param name="length">The number of elements in the array.</param> public ArrayTypeRecord(CodeViewTypeRecord elementType, CodeViewTypeRecord indexType, ulong length) : base(0) { _elementType = new LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?>(elementType); _indexType = new LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?>(indexType); _name = new LazyVariable<ArrayTypeRecord, Utf8String>(Utf8String.Empty); Length = length; } /// <summary> /// Creates a new array type. /// </summary> /// <param name="elementType">The type of each element in the array.</param> /// <param name="indexType">The type to use for indexing into the array.</param> /// <param name="length">The number of elements in the array.</param> /// <param name="name">The name of the array type.</param> public ArrayTypeRecord(CodeViewTypeRecord elementType, CodeViewTypeRecord indexType, ulong length, Utf8String name) : base(0) { _elementType = new LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?>(elementType); _indexType = new LazyVariable<ArrayTypeRecord, CodeViewTypeRecord?>(indexType); _name = new LazyVariable<ArrayTypeRecord, Utf8String>(name); Length = length; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.Array; /// <summary> /// Gets or sets the type of each element in the array. /// </summary> public CodeViewTypeRecord? ElementType { get => _elementType.GetValue(this); set => _elementType.SetValue(value); } /// <summary> /// Gets or sets the type that is used to index into the array. /// </summary> public CodeViewTypeRecord? IndexType { get => _indexType.GetValue(this); set => _indexType.SetValue(value); } /// <summary> /// Gets or sets the number of elements in the array. /// </summary> public ulong Length { get; set; } /// <summary> /// Gets or sets the name of the type. /// </summary> public Utf8String Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the element type of the array. /// </summary> /// <returns>The element type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="ElementType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetElementType() => null; /// <summary> /// Obtains the index type of the array. /// </summary> /// <returns>The index type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="IndexType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetIndexType() => null; /// <summary> /// Obtains the name type of the array. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String GetName() => Utf8String.Empty; /// <inheritdoc /> public override string ToString() => $"{ElementType}[{Length}]"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\BitFieldTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
BitFieldTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class BitFieldTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public BitFieldTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadBaseType() { var type = (BitFieldTypeRecord) _fixture.MyTestApplication.GetLeafRecord(0x1060); Assert.Equal(SimpleTypeKind.UInt32Long, Assert.IsAssignableFrom<SimpleTypeRecord>(type.Type).Kind); } [Fact] public void ReadPosition() { var type = (BitFieldTypeRecord) _fixture.MyTestApplication.GetLeafRecord(0x1060); Assert.Equal(2, type.Position); } [Fact] public void ReadLength() { var type = (BitFieldTypeRecord) _fixture.MyTestApplication.GetLeafRecord(0x1060); Assert.Equal(30, type.Length); } }
106
971
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a bit field type. /// </summary> public class BitFieldTypeRecord : CodeViewTypeRecord { private readonly LazyVariable<BitFieldTypeRecord, CodeViewTypeRecord?> _type; /// <summary> /// Initializes an empty bit field record. /// </summary> /// <param name="typeIndex">The type index to assign to the bit field type.</param> protected BitFieldTypeRecord(uint typeIndex) : base(typeIndex) { _type = new LazyVariable<BitFieldTypeRecord, CodeViewTypeRecord?>(x => x.GetBaseType()); } /// <summary> /// Creates a new bit field record. /// </summary> /// <param name="type">The type of the bit field.</param> /// <param name="position">The bit index the bit field starts at.</param> /// <param name="length">The number of bits the bit field spans.</param> public BitFieldTypeRecord(CodeViewTypeRecord type, byte position, byte length) : base(0) { _type = new LazyVariable<BitFieldTypeRecord, CodeViewTypeRecord?>(type); Position = position; Length = length; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.BitField; /// <summary> /// Gets or sets the base type that this bit field is referencing. /// </summary> public CodeViewTypeRecord? Type { get => _type.GetValue(this); set => _type.SetValue(value); } /// <summary> /// Gets or sets the bit index that this bit fields starts at. /// </summary> public byte Position { get; set; } /// <summary> /// Gets or sets the number of bits that this bit fields spans. /// </summary> public byte Length { get; set; } /// <summary> /// Obtains the base type that the bit field is referencing. /// </summary> /// <returns>The base type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Type"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetBaseType() => null; /// <inheritdoc /> public override string ToString() => $"{Type} : {Length}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\BuildInfoLeafTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
BuildInfoLeafTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class BuildInfoLeafTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public BuildInfoLeafTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Entries() { var info = _fixture.SimplePdb.GetIdLeafRecord<BuildInfoLeaf>(0x100d); Assert.Equal(new[] { @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll", @"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.29.30133\bin\HostX86\x86\CL.exe", @"dllmain.cpp", @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\vc142.pdb", @" Files (x86)\Windows Kits\10\Include\10.0.19041.0\winrt"" -external:I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\cppwinrt"" -external:I""C:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\Include\um"" -X" }, info.Entries.Select(e => e.Value.Value)); } }
126
1,158
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a leaf containing build information for a file in a PDB image. /// </summary> public class BuildInfoLeaf : SubStringListLeaf { /// <summary> /// Initializes an empty build information leaf. /// </summary> /// <param name="typeIndex">The type index associated to the leaf.</param> protected BuildInfoLeaf(uint typeIndex) : base(typeIndex) { } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.BuildInfo; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\ClassTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
ClassTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['System', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class ClassTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ClassTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Theory] [InlineData(CodeViewLeafKind.Class)] [InlineData(CodeViewLeafKind.Structure)] [InlineData(CodeViewLeafKind.Interface)] public void CreateNewValidType(CodeViewLeafKind kind) { var type = new ClassTypeRecord(kind, "MyType", "MyUniqueType", 4, StructureAttributes.FwdRef, null); Assert.Equal(kind, type.LeafKind); Assert.Equal("MyType", type.Name); Assert.Equal("MyUniqueType", type.UniqueName); Assert.Equal(4u, type.Size); Assert.Equal(StructureAttributes.FwdRef, type.StructureAttributes); Assert.Null(type.BaseType); } [Fact] public void CreateNonValidType() { Assert.Throws<ArgumentOutOfRangeException>(() => new ClassTypeRecord( CodeViewLeafKind.Char, "Invalid", "Invalid", 4, StructureAttributes.FwdRef, null)); } [Fact] public void ReadFieldList() { var type = (ClassTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x101b); Assert.NotNull(type.Fields); } [Fact] public void ReadVTableShape() { var type = (ClassTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x239f); Assert.NotNull(type.VTableShape); Assert.Equal(new[] { VTableShapeEntry.Near32, VTableShapeEntry.Near32, }, type.VTableShape.Entries); } }
121
1,794
using System; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a class, structure or interface type in a PDB. /// </summary> public class ClassTypeRecord : CodeViewDerivedTypeRecord { private readonly LazyVariable<ClassTypeRecord, Utf8String> _uniqueName; private readonly LazyVariable<ClassTypeRecord, VTableShapeLeaf?> _vtableShape; /// <summary> /// Initializes an empty class type. /// </summary> /// <param name="kind">The kind of type.</param> /// <param name="typeIndex">The type index to assign to the class type.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Occurs when the provided kind is not a class, structure or interface. /// </exception> protected ClassTypeRecord(CodeViewLeafKind kind, uint typeIndex) : base(typeIndex) { if (kind is not (CodeViewLeafKind.Class or CodeViewLeafKind.Structure or CodeViewLeafKind.Interface)) throw new ArgumentOutOfRangeException(nameof(kind)); LeafKind = kind; _uniqueName = new LazyVariable<ClassTypeRecord, Utf8String>(x => x.GetUniqueName()); _vtableShape = new LazyVariable<ClassTypeRecord, VTableShapeLeaf?>(x => x.GetVTableShape()); } /// <summary> /// Creates a new class type record. /// </summary> /// <param name="kind">The kind.</param> /// <param name="name">The name of the type.</param> /// <param name="uniqueName">The unique mangled name of the type.</param> /// <param name="size">The size in bytes of the type.</param> /// <param name="attributes">Attributes describing the shape of the type.</param> /// <param name="baseType">The type that this type is derived from, if any.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Occurs when the provided kind is not a class, structure or interface. /// </exception> public ClassTypeRecord(CodeViewLeafKind kind, Utf8String name, Utf8String uniqueName, ulong size, StructureAttributes attributes, CodeViewTypeRecord? baseType) : base(0) { if (kind is not (CodeViewLeafKind.Class or CodeViewLeafKind.Structure or CodeViewLeafKind.Interface)) throw new ArgumentOutOfRangeException(nameof(kind)); LeafKind = kind; Name = name; _uniqueName = new LazyVariable<ClassTypeRecord, Utf8String>(uniqueName); _vtableShape = new LazyVariable<ClassTypeRecord, VTableShapeLeaf?>(default(VTableShapeLeaf)); Size = size; StructureAttributes = attributes; BaseType = baseType; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind { get; } /// <summary> /// Gets or sets the number bytes that this class spans. /// </summary> public ulong Size { get; set; } /// <summary> /// Gets or sets the uniquely identifiable name for this type. /// </summary> public Utf8String UniqueName { get => _uniqueName.GetValue(this); set => _uniqueName.SetValue(value); } /// <summary> /// Gets or sets the shape of the virtual function table of this type, if available. /// </summary> public VTableShapeLeaf? VTableShape { get => _vtableShape.GetValue(this); set => _vtableShape.SetValue(value); } /// <summary> /// Obtains the uniquely identifiable name of the type. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="UniqueName"/> property. /// </remarks> protected virtual Utf8String GetUniqueName() => Utf8String.Empty; /// <summary> /// Obtains the shape of the virtual function table name of the type. /// </summary> /// <returns>The shape.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="VTableShape"/> property. /// </remarks> protected virtual VTableShapeLeaf? GetVTableShape() => null; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\EnumTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
EnumTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class EnumTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public EnumTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void FieldList() { var leaf = _fixture.SimplePdb.GetLeafRecord(0x1009); var fields = Assert.IsAssignableFrom<EnumTypeRecord>(leaf).Fields!.Entries.Cast<EnumerateField>().ToArray(); var names = new[] { "DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED", "DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE", "DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED", "DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST", "DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST", "DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32", }; Assert.Equal(names[0], fields[0].Name); Assert.Equal(names[1], fields[1].Name); Assert.Equal(names[2], fields[2].Name); Assert.Equal(names[3], fields[3].Name); Assert.Equal(names[4], fields[4].Name); Assert.Equal(names[5], fields[5].Name); } }
126
1,313
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents an enum type. /// </summary> public class EnumTypeRecord : CodeViewDerivedTypeRecord { /// <summary> /// Initializes a new empty enum type. /// </summary> /// <param name="typeIndex">The type index to assign to the enum type.</param> protected EnumTypeRecord(uint typeIndex) : base(typeIndex) { } /// <summary> /// Creates a new enum type. /// </summary> /// <param name="name">The name of the enum.</param> /// <param name="underlyingType">The underlying type of all members in the enum.</param> /// <param name="attributes">The structural attributes assigned to the enum.</param> public EnumTypeRecord(Utf8String name, CodeViewTypeRecord underlyingType, StructureAttributes attributes) : base(0) { Name = name; BaseType = underlyingType; StructureAttributes = attributes; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.Enum; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\FieldListLeafTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
FieldListLeafTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit', 'AsmResolver.Symbols.Pdb.Leaves.CodeViewFieldAttributes']
xUnit
net8.0
public class FieldListLeafTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public FieldListLeafTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadEnumerateList() { var list = (FieldListLeaf) _fixture.SimplePdb.GetLeafRecord(0x1008); var enumerates = list.Entries .Cast<EnumerateField>() .Select(f => (f.Attributes, f.Name.Value, f.Value)) .ToArray(); Assert.Equal((Public, "DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED", 0u), enumerates[0]); Assert.Equal((Public, "DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE", 1u), enumerates[1]); Assert.Equal((Public, "DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED", 2u), enumerates[2]); Assert.Equal((Public, "DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST", 2u), enumerates[3]); Assert.Equal((Public, "DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST", 3u), enumerates[4]); Assert.Equal((Public, "DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32", '\xff'), enumerates[5]); } [Fact] public void ReadInstanceDataMemberList() { var list = (FieldListLeaf) _fixture.SimplePdb.GetLeafRecord(0x1017); var enumerates = list.Entries .Cast<InstanceDataField>() .Select(f => (f.Attributes, f.Name.Value, f.Offset)) .ToArray(); Assert.Equal((Public, "cbSize", 0ul), enumerates[0]); Assert.Equal((Public, "fMask", 4ul), enumerates[1]); Assert.Equal((Public, "fType", 8ul), enumerates[2]); Assert.Equal((Public, "fState", 12ul), enumerates[3]); Assert.Equal((Public, "wID", 16ul), enumerates[4]); Assert.Equal((Public, "hSubMenu", 20ul), enumerates[5]); Assert.Equal((Public, "hbmpChecked", 24ul), enumerates[6]); Assert.Equal((Public, "hbmpUnchecked", 28ul), enumerates[7]); Assert.Equal((Public, "dwItemData", 32ul), enumerates[8]); Assert.Equal((Public, "dwTypeData", 36ul), enumerates[9]); Assert.Equal((Public, "cch", 40ul), enumerates[10]); Assert.Equal((Public, "hbmpItem", 44ul), enumerates[11]); } [Fact] public void ReadMethodsAndBaseClass() { var list = (FieldListLeaf) _fixture.SimplePdb.GetLeafRecord(0x239d); Assert.Equal("std::exception", Assert.IsAssignableFrom<ClassTypeRecord>( Assert.IsAssignableFrom<BaseClassField>(list.Entries[0]).Type).Name); Assert.Equal("bad_cast", Assert.IsAssignableFrom<OverloadedMethod>(list.Entries[1]).Name); Assert.Equal("__construct_from_string_literal", Assert.IsAssignableFrom<NonOverloadedMethod>(list.Entries[2]).Name); Assert.Equal("~bad_cast", Assert.IsAssignableFrom<NonOverloadedMethod>(list.Entries[3]).Name); Assert.Equal("operator=", Assert.IsAssignableFrom<OverloadedMethod>(list.Entries[4]).Name); Assert.Equal("__local_vftable_ctor_closure", Assert.IsAssignableFrom<NonOverloadedMethod>(list.Entries[5]).Name); Assert.Equal("__vecDelDtor", Assert.IsAssignableFrom<NonOverloadedMethod>(list.Entries[6]).Name); } [Fact] public void ReadNestedTypes() { var list = (FieldListLeaf) _fixture.SimplePdb.GetLeafRecord(0x1854); Assert.Equal("_LDT_ENTRY::<unnamed-type-HighWord>::<unnamed-type-Bytes>", Assert.IsAssignableFrom<ClassTypeRecord>(Assert.IsAssignableFrom<NestedTypeField>(list.Entries[0]).Type).Name); Assert.Equal("_LDT_ENTRY::<unnamed-type-HighWord>::<unnamed-type-Bits>", Assert.IsAssignableFrom<ClassTypeRecord>(Assert.IsAssignableFrom<NestedTypeField>(list.Entries[2]).Type).Name); } [Fact] public void ReadVirtualBaseClass() { var list = (FieldListLeaf) _fixture.MyTestApplication.GetLeafRecord(0x1347); var baseClass = Assert.IsAssignableFrom<VBaseClassField>(list.Entries[0]); Assert.Equal("std::basic_ios<char,std::char_traits<char> >", Assert.IsAssignableFrom<ClassTypeRecord>(baseClass.Type).Name); Assert.True(Assert.IsAssignableFrom<PointerTypeRecord>(baseClass.PointerType).IsNear64); Assert.False(baseClass.IsIndirect); Assert.Equal(0ul, baseClass.PointerOffset); Assert.Equal(1ul, baseClass.TableOffset); } [Fact] public void ReadIndirectVirtualBaseClass() { var list = (FieldListLeaf) _fixture.MyTestApplication.GetLeafRecord(0x1e97); var baseClass = Assert.IsAssignableFrom<VBaseClassField>(list.Entries[2]); Assert.Equal("std::basic_ios<char,std::char_traits<char> >", Assert.IsAssignableFrom<ClassTypeRecord>(baseClass.Type).Name); Assert.True(Assert.IsAssignableFrom<PointerTypeRecord>(baseClass.PointerType).IsNear64); Assert.True(baseClass.IsIndirect); Assert.Equal(0ul, baseClass.PointerOffset); Assert.Equal(1ul, baseClass.TableOffset); } [Fact] public void ReadStaticFields() { var list = (FieldListLeaf) _fixture.MyTestApplication.GetLeafRecord(0x1423); Assert.Equal("is_bounded", Assert.IsAssignableFrom<StaticDataField>(list.Entries[1]).Name); Assert.Equal("is_exact", Assert.IsAssignableFrom<StaticDataField>(list.Entries[2]).Name); Assert.Equal("is_integer", Assert.IsAssignableFrom<StaticDataField>(list.Entries[3]).Name); Assert.Equal("is_specialized", Assert.IsAssignableFrom<StaticDataField>(list.Entries[4]).Name); Assert.Equal("radix", Assert.IsAssignableFrom<StaticDataField>(list.Entries[5]).Name); } [Fact] public void ReadVTableField() { var list = (FieldListLeaf) _fixture.MyTestApplication.GetLeafRecord(0x1215); Assert.IsAssignableFrom<PointerTypeRecord>(Assert.IsAssignableFrom<VTableField>(list.Entries[0]).PointerType); Assert.IsAssignableFrom<OverloadedMethod>(list.Entries[1]); } }
196
6,258
using System.Collections.Generic; using System.Threading; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a leaf containing a list of fields. /// </summary> public class FieldListLeaf : CodeViewLeaf, ITpiLeaf { private IList<CodeViewField>? _fields; /// <summary> /// Initializes an empty field list. /// </summary> /// <param name="typeIndex">The type index to assign to the list.</param> protected FieldListLeaf(uint typeIndex) : base(typeIndex) { } /// <summary> /// Creates a new empty field list. /// </summary> public FieldListLeaf() : base(0) { } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.FieldList; /// <summary> /// Gets a collection of fields stored in the list. /// </summary> public IList<CodeViewField> Entries { get { if (_fields is null) Interlocked.CompareExchange(ref _fields, GetEntries(), null); return _fields; } } /// <summary> /// Obtains the fields stored in the list. /// </summary> /// <returns>The fields</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Entries"/> property. /// </remarks> protected virtual IList<CodeViewField> GetEntries() => new List<CodeViewField>(); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\FunctionIdentifierTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
FunctionIdentifierTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class FunctionIdentifierTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public FunctionIdentifierTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Name() { var leaf = _fixture.SimplePdb.GetIdLeafRecord<FunctionIdentifier>(0x1453); Assert.Equal("__get_entropy", leaf.Name); } [Fact] public void FunctionType() { var leaf = _fixture.SimplePdb.GetIdLeafRecord<FunctionIdentifier>(0x1453); Assert.IsAssignableFrom<ProcedureTypeRecord>(leaf.FunctionType); } }
106
735
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a function identifier, consisting of its name and its signature. /// </summary> public class FunctionIdentifier : CodeViewLeaf, IIpiLeaf { private readonly LazyVariable<FunctionIdentifier, Utf8String?> _name; private readonly LazyVariable<FunctionIdentifier, CodeViewTypeRecord?> _functionType; /// <summary> /// Initializes an empty function identifier leaf. /// </summary> /// <param name="typeIndex">The type index.</param> protected FunctionIdentifier(uint typeIndex) : base(typeIndex) { _name = new LazyVariable<FunctionIdentifier, Utf8String?>(x => x.GetName()); _functionType = new LazyVariable<FunctionIdentifier, CodeViewTypeRecord?>(x => x.GetFunctionType()); } /// <summary> /// Creates a new function identifier leaf. /// </summary> /// <param name="scopeId">The identifier of the scope defining the function (if available).</param> /// <param name="name">The name of the function.</param> /// <param name="functionType">The type describing the shape of the function.</param> public FunctionIdentifier(uint scopeId, Utf8String name, CodeViewTypeRecord functionType) : base(0) { ScopeId = scopeId; _name = new LazyVariable<FunctionIdentifier, Utf8String?>(name); _functionType = new LazyVariable<FunctionIdentifier, CodeViewTypeRecord?>(functionType); } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.FuncId; /// <summary> /// Gets or sets the identifier of the scope defining the function (if available). /// </summary> public uint ScopeId { get; set; } /// <summary> /// Gets or sets the name of the function. /// </summary> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Gets or sets the type describing the shape of the function. /// </summary> public CodeViewTypeRecord? FunctionType { get => _functionType.GetValue(this); set => _functionType.SetValue(value); } /// <summary> /// Obtains the name of the function. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <summary> /// Obtains the type of the function. /// </summary> /// <returns>The type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="FunctionType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetFunctionType() => null; /// <inheritdoc /> public override string ToString() => Name ?? "<<<NULL NAME>>>"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\MemberFunctionLeafTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
MemberFunctionLeafTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class MemberFunctionLeafTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public MemberFunctionLeafTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadReturnType() { var function = (MemberFunctionLeaf) _fixture.SimplePdb.GetLeafRecord(0x2392); Assert.Equal(SimpleTypeKind.Void, Assert.IsAssignableFrom<SimpleTypeRecord>(function.ReturnType).Kind); } [Fact] public void ReadDeclaringType() { var function = (MemberFunctionLeaf) _fixture.SimplePdb.GetLeafRecord(0x2392); Assert.Equal("std::bad_cast", Assert.IsAssignableFrom<ClassTypeRecord>(function.DeclaringType).Name); } [Fact] public void ReadNonNullThisType() { var function = (MemberFunctionLeaf) _fixture.SimplePdb.GetLeafRecord(0x2392); Assert.IsAssignableFrom<PointerTypeRecord>(function.ThisType); } [Fact] public void ReadArgumentList() { var function = (MemberFunctionLeaf) _fixture.SimplePdb.GetLeafRecord(0x2392); Assert.NotNull(function.Arguments); Assert.IsAssignableFrom<PointerTypeRecord>(function.Arguments!.Types[0]); Assert.IsAssignableFrom<SimpleTypeRecord>(function.Arguments.Types[1]); } }
106
1,441
using System.Linq; using AsmResolver.Shims; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a single instance member function. /// </summary> public class MemberFunctionLeaf : CodeViewLeaf, ITpiLeaf { private readonly LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?> _returnType; private readonly LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?> _declaringType; private readonly LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?> _thisType; private readonly LazyVariable<MemberFunctionLeaf, ArgumentListLeaf?> _argumentList; /// <summary> /// Initializes an empty member function. /// </summary> /// <param name="typeIndex">The type index to assign to the function.</param> protected MemberFunctionLeaf(uint typeIndex) : base(typeIndex) { _returnType = new LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?>(x => x.GetReturnType()); _declaringType = new LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?>(x => x.GetDeclaringType()); _thisType = new LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?>(x => x.GetThisType()); _argumentList = new LazyVariable<MemberFunctionLeaf, ArgumentListLeaf?>(x => x.GetArguments()); } /// <summary> /// Creates a new member function. /// </summary> /// <param name="returnType">The return type of the function.</param> /// <param name="declaringType">The declaring type of the function.</param> /// <param name="arguments">The argument types of the function.</param> public MemberFunctionLeaf(CodeViewTypeRecord returnType, CodeViewTypeRecord declaringType, ArgumentListLeaf arguments) : base(0) { _returnType = new LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?>(returnType); _declaringType = new LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?>(declaringType); _thisType = new LazyVariable<MemberFunctionLeaf, CodeViewTypeRecord?>(default(CodeViewTypeRecord)); _argumentList = new LazyVariable<MemberFunctionLeaf, ArgumentListLeaf?>(arguments); CallingConvention = CodeViewCallingConvention.NearC; Attributes = 0; ThisAdjuster = 0; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.MFunction; /// <summary> /// Gets or sets the return type of the function. /// </summary> public CodeViewTypeRecord? ReturnType { get => _returnType.GetValue(this); set => _returnType.SetValue(value); } /// <summary> /// Gets or sets the type that declares this member function. /// </summary> public CodeViewTypeRecord? DeclaringType { get => _declaringType.GetValue(this); set => _declaringType.SetValue(value); } /// <summary> /// Gets or sets the type of the this pointer that is used to access the member function. /// </summary> public CodeViewTypeRecord? ThisType { get => _thisType.GetValue(this); set => _thisType.SetValue(value); } /// <summary> /// Gets or sets the convention that is used when calling the member function. /// </summary> public CodeViewCallingConvention CallingConvention { get; set; } /// <summary> /// Gets or sets the attributes associated to the function. /// </summary> public MemberFunctionAttributes Attributes { get; set; } /// <summary> /// Gets or sets the list of types of the parameters that this function defines. /// </summary> public ArgumentListLeaf? Arguments { get => _argumentList.GetValue(this); set => _argumentList.SetValue(value); } /// <summary> /// Gets or sets the offset to adjust the this pointer with before devirtualization of this method. /// </summary> public uint ThisAdjuster { get; set; } /// <summary> /// Obtains the return type of the function. /// </summary> /// <returns>The return type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="ReturnType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetReturnType() => null; /// <summary> /// Obtains the declaring type of the function. /// </summary> /// <returns>The declaring type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="DeclaringType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetDeclaringType() => null; /// <summary> /// Obtains the this-type of the function. /// </summary> /// <returns>The this-type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="ThisType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetThisType() => null; /// <summary> /// Obtains the argument types of the function. /// </summary> /// <returns>The argument types.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Arguments"/> property. /// </remarks> protected virtual ArgumentListLeaf? GetArguments() => null; /// <inheritdoc /> public override string ToString() { string args = StringShim.Join(", ", Arguments?.Types ?? Enumerable.Empty<CodeViewTypeRecord>()); return $"{CallingConvention} {ReturnType} {DeclaringType}::*({args})"; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\MethodListLeafTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
MethodListLeafTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit', 'AsmResolver.Symbols.Pdb.Leaves.CodeViewFieldAttributes']
xUnit
net8.0
public class MethodListLeafTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public MethodListLeafTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadNonIntroVirtualEntries() { var list = (MethodListLeaf) _fixture.SimplePdb.GetLeafRecord(0x2394); var entries = list.Entries; Assert.Equal(new[] { Public | CompilerGenerated, Public | CompilerGenerated, Private, Public, }, entries.Select(e => e.Attributes)); Assert.All(entries, Assert.NotNull); } }
196
864
using System.Collections.Generic; using System.Linq; using System.Threading; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a leaf record containing a list of overloaded methods. /// </summary> public class MethodListLeaf : CodeViewLeaf, ITpiLeaf { private IList<MethodListEntry>? _entries; /// <summary> /// Initializes an empty method list. /// </summary> /// <param name="typeIndex">The type index to assign to the list.</param> protected MethodListLeaf(uint typeIndex) : base(typeIndex) { } /// <summary> /// Creates a new empty method list. /// </summary> public MethodListLeaf() : base(0) { } /// <summary> /// Creates a new method list. /// </summary> /// <param name="entries">The methods to include.</param> public MethodListLeaf(params MethodListEntry[] entries) : base(0) { _entries = entries.ToList(); } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.MethodList; /// <summary> /// Gets a collection of methods stored in the list. /// </summary> public IList<MethodListEntry> Entries { get { if (_entries is null) Interlocked.CompareExchange(ref _entries, GetEntries(), null); return _entries; } } /// <summary> /// Obtains the methods stored in the list. /// </summary> /// <returns>The methods</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Entries"/> property. /// </remarks> protected virtual IList<MethodListEntry> GetEntries() => new List<MethodListEntry>(); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\ModifierTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
ModifierTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class ModifierTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ModifierTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void CreateNewType() { var type = new ModifierTypeRecord(new SimpleTypeRecord(SimpleTypeKind.Character8), ModifierAttributes.Const); Assert.True(type.IsConst); } [Fact] public void ReadAttributes() { var type = (ModifierTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1011); Assert.True(type.IsConst); } [Fact] public void ReadBaseType() { var type = (ModifierTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1011); Assert.Equal(CodeViewLeafKind.Structure, type.BaseType.LeafKind); } }
106
945
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a type that is annotated with extra modifiers. /// </summary> public class ModifierTypeRecord : CodeViewTypeRecord { private readonly LazyVariable<ModifierTypeRecord, CodeViewTypeRecord> _baseType; /// <summary> /// Initializes a new empty modifier type. /// </summary> /// <param name="typeIndex">The type index to assign to the modifier type.</param> protected ModifierTypeRecord(uint typeIndex) : base(typeIndex) { _baseType = new LazyVariable<ModifierTypeRecord, CodeViewTypeRecord>(x => x.GetBaseType()); } /// <summary> /// Creates a new modified type. /// </summary> /// <param name="type">The type to be modified.</param> /// <param name="attributes">The attributes describing the shape of the pointer.</param> public ModifierTypeRecord(CodeViewTypeRecord type, ModifierAttributes attributes) : base(0) { _baseType = new LazyVariable<ModifierTypeRecord, CodeViewTypeRecord>(type); Attributes = attributes; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.Modifier; /// <summary> /// Gets or sets the type that is annotated. /// </summary> public CodeViewTypeRecord BaseType { get => _baseType.GetValue(this); set => _baseType.SetValue(value); } /// <summary> /// Gets or sets the annotations that were added to the type. /// </summary> public ModifierAttributes Attributes { get; set; } /// <summary> /// Gets or sets a value indicating whether the type is marked as const. /// </summary> public bool IsConst { get => (Attributes & ModifierAttributes.Const) != 0; set => Attributes = (Attributes & ~ModifierAttributes.Const) | (value ? ModifierAttributes.Const : 0); } /// <summary> /// Gets or sets a value indicating whether the type is marked as volatile. /// </summary> public bool IsVolatile { get => (Attributes & ModifierAttributes.Volatile) != 0; set => Attributes = (Attributes & ~ModifierAttributes.Volatile) | (value ? ModifierAttributes.Volatile : 0); } /// <summary> /// Gets or sets a value indicating whether the type is marked as unaligned. /// </summary> public bool IsUnaligned { get => (Attributes & ModifierAttributes.Unaligned) != 0; set => Attributes = (Attributes & ~ModifierAttributes.Unaligned) | (value ? ModifierAttributes.Unaligned : 0); } /// <summary> /// Obtains the base type of the modifier type. /// </summary> /// <returns>The base type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="BaseType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetBaseType() => null; /// <inheritdoc /> public override string ToString() => $"{BaseType} {Attributes}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\PointerTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
PointerTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class PointerTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public PointerTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void CreateNewType() { var type = new PointerTypeRecord(new SimpleTypeRecord(SimpleTypeKind.Character8), PointerAttributes.Const, 4); Assert.True(type.IsConst); Assert.Equal(4, type.Size); } [Fact] public void UpdateKind() { var type = new PointerTypeRecord(new SimpleTypeRecord(SimpleTypeKind.Character8), PointerAttributes.Const, 4); type.Kind = PointerAttributes.Near32; Assert.Equal(PointerAttributes.Near32, type.Kind); } [Fact] public void UpdateMode() { var type = new PointerTypeRecord(new SimpleTypeRecord(SimpleTypeKind.Character8), PointerAttributes.Const, 4); type.Mode = PointerAttributes.LValueReference; Assert.Equal(PointerAttributes.LValueReference, type.Mode); } [Fact] public void UpdateSize() { var type = new PointerTypeRecord(new SimpleTypeRecord(SimpleTypeKind.Character8), PointerAttributes.Const, 4); type.Size = 8; Assert.Equal(8, type.Size); } [Fact] public void ReadAttributes() { var type = (PointerTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1012); Assert.True(type.IsNear32); } [Fact] public void ReadBaseType() { var type = (PointerTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1012); Assert.Equal(CodeViewLeafKind.Modifier, type.BaseType.LeafKind); } }
106
1,806
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a pointer type in a TPI or IPI stream. /// </summary> public class PointerTypeRecord : CodeViewTypeRecord { private readonly LazyVariable<PointerTypeRecord, CodeViewTypeRecord> _baseType; /// <summary> /// Initializes a new empty pointer type. /// </summary> /// <param name="typeIndex">The type index to assign to the type.</param> protected PointerTypeRecord(uint typeIndex) : base(typeIndex) { _baseType = new LazyVariable<PointerTypeRecord, CodeViewTypeRecord>(x => x.GetBaseType()); } /// <summary> /// Creates a new pointer type. /// </summary> /// <param name="type">The referent type.</param> /// <param name="attributes">The attributes describing the shape of the pointer.</param> public PointerTypeRecord(CodeViewTypeRecord type, PointerAttributes attributes) : base(0) { _baseType = new LazyVariable<PointerTypeRecord, CodeViewTypeRecord>(type); Attributes = attributes; } /// <summary> /// Creates a new pointer type. /// </summary> /// <param name="type">The referent type.</param> /// <param name="attributes">The attributes describing the shape of the pointer.</param> /// <param name="size">The size of the pointer.</param> public PointerTypeRecord(CodeViewTypeRecord type, PointerAttributes attributes, byte size) : base(0) { _baseType = new LazyVariable<PointerTypeRecord, CodeViewTypeRecord>(type); Attributes = attributes; Size = size; } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.Pointer; /// <summary> /// Gets or sets the referent type of the pointer. /// </summary> public CodeViewTypeRecord BaseType { get => _baseType.GetValue(this); set => _baseType.SetValue(value); } /// <summary> /// Gets or sets the attributes describing the shape of the pointer type. /// </summary> public PointerAttributes Attributes { get; set; } /// <summary> /// Gets or sets the kind of the pointer. /// </summary> public PointerAttributes Kind { get => Attributes & PointerAttributes.KindMask; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value & PointerAttributes.KindMask); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 16 bit pointer. /// </summary> public bool IsNear16 { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.Near16; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.Near16 : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 16:16 far pointer. /// </summary> public bool IsFar16 { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.Far16; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.Far16 : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 16:16 huge pointer. /// </summary> public bool IsHuge16 { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.Huge16; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.Huge16 : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on segment. /// </summary> public bool IsBasedOnSegment { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnSegment; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnSegment : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on value of base. /// </summary> public bool IsBasedOnValue { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnValue; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnValue : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on segment value of base. /// </summary> public bool IsBasedOnSegmentValue { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnSegmentValue; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnSegmentValue : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on address of base. /// </summary> public bool IsBasedOnAddress { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnAddress; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnAddress : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on segment address of base. /// </summary> public bool IsBasedOnSegmentAddress { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnSegmentAddress; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnSegmentAddress : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on type. /// </summary> public bool IsBasedOnType { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnType; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnType : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a based on self. /// </summary> public bool IsBasedOnSelf { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.BasedOnSelf; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.BasedOnSelf : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 32 bit pointer. /// </summary> public bool IsNear32 { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.Near32; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.Near32 : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 16:32 pointer. /// </summary> public bool IsFar32 { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.Far32; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.Far32 : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 64 bit pointer. /// </summary> public bool IsNear64 { get => (Attributes & PointerAttributes.KindMask) == PointerAttributes.Near64; set => Attributes = (Attributes & ~PointerAttributes.KindMask) | (value ? PointerAttributes.Near64 : 0); } /// <summary> /// Gets or sets the mode of the pointer. /// </summary> public PointerAttributes Mode { get => Attributes & PointerAttributes.ModeMask; set => Attributes = (Attributes & ~PointerAttributes.ModeMask) | (value & PointerAttributes.ModeMask); } /// <summary> /// Gets or sets a value indicating whether the pointer is an "old" reference. /// </summary> public bool IsLValueReference { get => (Attributes & PointerAttributes.ModeMask) == PointerAttributes.LValueReference; set => Attributes = (Attributes & ~PointerAttributes.ModeMask) | (value ? PointerAttributes.LValueReference : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a pointer to data member. /// </summary> public bool IsPointerToDataMember { get => (Attributes & PointerAttributes.ModeMask) == PointerAttributes.PointerToDataMember; set => Attributes = (Attributes & ~PointerAttributes.ModeMask) | (value ? PointerAttributes.PointerToDataMember : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a pointer to member function. /// </summary> public bool IsPointerToMemberFunction { get => (Attributes & PointerAttributes.ModeMask) == PointerAttributes.PointerToMemberFunction; set => Attributes = (Attributes & ~PointerAttributes.ModeMask) | (value ? PointerAttributes.PointerToMemberFunction : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is an r-value reference. /// </summary> public bool IsRValueReference { get => (Attributes & PointerAttributes.ModeMask) == PointerAttributes.RValueReference; set => Attributes = (Attributes & ~PointerAttributes.ModeMask) | (value ? PointerAttributes.RValueReference : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a "flat" pointer. /// </summary> public bool IsFlat32 { get => (Attributes & PointerAttributes.Flat32) != 0; set => Attributes = (Attributes & ~PointerAttributes.Flat32) | (value ? PointerAttributes.Flat32 : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is marked volatile. /// </summary> public bool IsVolatile { get => (Attributes & PointerAttributes.Volatile) != 0; set => Attributes = (Attributes & ~PointerAttributes.Volatile) | (value ? PointerAttributes.Volatile : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is marked const. /// </summary> public bool IsConst { get => (Attributes & PointerAttributes.Const) != 0; set => Attributes = (Attributes & ~PointerAttributes.Const) | (value ? PointerAttributes.Const : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is marked unaligned. /// </summary> public bool IsUnaligned { get => (Attributes & PointerAttributes.Unaligned) != 0; set => Attributes = (Attributes & ~PointerAttributes.Unaligned) | (value ? PointerAttributes.Unaligned : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is marked restrict. /// </summary> public bool IsRestrict { get => (Attributes & PointerAttributes.Restrict) != 0; set => Attributes = (Attributes & ~PointerAttributes.Restrict) | (value ? PointerAttributes.Restrict : 0); } /// <summary> /// Gets or sets the size of the pointer. /// </summary> public byte Size { get => (byte) (((uint) Attributes >> 0xD) & 0b111111); set => Attributes = (PointerAttributes) (((uint) Attributes & ~(0b111111u << 0xD)) | (((uint) value & 0b111111) << 0xD)); } /// <summary> /// Gets or sets a value indicating whether the pointer is a WinRT smart pointer. /// </summary> public bool IsWinRTSmartPointer { get => (Attributes & PointerAttributes.WinRTSmartPointer) != 0; set => Attributes = (Attributes & ~PointerAttributes.WinRTSmartPointer) | (value ? PointerAttributes.WinRTSmartPointer : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 'this' pointer of a member function with ref qualifier. /// </summary> public bool IsLValueRefThisPointer { get => (Attributes & PointerAttributes.LValueRefThisPointer) != 0; set => Attributes = (Attributes & ~PointerAttributes.LValueRefThisPointer) | (value ? PointerAttributes.LValueRefThisPointer : 0); } /// <summary> /// Gets or sets a value indicating whether the pointer is a 'this' pointer of a member function with ref qualifier. /// </summary> public bool IsRValueRefThisPointer { get => (Attributes & PointerAttributes.RValueRefThisPointer) != 0; set => Attributes = (Attributes & ~PointerAttributes.RValueRefThisPointer) | (value ? PointerAttributes.RValueRefThisPointer : 0); } /// <summary> /// Obtains the base type of the pointer. /// </summary> /// <returns>The base type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="BaseType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetBaseType() => null; /// <inheritdoc /> public override string ToString() => $"({BaseType})*"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\ProcedureTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
ProcedureTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class ProcedureTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ProcedureTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadReturnType() { var procedure = (ProcedureTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x18f7); Assert.Equal(SimpleTypeKind.Void, Assert.IsAssignableFrom<SimpleTypeRecord>(procedure.ReturnType).Kind); } [Fact] public void ReadCallingConvention() { var procedure = (ProcedureTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x18f7); Assert.Equal(CodeViewCallingConvention.NearStd, procedure.CallingConvention); } [Fact] public void ReadArguments() { var procedure = (ProcedureTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x18f7); Assert.NotNull(procedure.Arguments); Assert.Equal(2, procedure.Arguments!.Types.Count); } }
106
1,098
using System.Linq; using AsmResolver.Shims; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a function pointer or procedure type. /// </summary> public class ProcedureTypeRecord : CodeViewTypeRecord { private readonly LazyVariable<ProcedureTypeRecord, CodeViewTypeRecord?> _returnType; private readonly LazyVariable<ProcedureTypeRecord, ArgumentListLeaf?> _argumentList; /// <summary> /// Initializes an empty procedure type. /// </summary> /// <param name="typeIndex">The type index to assign to the type.</param> protected ProcedureTypeRecord(uint typeIndex) : base(typeIndex) { _returnType = new LazyVariable<ProcedureTypeRecord, CodeViewTypeRecord?>(x => x.GetReturnType()); _argumentList = new LazyVariable<ProcedureTypeRecord, ArgumentListLeaf?>(x => x.GetArguments()); } /// <summary> /// Creates a new procedure type. /// </summary> /// <param name="callingConvention">The convention to use when calling the function pointed by values of this type.</param> /// <param name="returnType">The return type of the function.</param> /// <param name="arguments">The argument type list of the function.</param> public ProcedureTypeRecord(CodeViewCallingConvention callingConvention, CodeViewTypeRecord returnType, ArgumentListLeaf arguments) : base(0) { CallingConvention = callingConvention; _returnType = new LazyVariable<ProcedureTypeRecord, CodeViewTypeRecord?>(returnType); _argumentList = new LazyVariable<ProcedureTypeRecord, ArgumentListLeaf?>(arguments); } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.Procedure; /// <summary> /// Gets or sets the return type of the function. /// </summary> public CodeViewTypeRecord? ReturnType { get => _returnType.GetValue(this); set => _returnType.SetValue(value); } /// <summary> /// Gets or sets the convention that is used when calling the member function. /// </summary> public CodeViewCallingConvention CallingConvention { get; set; } /// <summary> /// Gets or sets the attributes associated to the function. /// </summary> public MemberFunctionAttributes Attributes { get; set; } /// <summary> /// Gets or sets the list of types of the parameters that this function defines. /// </summary> public ArgumentListLeaf? Arguments { get => _argumentList.GetValue(this); set => _argumentList.SetValue(value); } /// <summary> /// Obtains the return type of the procedure. /// </summary> /// <returns>The return type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="ReturnType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetReturnType() => null; /// <summary> /// Obtains the argument types of the procedure.. /// </summary> /// <returns>The argument types.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Arguments"/> property. /// </remarks> protected virtual ArgumentListLeaf? GetArguments() => null; /// <inheritdoc /> public override string ToString() { string args = StringShim.Join(", ", Arguments?.Types ?? Enumerable.Empty<CodeViewTypeRecord>()); return $"{CallingConvention} {ReturnType} *({args})"; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\SimpleTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
SimpleTypeRecordTest
[]
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class SimpleTypeRecordTest { [Theory] [InlineData(0x00_75, SimpleTypeKind.UInt32, SimpleTypeMode.Direct)] [InlineData(0x04_03, SimpleTypeKind.Void, SimpleTypeMode.NearPointer32)] public void TypeIndexParsing(uint typeIndex, SimpleTypeKind kind, SimpleTypeMode mode) { var type = new SimpleTypeRecord(typeIndex); Assert.Equal(kind, type.Kind); Assert.Equal(mode, type.Mode); } }
106
549
using System; namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a simple type referenced by a simple type index. /// </summary> public class SimpleTypeRecord : CodeViewTypeRecord { /// <summary> /// Constructs a new simple type based on the provided type index. /// </summary> /// <param name="typeIndex">The type index.</param> public SimpleTypeRecord(uint typeIndex) : base(typeIndex) { } /// <summary> /// Constructs a new simple type with the provided type kind. /// </summary> /// <param name="kind">The type kind.</param> public SimpleTypeRecord(SimpleTypeKind kind) : base((uint) kind) { } /// <summary> /// Constructs a new simple type with the provided type kind and mode. /// </summary> /// <param name="kind">The type kind.</param> /// <param name="mode">The mode indicating the pointer specifiers added to the type.</param> public SimpleTypeRecord(SimpleTypeKind kind, SimpleTypeMode mode) : base((uint) kind | ((uint) mode << 8)) { } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.SimpleType; /// <summary> /// Gets the kind of the simple type. /// </summary> public SimpleTypeKind Kind => (SimpleTypeKind) (TypeIndex & 0b1111_1111); /// <summary> /// Gets the mode describing the pointer specifiers that are added to the simple type. /// </summary> public SimpleTypeMode Mode => (SimpleTypeMode) ((TypeIndex >> 8) & 0b1111); /// <summary> /// Gets a value indicating whether the type is a pointer or not. /// </summary> public bool IsPointer => Mode != SimpleTypeMode.Direct; /// <inheritdoc /> public override string ToString() => Mode == SimpleTypeMode.Direct ? Kind.ToString() : $"{Kind}*"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\StringIdentifierTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
StringIdentifierTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class StringIdentifierTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public StringIdentifierTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Value() { var id = _fixture.SimplePdb.GetIdLeafRecord<StringIdentifier>(0x1000); Assert.Equal(@"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll", id.Value); } [Fact] public void NoSubStrings() { var id = _fixture.SimplePdb.GetIdLeafRecord<StringIdentifier>(0x1000); Assert.Null(id.SubStrings); } [Fact] public void SubStrings() { var id = _fixture.SimplePdb.GetIdLeafRecord<StringIdentifier>(0x100c); var subStrings = id.SubStrings; Assert.NotNull(subStrings); Assert.Equal(new[] { @"-c -Zi -nologo -W3 -WX- -diagnostics:column -sdl -O2 -Oi -Oy- -GL -DWIN32 -DNDEBUG -DSIMPLEDLL_EXPORTS -D_WINDOWS -D_USRDLL -D_WINDLL -D_UNICODE -DUNICODE -Gm- -EHs -EHc -MD -GS -Gy -fp:precise -permissive- -Zc:wchar_t -Zc:forScope", @" -Zc:inline -Yupch.h -FpC:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\SimpleDll.pch -external:W3 -Gd -TP -analyze- -FC -errorreport:prompt -I""C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.29.3013", @"3\include"" -I""C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.29.30133\atlmfc\include"" -I""C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include"" -I""C:\Program Files (x86)\Windows", @" Kits\10\Include\10.0.19041.0\ucrt"" -I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um"" -I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared"" -I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\winrt""", @" -I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\cppwinrt"" -I""C:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\Include\um"" -external:I""C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.29.30133\include""", @" -external:I""C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.29.30133\atlmfc\include"" -external:I""C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include"" -external:I""C:\Program Files", @" (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt"" -external:I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um"" -external:I""C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared"" -external:I""C:\Program", }, subStrings.Entries.Select(x => x.Value.Value)); } }
126
2,904
using AsmResolver.IO; namespace AsmResolver.Symbols.Pdb.Leaves.Serialized; /// <summary> /// Provides a lazily initialized implementation of <see cref="StringIdentifier"/> that is read from a PDB image. /// </summary> public class SerializedStringIdentifier : StringIdentifier { private readonly PdbReaderContext _context; private readonly BinaryStreamReader _reader; private readonly uint _subStringsIndex; /// <summary> /// Reads a string ID from the provided input stream. /// </summary> /// <param name="context">The reading context in which the member is situated in.</param> /// <param name="typeIndex">The type index to assign to the member.</param> /// <param name="reader">The input stream to read from.</param> public SerializedStringIdentifier(PdbReaderContext context, uint typeIndex, BinaryStreamReader reader) : base(typeIndex) { _context = context; _subStringsIndex = reader.ReadUInt32(); _reader = reader; } /// <inheritdoc /> protected override Utf8String GetValue() => _reader.Fork().ReadUtf8String(); /// <inheritdoc /> protected override SubStringListLeaf? GetSubStrings() { if (_subStringsIndex == 0) return null; return _context.ParentImage.TryGetIdLeafRecord(_subStringsIndex, out SubStringListLeaf? list) ? list : _context.Parameters.ErrorListener.BadImageAndReturn<SubStringListLeaf>( $"String ID {TypeIndex:X8} contains an invalid substrings type index {_subStringsIndex:X8}."); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\UnionTypeRecordTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
UnionTypeRecordTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class UnionTypeRecordTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public UnionTypeRecordTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void ReadSize() { var type = (UnionTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1855); Assert.Equal(4ul, type.Size); } [Fact] public void ReadName() { var type = (UnionTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1855); Assert.Equal("_LDT_ENTRY::<unnamed-type-HighWord>", type.Name); } [Fact] public void ReadUniqueName() { var type = (UnionTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1855); Assert.Equal(".?AT<unnamed-type-HighWord>@_LDT_ENTRY@@", type.UniqueName); } [Fact] public void ReadFieldList() { var type = (UnionTypeRecord) _fixture.SimplePdb.GetLeafRecord(0x1855); var fields = type.Fields!; Assert.NotNull(fields); Assert.IsAssignableFrom<NestedTypeField>(fields.Entries[0]); Assert.IsAssignableFrom<InstanceDataField>(fields.Entries[1]); Assert.IsAssignableFrom<NestedTypeField>(fields.Entries[2]); Assert.IsAssignableFrom<InstanceDataField>(fields.Entries[3]); } }
106
1,428
using System; using AsmResolver.IO; namespace AsmResolver.Symbols.Pdb.Leaves.Serialized; /// <summary> /// Provides a lazily initialized implementation of <see cref="UnionTypeRecord"/> that is read from a PDB image. /// </summary> public class SerializedUnionTypeRecord : UnionTypeRecord { private readonly PdbReaderContext _context; private readonly ushort _memberCount; private readonly uint _fieldIndex; private readonly BinaryStreamReader _nameReader; private readonly BinaryStreamReader _uniqueNameReader; /// <summary> /// Reads a union type from the provided input stream. /// </summary> /// <param name="context">The reading context in which the type is situated in.</param> /// <param name="typeIndex">The index to assign to the type.</param> /// <param name="reader">The input stream to read from.</param> public SerializedUnionTypeRecord(PdbReaderContext context, uint typeIndex, BinaryStreamReader reader) : base(typeIndex) { _context = context; _memberCount = reader.ReadUInt16(); StructureAttributes = (StructureAttributes) reader.ReadUInt16(); _fieldIndex = reader.ReadUInt32(); Size = Convert.ToUInt64(ReadNumeric(ref reader)); _nameReader = reader.Fork(); reader.AdvanceUntil(0, true); _uniqueNameReader = reader.Fork(); } /// <inheritdoc /> protected override Utf8String GetName() => _nameReader.Fork().ReadUtf8String(); /// <inheritdoc /> protected override Utf8String GetUniqueName() => _uniqueNameReader.Fork().ReadUtf8String(); /// <inheritdoc /> protected override FieldListLeaf? GetFields() { if (_fieldIndex == 0) return null; return _context.ParentImage.TryGetLeafRecord(_fieldIndex, out SerializedFieldListLeaf? list) ? list : _context.Parameters.ErrorListener.BadImageAndReturn<FieldListLeaf>( $"Union type {TypeIndex:X8} contains an invalid field list index {_fieldIndex:X8}."); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Leaves\VTableShapeLeafTest.cs
AsmResolver.Symbols.Pdb.Tests.Leaves
VTableShapeLeafTest
['private readonly MockPdbFixture _fixture;']
['AsmResolver.Symbols.Pdb.Leaves', 'Xunit']
xUnit
net8.0
public class VTableShapeLeafTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public VTableShapeLeafTest(MockPdbFixture fixture) { _fixture = fixture; } [Theory] [InlineData(0x2416, new[] { VTableShapeEntry.Near })] [InlineData(0x239e, new[] { VTableShapeEntry.Near32,VTableShapeEntry.Near32 })] public void ReadEntries(uint typeIndex, VTableShapeEntry[] expectedEntries) { var shape = (VTableShapeLeaf) _fixture.SimplePdb.GetLeafRecord(typeIndex); Assert.Equal(expectedEntries, shape.Entries); } }
106
718
using System.Collections.Generic; using AsmResolver.IO; namespace AsmResolver.Symbols.Pdb.Leaves.Serialized; /// <summary> /// Provides a lazily initialized implementation of <see cref="VTableShapeLeaf"/> that is read from a PDB image. /// </summary> public class SerializedVTableShapeLeaf : VTableShapeLeaf { private readonly ushort _count; private readonly BinaryStreamReader _entriesReader; /// <summary> /// Reads a virtual function table shape from the provided input stream. /// </summary> /// <param name="context">The reading context in which the shape is situated in.</param> /// <param name="typeIndex">The index to assign to the shape.</param> /// <param name="reader">The input stream to read from.</param> public SerializedVTableShapeLeaf(PdbReaderContext context, uint typeIndex, BinaryStreamReader reader) : base(typeIndex) { _count = reader.ReadUInt16(); _entriesReader = reader; } /// <inheritdoc /> protected override IList<VTableShapeEntry> GetEntries() { var result = new List<VTableShapeEntry>(_count); var reader = _entriesReader.Fork(); // Entries are stored as 4-bit values. byte currentByte = 0; for (int i = 0; i < _count; i++) { if (i % 2 == 0) { currentByte = reader.ReadByte(); result.Add((VTableShapeEntry) (currentByte & 0xF)); } else { result.Add((VTableShapeEntry) ((currentByte >> 4) & 0xF)); } } return result; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Metadata\Dbi\DbiStreamTest.cs
AsmResolver.Symbols.Pdb.Tests.Metadata.Dbi
DbiStreamTest
[]
['System', 'System.IO', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.PE.File', 'AsmResolver.Symbols.Pdb.Metadata.Dbi', 'AsmResolver.Symbols.Pdb.Msf', 'Xunit']
xUnit
net8.0
public class DbiStreamTest { private DbiStream GetDbiStream(bool rebuild) { var file = MsfFile.FromBytes(Properties.Resources.SimpleDllPdb); var dbiStream = DbiStream.FromReader(file.Streams[DbiStream.StreamIndex].CreateReader()); if (rebuild) { using var stream = new MemoryStream(); dbiStream.Write(new BinaryStreamWriter(stream)); dbiStream = DbiStream.FromReader(new BinaryStreamReader(stream.ToArray())); } return dbiStream; } [Theory] [InlineData(false)] [InlineData(true)] public void Header(bool rebuild) { var dbiStream = GetDbiStream(rebuild); Assert.Equal(1u, dbiStream.Age); Assert.Equal(DbiAttributes.None, dbiStream.Attributes); Assert.Equal(MachineType.I386, dbiStream.Machine); Assert.Equal(14, dbiStream.BuildMajorVersion); Assert.Equal(29, dbiStream.BuildMinorVersion); Assert.True(dbiStream.IsNewVersionFormat); } [Theory] [InlineData(false)] [InlineData(true)] public void ModuleNames(bool rebuild) { var dbiStream = GetDbiStream(rebuild); Assert.Equal(new[] { "* CIL *", "C:\\Users\\Admin\\source\\repos\\AsmResolver\\test\\TestBinaries\\Native\\SimpleDll\\Release\\dllmain.obj", "C:\\Users\\Admin\\source\\repos\\AsmResolver\\test\\TestBinaries\\Native\\SimpleDll\\Release\\pch.obj", "* Linker Generated Manifest RES *", "Import:KERNEL32.dll", "KERNEL32.dll", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\sehprolg4.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\gs_cookie.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\gs_report.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\gs_support.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\guard_support.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\loadcfg.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\dyn_tls_init.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\ucrt_detection.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\cpu_disp.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\chandler4gs.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\secchk.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\argv_mode.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\default_local_stdio_options.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\tncleanup.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\dll_dllmain.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\initializers.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\utility.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\ucrt_stubs.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\utility_desktop.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\initsect.obj", "D:\\a\\_work\\1\\s\\Intermediate\\vctools\\msvcrt.nativeproj_110336922\\objr\\x86\\x86_exception_filter.obj", "VCRUNTIME140.dll", "Import:VCRUNTIME140.dll", "Import:api-ms-win-crt-runtime-l1-1-0.dll", "api-ms-win-crt-runtime-l1-1-0.dll", "* Linker *", }, dbiStream.Modules.Select(m => m.ModuleName?.Value)); } [Theory] [InlineData(false)] [InlineData(true)] public void SectionContributions(bool rebuild) { var dbiStream = GetDbiStream(rebuild); Assert.Equal(new (ushort, uint)[] { (1, 1669053862), (16, 2162654757), (20, 1635644926), (20, 3159649454), (20, 1649652954), (20, 3877379438), (20, 4262788820), (20, 199934614), (8, 4235719287), (8, 1374843914), (9, 4241735292), (9, 2170796787), (19, 1300950661), (19, 3968158929), (18, 3928463356), (18, 3928463356), (18, 2109213706), (22, 1457516325), (22, 3939645857), (22, 1393694582), (22, 546064581), (22, 1976627334), (22, 513172946), (22, 25744891), (22, 1989765812), (22, 2066266302), (22, 3810887196), (22, 206965504), (22, 647717352), (22, 3911072265), (22, 3290064241), (12, 3928463356), (24, 2717331243), (24, 3687876222), (25, 2318145338), (25, 2318145338), (6, 542071654), (15, 1810708069), (10, 3974941622), (14, 1150179208), (17, 2709606169), (13, 2361171624), (28, 0), (28, 0), (28, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (23, 3467414241), (23, 4079273803), (26, 1282639619), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (5, 0), (28, 0), (28, 0), (28, 0), (27, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (30, 0), (10, 2556510175), (21, 2556510175), (21, 2556510175), (21, 2556510175), (21, 2556510175), (21, 2556510175), (21, 2556510175), (21, 2556510175), (21, 2556510175), (20, 2556510175), (8, 4117779887), (31, 0), (11, 525614319), (31, 0), (31, 0), (31, 0), (31, 0), (31, 0), (25, 2556510175), (25, 2556510175), (25, 2556510175), (25, 2556510175), (20, 3906165615), (20, 1185345766), (20, 407658226), (22, 2869884627), (27, 0), (30, 0), (5, 0), (27, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (5, 0), (28, 0), (28, 0), (28, 0), (27, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (30, 0), (28, 0), (28, 0), (28, 0), (27, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (29, 0), (30, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (5, 0), (7, 4096381681), (22, 454268333), (14, 1927129959), (23, 1927129959), (20, 0), (8, 0), (19, 0), (18, 0), (18, 0), (22, 0), (24, 0), (10, 0), (14, 0), (2, 0), (31, 0), (3, 0), (3, 0) }, dbiStream.SectionContributions.Select(x => (x.ModuleIndex, x.DataCrc))); } [Theory] [InlineData(false)] [InlineData(true)] public void SectionMaps(bool rebuild) { var dbiStream = GetDbiStream(rebuild); Assert.Equal(new (ushort, ushort, ushort, ushort, ushort, ushort, uint, uint)[] { (0x010d, 0x0000, 0x0000, 0x0001, 0xffff, 0xffff, 0x00000000, 0x00000ce8), (0x0109, 0x0000, 0x0000, 0x0002, 0xffff, 0xffff, 0x00000000, 0x00000834), (0x010b, 0x0000, 0x0000, 0x0003, 0xffff, 0xffff, 0x00000000, 0x00000394), (0x0109, 0x0000, 0x0000, 0x0004, 0xffff, 0xffff, 0x00000000, 0x000000f8), (0x0109, 0x0000, 0x0000, 0x0005, 0xffff, 0xffff, 0x00000000, 0x0000013c), (0x0208, 0x0000, 0x0000, 0x0000, 0xffff, 0xffff, 0x00000000, 0xffffffff), }, dbiStream.SectionMaps.Select(m => ((ushort) m.Attributes, m.LogicalOverlayNumber, m.Group, m.Frame, m.SectionName, m.ClassName, m.Offset, m.SectionLength))); } [Theory] [InlineData(false)] [InlineData(true)] public void SourceFiles(bool rebuild) { var dbiStream = GetDbiStream(rebuild); string[][] firstThreeActualFileLists = dbiStream.SourceFiles .Take(3) .Select(x => x .Select(y => y.ToString()) .ToArray() ).ToArray(); Assert.Equal(new[] { Array.Empty<string>(), new[] { @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\pch.h", @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\dllmain.cpp", @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\SimpleDll.pch", }, new[] { @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winuser.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\basetsd.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winbase.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\stralign.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\guiddef.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\winerror.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\corecrt_wstring.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\processthreadsapi.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winnt.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\ctype.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\string.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\corecrt_memory.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\memoryapi.h", @"C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\corecrt_memcpy_s.h", @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\SimpleDll.pch", } }, firstThreeActualFileLists); } [Theory] [InlineData(false)] [InlineData(true)] public void ExtraDebugIndices(bool rebuild) { var dbiStream = GetDbiStream(rebuild); Assert.Equal(new ushort[] { 0x7, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xB, 0xFFFF, 0xFFFF, 0xFFFF, 0xD, 0xFFFF }, dbiStream.ExtraStreamIndices); } [Fact] public void SizeCalculation() { var file = MsfFile.FromBytes(Properties.Resources.SimpleDllPdb); var infoStream = DbiStream.FromReader(file.Streams[DbiStream.StreamIndex].CreateReader()); uint calculatedSize = infoStream.GetPhysicalSize(); using var stream = new MemoryStream(); infoStream.Write(new BinaryStreamWriter(stream)); Assert.Equal(stream.Length, calculatedSize); } }
258
11,754
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using AsmResolver.IO; using AsmResolver.PE.File; namespace AsmResolver.Symbols.Pdb.Metadata.Dbi; /// <summary> /// Represents the DBI Stream (also known as the Debug Information stream). /// </summary> public class DbiStream : SegmentBase { /// <summary> /// Gets the default fixed MSF stream index for the DBI stream. /// </summary> public const int StreamIndex = 3; private IList<ModuleDescriptor>? _modules; private IList<SectionContribution>? _sectionContributions; private IList<SectionMap>? _sectionMaps; private readonly LazyVariable<DbiStream, ISegment?> _typeServerMapStream; private readonly LazyVariable<DbiStream, ISegment?> _ecStream; private IList<SourceFileCollection>? _sourceFiles; private IList<ushort>? _extraStreamIndices; /// <summary> /// Creates a new empty DBI stream. /// </summary> public DbiStream() { _typeServerMapStream = new LazyVariable<DbiStream, ISegment?>(x => x.GetTypeServerMapStream()); _ecStream = new LazyVariable<DbiStream, ISegment?>(x => x.GetECStream()); IsNewVersionFormat = true; } /// <summary> /// Gets or sets the version signature assigned to the DBI stream. /// </summary> /// <remarks> /// This value should always be -1 for valid PDB files. /// </remarks> public int VersionSignature { get; set; } = -1; /// <summary> /// Gets or sets the version number of the DBI header. /// </summary> /// <remarks> /// Modern tooling only recognize the VC7.0 file format. /// </remarks> public DbiStreamVersion VersionHeader { get; set; } = DbiStreamVersion.V70; /// <summary> /// Gets or sets the number of times the DBI stream has been written. /// </summary> public uint Age { get; set; } = 1; /// <summary> /// Gets or sets the MSF stream index of the Global Symbol Stream. /// </summary> public ushort GlobalStreamIndex { get; set; } /// <summary> /// Gets or sets a bitfield containing the major and minor version of the toolchain that was used to build the program. /// </summary> public ushort BuildNumber { get; set; } /// <summary> /// Gets or sets a value indicating that the DBI stream is using the new file format (NewDBI). /// </summary> public bool IsNewVersionFormat { get => (BuildNumber & 0x8000) != 0; set => BuildNumber = (ushort) ((BuildNumber & ~0x8000) | (value ? 0x8000 : 0)); } /// <summary> /// Gets or sets the major version of the toolchain that was used to build the program. /// </summary> public byte BuildMajorVersion { get => (byte) ((BuildNumber >> 8) & 0x7F); set => BuildNumber = (ushort) ((BuildNumber & ~0x7F00) | (value << 8)); } /// <summary> /// Gets or sets the minor version of the toolchain that was used to build the program. /// </summary> public byte BuildMinorVersion { get => (byte) (BuildNumber & 0xFF); set => BuildNumber = (ushort) ((BuildNumber & ~0x00FF) | value); } /// <summary> /// Gets or sets the MSF stream index of the Public Symbol Stream. /// </summary> public ushort PublicStreamIndex { get; set; } /// <summary> /// Gets or sets the version number of mspdbXXXX.dll that was used to produce this PDB file. /// </summary> public ushort PdbDllVersion { get; set; } /// <summary> /// Gets or sets the MSF stream index of the Symbol Record Stream. /// </summary> public ushort SymbolRecordStreamIndex { get; set; } /// <summary> /// Unknown. /// </summary> public ushort PdbDllRbld { get; set; } /// <summary> /// Gets or sets the MSF stream index of the MFC type server. /// </summary> public uint MfcTypeServerIndex { get; set; } /// <summary> /// Gets or sets attributes associated to the DBI stream. /// </summary> public DbiAttributes Attributes { get; set; } /// <summary> /// Gets or sets the machine type the program was compiled for. /// </summary> public MachineType Machine { get; set; } /// <summary> /// Gets a collection of modules (object files) that were linked together into the program. /// </summary> public IList<ModuleDescriptor> Modules { get { if (_modules is null) Interlocked.CompareExchange(ref _modules, GetModules(), null); return _modules; } } /// <summary> /// Gets a collection of section contributions describing the layout of the sections of the final executable file. /// </summary> public IList<SectionContribution> SectionContributions { get { if (_sectionContributions is null) Interlocked.CompareExchange(ref _sectionContributions, GetSectionContributions(), null); return _sectionContributions; } } /// <summary> /// Gets a collection of section mappings stored in the section mapping sub stream. /// </summary> /// <remarks> /// The exact purpose of this is unknown, but it seems to be always containing a copy of the sections in the final /// executable file. /// </remarks> public IList<SectionMap> SectionMaps { get { if (_sectionMaps is null) Interlocked.CompareExchange(ref _sectionMaps, GetSectionMaps(), null); return _sectionMaps; } } /// <summary> /// Gets or sets the contents of the type server map sub stream. /// </summary> /// <remarks> /// The exact purpose and layout of this sub stream is unknown, hence this property exposes the stream as /// a raw segment. /// </remarks> public ISegment? TypeServerMapStream { get => _typeServerMapStream.GetValue(this); set => _typeServerMapStream.SetValue(value); } /// <summary> /// Gets or sets the contents of the Edit-and-Continue sub stream. /// </summary> /// <remarks> /// The exact purpose and layout of this sub stream is unknown, hence this property exposes the stream as /// a raw segment. /// </remarks> public ISegment? ECStream { get => _ecStream.GetValue(this); set => _ecStream.SetValue(value); } /// <summary> /// Gets a collection of source files assigned to each module in <see cref="Modules"/>. /// </summary> /// <remarks> /// Every collection of source files within this list corresponds to exactly the module within <see cref="Modules"/> /// at the same index. For example, the first source file list in this collection is the source file list of the /// first module. /// </remarks> public IList<SourceFileCollection> SourceFiles { get { if (_sourceFiles is null) Interlocked.CompareExchange(ref _sourceFiles, GetSourceFiles(), null); return _sourceFiles; } } /// <summary> /// Gets a collection of indices referring to additional debug streams in the MSF file. /// </summary> public IList<ushort> ExtraStreamIndices { get { if (_extraStreamIndices is null) Interlocked.CompareExchange(ref _extraStreamIndices, GetExtraStreamIndices(), null); return _extraStreamIndices; } } /// <summary> /// Reads a single DBI stream from the provided input stream. /// </summary> /// <param name="reader">The input stream.</param> /// <returns>The parsed DBI stream.</returns> public static DbiStream FromReader(BinaryStreamReader reader) => new SerializedDbiStream(reader); /// <summary> /// Obtains the list of module descriptors. /// </summary> /// <returns>The module descriptors</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Modules"/> property. /// </remarks> protected virtual IList<ModuleDescriptor> GetModules() => new List<ModuleDescriptor>(); /// <summary> /// Obtains the list of section contributions. /// </summary> /// <returns>The section contributions.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="SectionContributions"/> property. /// </remarks> protected virtual IList<SectionContribution> GetSectionContributions() => new List<SectionContribution>(); /// <summary> /// Obtains the list of section maps. /// </summary> /// <returns>The section maps.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="SectionMaps"/> property. /// </remarks> protected virtual IList<SectionMap> GetSectionMaps() => new List<SectionMap>(); /// <summary> /// Obtains the contents of the type server map sub stream. /// </summary> /// <returns>The contents of the sub stream.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="TypeServerMapStream"/> property. /// </remarks> protected virtual ISegment? GetTypeServerMapStream() => null; /// <summary> /// Obtains the contents of the EC sub stream. /// </summary> /// <returns>The contents of the sub stream.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="ECStream"/> property. /// </remarks> protected virtual ISegment? GetECStream() => null; /// <summary> /// Obtains a table that assigns a list of source files to every module referenced in the PDB file. /// </summary> /// <returns>The table.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="SourceFiles"/> property. /// </remarks> protected virtual IList<SourceFileCollection> GetSourceFiles() => new List<SourceFileCollection>(); /// <summary> /// Obtains the list of indices referring to additional debug streams in the MSF file. /// </summary> /// <returns>The list of indices.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="ExtraStreamIndices"/> property. /// </remarks> protected virtual IList<ushort> GetExtraStreamIndices() => new List<ushort>(); /// <inheritdoc /> public override uint GetPhysicalSize() { return GetHeaderSize() + GetModuleStreamSize() + GetSectionContributionStreamSize() + GetSectionMapStreamSize() + GetSourceInfoStreamSize() + GetTypeServerMapStreamSize() + GetECStreamSize() + GetOptionalDebugStreamSize() ; } private static uint GetHeaderSize() { return sizeof(int) // VersionSignature + sizeof(DbiStreamVersion) // VersionHeader + sizeof(uint) // Age + sizeof(ushort) // GlobalStreamIndex + sizeof(ushort) // BuildNumber + sizeof(ushort) // PublicStreamIndex + sizeof(ushort) // PdbDllVersion + sizeof(ushort) // SymbolRecordStreamIndex + sizeof(ushort) // PdbDllRbld + sizeof(uint) // ModuleInfoSize + sizeof(uint) // SectionContributionSize + sizeof(uint) // SectionMapSize + sizeof(uint) // SourceInfoSize + sizeof(uint) // TypeServerMapSize + sizeof(uint) // MfcTypeServerIndex + sizeof(uint) // OptionalDebugStreamSize + sizeof(uint) // ECStreamSize + sizeof(DbiAttributes) // Attributes + sizeof(MachineType) // MachineType + sizeof(uint) // Padding ; } private uint GetModuleStreamSize() { return ((uint) Modules.Sum(m => m.GetPhysicalSize())).Align(sizeof(uint)); } private uint GetSectionContributionStreamSize() { return sizeof(uint) // version + SectionContribution.EntrySize * (uint) SectionContributions.Count; } private uint GetSectionMapStreamSize() { return sizeof(ushort) // Count + sizeof(ushort) // LogCount + SectionMap.EntrySize * (uint) SectionMaps.Count; } private uint GetSourceInfoStreamSize() { uint totalFileCount = 0; uint nameBufferSize = 0; var stringOffsets = new Dictionary<Utf8String, uint>(); // Simulate the construction of name buffer for (int i = 0; i < SourceFiles.Count; i++) { var collection = SourceFiles[i]; totalFileCount += (uint) collection.Count; for (int j = 0; j < collection.Count; j++) { // If name is not added yet, "append" to the name buffer. var name = collection[j]; if (!stringOffsets.ContainsKey(name)) { stringOffsets[name] = nameBufferSize; nameBufferSize += (uint) name.ByteCount + 1u; } } } return (sizeof(ushort) // ModuleCount + sizeof(ushort) // SourceFileCount + sizeof(ushort) * (uint) SourceFiles.Count // ModuleIndices + sizeof(ushort) * (uint) SourceFiles.Count // SourceFileCounts + sizeof(uint) * totalFileCount // NameOffsets + nameBufferSize // NameBuffer ).Align(4); } private uint GetTypeServerMapStreamSize() { return TypeServerMapStream?.GetPhysicalSize().Align(sizeof(uint)) ?? 0u; } private uint GetOptionalDebugStreamSize() { return (uint) (ExtraStreamIndices.Count * sizeof(ushort)); } private uint GetECStreamSize() { return ECStream?.GetPhysicalSize() ?? 0u; } /// <inheritdoc /> public override void Write(BinaryStreamWriter writer) { WriteHeader(writer); WriteModuleStream(writer); WriteSectionContributionStream(writer); WriteSectionMapStream(writer); WriteSourceInfoStream(writer); WriteTypeServerMapStream(writer); WriteECStream(writer); WriteOptionalDebugStream(writer); } private void WriteHeader(BinaryStreamWriter writer) { writer.WriteInt32(VersionSignature); writer.WriteUInt32((uint) VersionHeader); writer.WriteUInt32(Age); writer.WriteUInt16(GlobalStreamIndex); writer.WriteUInt16(BuildNumber); writer.WriteUInt16(PublicStreamIndex); writer.WriteUInt16(PdbDllVersion); writer.WriteUInt16(SymbolRecordStreamIndex); writer.WriteUInt16(PdbDllRbld); writer.WriteUInt32(GetModuleStreamSize()); writer.WriteUInt32(GetSectionContributionStreamSize()); writer.WriteUInt32(GetSectionMapStreamSize()); writer.WriteUInt32(GetSourceInfoStreamSize()); writer.WriteUInt32(GetTypeServerMapStreamSize()); writer.WriteUInt32(MfcTypeServerIndex); writer.WriteUInt32(GetOptionalDebugStreamSize()); writer.WriteUInt32(GetECStreamSize()); writer.WriteUInt16((ushort) Attributes); writer.WriteUInt16((ushort) Machine); writer.WriteUInt32(0); } private void WriteModuleStream(BinaryStreamWriter writer) { var modules = Modules; for (int i = 0; i < modules.Count; i++) modules[i].Write(writer); writer.Align(sizeof(uint)); } private void WriteSectionContributionStream(BinaryStreamWriter writer) { // TODO: make customizable writer.WriteUInt32((uint) SectionContributionStreamVersion.Ver60); var contributions = SectionContributions; for (int i = 0; i < contributions.Count; i++) contributions[i].Write(writer); writer.Align(sizeof(uint)); } private void WriteSectionMapStream(BinaryStreamWriter writer) { var maps = SectionMaps; // Count and LogCount. writer.WriteUInt16((ushort) maps.Count); writer.WriteUInt16((ushort) maps.Count); // Entries. for (int i = 0; i < maps.Count; i++) maps[i].Write(writer); writer.Align(sizeof(uint)); } private void WriteSourceInfoStream(BinaryStreamWriter writer) { var sourceFiles = SourceFiles; int totalFileCount = sourceFiles.Sum(x => x.Count); // Module and total file count (truncated to 16 bits) writer.WriteUInt16((ushort) (sourceFiles.Count & 0xFFFF)); writer.WriteUInt16((ushort) (totalFileCount & 0xFFFF)); // Module indices. Unsure if this is correct, but this array does not seem to be really used by the ref impl. for (ushort i = 0; i < sourceFiles.Count; i++) writer.WriteUInt16(i); // Source file counts. for (int i = 0; i < sourceFiles.Count; i++) writer.WriteUInt16((ushort) sourceFiles[i].Count); // Build up string buffer and name offset table. using var stringBuffer = new MemoryStream(); var stringWriter = new BinaryStreamWriter(stringBuffer); var stringOffsets = new Dictionary<Utf8String, uint>(); for (int i = 0; i < sourceFiles.Count; i++) { var collection = sourceFiles[i]; for (int j = 0; j < collection.Count; j++) { // If not present already, append to string buffer. var name = collection[j]; if (!stringOffsets.TryGetValue(name, out uint offset)) { offset = (uint) stringWriter.Offset; stringOffsets[name] = offset; stringWriter.WriteBytes(name.GetBytesUnsafe()); stringWriter.WriteByte(0); } // Write name offset writer.WriteUInt32(offset); } } // Write string buffer. writer.WriteBytes(stringBuffer.ToArray()); writer.Align(sizeof(uint)); } private void WriteTypeServerMapStream(BinaryStreamWriter writer) { TypeServerMapStream?.Write(writer); writer.Align(sizeof(uint)); } private void WriteOptionalDebugStream(BinaryStreamWriter writer) { var extraIndices = ExtraStreamIndices; for (int i = 0; i < extraIndices.Count; i++) writer.WriteUInt16(extraIndices[i]); } private void WriteECStream(BinaryStreamWriter writer) => ECStream?.Write(writer); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Metadata\Info\InfoStreamTest.cs
AsmResolver.Symbols.Pdb.Tests.Metadata.Info
InfoStreamTest
[]
['System', 'System.Collections.Generic', 'System.IO', 'AsmResolver.IO', 'AsmResolver.Symbols.Pdb.Metadata.Info', 'AsmResolver.Symbols.Pdb.Msf', 'Xunit']
xUnit
net8.0
public class InfoStreamTest { private static InfoStream GetInfoStream(bool rebuild) { var file = MsfFile.FromBytes(Properties.Resources.SimpleDllPdb); var infoStream = InfoStream.FromReader(file.Streams[InfoStream.StreamIndex].CreateReader()); if (rebuild) { using var stream = new MemoryStream(); infoStream.Write(new BinaryStreamWriter(stream)); infoStream = InfoStream.FromReader(new BinaryStreamReader(stream.ToArray())); } return infoStream; } [Theory] [InlineData(false)] [InlineData(true)] public void Header(bool rebuild) { var infoStream = GetInfoStream(rebuild); Assert.Equal(InfoStreamVersion.VC70, infoStream.Version); Assert.Equal(1u, infoStream.Age); Assert.Equal(Guid.Parse("205dc366-d8f8-4175-8e06-26dd76722df5"), infoStream.UniqueId); } [Theory] [InlineData(false)] [InlineData(true)] public void NameTable(bool rebuild) { var infoStream = GetInfoStream(rebuild); Assert.Equal(new Dictionary<Utf8String, int> { ["/UDTSRCLINEUNDONE"] = 48, ["/src/headerblock"] = 46, ["/LinkInfo"] = 5, ["/TMCache"] = 6, ["/names"] = 12 }, infoStream.StreamIndices); } [Theory] [InlineData(false)] [InlineData(true)] public void FeatureCodes(bool rebuild) { var infoStream = GetInfoStream(rebuild); Assert.Equal(new[] {PdbFeature.VC140}, infoStream.Features); } [Fact] public void SizeCalculation() { var file = MsfFile.FromBytes(Properties.Resources.SimpleDllPdb); var infoStream = InfoStream.FromReader(file.Streams[InfoStream.StreamIndex].CreateReader()); uint calculatedSize = infoStream.GetPhysicalSize(); using var stream = new MemoryStream(); infoStream.Write(new BinaryStreamWriter(stream)); Assert.Equal(stream.Length, calculatedSize); } }
247
2,347
using System; using System.Collections.Generic; using System.IO; using System.Threading; using AsmResolver.IO; namespace AsmResolver.Symbols.Pdb.Metadata.Info; /// <summary> /// Represents the PDB Info Stream (also known as the PDB stream) /// </summary> public class InfoStream : SegmentBase { /// <summary> /// Gets the default fixed MSF stream index for the PDB Info stream. /// </summary> public const int StreamIndex = 1; private const int HeaderSize = sizeof(InfoStreamVersion) // Version + sizeof(uint) // Signature + sizeof(uint) // Aage + 16 //UniqueId + sizeof(uint) // NameBufferSize ; private IDictionary<Utf8String, int>? _streamIndices; private IList<PdbFeature>? _features; /// <summary> /// Gets or sets the version of the file format of the PDB info stream. /// </summary> /// <remarks> /// Modern tooling only recognize the VC7.0 file format. /// </remarks> public InfoStreamVersion Version { get; set; } = InfoStreamVersion.VC70; /// <summary> /// Gets or sets the 32-bit UNIX time-stamp of the PDB file. /// </summary> public uint Signature { get; set; } /// <summary> /// Gets or sets the number of times the PDB file has been written. /// </summary> public uint Age { get; set; } = 1; /// <summary> /// Gets or sets the unique identifier assigned to the PDB file. /// </summary> public Guid UniqueId { get; set; } /// <summary> /// Gets a mapping from stream names to their respective stream index within the underlying MSF file. /// </summary> public IDictionary<Utf8String, int> StreamIndices { get { if (_streamIndices is null) Interlocked.CompareExchange(ref _streamIndices, GetStreamIndices(), null); return _streamIndices; } } /// <summary> /// Gets a list of characteristics that this PDB has. /// </summary> public IList<PdbFeature> Features { get { if (_features is null) Interlocked.CompareExchange(ref _features, GetFeatures(), null); return _features; } } /// <summary> /// Reads a single PDB info stream from the provided input stream. /// </summary> /// <param name="reader">The input stream.</param> /// <returns>The parsed info stream.</returns> public static InfoStream FromReader(BinaryStreamReader reader) => new SerializedInfoStream(reader); /// <summary> /// Obtains the stream name to index mapping of the PDB file. /// </summary> /// <returns>The mapping.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="StreamIndices"/> property. /// </remarks> protected virtual IDictionary<Utf8String, int> GetStreamIndices() => new Dictionary<Utf8String, int>(); /// <summary> /// Obtains the features of the PDB file. /// </summary> /// <returns>The features.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Features"/> property. /// </remarks> protected virtual IList<PdbFeature> GetFeatures() => new List<PdbFeature> { PdbFeature.VC140 }; /// <inheritdoc /> public override uint GetPhysicalSize() { uint totalSize = HeaderSize; // Name buffer foreach (var entry in StreamIndices) totalSize += (uint) entry.Key.ByteCount + 1u; // Stream indices hash table. totalSize += StreamIndices.GetPdbHashTableSize(ComputeStringHash); // Last NI totalSize += sizeof(uint); // Feature codes. totalSize += (uint) Features.Count * sizeof(PdbFeature); return totalSize; } /// <inheritdoc /> public override void Write(BinaryStreamWriter writer) { // Write basic info stream header. writer.WriteUInt32((uint) Version); writer.WriteUInt32(Signature); writer.WriteUInt32(Age); writer.WriteBytes(UniqueId.ToByteArray()); // Construct name buffer, keeping track of the offsets of every name. using var nameBuffer = new MemoryStream(); var nameWriter = new BinaryStreamWriter(nameBuffer); var stringOffsets = new Dictionary<Utf8String, uint>(); foreach (var entry in StreamIndices) { uint offset = (uint) nameWriter.Offset; nameWriter.WriteBytes(entry.Key.GetBytesUnsafe()); nameWriter.WriteByte(0); stringOffsets.Add(entry.Key, offset); } writer.WriteUInt32((uint) nameBuffer.Length); writer.WriteBytes(nameBuffer.ToArray()); // Write the hash table. StreamIndices.WriteAsPdbHashTable(writer, ComputeStringHash, (key, value) => (stringOffsets[key], (uint) value)); // last NI, safe to put always zero. writer.WriteUInt32(0); // Write feature codes. var features = Features; for (int i = 0; i < features.Count; i++) writer.WriteUInt32((uint) features[i]); } private static uint ComputeStringHash(Utf8String str) { // Note: The hash of a single entry is **deliberately** truncated to a 16 bit number. This is because // the reference implementation of the name table returns a number of type HASH, which is a typedef // for "unsigned short". If we don't do this, this will result in wrong buckets being filled in the // hash table, and thus the serialization would fail. See NMTNI::hash() in Microsoft/microsoft-pdb. return (ushort) PdbHash.ComputeV1(str); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Metadata\PdbHashTest.cs
AsmResolver.Symbols.Pdb.Tests.Metadata
PdbHashTest
[]
['AsmResolver.Symbols.Pdb.Metadata', 'Xunit']
xUnit
net8.0
public class PdbHashTest { [Theory] [InlineData("/UDTSRCLINEUNDONE", 0x23296bb2)] [InlineData("/src/headerblock", 0x2b237ecd)] [InlineData("/LinkInfo", 0x282209ed)] [InlineData("/TMCache", 0x2621d5e9)] [InlineData("/names", 0x6d6cfc21)] public void HashV1(string value, uint expected) { Assert.Equal(expected, PdbHash.ComputeV1(value)); } }
110
506
namespace AsmResolver.Symbols.Pdb.Metadata; /// <summary> /// Provides methods for computing hash codes for a PDB hash table. /// </summary> public static class PdbHash { /// <summary> /// Computes the V1 hash code for a UTF-8 string. /// </summary> /// <param name="value">The string to compute the hash for.</param> /// <returns>The hash code.</returns> /// <remarks> /// See PDB/include/misc.h for reference implementation. /// </remarks> public static unsafe uint ComputeV1(Utf8String value) { uint result = 0; uint count = (uint) value.ByteCount; fixed (byte* ptr = value.GetBytesUnsafe()) { byte* p = ptr; while (count >= 4) { result ^= *(uint*) p; count -= 4; p += 4; } if (count >= 2) { result ^= *(ushort*) p; count -= 2; p += 2; } if (count == 1) result ^= *p; } result |= 0x20202020; result ^= result >> 11; return result ^ (result >> 16); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Msf\MsfFileTest.cs
AsmResolver.Symbols.Pdb.Tests.Msf
MsfFileTest
[]
['System.IO', 'System.Linq', 'AsmResolver.Symbols.Pdb.Msf', 'Xunit']
xUnit
net8.0
public class MsfFileTest { [Fact] public void RoundTrip() { var file = MsfFile.FromBytes(Properties.Resources.SimpleDllPdb); using var stream = new MemoryStream(); file.Write(stream); var newFile = MsfFile.FromBytes(stream.ToArray()); Assert.Equal(file.BlockSize, newFile.BlockSize); Assert.Equal(file.Streams.Count, newFile.Streams.Count); Assert.All(Enumerable.Range(0, file.Streams.Count), i => { Assert.Equal(file.Streams[i].CreateReader().ReadToEnd(), newFile.Streams[i].CreateReader().ReadToEnd());; }); } }
138
773
using System; using System.Collections.Generic; using System.IO; using System.Threading; using AsmResolver.Collections; using AsmResolver.IO; using AsmResolver.Symbols.Pdb.Msf.Builder; namespace AsmResolver.Symbols.Pdb.Msf; /// <summary> /// Models a file that is in the Microsoft Multi-Stream Format (MSF). /// </summary> public class MsfFile { private uint _blockSize; private IList<MsfStream>? _streams; /// <summary> /// Gets or sets the size of each block in the MSF file. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// Occurs when the provided value is neither 512, 1024, 2048 or 4096. /// </exception> public uint BlockSize { get => _blockSize; set { if (value is not (512 or 1024 or 2048 or 4096)) { throw new ArgumentOutOfRangeException( nameof(value), "Block size must be either 512, 1024, 2048 or 4096 bytes."); } _blockSize = value; } } /// <summary> /// Gets a collection of streams that are present in the MSF file. /// </summary> public IList<MsfStream> Streams { get { if (_streams is null) Interlocked.CompareExchange(ref _streams, GetStreams(), null); return _streams; } } /// <summary> /// Creates a new empty MSF file with a default block size of 4096. /// </summary> public MsfFile() : this(4096) { } /// <summary> /// Creates a new empty MSF file with the provided block size. /// </summary> /// <param name="blockSize">The block size to use. This must be a value of 512, 1024, 2048 or 4096.</param> /// <exception cref="ArgumentOutOfRangeException">Occurs when an invalid block size was provided.</exception> public MsfFile(uint blockSize) { BlockSize = blockSize; } /// <summary> /// Reads an MSF file from a file on the disk. /// </summary> /// <param name="path">The path to the file to read.</param> /// <returns>The read MSF file.</returns> public static MsfFile FromFile(string path) => FromFile(UncachedFileService.Instance.OpenFile(path)); /// <summary> /// Reads an MSF file from an input file. /// </summary> /// <param name="file">The file to read.</param> /// <returns>The read MSF file.</returns> public static MsfFile FromFile(IInputFile file) => FromReader(file.CreateReader()); /// <summary> /// Interprets a byte array as an MSF file. /// </summary> /// <param name="data">The data to interpret.</param> /// <returns>The read MSF file.</returns> public static MsfFile FromBytes(byte[] data) => FromReader(new BinaryStreamReader(data)); /// <summary> /// Reads an MSF file from the provided input stream reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns>The read MSF file.</returns> public static MsfFile FromReader(BinaryStreamReader reader) => new SerializedMsfFile(reader); /// <summary> /// Obtains the list of streams stored in the MSF file. /// </summary> /// <returns>The streams.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Streams"/> property. /// </remarks> protected virtual IList<MsfStream> GetStreams() => new OwnedCollection<MsfFile, MsfStream>(this); /// <summary> /// Reconstructs and writes the MSF file to the disk. /// </summary> /// <param name="path">The path of the file to write to.</param> public void Write(string path) { using var fs = File.Create(path); Write(fs); } /// <summary> /// Reconstructs and writes the MSF file to an output stream. /// </summary> /// <param name="stream">The output stream.</param> public void Write(Stream stream) => Write(new BinaryStreamWriter(stream)); /// <summary> /// Reconstructs and writes the MSF file to an output stream. /// </summary> /// <param name="writer">The output stream.</param> public void Write(BinaryStreamWriter writer) => Write(writer, SequentialMsfFileBuilder.Instance); /// <summary> /// Reconstructs and writes the MSF file to an output stream. /// </summary> /// <param name="writer">The output stream.</param> /// <param name="builder">The builder to use for reconstructing the MSF file.</param> public void Write(BinaryStreamWriter writer, IMsfFileBuilder builder) => builder.CreateFile(this).Write(writer); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Msf\MsfStreamDataSourceTest.cs
AsmResolver.Symbols.Pdb.Tests.Msf
MsfStreamDataSourceTest
[]
['System', 'System.Linq', 'AsmResolver.IO', 'AsmResolver.Symbols.Pdb.Msf', 'Xunit']
xUnit
net8.0
public class MsfStreamDataSourceTest { [Fact] public void EmptyStream() { var source = new MsfStreamDataSource(0, 0x200, Array.Empty<IDataSource>()); byte[] buffer = new byte[0x1000]; int readCount = source.ReadBytes(0, buffer, 0, buffer.Length); Assert.Equal(0, readCount); Assert.All(buffer, b => Assert.Equal(0, b)); } [Theory] [InlineData(0x200, 0x200)] [InlineData(0x200, 0x100)] public void StreamWithOneBlock(int blockSize, int actualSize) { byte[] block = new byte[blockSize]; for (int i = 0; i < blockSize; i++) block[i] = (byte) (i & 0xFF); var source = new MsfStreamDataSource((ulong) actualSize, (uint) blockSize, new[] {block}); byte[] buffer = new byte[0x1000]; int readCount = source.ReadBytes(0, buffer, 0, buffer.Length); Assert.Equal(actualSize, readCount); Assert.Equal(block.Take(actualSize), buffer.Take(actualSize)); } [Theory] [InlineData(0x200, 0x400)] [InlineData(0x200, 0x300)] public void StreamWithTwoBlocks(int blockSize, int actualSize) { byte[] block1 = new byte[blockSize]; for (int i = 0; i < blockSize; i++) block1[i] = (byte) 'A'; byte[] block2 = new byte[blockSize]; for (int i = 0; i < blockSize; i++) block2[i] = (byte) 'B'; var source = new MsfStreamDataSource((ulong) actualSize, (uint) blockSize, new[] {block1, block2}); byte[] buffer = new byte[0x1000]; int readCount = source.ReadBytes(0, buffer, 0, buffer.Length); Assert.Equal(actualSize, readCount); Assert.Equal(block1.Concat(block2).Take(actualSize), buffer.Take(actualSize)); } [Theory] [InlineData(0x200, 0x400)] public void ReadInMiddleOfBlock(int blockSize, int actualSize) { byte[] block1 = new byte[blockSize]; for (int i = 0; i < blockSize; i++) block1[i] = (byte) ((i*2) & 0xFF); byte[] block2 = new byte[blockSize]; for (int i = 0; i < blockSize; i++) block2[i] = (byte) ((i * 2 + 1) & 0xFF); var source = new MsfStreamDataSource((ulong) actualSize, (uint) blockSize, new[] {block1, block2}); byte[] buffer = new byte[blockSize]; int readCount = source.ReadBytes((ulong) blockSize / 4, buffer, 0, blockSize); Assert.Equal(blockSize, readCount); Assert.Equal(block1.Skip(blockSize / 4).Concat(block2).Take(blockSize), buffer); } }
158
2,761
using System; using System.Collections.Generic; using System.Linq; using AsmResolver.IO; namespace AsmResolver.Symbols.Pdb.Msf; /// <summary> /// Implements a data source for a single MSF stream that pulls data from multiple (fragmented) blocks. /// </summary> public class MsfStreamDataSource : IDataSource { private readonly IDataSource[] _blocks; private readonly long _blockSize; /// <summary> /// Creates a new MSF stream data source. /// </summary> /// <param name="length">The length of the stream.</param> /// <param name="blockSize">The size of an individual block.</param> /// <param name="blocks">The blocks</param> /// <exception cref="ArgumentException"> /// Occurs when the total size of the provided blocks is smaller than /// <paramref name="length"/> * <paramref name="blockSize"/>. /// </exception> public MsfStreamDataSource(ulong length, uint blockSize, IEnumerable<byte[]> blocks) : this(length, blockSize, blocks.Select(x => (IDataSource) new ByteArrayDataSource(x))) { } /// <summary> /// Creates a new MSF stream data source. /// </summary> /// <param name="length">The length of the stream.</param> /// <param name="blockSize">The size of an individual block.</param> /// <param name="blocks">The blocks</param> /// <exception cref="ArgumentException"> /// Occurs when the total size of the provided blocks is smaller than /// <paramref name="length"/> * <paramref name="blockSize"/>. /// </exception> public MsfStreamDataSource(ulong length, uint blockSize, IEnumerable<IDataSource> blocks) { Length = length; _blocks = blocks.ToArray(); _blockSize = blockSize; if (length > (ulong) (_blocks.Length * blockSize)) throw new ArgumentException("Provided length is larger than the provided blocks combined."); } /// <inheritdoc /> public ulong BaseAddress => 0; /// <inheritdoc /> public ulong Length { get; } /// <inheritdoc /> public byte this[ulong address] { get { if (!IsValidAddress(address)) throw new IndexOutOfRangeException(); var block = GetBlockAndOffset(address, out ulong offset); return block[block.BaseAddress + offset]; } } /// <inheritdoc /> public bool IsValidAddress(ulong address) => address < Length; /// <inheritdoc /> public int ReadBytes(ulong address, byte[] buffer, int index, int count) { int totalReadCount = 0; int remainingBytes = Math.Min(count, (int) (Length - (address - BaseAddress))); while (remainingBytes > 0) { // Obtain current block and offset within block. var block = GetBlockAndOffset(address, out ulong offset); // Read available bytes. int readCount = Math.Min(remainingBytes, (int) _blockSize); int actualReadCount = block.ReadBytes(block.BaseAddress + offset, buffer, index, readCount); // Move to the next block. totalReadCount += actualReadCount; address += (ulong) actualReadCount; index += actualReadCount; remainingBytes -= actualReadCount; } return totalReadCount; } private IDataSource GetBlockAndOffset(ulong address, out ulong offset) { var block = _blocks[Math.DivRem((long) address, _blockSize, out long x)]; offset = (ulong) x; return block; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\PdbImageTest.cs
AsmResolver.Symbols.Pdb.Tests
PdbImageTest
['private readonly MockPdbFixture _fixture;']
['System', 'System.Linq', 'AsmResolver.PE.File', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Metadata.Dbi', 'Xunit']
xUnit
net8.0
public class PdbImageTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public PdbImageTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void BasicMetadata() { var image = _fixture.SimplePdb; Assert.Equal(1u, image.Age); Assert.Equal(Guid.Parse("205dc366-d8f8-4175-8e06-26dd76722df5"), image.UniqueId); Assert.Equal(DbiAttributes.None, image.Attributes); Assert.Equal(MachineType.I386, image.Machine); Assert.Equal(14, image.BuildMajorVersion); Assert.Equal(29, image.BuildMinorVersion); } [Theory] [InlineData(0x00_75, SimpleTypeKind.UInt32, SimpleTypeMode.Direct)] [InlineData(0x04_03, SimpleTypeKind.Void, SimpleTypeMode.NearPointer32)] public void SimpleTypeLookup(uint typeIndex, SimpleTypeKind kind, SimpleTypeMode mode) { var type = Assert.IsAssignableFrom<SimpleTypeRecord>(_fixture.SimplePdb.GetLeafRecord(typeIndex)); Assert.Equal(kind, type.Kind); Assert.Equal(mode, type.Mode); } [Fact] public void SimpleTypeLookupTwiceShouldCache() { var image = _fixture.SimplePdb; var type = image.GetLeafRecord(0x00_75); var type2 = image.GetLeafRecord(0x00_75); Assert.Same(type, type2); } [Fact] public void ReadModules() { Assert.Equal(new[] { @"* CIL *", @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\dllmain.obj", @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\pch.obj", @"* Linker Generated Manifest RES *", @"Import:KERNEL32.dll", @"KERNEL32.dll", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\sehprolg4.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\gs_cookie.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\gs_report.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\gs_support.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\guard_support.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\loadcfg.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\dyn_tls_init.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\ucrt_detection.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\cpu_disp.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\chandler4gs.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\secchk.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\argv_mode.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\default_local_stdio_options.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\tncleanup.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\dll_dllmain.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\initializers.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\utility.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\ucrt_stubs.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\utility_desktop.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\initsect.obj", @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\x86_exception_filter.obj", @"VCRUNTIME140.dll", @"Import:VCRUNTIME140.dll", @"Import:api-ms-win-crt-runtime-l1-1-0.dll", @"api-ms-win-crt-runtime-l1-1-0.dll", "* Linker *" }, _fixture.SimplePdb.Modules.Select(m => m.Name!.Value)); } }
207
4,557
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using AsmResolver.IO; using AsmResolver.PE.File; using AsmResolver.Symbols.Pdb.Leaves; using AsmResolver.Symbols.Pdb.Metadata.Dbi; using AsmResolver.Symbols.Pdb.Metadata.Info; using AsmResolver.Symbols.Pdb.Msf; using AsmResolver.Symbols.Pdb.Records; namespace AsmResolver.Symbols.Pdb; /// <summary> /// Represents a single Program Debug Database (PDB) image. /// </summary> public class PdbImage : ICodeViewSymbolProvider { private readonly ConcurrentDictionary<uint, SimpleTypeRecord> _simpleTypes = new(); private IList<ICodeViewSymbol>? _symbols; private IList<PdbModule>? _modules; /// <summary> /// Gets or sets the time-stamp of the PDB file. /// </summary> public DateTime Timestamp { get; set; } /// <summary> /// Gets or sets the number of times the PDB file has been written. /// </summary> public uint Age { get; set; } = 1; /// <summary> /// Gets or sets the unique identifier assigned to the PDB file. /// </summary> public Guid UniqueId { get; set; } /// <summary> /// Gets or sets the major version of the toolchain that was used to build the program. /// </summary> public byte BuildMajorVersion { get; set; } /// <summary> /// Gets or sets the minor version of the toolchain that was used to build the program. /// </summary> public byte BuildMinorVersion { get; set; } /// <summary> /// Gets or sets the version number of mspdbXXXX.dll that was used to produce this PDB file. /// </summary> public ushort PdbDllVersion { get; set; } /// <summary> /// Gets or sets attributes associated to the DBI stream. /// </summary> public DbiAttributes Attributes { get; set; } /// <summary> /// Gets or sets the machine type the program was compiled for. /// </summary> public MachineType Machine { get; set; } /// <inheritdoc /> public IList<ICodeViewSymbol> Symbols { get { if (_symbols is null) Interlocked.CompareExchange(ref _symbols, GetSymbols(), null); return _symbols; } } /// <summary> /// Gets a collection of all modules stored in the PDB image. /// </summary> public IList<PdbModule> Modules { get { if (_modules is null) Interlocked.CompareExchange(ref _modules, GetModules(), null); return _modules; } } /// <summary> /// Reads a PDB image from the provided input file. /// </summary> /// <param name="path">The path to the PDB file.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromFile(string path) => FromFile(MsfFile.FromFile(path)); /// <summary> /// Reads a PDB image from the provided input file. /// </summary> /// <param name="path">The path to the PDB file.</param> /// <param name="readerParameters">The parameters to use while reading the PDB image.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromFile(string path, PdbReaderParameters readerParameters) => FromFile(MsfFile.FromFile(path), readerParameters); /// <summary> /// Reads a PDB image from the provided input file. /// </summary> /// <param name="file">The input file.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromFile(IInputFile file) => FromFile(MsfFile.FromFile(file)); /// <summary> /// Reads a PDB image from the provided input file. /// </summary> /// <param name="file">The input file.</param> /// <param name="readerParameters">The parameters to use while reading the PDB image.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromFile(IInputFile file, PdbReaderParameters readerParameters) => FromFile(MsfFile.FromFile(file), readerParameters); /// <summary> /// Interprets a byte array as a PDB image. /// </summary> /// <param name="data">The data to interpret.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromBytes(byte[] data) => FromFile(MsfFile.FromBytes(data)); /// <summary> /// Interprets a byte array as a PDB image. /// </summary> /// <param name="data">The data to interpret.</param> /// <param name="readerParameters">The parameters to use while reading the PDB image.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromBytes(byte[] data, PdbReaderParameters readerParameters) => FromFile(MsfFile.FromBytes(data), readerParameters); /// <summary> /// Reads an PDB image from the provided input stream reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromReader(BinaryStreamReader reader) => FromFile(MsfFile.FromReader(reader)); /// <summary> /// Reads an PDB image from the provided input stream reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="readerParameters">The parameters to use while reading the PDB image.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromReader(BinaryStreamReader reader, PdbReaderParameters readerParameters) => FromFile(MsfFile.FromReader(reader), readerParameters); /// <summary> /// Loads a PDB image from the provided MSF file. /// </summary> /// <param name="file">The MSF file.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromFile(MsfFile file) => FromFile(file, new PdbReaderParameters(ThrowErrorListener.Instance)); /// <summary> /// Loads a PDB image from the provided MSF file. /// </summary> /// <param name="file">The MSF file.</param> /// <param name="readerParameters">The parameters to use while reading the PDB image.</param> /// <returns>The read PDB image.</returns> public static PdbImage FromFile(MsfFile file, PdbReaderParameters readerParameters) => new SerializedPdbImage(file, readerParameters); /// <summary> /// Obtains all records stored in the original TPI stream of the PDB image. /// </summary> /// <returns>An object that lazily enumerates all TPI leaf records.</returns> public virtual IEnumerable<ITpiLeaf> GetLeafRecords() => Enumerable.Empty<ITpiLeaf>(); /// <summary> /// Obtains all records stored in the original IPI stream of the PDB image. /// </summary> /// <returns>An object that lazily enumerates all IPI leaf records.</returns> public virtual IEnumerable<IIpiLeaf> GetIdLeafRecords() => Enumerable.Empty<IIpiLeaf>(); /// <summary> /// Attempts to obtain a type record from the TPI stream based on its type index. /// </summary> /// <param name="typeIndex">The type index.</param> /// <param name="leaf">The resolved type.</param> /// <returns><c>true</c> if the type was found, <c>false</c> otherwise.</returns> public virtual bool TryGetLeafRecord(uint typeIndex, [NotNullWhen(true)] out ITpiLeaf? leaf) { typeIndex &= 0x7fffffff; if (typeIndex is > 0 and < 0x1000) { leaf = _simpleTypes.GetOrAdd(typeIndex, i => new SimpleTypeRecord(i)); return true; } leaf = null; return false; } /// <summary> /// Attempts to obtain a type record from the TPI stream based on its type index. /// </summary> /// <param name="typeIndex">The type index.</param> /// <param name="leaf">The resolved type.</param> /// <returns><c>true</c> if the type was found, <c>false</c> otherwise.</returns> public bool TryGetLeafRecord<TLeaf>(uint typeIndex, [NotNullWhen(true)] out TLeaf? leaf) where TLeaf : ITpiLeaf { if (TryGetLeafRecord(typeIndex, out var x) && x is TLeaf resolved) { leaf = resolved; return true; } leaf = default; return false; } /// <summary> /// Obtains a type record from the TPI stream based on its type index. /// </summary> /// <param name="typeIndex">The type index.</param> /// <returns>The resolved type.</returns> /// <exception cref="ArgumentException">Occurs when the type index is invalid.</exception> public ITpiLeaf GetLeafRecord(uint typeIndex) { if (!TryGetLeafRecord(typeIndex, out var type)) throw new ArgumentException("Invalid type index."); return type; } /// <summary> /// Obtains a type record from the TPI stream based on its type index. /// </summary> /// <param name="typeIndex">The type index.</param> /// <returns>The resolved type.</returns> /// <exception cref="ArgumentException">Occurs when the type index is invalid.</exception> public TLeaf GetLeafRecord<TLeaf>(uint typeIndex) where TLeaf : ITpiLeaf { return (TLeaf) GetLeafRecord(typeIndex); } /// <summary> /// Attempts to obtain an ID record from the IPI stream based on its ID index. /// </summary> /// <param name="idIndex">The ID index.</param> /// <param name="leaf">The resolved leaf.</param> /// <returns><c>true</c> if the leaf was found, <c>false</c> otherwise.</returns> public virtual bool TryGetIdLeafRecord(uint idIndex, [NotNullWhen(true)] out IIpiLeaf? leaf) { leaf = null; return false; } /// <summary> /// Attempts to obtain an ID record from the IPI stream based on its ID index. /// </summary> /// <param name="idIndex">The ID index.</param> /// <param name="leaf">The resolved leaf.</param> /// <returns><c>true</c> if the leaf was found, <c>false</c> otherwise.</returns> public bool TryGetIdLeafRecord<TLeaf>(uint idIndex, [NotNullWhen(true)] out TLeaf? leaf) where TLeaf : IIpiLeaf { if (TryGetIdLeafRecord(idIndex, out var x) && x is TLeaf resolved) { leaf = resolved; return true; } leaf = default; return false; } /// <summary> /// Obtains an ID record from the IPI stream based on its ID index. /// </summary> /// <param name="idIndex">The ID index.</param> /// <returns>The resolved leaf</returns> /// <exception cref="ArgumentException">Occurs when the ID index is invalid.</exception> public IIpiLeaf GetIdLeafRecord(uint idIndex) { if (!TryGetIdLeafRecord(idIndex, out var leaf)) throw new ArgumentException("Invalid ID index."); return leaf; } /// <summary> /// Obtains an ID record from the IPI stream based on its ID index. /// </summary> /// <param name="idIndex">The ID index.</param> /// <returns>The resolved leaf</returns> /// <exception cref="ArgumentException">Occurs when the ID index is invalid.</exception> public TLeaf GetIdLeafRecord<TLeaf>(uint idIndex) where TLeaf : CodeViewLeaf { return (TLeaf) GetIdLeafRecord(idIndex); } /// <summary> /// Obtains a collection of symbols stored in the symbol record stream of the PDB image. /// </summary> /// <returns>The symbols.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Symbols"/> property. /// </remarks> protected virtual IList<ICodeViewSymbol> GetSymbols() => new List<ICodeViewSymbol>(); /// <summary> /// Obtains a collection of modules stored in the DBI stream of the PDB image. /// </summary> /// <returns>The modules.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Modules"/> property. /// </remarks> protected virtual IList<PdbModule> GetModules() => new List<PdbModule>(); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\PdbModuleTest.cs
AsmResolver.Symbols.Pdb.Tests
PdbModuleTest
['private readonly MockPdbFixture _fixture;']
['System.Collections.Generic', 'System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class PdbModuleTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public PdbModuleTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Name() { Assert.Equal("* CIL *", _fixture.SimplePdb.Modules[0].Name); } [Fact] public void ObjectFileName() { var module = _fixture.SimplePdb.Modules[4]; Assert.Equal("Import:KERNEL32.dll", module.Name); Assert.Equal( @"C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x86\kernel32.lib", module.ObjectFileName); } [Fact] public void Children() { var module = _fixture.SimplePdb.Modules.First(m => m.Name!.Contains("dllmain.obj")); Assert.Equal(new[] { CodeViewSymbolType.ObjName, CodeViewSymbolType.Compile3, CodeViewSymbolType.BuildInfo, CodeViewSymbolType.GProc32, }, module.Symbols.Select(x => x.CodeViewSymbolType)); } [Fact] public void SourceFiles() { var module = _fixture.SimplePdb.Modules.First(m => m.Name!.Contains("dllmain.obj")); Assert.Equal(new Utf8String[] { "C:\\Users\\Admin\\source\\repos\\AsmResolver\\test\\TestBinaries\\Native\\SimpleDll\\pch.h", "C:\\Users\\Admin\\source\\repos\\AsmResolver\\test\\TestBinaries\\Native\\SimpleDll\\dllmain.cpp", "C:\\Users\\Admin\\source\\repos\\AsmResolver\\test\\TestBinaries\\Native\\SimpleDll\\Release\\SimpleDll.pch" }, module.SourceFiles.Select(f => f.FileName)); } }
155
1,832
using System.Collections.Generic; using System.Threading; using AsmResolver.Symbols.Pdb.Metadata.Dbi; using AsmResolver.Symbols.Pdb.Records; namespace AsmResolver.Symbols.Pdb; /// <summary> /// Represents a single module stored in a PDB image. /// </summary> public class PdbModule : ICodeViewSymbolProvider { private readonly LazyVariable<PdbModule, Utf8String?> _name; private readonly LazyVariable<PdbModule, Utf8String?> _objectFileName; private IList<PdbSourceFile>? _sourceFiles; private readonly LazyVariable<PdbModule, SectionContribution> _sectionContribution; private IList<ICodeViewSymbol>? _symbols; /// <summary> /// Initialize an empty module in a PDB image. /// </summary> protected PdbModule() { _name = new LazyVariable<PdbModule, Utf8String?>(x => x.GetName()); _objectFileName = new LazyVariable<PdbModule, Utf8String?>(x => x.GetObjectFileName()); _sectionContribution = new LazyVariable<PdbModule, SectionContribution>(x => x.GetSectionContribution()); } /// <summary> /// Creates a new linked module in a PDB image. /// </summary> /// <param name="name">The name of the module.</param> public PdbModule(Utf8String name) : this(name, name) { } /// <summary> /// Creates a new module in a PDB image that was constructed from an object file. /// </summary> /// <param name="name">The name of the module.</param> /// <param name="objectFileName">The path to the object file.</param> public PdbModule(Utf8String name, Utf8String objectFileName) { _name = new LazyVariable<PdbModule, Utf8String?>(name); _objectFileName = new LazyVariable<PdbModule, Utf8String?>(objectFileName); _sectionContribution = new LazyVariable<PdbModule, SectionContribution>(new SectionContribution()); } /// <summary> /// Gets or sets the name of the module. /// </summary> /// <remarks> /// This is often a full path to the object file that was passed into <c>link.exe</c> directly, or a string in the /// form of <c>Import:dll_name</c> /// </remarks> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Gets or sets the name of the object file name. /// </summary> /// <remarks> /// In the case this module is linked directly passed to <c>link.exe</c>, this is the same as <see cref="Name"/>. /// If the module comes from an archive, this is the full path to that archive. /// </remarks> public Utf8String? ObjectFileName { get => _objectFileName.GetValue(this); set => _objectFileName.SetValue(value); } /// <summary> /// Gets a collection of source files that were used to compile the module. /// </summary> public IList<PdbSourceFile> SourceFiles { get { if (_sourceFiles is null) Interlocked.CompareExchange(ref _sourceFiles, GetSourceFiles(), null); return _sourceFiles; } } /// <summary> /// Gets or sets a description of the section within the final binary which contains code /// and/or data from this module. /// </summary> public SectionContribution SectionContribution { get => _sectionContribution.GetValue(this); set => _sectionContribution.SetValue(value); } /// <inheritdoc /> public IList<ICodeViewSymbol> Symbols { get { if (_symbols is null) Interlocked.CompareExchange(ref _symbols, GetSymbols(), null); return _symbols; } } /// <summary> /// Obtains the name of the module. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon the initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <summary> /// Obtains the object file name of the module. /// </summary> /// <returns>The object file name.</returns> /// <remarks> /// This method is called upon the initialization of the <see cref="ObjectFileName"/> property. /// </remarks> protected virtual Utf8String? GetObjectFileName() => null; /// <summary> /// Obtains the source file names associated to the module. /// </summary> /// <returns>The source file names.</returns> /// <remarks> /// This method is called upon the initialization of the <see cref="SourceFiles"/> property. /// </remarks> protected virtual IList<PdbSourceFile> GetSourceFiles() => new List<PdbSourceFile>(); /// <summary> /// Obtains the section contribution of the module. /// </summary> /// <returns>The section contribution.</returns> /// <remarks> /// This method is called upon the initialization of the <see cref="SectionContribution"/> property. /// </remarks> protected virtual SectionContribution? GetSectionContribution() => new(); /// <summary> /// Obtains the symbols stored in the module. /// </summary> /// <returns>The symbols.</returns> /// <remarks> /// This method is called upon the initialization of the <see cref="Symbols"/> property. /// </remarks> protected virtual IList<ICodeViewSymbol> GetSymbols() => new List<ICodeViewSymbol>(); /// <inheritdoc /> public override string ToString() => Name ?? ObjectFileName ?? "<<<NULL NAME>>>"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\BasePointerRelativeSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
BasePointerRelativeSymbolTest
['private readonly BasePointerRelativeSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class BasePointerRelativeSymbolTest : IClassFixture<MockPdbFixture> { private readonly BasePointerRelativeSymbol _symbol; public BasePointerRelativeSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("gs_report.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<BasePointerRelativeSymbol>() .First(); } [Fact] public void Name() { Assert.Equal("exception_pointers", _symbol.Name); } [Fact] public void Offset() { Assert.Equal(8, _symbol.Offset); } [Fact] public void Type() { Assert.IsAssignableFrom<PointerTypeRecord>(_symbol.VariableType); } }
167
964
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a symbol that is defined by an offset relative to the base pointer register. /// </summary> public class BasePointerRelativeSymbol : CodeViewSymbol, IRegisterRelativeSymbol { private readonly LazyVariable<BasePointerRelativeSymbol, CodeViewTypeRecord?> _variableType; private readonly LazyVariable<BasePointerRelativeSymbol, Utf8String?> _name; /// <summary> /// Initializes an empty base-pointer relative symbol. /// </summary> protected BasePointerRelativeSymbol() { _name = new LazyVariable<BasePointerRelativeSymbol, Utf8String?>(x => x.GetName()); _variableType = new LazyVariable<BasePointerRelativeSymbol, CodeViewTypeRecord?>(x => x.GetVariableType()); } /// <summary> /// Creates a new base-pointer relative symbol. /// </summary> /// <param name="name">The name of the symbol.</param> /// <param name="offset">The offset relative to the base pointer.</param> /// <param name="variableType">The type of variable the symbol stores.</param> public BasePointerRelativeSymbol(Utf8String name, CodeViewTypeRecord variableType, int offset) { _name = new LazyVariable<BasePointerRelativeSymbol, Utf8String?>(name); _variableType = new LazyVariable<BasePointerRelativeSymbol, CodeViewTypeRecord?>(variableType); Offset = offset; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.BPRel32; /// <summary> /// Gets or sets the offset relative to the base pointer. /// </summary> public int Offset { get; set; } /// <summary> /// Gets or sets the type of values the symbol stores. /// </summary> public CodeViewTypeRecord? VariableType { get => _variableType.GetValue(this); set => _variableType.SetValue(value); } /// <summary> /// Gets or sets the name of the symbol. /// </summary> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the variable type of the symbol. /// </summary> /// <returns>The variable type</returns> /// <remarks> /// This method is called upon initialization of the <see cref="VariableType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetVariableType() => null; /// <summary> /// Obtains the name of the symbol. /// </summary> /// <returns>The name</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_BPREL32 [{Offset:X}]: {VariableType} {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\BuildInfoSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
BuildInfoSymbolTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class BuildInfoSymbolTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public BuildInfoSymbolTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Info() { var symbol = _fixture.SimplePdb.Modules[1].Symbols.OfType<BuildInfoSymbol>().First(); var info = symbol.Info; Assert.NotNull(info); Assert.Equal(5, info.Entries.Count); } }
128
605
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a symbol containing build information for a file in a PDB image. /// </summary> public class BuildInfoSymbol : CodeViewSymbol { private readonly LazyVariable<BuildInfoSymbol, BuildInfoLeaf?> _info; /// <summary> /// Initializes an empty build information symbol. /// </summary> protected BuildInfoSymbol() { _info = new LazyVariable<BuildInfoSymbol, BuildInfoLeaf?>(x => x.GetInfo()); } /// <summary> /// Wraps a build information leaf into a symbol. /// </summary> /// <param name="info">The information to wrap.</param> public BuildInfoSymbol(BuildInfoLeaf info) { _info = new LazyVariable<BuildInfoSymbol, BuildInfoLeaf?>(info); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.BuildInfo; /// <summary> /// Gets or sets the information that is wrapped into a symbol. /// </summary> public BuildInfoLeaf? Info { get => _info.GetValue(this); set => _info.SetValue(value); } /// <summary> /// Obtains the wrapped build information. /// </summary> /// <returns>The information.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Info"/> property. /// </remarks> protected virtual BuildInfoLeaf? GetInfo() => null; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\CallSiteSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
CallSiteSymbolTest
['private readonly CallSiteSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class CallSiteSymbolTest : IClassFixture<MockPdbFixture> { private readonly CallSiteSymbol _symbol; public CallSiteSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("gs_report.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<CallSiteSymbol>() .First(); } [Fact] public void Offset() { Assert.Equal(0x0000037E, _symbol.Offset); } [Fact] public void FunctionType() { Assert.IsAssignableFrom<PointerTypeRecord>(_symbol.FunctionType); } }
167
824
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Provides information about the signature of an indirect call. /// </summary> public class CallSiteSymbol : CodeViewSymbol { private readonly LazyVariable<CallSiteSymbol, CodeViewTypeRecord?> _functionType; /// <summary> /// Initializes an empty call site symbol. /// </summary> protected CallSiteSymbol() { _functionType = new LazyVariable<CallSiteSymbol, CodeViewTypeRecord?>(x => x.GetFunctionType()); } /// <summary> /// Creates a new call site info symbol. /// </summary> /// <param name="sectionIndex">The index of the section the call resides in.</param> /// <param name="offset">The offset to the call.</param> /// <param name="functionType">The type describing the shape of the function.</param> public CallSiteSymbol(ushort sectionIndex, int offset, CodeViewTypeRecord functionType) { SectionIndex = sectionIndex; Offset = offset; _functionType = new LazyVariable<CallSiteSymbol, CodeViewTypeRecord?>(functionType); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.CallSiteInfo; /// <summary> /// Gets or sets the index of the section the call resides in. /// </summary> public ushort SectionIndex { get; set; } /// <summary> /// Gets or sets the offset to the call. /// </summary> public int Offset { get; set; } /// <summary> /// Gets or sets the type describing the shape of the function that is called. /// </summary> public CodeViewTypeRecord? FunctionType { get => _functionType.GetValue(this); set => _functionType.SetValue(value); } /// <summary> /// Obtains the function type of the call. /// </summary> /// <returns>The type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="FunctionType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetFunctionType() => null; /// <inheritdoc /> public override string ToString() => $"S_CALLSITEINFO [{SectionIndex:X4}:{Offset:X8}]: {FunctionType}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\CoffGroupSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
CoffGroupSymbolTest
['private readonly CoffGroupSymbol _symbol;']
['System.Linq', 'AsmResolver.PE.File', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class CoffGroupSymbolTest : IClassFixture<MockPdbFixture> { private readonly CoffGroupSymbol _symbol; public CoffGroupSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name == "* Linker *") .Symbols.OfType<CoffGroupSymbol>() .First(); } [Fact] public void BasicProperties() { Assert.Equal(1, _symbol.SegmentIndex); Assert.Equal(0u, _symbol.Offset); Assert.Equal(0xCE8u, _symbol.Size); Assert.Equal( SectionFlags.ContentCode | SectionFlags.MemoryRead | SectionFlags.MemoryExecute, _symbol.Characteristics); } [Fact] public void Name() { Assert.Equal(".text$mn", _symbol.Name); } }
156
966
using AsmResolver.PE.File; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a single Common Object File Format (COFF) group symbol. /// </summary> public class CoffGroupSymbol : CodeViewSymbol { private readonly LazyVariable<CoffGroupSymbol, Utf8String?> _name; /// <summary> /// Initializes an empty COFF group symbol. /// </summary> protected CoffGroupSymbol() { _name = new LazyVariable<CoffGroupSymbol, Utf8String?>(x => x.GetName()); } /// <summary> /// Creates a new COFF group symbol. /// </summary> /// <param name="name">The name of the group.</param> /// <param name="segmentIndex">The index of the segment the group resides in.</param> /// <param name="offset">The offset within the segment.</param> /// <param name="size">The size of the group in bytes.</param> /// <param name="characteristics">The characteristics describing the group.</param> public CoffGroupSymbol(Utf8String name, ushort segmentIndex, uint offset, uint size, SectionFlags characteristics) { _name = new LazyVariable<CoffGroupSymbol, Utf8String?>(name); SegmentIndex = segmentIndex; Offset = offset; Size = size; Characteristics = characteristics; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.CoffGroup; /// <summary> /// Gets or sets the size of the group in bytes. /// </summary> public uint Size { get; set; } /// <summary> /// Gets or sets the characteristics describing the group. /// </summary> public SectionFlags Characteristics { get; set; } /// <summary> /// Gets or sets the index of the segment the group resides in. /// </summary> public ushort SegmentIndex { get; set; } /// <summary> /// Gets or sets the offset within the segment the group starts at. /// </summary> public uint Offset { get; set; } /// <summary> /// Gets or sets the name of the group. /// </summary> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the name of the group. /// </summary> /// <returns>The name</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_COFFGROUP: [{SegmentIndex:X4}:{Offset:X8}], Cb: {Size:X8}, Name: {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\CompileSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
CompileSymbolTest
['private readonly Compile2Symbol _compile2Symbol;', 'private readonly Compile3Symbol _compile3Symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class CompileSymbolTest : IClassFixture<MockPdbFixture> { private readonly Compile2Symbol _compile2Symbol; private readonly Compile3Symbol _compile3Symbol; public CompileSymbolTest(MockPdbFixture fixture) { var kernel32Module = fixture.SimplePdb.Modules.First(m => m.Name == "KERNEL32.dll"); var dllmainModule = fixture.SimplePdb.Modules.First(m => m.Name == @"C:\Users\Admin\source\repos\AsmResolver\test\TestBinaries\Native\SimpleDll\Release\dllmain.obj"); _compile2Symbol = kernel32Module.Symbols.OfType<Compile2Symbol>().First(); _compile3Symbol = dllmainModule.Symbols.OfType<Compile3Symbol>().First(); } [Fact] public void Flags2() { Assert.Equal(SourceLanguage.Link, _compile2Symbol.Language); Assert.Equal(CompileAttributes.None, _compile2Symbol.Attributes); } [Fact] public void Flags3() { Assert.Equal(SourceLanguage.Cpp, _compile3Symbol.Language); Assert.Equal( CompileAttributes.Sdl | CompileAttributes.SecurityChecks | CompileAttributes.Ltcg, _compile3Symbol.Attributes); } [Fact] public void Machine2() { Assert.Equal(CpuType.Intel80386, _compile2Symbol.Machine); } [Fact] public void Machine3() { Assert.Equal(CpuType.Pentium3, _compile3Symbol.Machine); } [Fact] public void NumericVersions2() { Assert.Equal(0, _compile2Symbol.FrontEndMajorVersion); Assert.Equal(0, _compile2Symbol.FrontEndMinorVersion); Assert.Equal(0, _compile2Symbol.FrontEndBuildVersion); Assert.Equal(14, _compile2Symbol.BackEndMajorVersion); Assert.Equal(20, _compile2Symbol.BackEndMinorVersion); Assert.Equal(27412, _compile2Symbol.BackEndBuildVersion); } [Fact] public void NumericVersions3() { Assert.Equal(19, _compile3Symbol.FrontEndMajorVersion); Assert.Equal(29, _compile3Symbol.FrontEndMinorVersion); Assert.Equal(30143, _compile3Symbol.FrontEndBuildVersion); Assert.Equal(0, _compile3Symbol.FrontEndQfeVersion); Assert.Equal(19, _compile3Symbol.BackEndMajorVersion); Assert.Equal(29, _compile3Symbol.BackEndMinorVersion); Assert.Equal(30143, _compile3Symbol.BackEndBuildVersion); Assert.Equal(0, _compile3Symbol.BackEndQfeVersion); } [Fact] public void CompilerVersionString2() { Assert.Equal("Microsoft (R) LINK", _compile2Symbol.CompilerVersion); } [Fact] public void CompilerVersionString3() { Assert.Equal("Microsoft (R) Optimizing Compiler", _compile3Symbol.CompilerVersion); } }
128
2,897
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a symbol that describes information about the compiler that was used to compile the file. /// </summary> public abstract class CompileSymbol : CodeViewSymbol { private readonly LazyVariable<CompileSymbol, Utf8String> _compilerVersion; /// <summary> /// Initializes an empty compile symbol. /// </summary> protected CompileSymbol() { _compilerVersion = new LazyVariable<CompileSymbol, Utf8String>(x => x.GetCompilerVersion()); } /// <summary> /// Gets or sets the identifier of the language that was used to compile the file. /// </summary> public SourceLanguage Language { get; set; } /// <summary> /// Gets or sets attributes associated to the compile symbol. /// </summary> public CompileAttributes Attributes { get; set; } /// <summary> /// Gets or sets the architecture the file is targeting. /// </summary> public CpuType Machine { get; set; } /// <summary> /// Gets or sets the front-end major version of the file. /// </summary> public ushort FrontEndMajorVersion { get; set; } /// <summary> /// Gets or sets the front-end minor version of the file. /// </summary> public ushort FrontEndMinorVersion { get; set; } /// <summary> /// Gets or sets the front-end build version of the file. /// </summary> public ushort FrontEndBuildVersion { get; set; } /// <summary> /// Gets or sets the back-end major version of the file. /// </summary> public ushort BackEndMajorVersion { get; set; } /// <summary> /// Gets or sets the back-end minor version of the file. /// </summary> public ushort BackEndMinorVersion { get; set; } /// <summary> /// Gets or sets the back-end build version of the file. /// </summary> public ushort BackEndBuildVersion { get; set; } /// <summary> /// Gets or sets the version of the compiler that was used to compile the file. /// </summary> public Utf8String CompilerVersion { get => _compilerVersion.GetValue(this); set => _compilerVersion.SetValue(value); } /// <summary> /// Obtains the compiler version string. /// </summary> /// <returns>The compiler version.</returns> /// <remarks> /// This method is called upon the initialization of the <see cref="CompilerVersion"/> property. /// </remarks> protected virtual Utf8String GetCompilerVersion() => Utf8String.Empty; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\DataSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
DataSymbolTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class DataSymbolTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public DataSymbolTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Global() { var symbol = _fixture.SimplePdb.Symbols.OfType<DataSymbol>().First(); Assert.True(symbol.IsGlobal); Assert.Equal(CodeViewSymbolType.GData32, symbol.CodeViewSymbolType); } [Fact] public void Local() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains("gs_report")) .Symbols.OfType<DataSymbol>() .First(); Assert.True(symbol.IsLocal); Assert.Equal(CodeViewSymbolType.LData32, symbol.CodeViewSymbolType); } [Fact] public void BasicProperties() { var symbol = _fixture.SimplePdb.Symbols.OfType<DataSymbol>().First(); Assert.Equal(3, symbol.SegmentIndex); Assert.Equal(0x38Cu, symbol.Offset); Assert.Equal(SimpleTypeKind.Int32, Assert.IsAssignableFrom<SimpleTypeRecord>(symbol.VariableType).Kind); } [Fact] public void Name() { var symbol = _fixture.SimplePdb.Symbols.OfType<DataSymbol>().First(); Assert.Equal( "__@@_PchSym_@00@UfhvihUzwnrmUhlfixvUivklhUzhnivhloeviUgvhgUgvhgyrmzirvhUmzgrevUhrnkovwooUivovzhvUkxsOlyq@4B2008FD98C1DD4", symbol.Name); } }
167
1,640
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a global or local data symbol. /// </summary> public class DataSymbol : CodeViewSymbol, IVariableSymbol { private readonly LazyVariable<DataSymbol, Utf8String?> _name; private readonly LazyVariable<DataSymbol, CodeViewTypeRecord?> _variableType; /// <summary> /// Initializes an empty data symbol. /// </summary> protected DataSymbol() { _name = new LazyVariable<DataSymbol, Utf8String?>(x => x.GetName()); _variableType = new LazyVariable<DataSymbol, CodeViewTypeRecord?>(x => x.GetVariableType()); } /// <summary> /// Creates a new named data symbol. /// </summary> /// <param name="name">The name of the symbol.</param> /// <param name="variableType">The data type of the symbol.</param> public DataSymbol(Utf8String name, CodeViewTypeRecord variableType) { _name = new LazyVariable<DataSymbol, Utf8String?>(name); _variableType = new LazyVariable<DataSymbol, CodeViewTypeRecord?>(variableType); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => IsGlobal ? CodeViewSymbolType.GData32 : CodeViewSymbolType.LData32; /// <summary> /// Gets or sets a value indicating whether the symbol is a global data symbol. /// </summary> public bool IsGlobal { get; set; } /// <summary> /// Gets or sets a value indicating whether the symbol is a local data symbol. /// </summary> public bool IsLocal { get => !IsGlobal; set => IsGlobal = !value; } /// <summary> /// Gets or sets the file segment index this symbol is located in. /// </summary> public ushort SegmentIndex { get; set; } /// <summary> /// Gets or sets the offset within the file that this symbol is defined at. /// </summary> public uint Offset { get; set; } /// <inheritdoc /> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <inheritdoc /> public CodeViewTypeRecord? VariableType { get => _variableType.GetValue(this); set => _variableType.SetValue(value); } /// <summary> /// Obtains the name of the symbol. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <summary> /// Obtains the type of the variable. /// </summary> /// <returns>The type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="VariableType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetVariableType() => null; /// <inheritdoc /> public override string ToString() { return $"S_{CodeViewSymbolType.ToString().ToUpper()}: [{SegmentIndex:X4}:{Offset:X8}] {VariableType} {Name}"; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\FileStaticSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
FileStaticSymbolTest
['private readonly FileStaticSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class FileStaticSymbolTest : IClassFixture<MockPdbFixture> { private readonly FileStaticSymbol _symbol; public FileStaticSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"msvcrt.nativeproj_110336922\objr\x86\dll_dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().ElementAt(2) .Symbols.OfType<FileStaticSymbol>() .First(); } [Fact] public void Name() { Assert.Equal("__proc_attached", _symbol.Name); } [Fact] public void Type() { Assert.Equal(SimpleTypeKind.Int32, Assert.IsAssignableFrom<SimpleTypeRecord>(_symbol.VariableType).Kind); } }
167
912
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a file static variable symbol. /// </summary> public class FileStaticSymbol : CodeViewSymbol, IVariableSymbol { private readonly LazyVariable<FileStaticSymbol, Utf8String?> _name; private readonly LazyVariable<FileStaticSymbol, CodeViewTypeRecord?> _variableType; /// <summary> /// Initializes an empty file static symbol. /// </summary> protected FileStaticSymbol() { _name = new LazyVariable<FileStaticSymbol, Utf8String?>(x => x.GetName()); _variableType = new LazyVariable<FileStaticSymbol, CodeViewTypeRecord?>(x => x.GetVariableType()); } /// <summary> /// Creates a new file static variable symbol. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="variableType">The data type of the variable.</param> /// <param name="attributes">The attributes describing the variable.</param> public FileStaticSymbol(Utf8String name, CodeViewTypeRecord variableType, LocalAttributes attributes) { Attributes = attributes; _name = new LazyVariable<FileStaticSymbol, Utf8String?>(name); _variableType = new LazyVariable<FileStaticSymbol, CodeViewTypeRecord?>(variableType); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.FileStatic; /// <summary> /// Gets or sets the index of the module's file name within the string table. /// </summary> public uint ModuleFileNameOffset { get; set; } /// <summary> /// Gets or sets the attributes describing the variable. /// </summary> public LocalAttributes Attributes { get; set; } /// <inheritdoc /> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <inheritdoc /> public CodeViewTypeRecord? VariableType { get => _variableType.GetValue(this); set => _variableType.SetValue(value); } /// <summary> /// Obtains the type of the variable. /// </summary> /// <returns>The type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="VariableType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetVariableType() => null; /// <summary> /// Obtains the name of the variable. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_FILESTATIC: {VariableType} {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\FrameCookieSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
FrameCookieSymbolTest
['private readonly FrameCookieSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class FrameCookieSymbolTest : IClassFixture<MockPdbFixture> { private readonly FrameCookieSymbol _symbol; public FrameCookieSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"msvcrt.nativeproj_110336922\objr\x86\dll_dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().ElementAt(1) .Symbols.OfType<FrameCookieSymbol>() .First(); } [Fact] public void BasicProperties() { Assert.Equal(-48, _symbol.FrameOffset); Assert.Equal(FrameCookieType.Copy, _symbol.CookieType); Assert.Equal(0, _symbol.Attributes); } }
128
825
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Describes the position and type of a security cookie within a stack frame. /// </summary> public class FrameCookieSymbol : CodeViewSymbol { /// <summary> /// Initializes an empty frame cookie symbol. /// </summary> protected FrameCookieSymbol() { } /// <summary> /// Creates a new frame cookie symbol. /// </summary> /// <param name="frameOffset">The offset relative to the frame pointer.</param> /// <param name="register">The register storing the cookie.</param> /// <param name="cookieType">The type of cookie that is computed.</param> /// <param name="attributes">The attributes associated to the cookie.</param> public FrameCookieSymbol(int frameOffset, ushort register, FrameCookieType cookieType, byte attributes) { FrameOffset = frameOffset; Register = register; CookieType = cookieType; Attributes = attributes; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.FrameCookie; /// <summary> /// Gets or sets the offset relative to the frame pointer where the cookie is stored. /// </summary> public int FrameOffset { get; set; } /// <summary> /// Gets or sets the register storing the cookie. /// </summary> public ushort Register { get; set; } /// <summary> /// Gets or sets the type of cookie that is computed. /// </summary> public FrameCookieType CookieType { get; set; } /// <summary> /// Gets or sets attributes describing the cookie. /// </summary> /// <remarks> /// This flags field is not well understood. /// </remarks> public byte Attributes { get; set; } /// <inheritdoc /> public override string ToString() => $"S_FRAMECOOKIE: {CookieType} +{FrameOffset:X}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\FramePointerRangeSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
FramePointerRangeSymbolTest
['private readonly MockPdbFixture _fixture;', 'private readonly FramePointerRangeSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class FramePointerRangeSymbolTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; private readonly FramePointerRangeSymbol _symbol; public FramePointerRangeSymbolTest(MockPdbFixture fixture) { _fixture = fixture; _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<FramePointerRangeSymbol>() .First(); } [Fact] public void Offset() { Assert.Equal(8, _symbol.Offset); } [Fact] public void FullScope() { Assert.True(_symbol.IsFullScope); Assert.Equal(default, _symbol.Range); Assert.Empty(_symbol.Gaps); } [Fact] public void NonFullScope() { string path = @"D:\a\_work\1\s\Intermediate\vctools\msvcrt.nativeproj_110336922\objr\x86\cpu_disp.obj"; var symbol = _fixture.SimplePdb .Modules.First(m => m.Name == path) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<FramePointerRangeSymbol>() .First(); Assert.False(symbol.IsFullScope); Assert.Equal(-12, symbol.Offset); Assert.Equal(0xa95u, symbol.Range.Start); Assert.Equal(0xc18u, symbol.Range.End); Assert.Empty(symbol.Gaps); } }
128
1,559
using System.Linq; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a symbol def-range that is stored at an offset relative to the frame pointer. /// </summary> public class FramePointerRangeSymbol : DefinitionRangeSymbol { private bool _isFullScope; /// <summary> /// Initializes an empty frame-pointer def-range. /// </summary> protected FramePointerRangeSymbol() { } /// <summary> /// Creates a new frame-pointer def-range. /// </summary> /// <param name="offset">The offset the symbol is declared at, relative to the frame pointer.</param> /// <param name="range">The address range the symbol is valid in.</param> public FramePointerRangeSymbol(int offset, LocalAddressRange range) : base(range, Enumerable.Empty<LocalAddressGap>()) { Offset = offset; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => IsFullScope ? CodeViewSymbolType.DefRangeFramePointerRelFullScope : CodeViewSymbolType.DefRangeFramePointerRel; /// <summary> /// Gets or sets a value indicating whether the symbol spans the full scope of the function or not. /// </summary> /// <remarks> /// When this value is set to <c>true</c>, the values in <see cref="DefinitionRangeSymbol.Range"/> and /// <see cref="DefinitionRangeSymbol.Gaps"/> have no meaning. /// </remarks> public bool IsFullScope { get => _isFullScope; set { _isFullScope = value; if (value) { Range = default; Gaps.Clear(); } } } /// <summary> /// Gets or sets the offset the symbol is declared at, relative to the frame pointer. /// </summary> public int Offset { get; set; } /// <inheritdoc /> public override string ToString() { string prefix = IsFullScope ? "S_DEFRANGE_FRAMEPOINTER_FULLSCOPE" : "S_DEFRANGE_FRAMEPOINTER"; return $"{prefix}: [{Offset:X}] Range: {Range} (Gap Count: {Gaps.Count})"; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\FrameProcedureSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
FrameProcedureSymbolTest
['private readonly FrameProcedureSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class FrameProcedureSymbolTest : IClassFixture<MockPdbFixture> { private readonly FrameProcedureSymbol _symbol; public FrameProcedureSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("cpu_disp.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<FrameProcedureSymbol>() .First(); } [Fact] public void BasicProperties() { Assert.Equal(0x24u, _symbol.FrameSize); Assert.Equal(0u, _symbol.PaddingSize); Assert.Equal(0, _symbol.PaddingOffset); Assert.Equal(0xCu, _symbol.CalleeSavesSize); Assert.Equal(0, _symbol.ExceptionHandlerOffset); Assert.Equal(0, _symbol.ExceptionHandlerSection); Assert.False((_symbol.Attributes & FrameProcedureAttributes.ValidCounts) != 0); Assert.True((_symbol.Attributes & FrameProcedureAttributes.GuardCF) != 0); } }
128
1,121
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Provides extra information about a procedure and its frame layout. /// </summary> public class FrameProcedureSymbol : CodeViewSymbol { /// <summary> /// Initializes an empty frame procedure symbol. /// </summary> protected FrameProcedureSymbol() { } /// <summary> /// Creates a new frame procedure symbol. /// </summary> /// <param name="frameSize">The size of the frame.</param> /// <param name="attributes">The attributes associated to the procedure.</param> public FrameProcedureSymbol(uint frameSize, FrameProcedureAttributes attributes) { FrameSize = frameSize; Attributes = attributes; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.FrameProc; /// <summary> /// Gets or sets the size (in bytes) of the procedure's frame. /// </summary> public uint FrameSize { get; set; } /// <summary> /// Gets or sets the size (in bytes) of the procedure's frame padding. /// </summary> public uint PaddingSize { get; set; } /// <summary> /// Gets or sets the offset relative to the frame pointer where the padding starts. /// </summary> public int PaddingOffset { get; set; } /// <summary> /// Gets or sets the size (in bytes) of the callee register saves storage. /// </summary> public uint CalleeSavesSize { get; set; } /// <summary> /// Gets or sets the offset to the exception handler (if available). /// </summary> public int ExceptionHandlerOffset { get; set; } /// <summary> /// Gets or sets the section index to the exception handler (if available). /// </summary> public ushort ExceptionHandlerSection { get; set; } /// <summary> /// Gets or sets the attributes associated to the procedure. /// </summary> public FrameProcedureAttributes Attributes { get; set; } /// <summary> /// Gets or sets the local base register pointer for the procedure. /// </summary> public byte LocalBasePointer { get => (byte) (((int) Attributes >> 14) & 0b11); set => Attributes = (Attributes & ~FrameProcedureAttributes.EncodedLocalBasePointerMask) | (FrameProcedureAttributes) ((value & 0b11) << 14); } /// <summary> /// Gets or sets the parameter base register pointer for the procedure. /// </summary> public byte ParameterBasePointer { get => (byte) (((int) Attributes >> 14) & 0b11); set => Attributes = (Attributes & ~FrameProcedureAttributes.EncodedParamBasePointerMask) | (FrameProcedureAttributes) ((value & 0b11) << 16); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\FunctionListSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
FunctionListSymbolTest
['private readonly FunctionListSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class FunctionListSymbolTest : IClassFixture<MockPdbFixture> { private readonly FunctionListSymbol _symbol; public FunctionListSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("chandler4gs.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<FunctionListSymbol>() .First(); } [Fact] public void Entries() { Assert.Equal(new[] { ("_filter_x86_sse2_floating_point_exception", 0), ("_except_handler4_common", 0) }, _symbol.Entries.Select(x => (x.Function!.Name!.Value, x.Count))); } }
128
842
using System.Collections.Generic; using System.Threading; using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Provides information about a function and the amount of times it is referenced. /// </summary> /// <param name="Function">The function that is referenced.</param> /// <param name="Count">The number of references this function has.</param> public record struct FunctionCountPair(FunctionIdentifier? Function, int Count); /// <summary> /// Represents a symbol containing a list of callers or callees. /// </summary> public class FunctionListSymbol : CodeViewSymbol { private IList<FunctionCountPair>? _entries; /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => IsCallersList ? CodeViewSymbolType.Callers : CodeViewSymbolType.Callees; /// <summary> /// Gets or sets a value indicating the functions in this list are callers. /// </summary> public bool IsCallersList { get; set; } /// <summary> /// Gets or sets a value indicating the functions in this list are callees. /// </summary> public bool IsCalleesList { get => !IsCallersList; set => IsCallersList = !value; } /// <summary> /// Gets a collection of functions stored in the list. /// </summary> public IList<FunctionCountPair> Entries { get { if (_entries is null) Interlocked.CompareExchange(ref _entries, GetEntries(), null); return _entries; } } /// <summary> /// Obtains the list of functions. /// </summary> /// <returns>The functions.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Entries"/> property. /// </remarks> protected virtual IList<FunctionCountPair> GetEntries() => new List<FunctionCountPair>(); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\InlineSiteSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
InlineSiteSymbolTest
['private readonly InlineSiteSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class InlineSiteSymbolTest : IClassFixture<MockPdbFixture> { private readonly InlineSiteSymbol _symbol; public InlineSiteSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"msvcrt.nativeproj_110336922\objr\x86\dll_dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().ElementAt(3) .Symbols.OfType<InlineSiteSymbol>().First(); } [Fact] public void Inlinee() { Assert.NotNull(_symbol.Inlinee); Assert.Equal("dllmain_crt_dispatch", _symbol.Inlinee.Name); } [Fact] public void BinaryAnnotations() { Assert.Equal(new[] { BinaryAnnotationOpCode.ChangeCodeLengthAndCodeOffset }, _symbol.Annotations.Select(x => x.OpCode)); } }
128
976
using System.Collections.Generic; using System.Threading; using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Provides information about an inlined call site. /// </summary> public class InlineSiteSymbol : CodeViewSymbol, IScopeCodeViewSymbol { private readonly LazyVariable<InlineSiteSymbol, FunctionIdentifier?> _inlinee; private IList<ICodeViewSymbol>? _symbols; private IList<BinaryAnnotation>? _annotations; /// <summary> /// Initializes an empty inline call site symbol. /// </summary> protected InlineSiteSymbol() { _inlinee = new LazyVariable<InlineSiteSymbol, FunctionIdentifier?>(x => x.GetInlinee()); } /// <summary> /// Creates a new inline site symbol. /// </summary> /// <param name="inlinee">The function that is being inlined.</param> public InlineSiteSymbol(FunctionIdentifier inlinee) { _inlinee = new LazyVariable<InlineSiteSymbol, FunctionIdentifier?>(inlinee); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.InlineSite; /// <inheritdoc /> public IList<ICodeViewSymbol> Symbols { get { if (_symbols is null) Interlocked.CompareExchange(ref _symbols, GetSymbols(), null); return _symbols; } } /// <summary> /// Gets or sets the identifier of the function that is being inlined. /// </summary> public FunctionIdentifier? Inlinee { get => _inlinee.GetValue(this); set => _inlinee.SetValue(value); } /// <summary> /// Gets a collection of annotations to the instruction stream. /// </summary> public IList<BinaryAnnotation> Annotations { get { if (_annotations is null) Interlocked.CompareExchange(ref _annotations, GetAnnotations(), null); return _annotations; } } /// <summary> /// Obtains the inlinee. /// </summary> /// <returns>The inlinee</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Inlinee"/> property. /// </remarks> protected virtual FunctionIdentifier? GetInlinee() => null; /// <summary> /// Obtains the sub-symbols defined in this inline site. /// </summary> /// <returns>The symbols.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Symbols"/> property. /// </remarks> protected virtual IList<ICodeViewSymbol> GetSymbols() => new List<ICodeViewSymbol>(); /// <summary> /// Obtains the collection of annotations added to the instruction stream. /// </summary> /// <returns>The annotations.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Annotations"/> property. /// </remarks> protected virtual IList<BinaryAnnotation> GetAnnotations() => new List<BinaryAnnotation>(); /// <inheritdoc /> public override string ToString() => $"S_INLINESITE: {Inlinee} (Annotation Count: {Annotations.Count})"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\LabelSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
LabelSymbolTest
['private readonly LabelSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class LabelSymbolTest : IClassFixture<MockPdbFixture> { private readonly LabelSymbol _symbol; public LabelSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"msvcrt.nativeproj_110336922\objr\x86\secchk.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<LabelSymbol>().First(); } [Fact] public void BasicProperties() { Assert.Equal(1, _symbol.SegmentIndex); Assert.Equal(0x11u, _symbol.Offset); } [Fact] public void Name() { Assert.Equal("failure", _symbol.Name); } }
128
811
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a named label within an instruction stream. /// </summary> public class LabelSymbol : CodeViewSymbol { private readonly LazyVariable<LabelSymbol, Utf8String?> _name; /// <summary> /// Initializes an empty label symbol. /// </summary> protected LabelSymbol() { _name = new LazyVariable<LabelSymbol, Utf8String?>(x => x.GetName()); } /// <summary> /// Creates a new label symbol. /// </summary> /// <param name="name">The name of the label.</param> /// <param name="segmentIndex">The index of the segment the label is defined in.</param> /// <param name="offset">The offset within the segment the label is defined at.</param> /// <param name="attributes">The attributes describing the label.</param> public LabelSymbol(Utf8String name, ushort segmentIndex, uint offset, ProcedureAttributes attributes) { _name = new LazyVariable<LabelSymbol, Utf8String?>(name); SegmentIndex = segmentIndex; Offset = offset; Attributes = attributes; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.Label32; /// <summary> /// Gets or sets the index of the segment the label is defined in. /// </summary> public ushort SegmentIndex { get; set; } /// <summary> /// Gets or sets the offset within the segment the label is defined at. /// </summary> public uint Offset { get; set; } /// <summary> /// Gets or sets the attributes describing the label. /// </summary> public ProcedureAttributes Attributes { get; set; } /// <summary> /// Gets or sets the name of the label. /// </summary> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the name of the label. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_LABEL32: [{SegmentIndex:X4}:{Offset:X8}] {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\LocalSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
LocalSymbolTest
['private readonly LocalSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class LocalSymbolTest : IClassFixture<MockPdbFixture> { private readonly LocalSymbol _symbol; public LocalSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<LocalSymbol>() .First(); } [Fact] public void Name() { Assert.Equal("hModule", _symbol.Name); } [Fact] public void Type() { Assert.IsAssignableFrom<PointerTypeRecord>(_symbol.VariableType); } }
167
797
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a symbol describing a local variable in a function or method. /// </summary> public class LocalSymbol : CodeViewSymbol, IVariableSymbol { private readonly LazyVariable<LocalSymbol, CodeViewTypeRecord?> _variableType; private readonly LazyVariable<LocalSymbol, Utf8String?> _name; /// <summary> /// Initializes an empty local variable symbol. /// </summary> protected LocalSymbol() { _variableType = new LazyVariable<LocalSymbol, CodeViewTypeRecord?>(x => x.GetVariableType()); _name = new LazyVariable<LocalSymbol, Utf8String?>(x => x.GetName()); } /// <summary> /// Creates a new local variable symbol. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="variableType">The type of the variable.</param> /// <param name="attributes">The attributes describing the variable.</param> public LocalSymbol(Utf8String? name, CodeViewTypeRecord? variableType, LocalAttributes attributes) { _variableType = new LazyVariable<LocalSymbol, CodeViewTypeRecord?>(variableType); _name = new LazyVariable<LocalSymbol, Utf8String?>(name); Attributes = attributes; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.Local; /// <inheritdoc /> public CodeViewTypeRecord? VariableType { get => _variableType.GetValue(this); set => _variableType.SetValue(value); } /// <summary> /// Gets or sets the attributes describing the variable. /// </summary> public LocalAttributes Attributes { get; set; } /// <inheritdoc /> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the type of the variable. /// </summary> /// <returns>The type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="VariableType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetVariableType() => null; /// <summary> /// Obtains the name of the variable. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_LOCAL32: {VariableType} {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\ProcedureReferenceSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
ProcedureReferenceSymbolTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class ProcedureReferenceSymbolTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ProcedureReferenceSymbolTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Name() { Assert.Equal("DllMain", _fixture.SimplePdb.Symbols.OfType<ProcedureReferenceSymbol>().First(s => !s.IsLocal).Name); } [Fact] public void LocalName() { Assert.Equal("__get_entropy", _fixture.SimplePdb.Symbols.OfType<ProcedureReferenceSymbol>().First(s => s.IsLocal).Name); } }
128
728
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a procedure reference symbol stored in a PDB symbol stream. /// </summary> public class ProcedureReferenceSymbol : CodeViewSymbol { private readonly LazyVariable<ProcedureReferenceSymbol, Utf8String> _name; private readonly bool _local; /// <summary> /// Initializes a new empty symbol. /// </summary> /// <param name="local">If true, this represents a local procedure reference.</param> protected ProcedureReferenceSymbol(bool local) { _name = new LazyVariable<ProcedureReferenceSymbol, Utf8String>(x => x.GetName()); _local = local; } /// <summary> /// Creates a new symbol. /// </summary> /// <param name="checksum">The checksum of the referenced symbol name.</param> /// <param name="offset">The offset within the segment the symbol starts at.</param> /// <param name="module">Index of the module that contains this procedure record.</param> /// <param name="name">The name of the symbol.</param> /// <param name="local">If true, this represents a local procedure reference.</param> public ProcedureReferenceSymbol(uint checksum, uint offset, ushort module, Utf8String name, bool local) { Checksum = checksum; Offset = offset; Module = module; _name = new LazyVariable<ProcedureReferenceSymbol, Utf8String>(name); _local = local; } /// <inheritdoc/> public override CodeViewSymbolType CodeViewSymbolType => _local ? CodeViewSymbolType.LProcRef : CodeViewSymbolType.ProcRef; /// <summary> /// Is the symbol a Local Procedure Reference? /// </summary> public bool IsLocal => _local; /// <summary> /// Gets the checksum of the referenced symbol name. The checksum used is the /// one specified in the header of the global symbols stream or static symbols stream. /// </summary> public uint Checksum { get; set; } /// <summary> /// Gets the offset of the procedure symbol record from the beginning of the /// $$SYMBOL table for the module. /// </summary> public uint Offset { get; set; } /// <summary> /// Index of the module that contains this procedure record. /// </summary> public ushort Module { get; set; } /// <summary> /// Gets or sets the name of the symbol. /// </summary> public Utf8String Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the name of the symbol. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String GetName() => Utf8String.Empty; /// <inheritdoc /> public override string ToString() => $"{CodeViewSymbolType}: [{Module:X4}:{Offset:X8}] {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\ProcedureSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
ProcedureSymbolTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class ProcedureSymbolTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public ProcedureSymbolTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Global() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.True(symbol.IsGlobal); Assert.Equal(CodeViewSymbolType.GProc32, symbol.CodeViewSymbolType); } [Fact] public void Local() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"gs_support.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.True(symbol.IsLocal); Assert.Equal(CodeViewSymbolType.LProc32, symbol.CodeViewSymbolType); } [Fact] public void Name() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.Equal("DllMain", symbol.Name); } [Fact] public void Size() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.Equal(8u, symbol.Size); } [Fact] public void DebugOffsets() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.Equal(0u, symbol.DebugStartOffset); Assert.Equal(5u, symbol.DebugEndOffset); } [Fact] public void Attributes() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.Equal(ProcedureAttributes.OptimizedDebugInfo, symbol.Attributes); } [Fact] public void ProcedureType() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.NotNull(symbol.ProcedureType); } [Fact] public void Children() { var symbol = _fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"SimpleDll\Release\dllmain.obj")) .Symbols.OfType<ProcedureSymbol>() .First(); Assert.Equal(new[] { CodeViewSymbolType.Local, CodeViewSymbolType.DefRangeRegisterRel, CodeViewSymbolType.DefRangeFramePointerRelFullScope, CodeViewSymbolType.Local, CodeViewSymbolType.DefRangeRegisterRel, CodeViewSymbolType.DefRangeFramePointerRelFullScope, CodeViewSymbolType.Local, CodeViewSymbolType.DefRangeRegisterRel, CodeViewSymbolType.DefRangeFramePointerRelFullScope, CodeViewSymbolType.FrameProc, CodeViewSymbolType.RegRel32, CodeViewSymbolType.RegRel32, CodeViewSymbolType.RegRel32, }, symbol.Symbols.Select(s => s.CodeViewSymbolType)); } }
128
3,665
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Provides extra information about a procedure and its frame layout. /// </summary> public class FrameProcedureSymbol : CodeViewSymbol { /// <summary> /// Initializes an empty frame procedure symbol. /// </summary> protected FrameProcedureSymbol() { } /// <summary> /// Creates a new frame procedure symbol. /// </summary> /// <param name="frameSize">The size of the frame.</param> /// <param name="attributes">The attributes associated to the procedure.</param> public FrameProcedureSymbol(uint frameSize, FrameProcedureAttributes attributes) { FrameSize = frameSize; Attributes = attributes; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.FrameProc; /// <summary> /// Gets or sets the size (in bytes) of the procedure's frame. /// </summary> public uint FrameSize { get; set; } /// <summary> /// Gets or sets the size (in bytes) of the procedure's frame padding. /// </summary> public uint PaddingSize { get; set; } /// <summary> /// Gets or sets the offset relative to the frame pointer where the padding starts. /// </summary> public int PaddingOffset { get; set; } /// <summary> /// Gets or sets the size (in bytes) of the callee register saves storage. /// </summary> public uint CalleeSavesSize { get; set; } /// <summary> /// Gets or sets the offset to the exception handler (if available). /// </summary> public int ExceptionHandlerOffset { get; set; } /// <summary> /// Gets or sets the section index to the exception handler (if available). /// </summary> public ushort ExceptionHandlerSection { get; set; } /// <summary> /// Gets or sets the attributes associated to the procedure. /// </summary> public FrameProcedureAttributes Attributes { get; set; } /// <summary> /// Gets or sets the local base register pointer for the procedure. /// </summary> public byte LocalBasePointer { get => (byte) (((int) Attributes >> 14) & 0b11); set => Attributes = (Attributes & ~FrameProcedureAttributes.EncodedLocalBasePointerMask) | (FrameProcedureAttributes) ((value & 0b11) << 14); } /// <summary> /// Gets or sets the parameter base register pointer for the procedure. /// </summary> public byte ParameterBasePointer { get => (byte) (((int) Attributes >> 14) & 0b11); set => Attributes = (Attributes & ~FrameProcedureAttributes.EncodedParamBasePointerMask) | (FrameProcedureAttributes) ((value & 0b11) << 16); } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\PublicSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
PublicSymbolTest
['private readonly MockPdbFixture _fixture;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class PublicSymbolTest : IClassFixture<MockPdbFixture> { private readonly MockPdbFixture _fixture; public PublicSymbolTest(MockPdbFixture fixture) { _fixture = fixture; } [Fact] public void Name() { Assert.Equal("___enclave_config", _fixture.SimplePdb.Symbols.OfType<PublicSymbol>().First().Name); } }
128
500
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a public symbol stored in a PDB symbol stream. /// </summary> public class PublicSymbol : CodeViewSymbol { private readonly LazyVariable<PublicSymbol, Utf8String> _name; /// <summary> /// Initializes a new empty public symbol. /// </summary> protected PublicSymbol() { _name = new LazyVariable<PublicSymbol, Utf8String>(x => x.GetName()); } /// <summary> /// Creates a new public symbol. /// </summary> /// <param name="segmentIndex">The segment index.</param> /// <param name="offset">The offset within the segment the symbol starts at.</param> /// <param name="name">The name of the symbol.</param> /// <param name="attributes">The attributes associated to the symbol.</param> public PublicSymbol(ushort segmentIndex, uint offset, Utf8String name, PublicSymbolAttributes attributes) { SegmentIndex = segmentIndex; Offset = offset; _name = new LazyVariable<PublicSymbol, Utf8String>(name); Attributes = attributes; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.Pub32; /// <summary> /// Gets or sets the file segment index this symbol is located in. /// </summary> public ushort SegmentIndex { get; set; } /// <summary> /// Gets or sets the offset within the file that this symbol is defined at. /// </summary> public uint Offset { get; set; } /// <summary> /// Gets or sets attributes associated to the public symbol. /// </summary> public PublicSymbolAttributes Attributes { get; set; } /// <summary> /// Gets or sets a value indicating whether the symbol is a code symbol. /// </summary> public bool IsCode { get => (Attributes & PublicSymbolAttributes.Code) != 0; set => Attributes = (Attributes & ~PublicSymbolAttributes.Code) | (value ? PublicSymbolAttributes.Code : 0); } /// <summary> /// Gets or sets a value indicating whether the symbol is a function symbol. /// </summary> public bool IsFunction { get => (Attributes & PublicSymbolAttributes.Function) != 0; set => Attributes = (Attributes & ~PublicSymbolAttributes.Function) | (value ? PublicSymbolAttributes.Function : 0); } /// <summary> /// Gets or sets a value indicating whether the symbol involves managed code. /// </summary> public bool IsManaged { get => (Attributes & PublicSymbolAttributes.Managed) != 0; set => Attributes = (Attributes & ~PublicSymbolAttributes.Managed) | (value ? PublicSymbolAttributes.Managed : 0); } /// <summary> /// Gets or sets a value indicating whether the symbol involves MSIL code. /// </summary> public bool IsMsil { get => (Attributes & PublicSymbolAttributes.Msil) != 0; set => Attributes = (Attributes & ~PublicSymbolAttributes.Msil) | (value ? PublicSymbolAttributes.Msil : 0); } /// <summary> /// Gets or sets the name of the symbol. /// </summary> public Utf8String Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the name of the public symbol. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String GetName() => Utf8String.Empty; /// <inheritdoc /> public override string ToString() => $"S_PUB32: [{SegmentIndex:X4}:{Offset:X8}] {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\RegisterRangeSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
RegisterRangeSymbolTest
['private readonly RegisterRangeSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class RegisterRangeSymbolTest : IClassFixture<MockPdbFixture> { private readonly RegisterRangeSymbol _symbol; public RegisterRangeSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("gs_support.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<RegisterRangeSymbol>().First(); } [Fact] public void BasicProperties() { Assert.Equal(0x0001, _symbol.Range.SectionStart); Assert.Equal(0x000004E1u, _symbol.Range.Start); Assert.Equal(0x000004E8 - 0x000004E1u, _symbol.Range.Length); } [Fact] public void EmptyGaps() { Assert.Empty(_symbol.Gaps); } }
128
896
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Defines an address range in which a local variable or parameter is defined that is fully defined by a register. /// </summary> public class RegisterRangeSymbol : DefinitionRangeSymbol { /// <summary> /// Initializes an empty register range symbol. /// </summary> protected RegisterRangeSymbol() { } /// <summary> /// Creates a new register range symbol. /// </summary> /// <param name="register">The register.</param> /// <param name="range">The range in which the symbol is valid.</param> public RegisterRangeSymbol(ushort register, LocalAddressRange range) { Register = register; Range = range; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.DefRangeRegister; /// <summary> /// Gets or sets the register that defines the symbol. /// </summary> public ushort Register { get; set; } /// <summary> /// Gets or sets a value indicating whether the symbol may have no user name on one of the control flow paths /// within the function. /// </summary> public bool IsMaybe { get; set; } /// <inheritdoc /> public override string ToString() => $"S_DEFRANGE_REGISTER: {Range} (Gap Count: {Gaps.Count})"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\RegisterRelativeRangeSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
RegisterRelativeRangeSymbolTest
['private readonly RegisterRelativeRangeSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class RegisterRelativeRangeSymbolTest : IClassFixture<MockPdbFixture> { private readonly RegisterRelativeRangeSymbol _symbol; public RegisterRelativeRangeSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<RegisterRelativeRangeSymbol>() .First(); } [Fact] public void BasicProperties() { Assert.Equal(4, _symbol.Offset); Assert.Equal(0u, _symbol.Range.Start); Assert.Equal(1u, _symbol.Range.SectionStart); Assert.Equal(1u, _symbol.Range.Length); } [Fact] public void NoGaps() { Assert.Empty(_symbol.Gaps); } }
128
943
using System.Collections.Generic; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Defines an address range in which a local variable or parameter is defined that is fully defined by a register and /// a relative starting offset and length. /// </summary> public class RegisterRelativeRangeSymbol : DefinitionRangeSymbol { /// <summary> /// Initializes an empty relative register range. /// </summary> protected RegisterRelativeRangeSymbol() { } /// <summary> /// Creates a new range. /// </summary> /// <param name="baseRegister">The base register.</param> /// <param name="offset">The offset.</param> /// <param name="range">The address range this range is valid.</param> /// <param name="gaps">A collection of gaps within the range that the symbol is invalid.</param> public RegisterRelativeRangeSymbol(ushort baseRegister, int offset, LocalAddressRange range, IEnumerable<LocalAddressGap> gaps) : base(range, gaps) { BaseRegister = baseRegister; Offset = offset; } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.DefRangeRegisterRel; /// <summary> /// Gets or sets the base register holding the pointer of the symbol. /// </summary> public ushort BaseRegister { get; set; } /// <summary> /// Gets or sets a value indicating whether the symbol is spilled. /// </summary> public bool IsSpilledUdtMember { get; set; } /// <summary> /// Gets or sets the offset within the parent variable this symbol starts at. /// </summary> public int ParentOffset { get; set; } /// <summary> /// Gets or sets the offset from the base register this symbol is defined at. /// </summary> public int Offset { get; set; } /// <inheritdoc /> public override string ToString() => $"S_DEFRANGE_REGISTER_REL: {Range} (Gap Count: {Gaps.Count})"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\RegisterRelativeSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
RegisterRelativeSymbolTest
['private readonly RegisterRelativeSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class RegisterRelativeSymbolTest : IClassFixture<MockPdbFixture> { private readonly RegisterRelativeSymbol _symbol; public RegisterRelativeSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains("dllmain.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<RegisterRelativeSymbol>() .First(); } [Fact] public void Offset() { Assert.Equal(8, _symbol.Offset); } [Fact] public void Type() { Assert.IsAssignableFrom<PointerTypeRecord>(_symbol.VariableType); } [Fact] public void Name() { Assert.Equal("hModule", _symbol.Name); } }
167
939
namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Describes a variable symbol that is defined by a register and an offset relative to that register. /// </summary> public interface IRegisterRelativeSymbol : IVariableSymbol { /// <summary> /// Gets or sets the offset relative to the base register. /// </summary> public int Offset { get; set; } }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\RegisterSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
RegisterSymbolTest
['private readonly RegisterSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Leaves', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class RegisterSymbolTest : IClassFixture<MockPdbFixture> { private readonly RegisterSymbol _symbol; public RegisterSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name!.Contains(@"msvcrt.nativeproj_110336922\objr\x86\secchk.obj")) .Symbols.OfType<ProcedureSymbol>().First() .Symbols.OfType<RegisterSymbol>().First(); } [Fact] public void Name() { Assert.Equal("cookie", _symbol.Name); } [Fact] public void Type() { Assert.Equal(SimpleTypeKind.UInt32, Assert.IsAssignableFrom<SimpleTypeRecord>(_symbol.VariableType).Kind); } }
167
872
using AsmResolver.Symbols.Pdb.Leaves; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Represents a symbol describing a register variable in a function or method. /// </summary> public class RegisterSymbol : CodeViewSymbol, IVariableSymbol { private readonly LazyVariable<RegisterSymbol, CodeViewTypeRecord?> _variableType; private readonly LazyVariable<RegisterSymbol, Utf8String?> _name; /// <summary> /// Initializes an empty register variable symbol. /// </summary> protected RegisterSymbol() { _variableType = new LazyVariable<RegisterSymbol, CodeViewTypeRecord?>(x => x.GetVariableType()); _name = new LazyVariable<RegisterSymbol, Utf8String?>(x => x.GetName()); } /// <summary> /// Creates a new register variable symbol. /// </summary> /// <param name="name">The name of the variable.</param> /// <param name="variableType">The type of the variable.</param> /// <param name="register">The register that defines the variable.</param> public RegisterSymbol(Utf8String? name, CodeViewTypeRecord? variableType, ushort register) { Register = register; _variableType = new LazyVariable<RegisterSymbol, CodeViewTypeRecord?>(variableType); _name = new LazyVariable<RegisterSymbol, Utf8String?>(name); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.Register; /// <summary> /// Gets or sets the register that defines the variable. /// </summary> public ushort Register { get; set; } /// <inheritdoc /> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <inheritdoc /> public CodeViewTypeRecord? VariableType { get => _variableType.GetValue(this); set => _variableType.SetValue(value); } /// <summary> /// Obtains the type of the variable. /// </summary> /// <returns>The type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="VariableType"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetVariableType() => null; /// <summary> /// Obtains the name of the variable. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_REGISTER: {VariableType} {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\SectionSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
SectionSymbolTest
['private readonly SectionSymbol _symbol;']
['System.Linq', 'AsmResolver.PE.File', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class SectionSymbolTest : IClassFixture<MockPdbFixture> { private readonly SectionSymbol _symbol; public SectionSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name == "* Linker *") .Symbols.OfType<SectionSymbol>().First(); } [Fact] public void BasicProperties() { Assert.Equal(1, _symbol.SectionNumber); Assert.Equal(0x1000u, _symbol.Rva); Assert.Equal(0xCE8u, _symbol.Size); Assert.Equal(0x1000u, _symbol.Alignment); Assert.Equal( SectionFlags.MemoryRead | SectionFlags.MemoryExecute | SectionFlags.ContentCode, _symbol.Attributes); } [Fact] public void Name() { Assert.Equal(".text", _symbol.Name); } }
156
990
using AsmResolver.PE.File; namespace AsmResolver.Symbols.Pdb.Records; /// <summary> /// Provides information about a section within a PE file. /// </summary> public class SectionSymbol : CodeViewSymbol { private readonly LazyVariable<SectionSymbol, Utf8String?> _name; /// <summary> /// Initializes an empty section symbol. /// </summary> protected SectionSymbol() { _name = new LazyVariable<SectionSymbol, Utf8String?>(x => x.GetName()); } /// <summary> /// Creates a new section symbol. /// </summary> /// <param name="name">The name of the section.</param> public SectionSymbol(Utf8String name) { _name = new LazyVariable<SectionSymbol, Utf8String?>(name); } /// <inheritdoc /> public override CodeViewSymbolType CodeViewSymbolType => CodeViewSymbolType.Section; /// <summary> /// Gets or sets the section number within the PE file. /// </summary> public ushort SectionNumber { get; set; } /// <summary> /// Gets or sets the alignment of the section. /// </summary> /// <remarks> /// This should be a power of 2. /// </remarks> public uint Alignment { get; set; } /// <summary> /// Gets or sets the starting relative virtual address (RVA) of the section. /// </summary> public uint Rva { get; set; } /// <summary> /// Gets or sets the size in bytes of the section. /// </summary> public uint Size { get; set; } /// <summary> /// Gets or sets the section flags describing the nature of the section. /// </summary> public SectionFlags Attributes { get; set; } /// <summary> /// Gets or sets the name of the section. /// </summary> public Utf8String? Name { get => _name.GetValue(this); set => _name.SetValue(value); } /// <summary> /// Obtains the name of the section. /// </summary> /// <returns>The name.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Name"/> property. /// </remarks> protected virtual Utf8String? GetName() => null; /// <inheritdoc /> public override string ToString() => $"S_SECTION: [{SectionNumber:X4}] {Name}"; }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\AsmResolver.Symbols.Pdb.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.Symbols.Pdb.Tests\Records\ThunkSymbolTest.cs
AsmResolver.Symbols.Pdb.Tests.Records
ThunkSymbolTest
['private readonly ThunkSymbol _symbol;']
['System.Linq', 'AsmResolver.Symbols.Pdb.Records', 'Xunit']
xUnit
net8.0
public class ThunkSymbolTest : IClassFixture<MockPdbFixture> { private readonly ThunkSymbol _symbol; public ThunkSymbolTest(MockPdbFixture fixture) { _symbol = fixture.SimplePdb .Modules.First(m => m.Name == "Import:VCRUNTIME140.dll") .Symbols.OfType<ThunkSymbol>() .First(); } [Fact] public void BasicProperties() { Assert.Equal(1, _symbol.SegmentIndex); Assert.Equal(0xC28u, _symbol.Offset); Assert.Equal(6u, _symbol.Size); } [Fact] public void Name() { Assert.Equal("__std_type_info_destroy_list", _symbol.Name); } [Fact] public void EmptyChildren() { Assert.Empty(_symbol.Symbols); } }
128
900
using AsmResolver.IO; namespace AsmResolver.Symbols.Pdb.Records.Serialized; /// <summary> /// Represents a lazily initialized implementation of <see cref="ThunkSymbol"/> that is read from a PDB image. /// </summary> public class SerializedThunkSymbol : ThunkSymbol { private readonly PdbReaderContext _context; private readonly BinaryStreamReader _nameReader; /// <summary> /// Reads a thunk symbol from the provided input stream. /// </summary> /// <param name="context">The reading context in which the symbol is situated in.</param> /// <param name="reader">The input stream to read from.</param> public SerializedThunkSymbol(PdbReaderContext context, BinaryStreamReader reader) { _context = context; _ = reader.ReadUInt32(); // pParent _ = reader.ReadUInt32(); // pEnd _ = reader.ReadUInt32(); // pNext Offset = reader.ReadUInt32(); SegmentIndex = reader.ReadUInt16(); Size = reader.ReadUInt16(); Ordinal = (ThunkOrdinal) reader.ReadByte(); _nameReader = reader; } /// <inheritdoc /> protected override Utf8String GetName() => _nameReader.Fork().ReadUtf8String(); }
Washi1337
AsmResolver
F:\Projects\TestMap\Temp\AsmResolver\AsmResolver.sln
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Dynamic.Tests\AsmResolver.DotNet.Dynamic.Tests.csproj
F:\Projects\TestMap\Temp\AsmResolver\test\AsmResolver.DotNet.Dynamic.Tests\DynamicMethodDefinitionTest.cs
AsmResolver.DotNet.Dynamic.Tests
DynamicMethodDefinitionTest
[]
['System', 'System.IO', 'System.Linq', 'System.Reflection', 'System.Reflection.Emit', 'AsmResolver.DotNet.Code.Cil', 'AsmResolver.DotNet.Signatures', 'AsmResolver.DotNet.TestCases.Generics', 'AsmResolver.DotNet.TestCases.Methods', 'AsmResolver.IO', 'AsmResolver.PE.DotNet.Cil', 'AsmResolver.PE.DotNet.Metadata.Tables', 'Xunit']
xUnit
net8.0
public class DynamicMethodDefinitionTest { [Fact] public void ReadDynamicMethod() { var module = ModuleDefinition.FromFile(typeof(TDynamicMethod).Assembly.Location); var generatedDynamicMethod = TDynamicMethod.GenerateDynamicMethod(); var dynamicMethodDef = new DynamicMethodDefinition(module, generatedDynamicMethod); Assert.NotNull(dynamicMethodDef); Assert.NotEmpty(dynamicMethodDef.CilMethodBody!.Instructions); Assert.Equal(new[] { CilCode.Ldarg_0, CilCode.Stloc_0, CilCode.Ldloc_0, CilCode.Call, CilCode.Ldarg_1, CilCode.Ret }, dynamicMethodDef.CilMethodBody.Instructions.Select(q => q.OpCode.Code)); Assert.Equal(new TypeSignature[] { module.CorLibTypeFactory.String, module.CorLibTypeFactory.Int32 }, dynamicMethodDef.Parameters.Select(q => q.ParameterType)); Assert.Equal(new TypeSignature[] { module.CorLibTypeFactory.String, }, dynamicMethodDef.CilMethodBody.LocalVariables.Select(v => v.VariableType)); } [Fact] public void RtDynamicMethod() { var module = ModuleDefinition.FromFile(typeof(TDynamicMethod).Assembly.Location); var generatedDynamicMethod = TDynamicMethod.GenerateDynamicMethod(); object rtDynamicMethod = generatedDynamicMethod .GetType() .GetField("m_dynMethod", (BindingFlags) (-1))? .GetValue(generatedDynamicMethod) ?? generatedDynamicMethod; var dynamicMethod = new DynamicMethodDefinition(module, rtDynamicMethod!); Assert.NotNull(dynamicMethod); Assert.NotEmpty(dynamicMethod.CilMethodBody!.Instructions); Assert.Equal(new[] { CilCode.Ldarg_0, CilCode.Stloc_0, CilCode.Ldloc_0, CilCode.Call, CilCode.Ldarg_1, CilCode.Ret }, dynamicMethod.CilMethodBody.Instructions.Select(q => q.OpCode.Code)); Assert.Equal(new TypeSignature[] { module.CorLibTypeFactory.String, module.CorLibTypeFactory.Int32 }, dynamicMethod.Parameters.Select(q => q.ParameterType)); Assert.Equal(new TypeSignature[] { module.CorLibTypeFactory.String, }, dynamicMethod.CilMethodBody.LocalVariables.Select(v => v.VariableType)); } [Fact] public void ReadDynamicMethodInitializedByDynamicILInfo() { var method = new DynamicMethod("Test", typeof(void), Type.EmptyTypes); var info = method.GetDynamicILInfo(); info.SetLocalSignature(new byte[] { 0x7, 0x0 }); info.SetCode(new byte[] {0x2a}, 1); var contextModule = ModuleDefinition.FromFile(typeof(DynamicMethodDefinitionTest).Assembly.Location); var definition = new DynamicMethodDefinition(contextModule, method); Assert.NotNull(definition.CilMethodBody); var instruction = Assert.Single(definition.CilMethodBody.Instructions); Assert.Equal(CilOpCodes.Ret, instruction.OpCode); } [Fact] public void ImportNestedType() { // https://github.com/Washi1337/AsmResolver/issues/363 var method = new DynamicMethod("Test", typeof(void), Type.EmptyTypes); var cil = method.GetILGenerator(); cil.Emit(OpCodes.Call, typeof(NestedClass).GetMethod(nameof(NestedClass.TestMethod))!); cil.Emit(OpCodes.Ret); var contextModule = ModuleDefinition.FromFile(typeof(DynamicMethodDefinitionTest).Assembly.Location); var definition = new DynamicMethodDefinition(contextModule, method); Assert.NotNull(definition.CilMethodBody); var reference = Assert.IsAssignableFrom<IMethodDescriptor>(definition.CilMethodBody.Instructions[0].Operand); var declaringType = reference.DeclaringType; Assert.NotNull(declaringType); Assert.Equal(nameof(NestedClass), declaringType.Name); Assert.NotNull(declaringType.DeclaringType); Assert.Equal(nameof(DynamicMethodDefinitionTest), declaringType.DeclaringType.Name); } [Fact] public void ImportGenericTypeInstantiation() { var method = new DynamicMethod("Test", typeof(void), Type.EmptyTypes); var cil = method.GetILGenerator(); cil.Emit(OpCodes.Call, typeof(GenericType<int, string, Stream>) .GetMethod(nameof(GenericType<int, string, Stream>.NonGenericMethodInGenericType))!); cil.Emit(OpCodes.Ret); var contextModule = ModuleDefinition.FromFile(typeof(DynamicMethodDefinitionTest).Assembly.Location); var definition = new DynamicMethodDefinition(contextModule, method); Assert.NotNull(definition.CilMethodBody); var instruction = definition.CilMethodBody.Instructions[0]; Assert.Equal(CilOpCodes.Call, instruction.OpCode); var operand = Assert.IsAssignableFrom<IMethodDescriptor>(instruction.Operand); var type = Assert.IsAssignableFrom<TypeSpecification>(operand.DeclaringType); var signature = Assert.IsAssignableFrom<GenericInstanceTypeSignature>(type.Signature); Assert.Equal("Int32", signature.TypeArguments[0].Name); Assert.Equal("String", signature.TypeArguments[1].Name); Assert.Equal("Stream", signature.TypeArguments[2].Name); } [Fact] public void ImportGenericMethodInstantiation() { var method = new DynamicMethod("Test", typeof(void), Type.EmptyTypes); var cil = method.GetILGenerator(); cil.Emit(OpCodes.Call, typeof(NonGenericType) .GetMethod(nameof(NonGenericType.GenericMethodInNonGenericType))! .MakeGenericMethod(typeof(int), typeof(string), typeof(Stream))); cil.Emit(OpCodes.Ret); var contextModule = ModuleDefinition.FromFile(typeof(DynamicMethodDefinitionTest).Assembly.Location); var definition = new DynamicMethodDefinition(contextModule, method); Assert.NotNull(definition.CilMethodBody); var instruction = definition.CilMethodBody.Instructions[0]; Assert.Equal(CilOpCodes.Call, instruction.OpCode); var operand = Assert.IsAssignableFrom<MethodSpecification>(instruction.Operand); Assert.Equal(nameof(NonGenericType.GenericMethodInNonGenericType), operand.Name); Assert.NotNull(operand.Signature); Assert.Equal(3, operand.Method!.Signature!.GenericParameterCount); Assert.Equal("Int32", operand.Signature.TypeArguments[0].Name); Assert.Equal("String", operand.Signature.TypeArguments[1].Name); Assert.Equal("Stream", operand.Signature.TypeArguments[2].Name); } [Fact] public void ReadDynamicMethodInitializedByDynamicILInfoWithTokens() { // Create new dynamic method. var method = new DynamicMethod("Test", typeof(void), Type.EmptyTypes); var info = method.GetDynamicILInfo(); info.SetLocalSignature(new byte[] { 0x7, 0x0 }); // Write some IL. using var codeStream = new MemoryStream(); var assembler = new CilAssembler( new BinaryStreamWriter(codeStream), new CilOperandBuilder(new OriginalMetadataTokenProvider(null), EmptyErrorListener.Instance)); uint token = (uint)info.GetTokenFor(typeof(Console).GetMethod("WriteLine", Type.EmptyTypes).MethodHandle); assembler.WriteInstruction(new CilInstruction(CilOpCodes.Call, new MetadataToken(token))); assembler.WriteInstruction(new CilInstruction(CilOpCodes.Ret)); // Set code. info.SetCode(codeStream.ToArray(), 1); // Pass into DynamicMethodDefinition var contextModule = ModuleDefinition.FromFile(typeof(DynamicMethodDefinitionTest).Assembly.Location); var definition = new DynamicMethodDefinition(contextModule, method); // Verify Assert.NotNull(definition.CilMethodBody); var instruction = definition.CilMethodBody.Instructions[0]; Assert.Equal(CilOpCodes.Call, instruction.OpCode); var reference = Assert.IsAssignableFrom<IMethodDescriptor>(instruction.Operand); Assert.Equal("WriteLine", reference.Name); } [SkippableFact] public void ReadDynamicMethodInitializedByDynamicILInfoWithLocals() { Skip.IfNot(DynamicTypeSignatureResolver.IsSupported, "Current platform does not support dynamic type resolution."); // Create new dynamic method. var method = new DynamicMethod("Test", typeof(void), Type.EmptyTypes); var info = method.GetDynamicILInfo(); var helper = SignatureHelper.GetLocalVarSigHelper(); helper.AddArgument(typeof(int)); helper.AddArgument(typeof(bool)); helper.AddArgument(typeof(Stream)); helper.AddArgument(typeof(Stream[])); info.SetLocalSignature(helper.GetSignature()); // Write some IL. info.SetCode(new byte[] {0x2a}, 1); // Pass into DynamicMethodDefinition var contextModule = ModuleDefinition.FromFile(typeof(DynamicMethodDefinitionTest).Assembly.Location); var definition = new DynamicMethodDefinition(contextModule, method); // Verify Assert.NotNull(definition.CilMethodBody); var locals = definition.CilMethodBody.LocalVariables; Assert.Equal(4, locals.Count); Assert.Equal("Int32", locals[0].VariableType.Name); Assert.Equal("Boolean", locals[1].VariableType.Name); Assert.Equal("Stream", locals[2].VariableType.Name); Assert.Equal("Stream", Assert.IsAssignableFrom<SzArrayTypeSignature>(locals[3].VariableType).BaseType.Name); } internal static class NestedClass { public static void TestMethod() => Console.WriteLine("TestMethod"); } }
445
11,243
using System; using System.Collections.Generic; using System.Reflection; using AsmResolver.DotNet.Code.Cil; using AsmResolver.DotNet.Serialized; using AsmResolver.DotNet.Signatures; using AsmResolver.IO; using AsmResolver.PE.DotNet.Cil; using AsmResolver.PE.DotNet.Metadata.Tables; using MethodAttributes = AsmResolver.PE.DotNet.Metadata.Tables.MethodAttributes; namespace AsmResolver.DotNet.Dynamic { /// <summary> /// Represents a single method in a type definition of a .NET module. /// </summary> public class DynamicMethodDefinition : MethodDefinition { /// <summary> /// Create a Dynamic Method Definition /// </summary> /// <param name="module">Target Module</param> /// <param name="dynamicMethodObj">Dynamic Method / Delegate / DynamicResolver</param> public DynamicMethodDefinition(ModuleDefinition module, object dynamicMethodObj) : base(new MetadataToken(TableIndex.Method, 0)) { object resolver = DynamicMethodHelper.ResolveDynamicResolver(dynamicMethodObj); var methodBase = FieldReader.ReadField<MethodBase>(resolver, "m_method"); if (methodBase is null) { throw new ArgumentException( "Could not get the underlying method base in the provided dynamic method object."); } Module = module; Name = methodBase.Name; Attributes = (MethodAttributes)methodBase.Attributes; Signature = module.DefaultImporter.ImportMethodSignature(ResolveSig(methodBase, module)); CilMethodBody = CreateDynamicMethodBody(this, resolver); } /// <summary> /// Determines whether dynamic method reading is fully supported in the current host's .NET environment. /// </summary> public static bool IsSupported => DynamicTypeSignatureResolver.IsSupported; /// <inheritdoc /> public override ModuleDefinition Module { get; } private MethodSignature ResolveSig(MethodBase methodBase, ModuleDefinition module) { var importer = module.DefaultImporter; var returnType = methodBase is MethodInfo info ? importer.ImportTypeSignature(info.ReturnType) : module.CorLibTypeFactory.Void; var parameters = methodBase.GetParameters(); var parameterTypes = new TypeSignature[parameters.Length]; for (int i = 0; i < parameterTypes.Length; i++) parameterTypes[i] = importer.ImportTypeSignature(parameters[i].ParameterType); return new MethodSignature( methodBase.IsStatic ? 0 : CallingConventionAttributes.HasThis, returnType, parameterTypes); } /// <summary> /// Creates a CIL method body from a dynamic method. /// </summary> /// <param name="method">The method that owns the method body.</param> /// <param name="dynamicMethodObj">The Dynamic Method/Delegate/DynamicResolver.</param> /// <returns>The method body.</returns> private static CilMethodBody CreateDynamicMethodBody(MethodDefinition method, object dynamicMethodObj) { if (method.Module is not SerializedModuleDefinition module) throw new ArgumentException("Method body should reference a serialized module."); var result = new CilMethodBody(method); object resolver = DynamicMethodHelper.ResolveDynamicResolver(dynamicMethodObj); // We prefer to extract the information from DynamicILInfo if it is there, as it has more accurate info // if the DynamicMethod code is not flushed yet into the resolver (e.g., it hasn't been invoked yet). object? dynamicILInfo = null; if (FieldReader.TryReadField<MethodBase>(resolver, "m_method", out var m) && m is not null) { if (!FieldReader.TryReadField(m, "m_DynamicILInfo", out dynamicILInfo)) FieldReader.TryReadField(m, "_dynamicILInfo", out dynamicILInfo); } // Extract all required information to construct the body. byte[]? code; object scope; List<object?> tokenList; byte[]? localSig; byte[]? ehHeader; IList<object>? ehInfos; if (resolver.GetType().FullName != "System.Reflection.Emit.DynamicILInfo" && dynamicILInfo is not null) { code = FieldReader.ReadField<byte[]>(dynamicILInfo, "m_code"); scope = FieldReader.ReadField<object>(dynamicILInfo, "m_scope")!; tokenList = FieldReader.ReadField<List<object?>>(scope, "m_tokens")!; localSig = FieldReader.ReadField<byte[]>(dynamicILInfo, "m_localSignature"); ehHeader = FieldReader.ReadField<byte[]>(dynamicILInfo, "m_exceptions"); // DynamicILInfo does not have EH info. Try recover it from the resolver. ehInfos = FieldReader.ReadField<IList<object>>(resolver, "m_exceptions"); } else { code = FieldReader.ReadField<byte[]>(resolver, "m_code"); scope = FieldReader.ReadField<object>(resolver, "m_scope")!; tokenList = FieldReader.ReadField<List<object?>>(scope, "m_tokens")!; localSig = FieldReader.ReadField<byte[]>(resolver, "m_localSignature"); ehHeader = FieldReader.ReadField<byte[]>(resolver, "m_exceptionHeader"); ehInfos = FieldReader.ReadField<IList<object>>(resolver, "m_exceptions"); } // Interpret local variables signatures. if (localSig is not null) DynamicMethodHelper.ReadLocalVariables(result, method, localSig); // Read raw instructions. if (code is not null) { var reader = new BinaryStreamReader(code); var operandResolver = new DynamicCilOperandResolver(module, result, tokenList); var disassembler = new CilDisassembler(reader, operandResolver); result.Instructions.AddRange(disassembler.ReadInstructions()); } // Interpret exception handler information or header. DynamicMethodHelper.ReadReflectionExceptionHandlers(result, ehHeader, ehInfos, module.DefaultImporter); return result; } } }
YAXLib
YAXLib
F:\Projects\TestMap\Temp\YAXLib\YAXLib.sln
F:\Projects\TestMap\Temp\YAXLib\YAXLibTests\YAXLibTests.csproj
F:\Projects\TestMap\Temp\YAXLib\YAXLibTests\ReflectionUtilsTest.cs
YAXLibTests
ReflectionUtilsTest
[]
['System', 'System.Collections', 'System.Collections.Generic', 'NUnit.Framework', 'YAXLib', 'YAXLibTests.SampleClasses']
NUnit
net461;netcoreapp3.1;net6.0
[TestFixture] public class ReflectionUtilsTest { [Test] public void IsArrayTest() { Assert.Multiple(() => { Assert.That(ReflectionUtils.IsArray(typeof(int[])), Is.True); Assert.That(ReflectionUtils.IsArray(typeof(int[,])), Is.True); Assert.That(ReflectionUtils.IsArray(typeof(Array)), Is.True); Assert.That(ReflectionUtils.IsArray(typeof(List<int>)), Is.False); Assert.That(ReflectionUtils.IsArray(typeof(List<>)), Is.False); Assert.That(ReflectionUtils.IsArray(typeof(Dictionary<,>)), Is.False); Assert.That(ReflectionUtils.IsArray(typeof(Dictionary<int, string>)), Is.False); Assert.That(ReflectionUtils.IsArray(typeof(string)), Is.False); }); } [Test] public void IsCollectionTypeTest() { Assert.Multiple(() => { Assert.That(ReflectionUtils.IsCollectionType(typeof(int[])), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(Array)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(List<int>)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(List<>)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(Dictionary<,>)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(Dictionary<int, string>)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(IEnumerable)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(IEnumerable<>)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(IEnumerable<int>)), Is.True); Assert.That(ReflectionUtils.IsCollectionType(typeof(string)), Is.False); }); } [Test] public void GetCollectionItemTypeTest() { Assert.Multiple(() => { Assert.That(ReflectionUtils.GetCollectionItemType(typeof(IEnumerable<int>)), Is.EqualTo(typeof(int))); Assert.That(ReflectionUtils.GetCollectionItemType(typeof(double[])), Is.EqualTo(typeof(double))); Assert.That(ReflectionUtils.GetCollectionItemType(typeof(float[][])), Is.EqualTo(typeof(float[]))); Assert.That(ReflectionUtils.GetCollectionItemType(typeof(string[,])), Is.EqualTo(typeof(string))); Assert.That(ReflectionUtils.GetCollectionItemType(typeof(List<char>)), Is.EqualTo(typeof(char))); Assert.That( ReflectionUtils.GetCollectionItemType(typeof(Dictionary<int, char>)), Is.EqualTo(typeof(KeyValuePair<int, char>))); Assert.That( ReflectionUtils.GetCollectionItemType(typeof(Dictionary<Dictionary<int, double>, char>)), Is.EqualTo(typeof(KeyValuePair<Dictionary<int, double>, char>))); }); //Assert.That(ReflectionUtils.GetCollectionItemType(typeof(IEnumerable<>)) == typeof(object), Is.True); } [Test] public void IsTypeEqualOrInheritedFromTypeTest() { Assert.Multiple(() => { Assert.That(ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(int), typeof(object)), Is.True); Assert.That(ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(string), typeof(object)), Is.True); Assert.That(ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Array), typeof(IEnumerable)), Is.True); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int>), typeof(Dictionary<,>)), Is.True); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int>), typeof(ICollection)), Is.True); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int>), typeof(IDictionary)), Is.True); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int>), typeof(IDictionary<,>)), Is.True); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int>), typeof(IDictionary<string, int>)), Is.True); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int>), typeof(IDictionary<int, string>)), Is.False); Assert.That( ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(Dictionary<string, int[]>), typeof(IDictionary<int, Array>)), Is.False); Assert.That(ReflectionUtils.IsTypeEqualOrInheritedFromType(typeof(ICollection), typeof(IEnumerable)), Is.True); }); } [Test] public void EqualsOrIsNullableOfTest() { Assert.Multiple(() => { Assert.That(typeof(int).EqualsOrIsNullableOf(typeof(int)), Is.True); Assert.That(typeof(int?).EqualsOrIsNullableOf(typeof(int)), Is.True); Assert.That(typeof(int).EqualsOrIsNullableOf(typeof(int?)), Is.True); Assert.That(typeof(double).EqualsOrIsNullableOf(typeof(double?)), Is.True); Assert.That(typeof(double?).EqualsOrIsNullableOf(typeof(Nullable<>)), Is.False); Assert.That(typeof(double?).EqualsOrIsNullableOf(typeof(double)), Is.True); Assert.That(typeof(char?).EqualsOrIsNullableOf(typeof(char?)), Is.True); }); Assert.Multiple(() => { Assert.That(typeof(char?).EqualsOrIsNullableOf(typeof(char?)), Is.True); Assert.That(typeof(int[]).EqualsOrIsNullableOf(typeof(Array)), Is.False); }); } #if NETFRAMEWORK [TestCase("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] // NETFRAMEWORK2.x [TestCase("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] // NETFRAMEWORK4.x #elif NETCOREAPP3_1 [TestCase("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] // NETSTANDARD #else [TestCase("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] // NETSTANDARD [TestCase("System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e")] // NET5.0 #endif public void GetTypeByNameTest(string coreLibName) { var type1 = ReflectionUtils.GetTypeByName( $"System.Collections.Generic.List`1[[System.Int32, {coreLibName}]]"); var type2 = ReflectionUtils.GetTypeByName("System.Collections.Generic.List`1[[System.Int32]]"); Assert.Multiple(() => { Assert.That(type1, Is.Not.Null); Assert.That(type2, Is.Not.Null); }); Assert.That(type2, Is.EqualTo(type1)); } [Test] public void GetSetFieldValues() { // The test includes private fields from base types var subClass = new ClassFlaggedToIncludePrivateBaseTypeFields(); // Initial values var subClassField = ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromLevel0"); var baseClassField1 = ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromBaseLevel1"); var baseClassField2 = ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromBaseLevel2"); // Change initial values ReflectionUtils.SetFieldValue(subClass, "_privateFieldFromLevel0", 3); ReflectionUtils.SetFieldValue(subClass, "_privateFieldFromBaseLevel1", 13); ReflectionUtils.SetFieldValue(subClass, "_privateFieldFromBaseLevel2", 23); // Get changed values var subClassFieldAfterSet = ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromLevel0"); var baseClassField1AfterSet = ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromBaseLevel1"); var baseClassField2AfterSet = ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromBaseLevel2"); Assert.Multiple(() => { // Initial values Assert.That(subClassField, Is.EqualTo(2)); Assert.That(baseClassField1, Is.EqualTo(12)); Assert.That(baseClassField2, Is.EqualTo(22)); Assert.That( // private base field not found code: () => { ReflectionUtils.GetFieldValue(subClass, "_privateFieldFromBaseLevel1", false); }, Throws.Exception); }); Assert.Multiple(() => { // Changed values Assert.That(subClassFieldAfterSet, Is.EqualTo(3)); Assert.That(baseClassField1AfterSet, Is.EqualTo(13)); Assert.That(baseClassField2AfterSet, Is.EqualTo(23)); }); } [Test] public void GetSetPropertyValues() { // The test includes private properties from base types var subClass = new ClassFlaggedToIncludePrivateBaseTypeFields(); // Initial values var subClassProperty = ReflectionUtils.GetPropertyValue(subClass, "PublicPropertyFromLevel0"); var baseClassProperty1 = ReflectionUtils.GetPropertyValue(subClass, "PrivatePropertyFromBaseLevel1"); var baseClassProperty2 = ReflectionUtils.GetPropertyValue(subClass, "PrivatePropertyFromBaseLevel2"); // Change initial values ReflectionUtils.SetPropertyValue(subClass, "PublicPropertyFromLevel0", 111); ReflectionUtils.SetPropertyValue(subClass, "PrivatePropertyFromBaseLevel1", 113); ReflectionUtils.SetPropertyValue(subClass, "PrivatePropertyFromBaseLevel2", 123); // Get changed values var subClassPropertyAfterSet = ReflectionUtils.GetPropertyValue(subClass, "PublicPropertyFromLevel0"); var baseClassProperty1AfterSet = ReflectionUtils.GetPropertyValue(subClass, "PrivatePropertyFromBaseLevel1"); var baseClassProperty2AfterSet = ReflectionUtils.GetPropertyValue(subClass, "PrivatePropertyFromBaseLevel2"); Assert.Multiple(() => { // Initial values Assert.That(subClassProperty, Is.EqualTo(1)); Assert.That(baseClassProperty1, Is.EqualTo(13)); Assert.That(baseClassProperty2, Is.EqualTo(23)); Assert.That( // private base property not found code: () => { ReflectionUtils.GetPropertyValue(subClass, "PrivatePropertyFromBaseLevel1", false); }, Throws.Exception); }); Assert.Multiple(() => { // Changed values Assert.That(subClassPropertyAfterSet, Is.EqualTo(111)); Assert.That(baseClassProperty1AfterSet, Is.EqualTo(113)); Assert.That(baseClassProperty2AfterSet, Is.EqualTo(123)); }); } [Test] public void GetDefaultValueTest() { Assert.Multiple(() => { Assert.That(ReflectionUtils.GetDefaultValue(typeof(string)), Is.EqualTo(null)); Assert.That(ReflectionUtils.GetDefaultValue(typeof(bool)), Is.EqualTo(default(bool))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(char)), Is.EqualTo(default(char))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(sbyte)), Is.EqualTo(default(sbyte))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(byte)), Is.EqualTo(default(byte))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(short)), Is.EqualTo(default(short))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(ushort)), Is.EqualTo(default(ushort))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(int)), Is.EqualTo(default(int))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(uint)), Is.EqualTo(default(uint))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(long)), Is.EqualTo(default(long))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(ulong)), Is.EqualTo(default(ulong))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(float)), Is.EqualTo(default(float))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(double)), Is.EqualTo(default(double))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(decimal)), Is.EqualTo(default(decimal))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(DateTime)), Is.EqualTo(default(DateTime))); Assert.That(ReflectionUtils.GetDefaultValue(typeof(DBNull)), Is.EqualTo(DBNull.Value)); }); } }
304
13,085
// Copyright (C) Sina Iravanian, Julian Verdurmen, axuno gGmbH and other contributors. // Licensed under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Numerics; using System.Reflection; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using YAXLib.Caching; using YAXLib.Options; using YAXLib.Pooling.SpecializedPools; namespace YAXLib; /// <summary> /// A utility class for reflection related stuff /// </summary> internal static class ReflectionUtils { private static readonly SerializerOptions DefaultSerializerOptions = new(); /// <summary> /// Determines whether the specified type is basic type. A basic type is one that can be wholly expressed /// as an XML attribute. All primitive data types and type <c>string</c> and <c>DataTime</c> are basic. /// </summary> /// <param name="t">The type to check.</param> /// <returns> /// <value><c>true</c> if the specified type is a basic type; otherwise, <c>false</c>.</value> /// </returns> public static bool IsBasicType(Type t) { if (t == typeof(string) || t.IsPrimitive || t.IsEnum || t == typeof(DateTime) || t == typeof(decimal) || t == typeof(Guid)) return true; if (IsNullable(t, out var nullableValueType) && nullableValueType != null) return IsBasicType(nullableValueType); return false; } /// <summary> /// Determines whether the specified type is array. /// </summary> /// <param name="type">The type to check</param> /// <param name="elementType">Type of the containing element.</param> /// <returns> /// <value><c>true</c> if the specified type is array; otherwise, <c>false</c>.</value> /// </returns> public static bool IsArray(Type type, out Type elementType) { if (type.IsArray) { elementType = type.GetElementType()!; return true; } if (type == typeof(Array)) // i.e., a direct ref to System.Array { elementType = typeof(object); return true; } elementType = typeof(object); return false; } /// <summary> /// Determines whether the specified type is array. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <c>true</c> if the specified type is array; otherwise, <c>false</c>. /// </returns> public static bool IsArray(Type type) { return IsArray(type, out _); } /// <summary> /// Gets the array dimensions. /// </summary> /// <param name="ar">The array to return its dimensions.</param> /// <returns>the specified array's dimensions</returns> public static int[] GetArrayDimensions(object ar) { var dims = Array.Empty<int>(); if (IsArray(ar.GetType()) && ar is Array arObj) { dims = new int[arObj.Rank]; for (var i = 0; i < dims.Length; i++) dims[i] = arObj.GetLength(i); } return dims; } /// <summary> /// Gets the friendly name for the type. Recommended for generic types. /// </summary> /// <param name="type">The type to get its friendly name</param> /// <returns>The friendly name for the type</returns> public static string GetTypeFriendlyName(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); var name = type.Name; if (type.IsGenericType) { var backTickIndex = name.IndexOf('`'); name = backTickIndex switch { 0 => throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Bad type name: {0}", name)), > 0 => name.Substring(0, backTickIndex), _ => name }; using var poolObject = StringBuilderPool.Instance.Get(out var sb); sb.Append(name); sb.Append("Of"); foreach (var genType in type.GetGenericArguments()) sb.Append(GetTypeFriendlyName(genType)); name = sb.ToString(); } else if (type.IsArray) { var t = type.GetElementType()!; name = string.Format(CultureInfo.InvariantCulture, "Array{0}Of{1}", type.GetArrayRank(), GetTypeFriendlyName(t)); } return name; } /// <summary> /// Determines whether the type specified contains generic parameters or not. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <value><c>true</c> if the type contains generic parameters; otherwise,<c>false</c>.</value> /// </returns> public static bool TypeContainsGenericParameters(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); if (type.IsGenericType) foreach (var genType in type.GetGenericArguments()) if (genType.IsGenericParameter) return true; else if (TypeContainsGenericParameters(genType)) return true; return false; } /// <summary> /// Determines whether the specified type is a collection type, i.e., it implements IEnumerable. /// Although System.String is derived from IEnumerable, it is considered as an exception. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <value><c>true</c> if the specified type is a collection type; otherwise, <c>false</c>.</value> /// </returns> public static bool IsCollectionType(Type type) { if (type == typeof(string)) return false; return IsIEnumerable(type); } public static bool IsDerivedFromGenericInterfaceType(Type givenType, Type genericInterfaceType, out Type? genericType) { genericType = null; if ((givenType.IsClass || givenType.IsValueType) && !givenType.IsAbstract) foreach (var interfaceType in givenType.GetInterfaces()) if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == genericInterfaceType) { var genArgs = interfaceType.GetGenericArguments(); if (genArgs.Length != 1) return false; genericType = genArgs[0]; return true; } return false; } /// <summary> /// Determines whether the specified type has implemented or is an <c>IEnumerable</c> or <c>IEnumerable&lt;&gt;</c> /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <value><c>true</c> if the specified type is enumerable; otherwise, <c>false</c>.</value> /// </returns> public static bool IsIEnumerable(Type type) { return IsIEnumerable(type, out _); } /// <summary> /// Determines whether the specified type has implemented or is an <c>IEnumerable</c> or <c>IEnumerable&lt;&gt;</c> . /// </summary> /// <param name="type">The type to check.</param> /// <param name="seqType">Type of the sequence items.</param> /// <returns> /// <value><c>true</c> if the specified type is enumerable; otherwise, <c>false</c>.</value> /// </returns> public static bool IsIEnumerable(Type type, out Type seqType) { // detect arrays early if (IsArray(type, out seqType)) return true; seqType = typeof(object); if (type == typeof(IEnumerable)) return true; var isNonGenericEnumerable = false; if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { seqType = type.GetGenericArguments()[0]; return true; } foreach (var interfaceType in type.GetInterfaces()) if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { var genArgs = interfaceType.GetGenericArguments(); seqType = genArgs[0]; return true; } else if (interfaceType == typeof(IEnumerable)) { isNonGenericEnumerable = true; } // the second case is a direct reference to IEnumerable if (isNonGenericEnumerable || type == typeof(IEnumerable)) { seqType = typeof(object); return true; } return false; } /// <summary> /// Gets the type of the items of a collection type. /// </summary> /// <param name="type">The type of the collection.</param> /// <returns>The type of the items of a collection type.</returns> public static Type GetCollectionItemType(Type type) { if (IsIEnumerable(type, out var itemType)) return itemType; throw new ArgumentException("The specified type must be a collection", nameof(type)); } /// <summary> /// Determines whether the specified type has implemented <c>IList</c>. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <value><c>true</c> if the specified type has implemented <c>IList</c>; otherwise, <c>false</c>.</value> /// </returns> public static bool IsIList(Type type) { // a direct reference to the interface itself is also OK. if (type.IsInterface && type.GetGenericTypeDefinition() == typeof(IList<>)) return true; foreach (var interfaceType in type.GetInterfaces()) if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>)) return true; return false; } /// <summary> /// Determines whether the specified type has implemented the <c>ICollection</c> interface. /// </summary> /// <param name="type">The type to check.</param> /// <param name="itemType">Type of the member items.</param> /// <returns> /// <value><c>true</c> if the specified type has implemented the <c>ICollection</c> interface; otherwise, <c>false</c>.</value> /// </returns> public static bool IsICollection(Type type, out Type itemType) { itemType = typeof(object); // a direct reference to the interface itself is also OK. if (type.IsInterface && type.GetGenericTypeDefinition() == typeof(ICollection<>)) { itemType = type.GetGenericArguments()[0]; return true; } foreach (var interfaceType in type.GetInterfaces()) if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>)) { itemType = interfaceType.GetGenericArguments()[0]; return true; } return false; } /// <summary> /// Determines whether the specified type is a generic dictionary. /// </summary> /// <param name="type">The type to check.</param> /// <param name="keyType">Type of the key.</param> /// <param name="valueType">Type of the value.</param> /// <returns> /// <value><c>true</c> if the specified type has implemented the IDictionary interface; otherwise, <c>false</c>.</value> /// </returns> public static bool IsIDictionary(Type type, out Type keyType, out Type valueType) { keyType = typeof(object); valueType = typeof(object); // a direct reference to the interface itself is also OK. if (type.IsInterface && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { var genArgs = type.GetGenericArguments(); keyType = genArgs[0]; valueType = genArgs[1]; return true; } foreach (var interfaceType in type.GetInterfaces()) if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { var genArgs = interfaceType.GetGenericArguments(); keyType = genArgs[0]; valueType = genArgs[1]; return true; } return false; } /// <summary> /// Determines whether the specified type is a generic dictionary. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <value><c>true</c> if the specified type is dictionary; otherwise, <c>false</c>.</value> /// </returns> public static bool IsIDictionary(Type type) { return IsIDictionary(type, out _, out _); } /// <summary> /// Determines whether the specified type is a non generic IDictionary, e.g., a Hashtable. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <c>true</c> if the specified type is a non generic IDictionary; otherwise, <c>false</c>. /// </returns> public static bool IsNonGenericIDictionary(Type type) { // a direct reference to the interface itself is also OK. if (type == typeof(IDictionary)) return true; foreach (var interfaceType in type.GetInterfaces()) if (interfaceType == typeof(IDictionary)) return true; return false; } /// <summary> /// Determines whether the specified type is equal to this type, /// or is a nullable of this type, or this type is a nullable of /// the other type. /// </summary> /// <param name="self"></param> /// <param name="other"></param> /// <returns></returns> public static bool EqualsOrIsNullableOf(this Type self, Type other) { if (self == other) return true; if (!IsNullable(self, out var selfBaseType)) selfBaseType = self; if (!IsNullable(other, out var otherBaseType)) otherBaseType = other; return selfBaseType == otherBaseType; } #pragma warning disable S3776 // disable sonar cognitive complexity warnings /// <summary> /// Determines whether the specified type is equal or inherited from another specified type. /// </summary> /// <param name="type">The type to check.</param> /// <param name="baseType"> /// Another type that the specified type is checked whether it is equal or /// has been driven from. /// </param> /// <returns> /// <c>true</c> if the specified type is equal or inherited from another specified type; otherwise, <c>false</c>. /// </returns> public static bool IsTypeEqualOrInheritedFromType(Type type, Type baseType) { if (type == baseType) return true; var isTypeGenDef = type.IsGenericTypeDefinition; var isBaseGenDef = baseType.IsGenericTypeDefinition; Type[]? typeGenArgs = null; Type[]? baseGenArgs = null; if (type.IsGenericType) { if (isBaseGenDef) { if (!isTypeGenDef) { type = type.GetGenericTypeDefinition(); isTypeGenDef = true; } } else { typeGenArgs = type.GetGenericArguments(); } } if (baseType.IsGenericType) { if (isTypeGenDef) { if (!isBaseGenDef) { baseType = baseType.GetGenericTypeDefinition(); } } else { baseGenArgs = baseType.GetGenericArguments(); } } if (type == baseType) return true; if (typeGenArgs != null && baseGenArgs != null) { if (typeGenArgs.Length != baseGenArgs.Length) return false; for (var i = 0; i < typeGenArgs.Length; i++) // Should this method be called for type args recursively? if (typeGenArgs[i] != baseGenArgs[i]) return false; } if (baseType.IsInterface) { foreach (var iface in type.GetInterfaces()) if (iface.Name == baseType.Name) return true; return false; } var curBaseType = type.BaseType; while (curBaseType != null) { if (curBaseType.Name == baseType.Name) return true; curBaseType = curBaseType.BaseType; } return false; } /// <summary> /// Converts the specified object from a basic type to another type as specified. /// It is meant by basic types, primitive data types, strings, and enums. /// </summary> /// <param name="value">The object to be converted.</param> /// <param name="dstType">the destination type of conversion.</param> /// <param name="culture">The <see cref="CultureInfo" /> to use for culture-specific value formats.</param> /// <returns>the converted object</returns> public static object? ConvertBasicType(object value, Type dstType, CultureInfo culture) { object convertedObj; var valueAsString = value.ToString()!; if (dstType.IsEnum) { var typeWrapper = UdtWrapperCache.Instance.GetOrAddItem(dstType, DefaultSerializerOptions); convertedObj = typeWrapper.EnumWrapper!.ParseAlias(valueAsString); } else if (dstType == typeof(DateTime)) { convertedObj = StringUtils.ParseDateTimeTimeZoneSafe(valueAsString, culture); } else if (dstType == typeof(decimal)) { // to fix the asymmetry of used locales for this type between serialization and deserialization convertedObj = Convert.ChangeType(value, dstType, culture); } else if (dstType == typeof(bool)) { var strValue = valueAsString.Trim().ToLower(); if (strValue == "false" || strValue == "no" || strValue == "0") { convertedObj = false; } else if (strValue == "true" || strValue == "yes" || strValue == "1") { convertedObj = true; } else { if (int.TryParse(strValue, out var boolIntValue)) convertedObj = boolIntValue != 0; else throw new ArgumentException($"The specified value {strValue} is not recognized as boolean", nameof(value)); } } else if (dstType == typeof(Guid)) { return new Guid(valueAsString); } else { if (IsNullable(dstType, out var nullableType)) { if (value.ToString() == string.Empty) return null; return ConvertBasicType(value, nullableType!, culture); } convertedObj = Convert.ChangeType(value, dstType, culture); } return convertedObj; } #pragma warning restore S3776 // enable sonar cognitive complexity warnings /// <summary> /// Determines whether the specified type is nullable. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <c>true</c> if the specified type is nullable; otherwise, <c>false</c>. /// </returns> public static bool IsNullable(Type type) { return IsNullable(type, out _); } /// <summary> /// Determines whether the specified type is nullable. /// </summary> /// <param name="type">The type to check.</param> /// <param name="valueType">The value type of the corresponding nullable type.</param> /// <returns> /// <c>true</c> if the specified type is nullable; otherwise, <c>false</c>. /// </returns> public static bool IsNullable(Type type, out Type? valueType) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { valueType = type.GetGenericArguments()[0]; return true; } valueType = null; return false; } /// <summary> /// Gets the default value for the specified type. /// </summary> /// <param name="type">The <see cref="Type"/> for which to retrieve the default value.</param> /// <returns> /// The default value for the specified type. If the type is a reference type or a nullable value type, returns <c>null</c>. /// </returns> public static object? GetDefaultValue(Type type) { if (type == typeof(BigInteger)) { return BigInteger.Zero; } if (type == typeof(Guid)) { return Guid.Empty; } if (type == typeof(DateTimeOffset)) { return DateTimeOffset.MinValue; } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return false; case TypeCode.Char: return (char) 0; case TypeCode.SByte: return (sbyte) 0; case TypeCode.Byte: return (byte) 0; case TypeCode.Int16: return (short) 0; case TypeCode.UInt16: return (ushort) 0; case TypeCode.Int32: return 0; case TypeCode.UInt32: return 0U; case TypeCode.Int64: return 0L; case TypeCode.UInt64: return 0UL; case TypeCode.Single: return 0F; case TypeCode.Double: return 0D; case TypeCode.Decimal: return 0M; case TypeCode.DateTime: return DateTime.MinValue; case TypeCode.DBNull: return DBNull.Value; case TypeCode.Empty: return null; } if (!type.IsValueType) { return null; } if (IsNullable(type)) { return null; } return Activator.CreateInstance(type); } /// <summary> /// Determines whether the specified type implements <c>IFormattable</c> /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <c>true</c> if the specified type implements <c>IFormattable</c>; otherwise, <c>false</c>. /// </returns> public static bool IsIFormattable(Type type) { // a direct reference to the interface itself is also OK. if (type == typeof(IFormattable)) return true; foreach (var interfaceType in type.GetInterfaces()) if (interfaceType == typeof(IFormattable)) return true; return false; } /// <summary> /// Determines whether the type provides the functionality /// to format the value of an object into a string representation. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// <value><c>true</c> if the specified type implements the <c>IFormattable</c> interface; otherwise, <c>false</c>.</value> /// </returns> public static bool IsStringConvertibleIFormattable(Type type) { // is IFormattable // accept parameterless ToString // accept ctor of string if (IsIFormattable(type) && !HasOneReadWriteProperty(type) && null != type.GetConstructor(new[] { typeof(string) }) && null != type.GetMethod("ToString", Type.EmptyTypes) && null != type.GetMethod("ToString", new[] { typeof(string) })) return true; return false; } /// <summary> /// Checks to see if the specified type has readable and writable properties. /// </summary> /// <param name="type">The type to check for.</param> /// <returns> /// <value><c>true</c> if the specified type has readable and writable properties; otherwise, <c>false</c>.</value> /// </returns> public static bool HasOneReadWriteProperty(Type type) { var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var pi in props) if (pi.CanRead && pi.CanWrite) { var getPi = pi.GetGetMethod(false); var setPi = pi.GetSetMethod(false); if (setPi != null && getPi != null) return true; } return false; } /// <summary> /// Tries to format the specified object using the format string provided. /// If the formatting operation is not applicable, the source object is returned intact. /// Note: The type of the returned object will be 'System.String' if formatting succeeds. /// </summary> /// <param name="src">The source object.</param> /// <param name="format">The format string.</param> /// <returns><code>System.String</code> if the format is successful; otherwise, the original object</returns> public static object? TryFormatObject(object? src, string? format) { if (format == null || src == null) return src; object formattedObject; try { formattedObject = src.GetType().InvokeMember("ToString", BindingFlags.InvokeMethod, null, src, new object[] { format })!; } catch { return src; } return formattedObject ?? src; } /// <summary> /// Searches all loaded assemblies to find a type with a special name. /// </summary> /// <remarks> /// Types from System.Private.CoreLib (NETSTANDARD, NET5.0) the corresponding type from mscorlib (NETFRAMEWORK) /// will be returned and vice versa, depending on the framework the executing assembly is compiled for. /// </remarks> /// <param name="name">The <see cref="Type.AssemblyQualifiedName" /> of the type to find.</param> /// <returns><see cref="Type" /> found using the specified name</returns> public static Type? GetTypeByName(string name) { var pattern = RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework") // Forward compatibility: // if we get a yaxlib:realtype which is NETSTANDARD (and later) System.Private.CoreLib, replace it with its equivalent ? @"\,\s+(System\.Private\.CoreLib)\,\s+Version\=\d+(\.\d+)*\,\s+Culture=\b\w+\b\,\s+PublicKeyToken\=\b\w+\b" // Backward compatibility: // if we get a yaxlib:realtype which is .Net Framework 2.x/3.x/4.x mscorlib, replace it with its equivalent : @"\,\s+(mscorlib)\,\s+Version\=\d+(\.\d+)*\,\s+Culture=\b\w+\b\,\s+PublicKeyToken\=\b\w+\b"; var execAppFxName = Regex.Replace(name, pattern, name.GetType().Assembly.FullName!, RegexOptions.None, TimeSpan.FromMilliseconds(100)); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // first search the 1st assembly (i.e. the mscorlib), then start from the last assembly backward, // the last assemblies are user defined ones for (var i = assemblies.Length; i > 0; i--) { var curAssembly = i == assemblies.Length ? assemblies[0] : assemblies[i]; try { var type = curAssembly.GetType(execAppFxName, false, true); if (type != null) return type; } catch { // ignored } } return null; } /// <summary> /// Determines whether the specified property is public. /// </summary> /// <param name="pi">The property.</param> /// <returns> /// <c>true</c> if the specified property is public; otherwise, <c>false</c>. /// </returns> public static bool IsPublicProperty(PropertyInfo pi) { foreach (var m in pi.GetAccessors()) if (m.IsPublic) return true; return false; } /// <summary> /// Test whether the <see cref="MemberInfo" /> parameter is part of a .NET assembly. /// </summary> /// <remarks> /// Might require modifications when supporting future versions of .NET. /// </remarks> /// <param name="memberInfo"></param> /// <returns> /// Returns <see langword="true" />, if the <see cref="MemberInfo" /> parameter is part of a .NET assembly, else /// <see langword="false" />. /// </returns> public static bool IsPartOfNetFx(MemberInfo memberInfo) { var assemblyName = memberInfo.DeclaringType?.Assembly.GetName().Name; if (assemblyName == null) return false; #pragma warning disable S2681 // conditional execution #if NETSTANDARD || NET return assemblyName.StartsWith("System.", StringComparison.OrdinalIgnoreCase) || assemblyName.Equals("mscorlib", StringComparison.OrdinalIgnoreCase) || assemblyName.StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase); #else return assemblyName.Equals("mscorlib", StringComparison.OrdinalIgnoreCase) || assemblyName.Equals("System", StringComparison.OrdinalIgnoreCase) || assemblyName.Equals("System.Core", StringComparison.OrdinalIgnoreCase); #endif } #pragma warning restore S2681 public static bool IsInstantiableCollection(Type colType) { return colType.GetConstructor(Type.EmptyTypes) != null; } public static T? InvokeGetProperty<T>(object srcObj, string propertyName) { return (T?) srcObj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance) ?.GetValue(srcObj, null); } public static T? InvokeIntIndexer<T>(object srcObj, int index) { var pi = srcObj.GetType().GetProperty("Item", new[] { typeof(int) }); return (T?) pi?.GetValue(srcObj, new object[] { index }); } public static object? InvokeStaticMethod(Type type, string methodName, params object[] args) { var argTypes = args.Select(x => x.GetType()).ToArray(); var method = type.GetMethod(methodName, argTypes); var result = method?.Invoke(null, args); return result; } public static object? InvokeMethod(object srcObj, string methodName, params object[] args) { var argTypes = args.Select(x => x.GetType()).ToArray(); var method = srcObj.GetType().GetMethod(methodName, argTypes); var result = method?.Invoke(srcObj, args); return result; } #pragma warning disable S3011 // disable sonar accessibility bypass warning: private members are intended /// <summary> /// Gets the value for a public or non-public instance field. /// Including private fields in base types is optional, and enabled by default. /// </summary> /// <param name="target"></param> /// <param name="fieldName"></param> /// <param name="includePrivateBaseTypeFields"></param> public static object? GetFieldValue(object target, string fieldName, bool includePrivateBaseTypeFields = true) { var field = target.GetType().GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (field == null && includePrivateBaseTypeFields) field = GetPrivateBaseField(target.GetType(), fieldName); return field!.GetValue(target); } /// <summary> /// Sets the value for a public or non-public instance field.. /// Including private fields in base types is optional, and enabled by default. /// </summary> /// <param name="target"></param> /// <param name="fieldName"></param> /// <param name="value"></param> /// <param name="includePrivateBaseTypeFields"></param> public static void SetFieldValue(object target, string fieldName, object? value, bool includePrivateBaseTypeFields = true) { var field = target.GetType().GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (field == null && includePrivateBaseTypeFields) field = GetPrivateBaseField(target.GetType(), fieldName); field!.SetValue(target, value); } /// <summary> /// Gets the value for a public or non-public instance property. /// Including private properties in base types is optional, and enabled by default. /// </summary> public static object? GetPropertyValue(object target, string propertyName, bool includePrivateBaseTypeProperties = true) { var property = target.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (property == null && includePrivateBaseTypeProperties) property = GetPrivateBaseProperty(target.GetType(), propertyName); return property!.GetValue(target); } /// <summary> /// Sets the value for a public or non-public instance property. /// Including private properties in base types is optional, and enabled by default. /// </summary> public static void SetPropertyValue(object target, string propertyName, object? value, bool includePrivateBaseTypeProperties = true) { var property = target.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (property == null && includePrivateBaseTypeProperties) property = GetPrivateBaseProperty(target.GetType(), propertyName); property!.SetValue(target, value); } private static FieldInfo? GetPrivateBaseField(Type type, string fieldName) { var currentType = type; while ((currentType = currentType.BaseType) != null) { var field = currentType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (field != null) return field; } return null; } private static PropertyInfo? GetPrivateBaseProperty(Type type, string propertyName) { var currentType = type; while ((currentType = currentType.BaseType) != null) { var property = currentType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (property != null) return property; } return null; } #pragma warning restore S3011 // restore sonar accessibility bypass warning public static bool IsBaseClassOrSubclassOf(Type? subType, string? baseName) { if (baseName == null || subType == null) return false; var baseType = Type.GetType(baseName); return baseType != null && (subType.FullName == baseName || subType.IsSubclassOf(baseType)); } }
YAXLib
YAXLib
F:\Projects\TestMap\Temp\YAXLib\YAXLib.sln
F:\Projects\TestMap\Temp\YAXLib\YAXLibTests\YAXLibTests.csproj
F:\Projects\TestMap\Temp\YAXLib\YAXLibTests\StringUtilsTest.cs
YAXLibTests
StringUtilsTest
[]
['NUnit.Framework', 'YAXLib']
NUnit
net461;netcoreapp3.1;net6.0
/// <summary> /// Summary description for StringUtilsTest /// </summary> [TestFixture] public class StringUtilsTest { [Test] public void RefineElementNameTest() { Assert.Multiple(() => { Assert.That(StringUtils.RefineLocationString(".."), Is.EqualTo("..")); Assert.That(StringUtils.RefineLocationString("."), Is.EqualTo(".")); Assert.That(StringUtils.RefineLocationString(" "), Is.EqualTo(".")); Assert.That(StringUtils.RefineLocationString(" / \\ "), Is.EqualTo(".")); Assert.That(StringUtils.RefineLocationString("ans"), Is.EqualTo("ans")); Assert.That(StringUtils.RefineLocationString("/ans"), Is.EqualTo("ans")); Assert.That(StringUtils.RefineLocationString("/ans/"), Is.EqualTo("ans")); Assert.That(StringUtils.RefineLocationString("ans/"), Is.EqualTo("ans")); Assert.That(StringUtils.RefineLocationString("ans/////"), Is.EqualTo("ans")); Assert.That(StringUtils.RefineLocationString("ans\\\\\\"), Is.EqualTo("ans")); Assert.That(StringUtils.RefineLocationString("..."), Is.EqualTo("_..")); Assert.That(StringUtils.RefineLocationString("one / two / three / four "), Is.EqualTo("one/two/three/four")); Assert.That(StringUtils.RefineLocationString("one / two \\ three / four "), Is.EqualTo("one/two/three/four")); Assert.That(StringUtils.RefineLocationString("one / two / three and else / four "), Is.EqualTo("one/two/three_and_else/four")); Assert.That(StringUtils.RefineLocationString("one / two / .. / four "), Is.EqualTo("one/two/../four")); Assert.That(StringUtils.RefineLocationString("one / two / .. / four / "), Is.EqualTo("one/two/../four")); Assert.That(StringUtils.RefineLocationString("one / two / . . / four / "), Is.EqualTo("one/two/__./four")); Assert.That(StringUtils.RefineLocationString("one / two / two:words.are / four "), Is.EqualTo("one/two/two_words.are/four")); Assert.That(StringUtils.RefineLocationString("one-two-three-four"), Is.EqualTo("one-two-three-four")); Assert.That(StringUtils.RefineLocationString("one.two.three.four"), Is.EqualTo("one.two.three.four")); Assert.That(StringUtils.RefineLocationString(".one"), Is.EqualTo("_one")); Assert.That(StringUtils.RefineLocationString("-one"), Is.EqualTo("_one")); Assert.That(StringUtils.RefineLocationString("one."), Is.EqualTo("one.")); Assert.That(StringUtils.RefineLocationString("one-"), Is.EqualTo("one-")); }); } [Test] public void ExtractPathAndAliasTest() { TestPathAndAlias("one/two#name", "one/two", "name"); TestPathAndAlias("one / two # name", "one / two", "name"); TestPathAndAlias("one / two # name1 name2", "one / two", "name1 name2"); TestPathAndAlias(" one / two # name1 name2", "one / two", "name1 name2"); TestPathAndAlias(" one / two name1 name2 ", " one / two name1 name2 ", ""); TestPathAndAlias(" one / two # name1 # name2 ", "one / two", "name1 # name2"); TestPathAndAlias(" one / two # ", "one / two", ""); TestPathAndAlias(" one / two #", "one / two", ""); TestPathAndAlias("# one / two ", "", "one / two"); } private static void TestPathAndAlias(string locationString, string expectedPath, string expectedAlias) { string path, alias; StringUtils.ExtractPathAndAliasFromLocationString(locationString, out path, out alias); Assert.Multiple(() => { Assert.That(path, Is.EqualTo(expectedPath)); Assert.That(alias, Is.EqualTo(expectedAlias)); }); } [Test] public void IsLocationAllGenericTest() { Assert.Multiple(() => { Assert.That(StringUtils.IsLocationAllGeneric(".."), Is.True); Assert.That(StringUtils.IsLocationAllGeneric("."), Is.True); Assert.That(StringUtils.IsLocationAllGeneric("./.."), Is.True); Assert.That(StringUtils.IsLocationAllGeneric("../.."), Is.True); Assert.That(StringUtils.IsLocationAllGeneric("../one/.."), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("../one"), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("one/.."), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("one"), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("one/../two"), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("../one/../two"), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("../one/../two/.."), Is.False); Assert.That(StringUtils.IsLocationAllGeneric("one/../two/.."), Is.False); }); } [Test] public void DivideLocationOneStepTest() { string newLocation; string newElement; var location = ".."; var returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo("..")); Assert.That(newElement, Is.Empty); Assert.That(returnValue, Is.False); }); location = "."; returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo(".")); Assert.That(newElement, Is.Empty); Assert.That(returnValue, Is.False); }); location = "../.."; returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo("../..")); Assert.That(newElement, Is.Empty); Assert.That(returnValue, Is.False); }); location = "../../folder"; returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo("../..")); Assert.That(newElement, Is.EqualTo("folder")); Assert.That(returnValue, Is.True); }); location = "../../folder/.."; returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo("../../folder/..")); Assert.That(newElement, Is.Empty); Assert.That(returnValue, Is.False); }); location = "one/two/three/four"; returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo("one/two/three")); Assert.That(newElement, Is.EqualTo("four")); Assert.That(returnValue, Is.True); }); location = "one"; returnValue = StringUtils.DivideLocationOneStep(location, out newLocation, out newElement); Assert.Multiple(() => { Assert.That(newLocation, Is.EqualTo(".")); Assert.That(newElement, Is.EqualTo("one")); Assert.That(returnValue, Is.True); }); } [Test] public void LooksLikeExpandedNameTest() { var falseCases = new[] { "", " ", "{}", "{a", "{} ", " {}", " {} ", " {a} ", "{a}", "{a} ", "something" }; var trueCases = new[] { "{a}b", " {a}b ", " {a}b" }; foreach (var falseCase in falseCases) Assert.That(StringUtils.LooksLikeExpandedXName(falseCase), Is.False); foreach (var trueCase in trueCases) Assert.That(StringUtils.LooksLikeExpandedXName(trueCase), Is.True); } }
269
8,288
// Copyright (C) Sina Iravanian, Julian Verdurmen, axuno gGmbH and other contributors. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Linq; using YAXLib.Pooling.SpecializedPools; namespace YAXLib; /// <summary> /// Provides string utility methods /// </summary> internal static class StringUtils { private static readonly char[] SplitChars = [',', ' ', '\t']; /// <summary> /// Refines the location string. Trims it, and replaces invalid characters with underscore. /// </summary> /// <param name="elemAddr">The element address to refine.</param> /// <returns>the refined location string</returns> public static string RefineLocationString(string elemAddr) { elemAddr = elemAddr.Trim(' ', '\t', '\r', '\n', '\v', '/', '\\'); if (string.IsNullOrEmpty(elemAddr)) return "."; // replace all back-slashes to slash elemAddr = elemAddr.Replace('\\', '/'); using var pooledObject = StringBuilderPool.Instance.Get(out var sb); sb.Capacity = elemAddr.Length; var steps = elemAddr.SplitPathNamespaceSafe(); foreach (var step in steps) sb.Append("/" + RefineSingleElement(step)); return sb.Remove(0, 1).ToString(); } /// <summary> /// Heuristically determines if the supplied name conforms to the "expanded XML name" form supported by the /// System.Xml.Linq.XName class. /// </summary> /// <param name="name">The name to be examined.</param> /// <returns><c>true</c> if the supplied name appears to be in expanded form, otherwise <c>false</c>.</returns> public static bool LooksLikeExpandedXName(string name) { // XName permits strings of the form '{namespace}localname'. Detecting such cases allows // YAXLib to support explicit namespace use. // http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.aspx name = name.Trim(); // Needs at least 3 chars ('{}a' is, in theory, valid), must start with '{', must have a following closing '}' which must not be last char. if (name.Length >= 3 && (name[0] == '{')) { var closingBrace = name.IndexOf('}', 1); return closingBrace != -1 && closingBrace < name.Length - 1; } return false; } /// <summary> /// Refines a single element name. Refines the location string. Trims it, and replaces invalid characters with /// underscore. /// </summary> /// <param name="elemName">Name of the element.</param> /// <returns>the refined element name</returns> #if NETSTANDARD2_1_OR_GREATER || NET public static string? RefineSingleElement([NotNullIfNotNull(nameof(elemName))] string? elemName) #else public static string? RefineSingleElement(string? elemName) #endif { if (elemName == null) return null; elemName = elemName.Trim(' ', '\t', '\r', '\n', '\v', '/', '\\'); if (IsSingleLocationGeneric(elemName)) return elemName; if (LooksLikeExpandedXName(elemName)) { // thanks go to CodePlex user: tg73 (http://www.codeplex.com/site/users/view/tg73) // for providing the code for expanded xml name support // XName permits strings of the form '{namespace}localname'. Detecting such cases allows // YAXLib to support explicit namespace use. // http://msdn.microsoft.com/en-us/library/system.xml.linq.xname.aspx // Leave namespace part alone, refine localname part. var closingBrace = elemName.IndexOf('}'); var refinedLocalname = RefineSingleElement(elemName.Substring(closingBrace + 1)); #if NET return string.Concat(elemName.AsSpan(0, closingBrace + 1), refinedLocalname); #else return elemName.Substring(0, closingBrace + 1) + refinedLocalname; #endif } using var pooledObject = StringBuilderPool.Instance.Get(out var sb); sb.Capacity = elemName.Length; // This uses the rules defined in http://www.w3.org/TR/xml/#NT-Name. // Thanks go to [@asbjornu] for pointing to the W3C standard for (var i = 0; i < elemName.Length; i++) if (i == 0) sb.Append(IsValidNameStartChar(elemName[i]) ? elemName[i] : '_'); else sb.Append(IsValidNameChar(elemName[i]) ? elemName[i] : '_'); return sb.ToString(); } private static bool IsValidNameStartChar(char ch) { // This uses the rules defined in http://www.w3.org/TR/xml/#NT-Name. // However colon (:) has been removed from the set of allowed characters, // because it is reserved for separating namespace prefix and XML-entity names. if ( //ch == ':' || ch == '_' || IsInRange(ch, 'A', 'Z') || IsInRange(ch, 'a', 'z') || IsInRange(ch, '\u00C0', '\u00D6') || IsInRange(ch, '\u00D8', '\u00F6') || IsInRange(ch, '\u00F8', '\u02FF') || IsInRange(ch, '\u0370', '\u037D') || IsInRange(ch, '\u037F', '\u1FFF') || IsInRange(ch, '\u200C', '\u200D') || IsInRange(ch, '\u2070', '\u218F') || IsInRange(ch, '\u2C00', '\u2FEF') || IsInRange(ch, '\u3001', '\uD7FF') || IsInRange(ch, '\uF900', '\uFDCF') || IsInRange(ch, '\uFDF0', '\uFFFD') //|| IsInRange(ch, '\u10000', '\uEFFFF') ) return true; return false; } private static bool IsValidNameChar(char ch) { return IsValidNameStartChar(ch) || ch == '-' || ch == '.' || IsInRange(ch, '0', '9') || ch == '\u00B7' || IsInRange(ch, '\u0300', '\u036F') || IsInRange(ch, '\u203F', '\u2040'); } private static bool IsInRange(char ch, char lower, char upper) { return lower <= ch && ch <= upper; } /// <summary> /// Extracts the path and alias from location string. /// A pure path location string: level1/level2 /// A location string augmented with alias: level1/level2#somename /// Here path is "level1/level2" and alias is "somename". /// </summary> /// <param name="locationString">The location string.</param> /// <param name="path">The path to be extracted.</param> /// <param name="alias">The alias to be extracted.</param> public static void ExtractPathAndAliasFromLocationString(string locationString, out string path, out string alias) { var poundIndex = locationString.IndexOf('#'); if (poundIndex >= 0) { if (poundIndex == 0) path = ""; else path = locationString.Substring(0, poundIndex).Trim(); if (poundIndex == locationString.Length - 1) alias = ""; else alias = locationString.Substring(poundIndex + 1).Trim(); } else { path = locationString; alias = ""; } } /// <summary> /// Combines a location string and an element name to form a bigger location string. /// </summary> /// <param name="location">The location string.</param> /// <param name="elemName">Name of the element.</param> /// <returns>a bigger location string formed by combining a location string and an element name.</returns> public static string CombineLocationAndElementName(string location, XName elemName) { return string.Format("{0}/{1}", location, elemName); } /// <summary> /// Divides the location string one step, to form a shorter location string. /// </summary> /// <param name="location">The location string to divide.</param> /// <param name="newLocation">The new location string which is one level shorter.</param> /// <param name="newElem">The element name removed from the end of location string.</param> /// <returns></returns> public static bool DivideLocationOneStep(string location, out string newLocation, out string newElem) { newLocation = location; newElem = string.Empty; var slashIdx = location.LastIndexOf('/'); if (slashIdx < 0) // no slashes found { if (IsLocationAllGeneric(location)) return false; newElem = location; newLocation = "."; return true; } var preSlash = location.Substring(0, slashIdx); var postSlash = location.Substring(slashIdx + 1); if (IsLocationAllGeneric(postSlash)) return false; newLocation = preSlash; newElem = postSlash; return true; } /// <summary> /// Determines whether the specified location is composed of levels /// which are themselves either "." or "..". /// </summary> /// <param name="location">The location string to check.</param> /// <returns> /// <c>true</c> if the specified location string is all composed of "." or ".." levels; otherwise, <c>false</c>. /// </returns> public static bool IsLocationAllGeneric(string location) { var locSteps = location.SplitPathNamespaceSafe(); foreach (var loc in locSteps) if (!IsSingleLocationGeneric(loc)) return false; return true; } /// <summary> /// Determines whether the specified location string is either "." or "..". /// </summary> /// <param name="location">The location string to check.</param> /// <returns> /// <c>true</c> if the specified location string is either "." or ".."; otherwise, <c>false</c>. /// </returns> public static bool IsSingleLocationGeneric(string location) { return location == "." || location == ".."; } /// <summary> /// Gets the string corresponding to the given array dimensions. /// </summary> /// <param name="dims">The array dimensions.</param> /// <returns>the string corresponding to the given array dimensions</returns> public static string GetArrayDimsString(int[] dims) { var sb = new StringBuilder(); for (var i = 0; i < dims.Length; i++) { if (i != 0) sb.Append(','); sb.Append(dims[i]); } return sb.ToString(); } /// <summary> /// Parses the array dimensions string, and returns the corresponding dimensions array. /// </summary> /// <param name="str">The string to parse.</param> /// <returns>the dimensions array corresponding to the given string</returns> public static int[] ParseArrayDimsString(string str) { var strDims = str.Split(SplitChars, StringSplitOptions.RemoveEmptyEntries); var lst = new List<int>(); foreach (var strDim in strDims) { if (int.TryParse(strDim, out var dim)) lst.Add(dim); } return lst.ToArray(); } /// <summary> /// Splits a string at each instance of a '/' except where such slashes /// are within {}. /// </summary> /// <param name="value">The string to split</param> /// <returns>An enumerable set of strings which were separated by '/'</returns> public static IEnumerable<string> SplitPathNamespaceSafe(this string value) { var bracketCount = 0; var lastStart = 0; var temp = value; if (value.Length <= 1) { yield return value; yield break; } for (var i = 0; i < temp.Length; i++) if (temp[i] == '{') bracketCount++; else if (temp[i] == '}') bracketCount--; else if (temp[i] == '/' && bracketCount == 0) { yield return temp.Substring(lastStart, i - lastStart); lastStart = i + 1; } if (lastStart <= temp.Length - 1) yield return temp.Substring(lastStart); } public static DateTime ParseDateTimeTimeZoneSafe(string str, IFormatProvider formatProvider) { if (!DateTimeOffset.TryParse(str, formatProvider, DateTimeStyles.None, out var dto)) return DateTime.MinValue; return dto.Offset == TimeSpan.Zero ? dto.UtcDateTime : dto.DateTime; } }
YAXLib
YAXLib
F:\Projects\TestMap\Temp\YAXLib\YAXLib.sln
F:\Projects\TestMap\Temp\YAXLib\YAXLibTests\YAXLibTests.csproj
F:\Projects\TestMap\Temp\YAXLib\YAXLibTests\XMLUtilsTest.cs
YAXLibTests
XmlUtilsTest
[]
['System.Globalization', 'System.Numerics', 'System.Text', 'System.Xml.Linq', 'NUnit.Framework', 'YAXLib']
NUnit
net461;netcoreapp3.1;net6.0
/// <summary> /// Summary description for XMLUtilsTest /// </summary> [TestFixture] public class XmlUtilsTest { [Test] public void CanCreateLocationTest() { var elem = new XElement("Base", string.Empty); Assert.That(XMLUtils.CanCreateLocation(elem, "level1/level2"), Is.True); var created = XMLUtils.CreateLocation(elem, "level1/level2"); Assert.Multiple(() => { Assert.That(created.Name.ToString(), Is.EqualTo("level2")); Assert.That(XMLUtils.LocationExists(elem, "level1/level2"), Is.True); }); created = XMLUtils.CreateLocation(elem, "level1/level3"); Assert.Multiple(() => { Assert.That(created.Name.ToString(), Is.EqualTo("level3")); Assert.That(XMLUtils.LocationExists(elem, "level1/level3"), Is.True); }); } [Test] public void ConvertObjectToXmlValue() { Assert.Multiple(() => { Assert.That(default(object).ToXmlValue(CultureInfo.InvariantCulture), Is.EqualTo(string.Empty)); Assert.That(true.ToXmlValue(CultureInfo.InvariantCulture), Is.EqualTo("true")); Assert.That(1.1234567d.ToXmlValue(CultureInfo.InvariantCulture), Is.EqualTo("1.1234567")); Assert.That(1.123f.ToXmlValue(CultureInfo.InvariantCulture), Is.EqualTo("1.123")); Assert.That(new BigInteger(1234567890).ToXmlValue(CultureInfo.InvariantCulture), Is.EqualTo("1234567890")); Assert.That(new StringBuilder("123.456").ToXmlValue(CultureInfo.InvariantCulture), Is.EqualTo("123.456")); }); } }
363
1,946
// Copyright (C) Sina Iravanian, Julian Verdurmen, axuno gGmbH and other contributors. // Licensed under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using System.Xml.Linq; using YAXLib.Exceptions; namespace YAXLib; /// <summary> /// Provides utility methods for manipulating XML. /// There are four methods for each unit. UnitExists, FindUnit, CanCreateUnit, CreateUnit /// Units are: Location, Element, and Attribute /// </summary> internal static class XMLUtils { /// <summary> /// Determines whether the location specified exists in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <returns>a value indicating whether the location specified exists in the given XML element</returns> public static bool LocationExists(XElement baseElement, string location) { var newLoc = FindLocation(baseElement, location); return newLoc != null; } /// <summary> /// Finds the location specified in the given XML element specified. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <returns>the XML element corresponding to the specified location, or <c>null</c> if it is not found</returns> public static XElement? FindLocation(XElement baseElement, string location) { if (baseElement == null) throw new ArgumentNullException(nameof(baseElement)); if (location == null) throw new ArgumentNullException(nameof(location)); var locSteps = location.SplitPathNamespaceSafe(); var currentLocation = baseElement; foreach (var loc in locSteps) if (loc == ".") { // nothing to do } else if (loc == "..") { currentLocation = currentLocation.Parent; if (currentLocation == null) break; } else { XName curLocName = loc; if (curLocName.Namespace.IsEmpty()) currentLocation = currentLocation.Element(curLocName); else currentLocation = currentLocation.Element_NamespaceNeutral(curLocName); if (currentLocation == null) break; } return currentLocation; } /// <summary> /// Strips all invalid characters from the input value, if <paramref name="enabled" /> is <see langword="true" />. /// </summary> /// <param name="input"></param> /// <param name="enabled"></param> /// <returns></returns> public static string StripInvalidXmlChars(this string? input, bool enabled) { if (!enabled || input == null) return input ?? string.Empty; var buffer = ArrayPool<char>.Shared.Rent(input.Length); try { var written = 0; foreach (var c in input.Where(XmlConvert.IsXmlChar)) { buffer[written++] = c; } return written == input.Length ? input : buffer.AsSpan(0, written).ToString(); } finally { ArrayPool<char>.Shared.Return(buffer); } } /// <summary> /// Determines whether the specified location can be created in the specified XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <returns> /// <c>true</c> if the specified location can be created in the specified XML element; otherwise, <c>false</c>. /// </returns> public static bool CanCreateLocation(XElement baseElement, string location) { var locSteps = location.SplitPathNamespaceSafe(); var currentLocation = baseElement; foreach (var loc in locSteps) if (loc == ".") { // nothing to do } else if (loc == "..") { currentLocation = currentLocation.Parent; if (currentLocation == null) return false; } else { XName curLocName = loc; if (curLocName.Namespace.IsEmpty()) currentLocation = currentLocation.Element(curLocName); else currentLocation = currentLocation.Element_NamespaceNeutral(curLocName); if (currentLocation == null) return true; } return true; } /// <summary> /// Creates and returns XML element corresponding to the specified location in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <returns>XML element corresponding to the specified location created in the given XML element</returns> public static XElement CreateLocation(XElement baseElement, string location) { var locSteps = location.SplitPathNamespaceSafe(); var currentLocation = baseElement; foreach (var loc in locSteps) if (loc == ".") { // nothing to do } else if (loc == "..") { currentLocation = currentLocation.Parent; if (currentLocation == null) break; } else { XName curLocName = loc; XElement? newLoc; if (curLocName.Namespace.IsEmpty()) newLoc = currentLocation.Element(curLocName); else newLoc = currentLocation.Element_NamespaceNeutral(curLocName); if (newLoc == null) { var newElem = new XElement(curLocName.OverrideNsIfEmpty(currentLocation.Name.Namespace)); currentLocation.Add(newElem); currentLocation = newElem; } else { currentLocation = newLoc; } } return currentLocation ?? baseElement; } /// <summary> /// Determines whether the attribute with the given name located in the given location string exists in the given XML /// element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="attrName">Name of the attribute.</param> /// <returns> /// a value indicating whether the attribute with the given name located in the given location string exists in the /// given XML element. /// </returns> public static bool AttributeExists(XElement baseElement, string location, XName attrName) { return FindAttribute(baseElement, location, attrName) != null; } /// <summary> /// Finds the attribute with the given name located in the given location string in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="attrName">Name of the attribute.</param> /// <returns> /// a value indicating whether the attribute with the given name located in /// the given location string in the given XML element has been found. /// </returns> public static XAttribute? FindAttribute(XElement baseElement, string location, XName attrName) { var newLoc = FindLocation(baseElement, location); if (newLoc == null) return null; var newAttrName = attrName; // the following stupid code is because of odd behaviour of LINQ to XML if (newAttrName.Namespace == newLoc.Name.Namespace) newAttrName = newAttrName.RemoveNamespace(); if (newAttrName.Namespace.IsEmpty()) return newLoc.Attribute(newAttrName); return newLoc.Attribute_NamespaceNeutral(newAttrName); } /// <summary> /// Determines whether the attribute with the given name can be created in the location /// specified by the given location string in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="attrName">Name of the attribute.</param> /// <returns> /// <c>true</c> if the attribute with the given name can be created in the location /// specified by the given location string in the given XML element; otherwise, <c>false</c>. /// </returns> public static bool CanCreateAttribute(XElement baseElement, string location, XName attrName) { var newLoc = FindLocation(baseElement, location); if (newLoc == null) //if the location does not exist { if (CanCreateLocation(baseElement, location)) // see if you can create the location // if you can create the location you can create the attribute too return true; return false; } var newAttrName = attrName; // the following stupid code is because of odd behaviour of LINQ to XML if (newAttrName.Namespace == newLoc.Name.Namespace) newAttrName = newAttrName.RemoveNamespace(); // check if the attribute does not exist if (newAttrName.Namespace.IsEmpty()) return newLoc.Attribute(newAttrName) == null; return newLoc.Attribute_NamespaceNeutral(newAttrName) == null; } /// <summary> /// Creates and returns the attribute with the given name in the location /// specified by the given location string in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="attrName">Name of the attribute.</param> /// <param name="attrValue">The value to be assigned to the attribute.</param> /// <param name="documentDefaultNamespace">The default namespace.</param> /// <param name="culture">The <see cref="CultureInfo" /> to use for formatting the value.</param> /// <returns> /// returns the attribute with the given name in the location /// specified by the given location string in the given XML element. /// </returns> public static XAttribute? CreateAttribute(XElement baseElement, string location, XName attrName, object? attrValue, XNamespace documentDefaultNamespace, CultureInfo culture) { var newLoc = FindLocation(baseElement, location); if (newLoc == null) { if (CanCreateLocation(baseElement, location)) newLoc = CreateLocation(baseElement, location); else return null; } // check if the attribute does not exist if (attrName.Namespace.IsEmpty() && attrName.Namespace != documentDefaultNamespace) { // i.e., the attribute already exists if (newLoc.Attribute(attrName) != null) return null; // we cannot create another one with the same name } else { if (newLoc.Attribute_NamespaceNeutral(attrName) != null) // i.e., the attribute already exists return null; // we cannot create another one with the same name } return newLoc.AddAttributeNamespaceSafe(attrName, attrValue, documentDefaultNamespace, culture); } /// <summary> /// Finds the element with the given name located in the given location string in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="elemName">Name of the element.</param> /// <returns> /// a value indicating whether the element with the given name located in /// the given location string in the given XML element has been found /// </returns> public static XElement? FindElement(XElement baseElement, string location, XName elemName) { return FindLocation(baseElement, StringUtils.CombineLocationAndElementName(location, elemName)); } /// <summary> /// Determines whether the XML element with the given name located in the /// given location string in the given XML element exists. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="elemName">Name of the element.</param> /// <returns> /// a value indicating whether the XML element with the given name located in the /// given location string in the given XML element exists /// </returns> public static bool ElementExists(XElement baseElement, string location, XName elemName) { return FindElement(baseElement, location, elemName) != null; } /// <summary> /// Determines whether the XML element with the given name located in the /// given location string in the given XML element can be created /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="elemName">Name of the element.</param> /// <returns> /// <c>true</c> if the XML element with the given name located in the given /// location string in the given XML element can be created; otherwise, <c>false</c>. /// </returns> public static bool CanCreateElement(XElement baseElement, string location, XName elemName) { return CanCreateLocation(baseElement, StringUtils.CombineLocationAndElementName(location, elemName)); } /// <summary> /// Creates and returns the XML element with the given name located in the /// given location string in the given XML element. /// </summary> /// <param name="baseElement">The parent XML element.</param> /// <param name="location">The location string.</param> /// <param name="elemName">Name of the element to create.</param> /// <returns> /// returns the XML element with the given name located in the /// given location string in the given XML element /// </returns> public static XElement CreateElement(XElement baseElement, string location, XName elemName) { return CreateLocation(baseElement, StringUtils.CombineLocationAndElementName(location, elemName)); } /// <summary> /// Creates and returns the XML element with the given name located in the /// given location string in the given XML element. /// </summary> /// <param name="baseElement">The parent XML element.</param> /// <param name="location">The location string.</param> /// <param name="elemName">Name of the element to create.</param> /// <param name="elemValue">The element value to be assigned to the created element.</param> /// <returns> /// returns the XML element with the given name located in the /// given location string in the given XML element. /// </returns> public static XElement CreateElement(XElement baseElement, string location, XName elemName, object elemValue) { var elem = CreateElement(baseElement, location, elemName); elem.SetValue(elemValue); return elem; } /// <summary> /// Moves all the children of src (including all its elements and attributes) to the /// destination element, dst. /// </summary> /// <param name="src">The source element.</param> /// <param name="dst">The destination element.</param> public static void MoveDescendants(XElement src, XElement dst) { foreach (var attr in src.Attributes()) { if (dst.Attribute(attr.Name) != null) throw new YAXAttributeAlreadyExistsException(attr.Name.ToString()); dst.Add(attr); } foreach (var elem in src.Nodes()) dst.Add(elem); } /// <summary> /// Determines whether the specified element has neither any child attributes nor any child elements. /// </summary> /// <param name="elem">The element.</param> /// <returns> /// <c>true</c> if the specified element has neither any child attributes nor any child elements; otherwise, /// <c>false</c>. /// </returns> public static bool IsElementCompletelyEmpty(XElement? elem) { return elem != null && !elem.HasAttributes && !elem.HasElements && elem.IsEmpty; } /// <summary> /// Decodes the XML escape sequences into normal string /// </summary> /// <param name="str">The string to decode.</param> /// <returns></returns> public static string DecodeXMLString(string str) { if (str.Contains('&')) return str.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace("&apos;", "'") .Replace("&amp;", "&"); // Make sure that &amp; is the final replace so that sequences such as &amp;gt; do not get corrupted return str; } /// <summary> /// Adds the 'xml:space="preserve"' attribute to the specified element. /// </summary> /// <param name="element">Element to add the 'xml:space="preserve"' attribute to</param> /// <param name="culture">The <see cref="CultureInfo" /> to use for string-formatting values.</param> /// <returns></returns> public static XElement AddPreserveSpaceAttribute(XElement element, CultureInfo culture) { element.AddAttributeNamespaceSafe(XNamespace.Xml + "space", "preserve", XNamespace.None, culture); return element; } public static string GetRandomPrefix(this XElement self) { var q = self.Attributes().Where(xa => xa.Name.Namespace == XNamespace.Xmlns).Select(xa => xa.Name.LocalName) .ToArray(); var setPrefixes = new HashSet<string>(q); var prefix = "p"; for (var i = 1; i <= 10000; i++) if (!setPrefixes.Contains(prefix + i)) return prefix + i; throw new InvalidOperationException("Cannot create a unique random prefix"); } /// <summary> /// Gets the string representation of the object, or <see cref="string.Empty" /> if the object is <see langword="null" />. /// </summary> /// <param name="self">The object to get as a string.</param> /// <param name="culture">The <see cref="CultureInfo" /> to use for culture-specific output.</param> /// <returns> /// The <see cref="CultureInfo" />-aware string representation of the object, or <see cref="string.Empty" /> if /// the object is <see langword="null" />. /// </returns> public static string ToXmlValue(this object? self, CultureInfo culture) { if (self == null) return string.Empty; return self.GetType().Name switch { "Boolean" => ((bool) self).ToString().ToLowerInvariant(), "Double" => ((double) self).ToString("R", culture), "Single" => ((float) self).ToString("R", culture), "BigInteger" => ReflectionUtils.InvokeMethod(self, "ToString", "R", culture) as string ?? string.Empty, _ => Convert.ToString(self, culture) ?? string.Empty }; } public static XAttribute AddAttributeNamespaceSafe(this XElement parent, XName attrName, object? attrValue, XNamespace documentDefaultNamespace, CultureInfo culture) { var newAttrName = attrName; if (newAttrName.Namespace == documentDefaultNamespace) newAttrName = newAttrName.RemoveNamespace(); var newAttr = new XAttribute(newAttrName, attrValue.ToXmlValue(culture)); parent.Add(newAttr); return newAttr; } public static XAttribute? Attribute_NamespaceSafe(this XElement parent, XName attrName, XNamespace documentDefaultNamespace) { if (attrName.Namespace == documentDefaultNamespace) attrName = attrName.RemoveNamespace(); return parent.Attribute(attrName); } public static IEnumerable<XAttribute> Attributes_NamespaceSafe(this XElement parent, XName attrName, XNamespace documentDefaultNamespace) { if (attrName.Namespace == documentDefaultNamespace) attrName = attrName.RemoveNamespace(); return parent.Attributes(attrName); } /// <summary> /// Gets the XML content of an <see cref="XElement" /> with the value parameter formatted <see cref="CultureInfo" /> /// -specific. /// </summary> /// <param name="self">The <see cref="XElement" /></param> /// <param name="contentValue">An <see cref="object" /> for the content value.</param> /// <param name="culture">The <see cref="CultureInfo" /> to use for string-formatting the content value.</param> /// <returns> /// The XML content of an <see cref="XElement" /> with the value parameter formatted <see cref="CultureInfo" /> /// -specific. /// </returns> public static XElement AddXmlContent(this XElement self, object? contentValue, CultureInfo culture) { self.Add(new XText(contentValue.ToXmlValue(culture))); return self; } public static string GetXmlContent(this XElement self) { var values = self.Nodes().OfType<XText>().ToArray(); if (values.Length > 0) return values[0].Value; return string.Empty; } public static XAttribute? Attribute_NamespaceNeutral(this XElement parent, XName name) { return parent.Attributes().FirstOrDefault(e => e.Name.LocalName == name.LocalName); } public static IEnumerable<XAttribute> Attributes_NamespaceNeutral(this XElement parent, XName name) { return parent.Attributes().Where(e => e.Name.LocalName == name.LocalName); } public static XElement? Element_NamespaceNeutral(this XContainer parent, XName name) { return parent.Elements().FirstOrDefault(e => e.Name.LocalName == name.LocalName); } public static IEnumerable<XElement> Elements_NamespaceNeutral(this XContainer parent, XName name) { return parent.Elements().Where(e => e.Name.LocalName == name.LocalName); } public static bool IsEmpty(this XNamespace self) { return !string.IsNullOrEmpty(self.NamespaceName.Trim()); } public static XNamespace IfEmptyThen(this XNamespace self, XNamespace next) { return self.IsEmpty() ? self : next; } public static XNamespace IfEmptyThenNone(this XNamespace self) { return IfEmptyThen(self, XNamespace.None); } public static XName OverrideNsIfEmpty(this XName self, XNamespace ns) { if (self.Namespace.IsEmpty()) return self; if (ns.IsEmpty()) return ns + self.LocalName; return self; } public static XName RemoveNamespace(this XName self) { return XName.Get(self.LocalName); } }
mono
mono-addins
F:\Projects\TestMap\Temp\mono-addins\Mono.Addins.sln
F:\Projects\TestMap\Temp\mono-addins\Test\UnitTests\UnitTests.csproj
F:\Projects\TestMap\Temp\mono-addins\Test\UnitTests\TestAddinDescription.cs
UnitTests
TestAddinDescription
['CultureInfo oldc;']
['System', 'NUnit.Framework', 'System.IO', 'Mono.Addins.Description', 'System.Globalization', 'Mono.Addins', 'System.Xml', 'System.Collections.Generic', 'System.Linq']
NUnit
net472;net6.0
[TestFixture] public class TestAddinDescription: TestBase { CultureInfo oldc; [SetUp] public void TestSetup () { oldc = System.Threading.Thread.CurrentThread.CurrentCulture; CultureInfo ci = CultureInfo.GetCultureInfo("ca-ES"); System.Threading.Thread.CurrentThread.CurrentCulture = ci; } [TearDown] public void TestTeardown () { System.Threading.Thread.CurrentThread.CurrentCulture = oldc; } [Test] public void PropertyLocalization () { AddinDescription desc = new AddinDescription (); desc.Properties.SetPropertyValue ("prop1", "val1"); Assert.AreEqual ("val1", desc.Properties.GetPropertyValue ("prop1")); Assert.AreEqual ("val1", desc.Properties.GetPropertyValue ("prop1", "en")); Assert.AreEqual ("val1", desc.Properties.GetPropertyValue ("prop1", "en-US")); Assert.AreEqual ("val1", desc.Properties.GetPropertyValue ("prop1", "en_US")); Assert.AreEqual ("val1", desc.Properties.GetPropertyValue ("prop1", null)); desc.Properties.SetPropertyValue ("prop2", "valCa", "ca"); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca-ES")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca_ES")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca-AN")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca_AN")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", "en")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", "en-US")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", "en_US")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", null)); desc.Properties.SetPropertyValue ("prop2", "valCaEs", "ca_ES"); Assert.AreEqual ("valCaEs", desc.Properties.GetPropertyValue ("prop2")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca")); Assert.AreEqual ("valCaEs", desc.Properties.GetPropertyValue ("prop2", "ca-ES")); Assert.AreEqual ("valCaEs", desc.Properties.GetPropertyValue ("prop2", "ca_ES")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca-AN")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca_AN")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", "en")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", "en-US")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", "en_US")); Assert.IsEmpty (desc.Properties.GetPropertyValue ("prop2", null)); desc.Properties.SetPropertyValue ("prop2", "val4", null); Assert.AreEqual ("valCaEs", desc.Properties.GetPropertyValue ("prop2")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca")); Assert.AreEqual ("valCaEs", desc.Properties.GetPropertyValue ("prop2", "ca-ES")); Assert.AreEqual ("valCaEs", desc.Properties.GetPropertyValue ("prop2", "ca_ES")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca-AN")); Assert.AreEqual ("valCa", desc.Properties.GetPropertyValue ("prop2", "ca_AN")); Assert.AreEqual ("val4", desc.Properties.GetPropertyValue ("prop2", "en")); Assert.AreEqual ("val4", desc.Properties.GetPropertyValue ("prop2", "en-US")); Assert.AreEqual ("val4", desc.Properties.GetPropertyValue ("prop2", "en_US")); Assert.AreEqual ("val4", desc.Properties.GetPropertyValue ("prop2", null)); } [Test] public void PropertiesFromAddin () { Addin ad = AddinManager.Registry.GetAddin ("SimpleApp.Core"); Assert.AreEqual ("Una aplicació simple", ad.Name); Assert.AreEqual ("A simple application", ad.Properties.GetPropertyValue ("Name","en-US")); Assert.AreEqual ("SimpleApp description", ad.Description.Description); Assert.AreEqual ("Lluis Sanchez", ad.Description.Author); Assert.AreEqual ("GPL", ad.Description.Copyright); Assert.AreEqual ("Val1", ad.Properties.GetPropertyValue ("Prop1","en-US")); Assert.AreEqual ("Val1Cat", ad.Properties.GetPropertyValue ("Prop1")); Assert.AreEqual ("Val2", ad.Properties.GetPropertyValue ("Prop2","en-US")); Assert.AreEqual ("Val2Cat", ad.Properties.GetPropertyValue ("Prop2")); oldc = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es-ES"); Assert.AreEqual ("Una aplicación simple", ad.Name); Assert.AreEqual ("Descripción de SimpleApp", ad.Description.Description); System.Threading.Thread.CurrentThread.CurrentCulture = oldc; } // Built-in [TestCase ("SimpleApp.SystemInfoExtension,0.1.0", "StringResource")] // In own addin [TestCase ("SimpleApp.CommandExtension,0.1.0", "CommandExtension.CustomLocalizerFactory, CommandExtension, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")] // In dependent addin [TestCase ("SimpleApp.HelloWorldExtension,0.1.0", "CommandExtension.CustomLocalizerFactory, CommandExtension, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")] // In imported assembly [TestCase ("MultiAssemblyAddin,0.1.0", "SecondAssembly.CustomLocalizerFactory, SecondAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")] public void LocalizerProperties (string addinId, string expectedType) { Addin ad = AddinManager.Registry.GetAddin (addinId); ExtensionNodeDescription localizer = ad.Description.Localizer; Assert.AreEqual (expectedType, localizer.GetAttribute ("type")); } [Test] public void CheckConditionAssemblyNames() { Addin ad = AddinManager.Registry.GetAddin ("SimpleApp.SystemInfoExtension,0.1.0"); var conditions = ad.Description.ConditionTypes; Assert.AreEqual (0, conditions.Count); foreach (ConditionTypeDescription cond in conditions) { } } [Test] public void TestAssemblyNamesWritten () { Addin ad = AddinManager.Registry.GetAddin ("MultiAssemblyAddin,0.1.0"); var assemblyNames = ad.Description.MainModule.AssemblyNames; Assert.AreEqual (ad.Description.MainModule.Assemblies.Count, assemblyNames.Count); Assert.AreEqual ("MultiAssemblyAddin, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", assemblyNames[0]); Assert.AreEqual ("SecondAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", assemblyNames[1]); assemblyNames = ad.Description.OptionalModules[0].AssemblyNames; Assert.AreEqual (1, assemblyNames.Count); Assert.AreEqual ("OptionalModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", assemblyNames[0]); } AddinDescription DescFromResource (string res) { using (Stream s = GetType().Assembly.GetManifestResourceStream (res)) { return AddinDescription.Read (s, "."); } } XmlDocument XmlFromResource (string res) { using (Stream s = GetType().Assembly.GetManifestResourceStream (res)) { XmlDocument doc = new XmlDocument (); doc.Load (s); return doc; } } [Test] public void ReadCoreProperties () { AddinDescription desc = DescFromResource ("TestManifest2.xml"); Assert.AreEqual ("Core", desc.LocalId); Assert.AreEqual ("0.1.0", desc.Version); Assert.AreEqual ("0.0.1", desc.CompatVersion); Assert.AreEqual (false, desc.EnabledByDefault); Assert.AreEqual (AddinFlags.CantDisable | AddinFlags.CantUninstall | AddinFlags.Hidden, desc.Flags); Assert.AreEqual (true, desc.IsRoot); Assert.AreEqual ("SimpleApp", desc.Namespace); } [Test] public void WriteCorePropertiesAsElems () { AddinDescription desc = DescFromResource ("TestManifest2.xml"); XmlDocument doc1 = XmlFromResource ("TestManifest2.xml"); XmlDocument doc2 = desc.SaveToXml (); Assert.AreEqual (Util.Infoset (doc1), Util.Infoset (doc2)); desc.LocalId = "Core2"; desc.Version = "0.2.0"; desc.CompatVersion = "0.0.2"; desc.EnabledByDefault = true; desc.Flags = AddinFlags.CantUninstall; desc.IsRoot = false; desc.Namespace = "SimpleApp2"; doc1 = XmlFromResource ("TestManifest2-bis.xml"); doc2 = desc.SaveToXml (); Assert.AreEqual (Util.Infoset (doc1), Util.Infoset (doc2)); } [Test] public void WriteCorePropertiesAsProps () { AddinDescription desc = DescFromResource ("TestManifest3.xml"); XmlDocument doc1 = XmlFromResource ("TestManifest3.xml"); XmlDocument doc2 = desc.SaveToXml (); Assert.AreEqual (Util.Infoset (doc1), Util.Infoset (doc2)); } }
1,498
10,232
// // AddinDescription.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Collections.Specialized; using Mono.Addins.Serialization; using Mono.Addins.Database; using System.Text; namespace Mono.Addins.Description { /// <summary> /// An add-in description /// </summary> /// <remarks> /// This class represent an add-in manifest. It has properties for getting /// all information, and methods for loading and saving files. /// </remarks> public class AddinDescription: IBinaryXmlElement { XmlDocument configDoc; string configFile; AddinDatabase ownerDatabase; string id; string name; string ns; string version; string compatVersion; string author; string url; string copyright; string description; string category; string basePath; string sourceAddinFile; bool isroot; bool hasUserId; bool canWrite = true; bool defaultEnabled = true; AddinFlags flags = AddinFlags.None; string domain; ModuleDescription mainModule; ModuleCollection optionalModules; ExtensionNodeSetCollection nodeSets; ConditionTypeDescriptionCollection conditionTypes; ExtensionPointCollection extensionPoints; ExtensionNodeDescription localizer; object[] fileInfo; AddinPropertyCollectionImpl properties; Dictionary<string,string> variables; internal static BinaryXmlTypeMap typeMap; static AddinDescription () { typeMap = new BinaryXmlTypeMap (); typeMap.RegisterType (typeof(AddinDescription), "AddinDescription"); typeMap.RegisterType (typeof(Extension), "Extension"); typeMap.RegisterType (typeof(ExtensionNodeDescription), "Node"); typeMap.RegisterType (typeof(ExtensionNodeSet), "NodeSet"); typeMap.RegisterType (typeof(ExtensionNodeType), "NodeType"); typeMap.RegisterType (typeof(ExtensionPoint), "ExtensionPoint"); typeMap.RegisterType (typeof(ModuleDescription), "ModuleDescription"); typeMap.RegisterType (typeof(ConditionTypeDescription), "ConditionType"); typeMap.RegisterType (typeof(Condition), "Condition"); typeMap.RegisterType (typeof(AddinDependency), "AddinDependency"); typeMap.RegisterType (typeof(AssemblyDependency), "AssemblyDependency"); typeMap.RegisterType (typeof(NodeTypeAttribute), "NodeTypeAttribute"); typeMap.RegisterType (typeof(AddinFileInfo), "FileInfo"); typeMap.RegisterType (typeof(AddinProperty), "Property"); } internal AddinDatabase OwnerDatabase { get { return ownerDatabase; } set { ownerDatabase = value; } } /// <summary> /// Gets or sets the path to the main addin file. /// </summary> /// <value> /// The addin file. /// </value> /// <remarks> /// The add-in file can be either the main assembly of an add-in or an xml manifest. /// </remarks> public string AddinFile { get { return sourceAddinFile; } set { sourceAddinFile = value; } } /// <summary> /// Gets the addin identifier. /// </summary> /// <value> /// The addin identifier. /// </value> public string AddinId { get { return Addin.GetFullId (Namespace, LocalId, Version); } } /// <summary> /// Gets or sets the local identifier. /// </summary> /// <value> /// The local identifier. /// </value> public string LocalId { get { return id != null ? ParseString (id) : string.Empty; } set { id = value; hasUserId = true; } } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value> /// The namespace. /// </value> public string Namespace { get { return ns != null ? ParseString (ns) : string.Empty; } set { ns = value; } } /// <summary> /// Gets or sets the display name of the add-in. /// </summary> /// <value> /// The name. /// </value> public string Name { get { string val = Properties.GetPropertyValue ("Name"); if (val.Length > 0) return val; if (name != null && name.Length > 0) return ParseString (name); if (HasUserId) return AddinId; else if (sourceAddinFile != null) return Path.GetFileNameWithoutExtension (sourceAddinFile); else return string.Empty; } set { name = value; } } /// <summary> /// Gets or sets the version. /// </summary> /// <value> /// The version. /// </value> public string Version { get { return version != null ? ParseString (version) : string.Empty; } set { version = value; } } /// <summary> /// Gets or sets the version of the add-in with which this add-in is backwards compatible. /// </summary> /// <value> /// The compat version. /// </value> public string CompatVersion { get { return compatVersion != null ? ParseString (compatVersion) : string.Empty; } set { compatVersion = value; } } /// <summary> /// Gets or sets the author. /// </summary> /// <value> /// The author. /// </value> public string Author { get { string val = Properties.GetPropertyValue ("Author"); if (val.Length > 0) return val; return ParseString (author) ?? string.Empty; } set { author = value; } } /// <summary> /// Gets or sets the Url where more information about the add-in can be found. /// </summary> /// <value> /// The URL. /// </value> public string Url { get { string val = Properties.GetPropertyValue ("Url"); if (val.Length > 0) return val; return ParseString (url) ?? string.Empty; } set { url = value; } } /// <summary> /// Gets or sets the copyright. /// </summary> /// <value> /// The copyright. /// </value> public string Copyright { get { string val = Properties.GetPropertyValue ("Copyright"); if (val.Length > 0) return val; return ParseString (copyright) ?? string.Empty; } set { copyright = value; } } /// <summary> /// Gets or sets the description of the add-in. /// </summary> /// <value> /// The description. /// </value> public string Description { get { string val = Properties.GetPropertyValue ("Description"); if (val.Length > 0) return val; return ParseString (description) ?? string.Empty; } set { description = value; } } /// <summary> /// Gets or sets the category of the add-in. /// </summary> /// <value> /// The category. /// </value> public string Category { get { string val = Properties.GetPropertyValue ("Category"); if (val.Length > 0) return val; return ParseString (category) ?? string.Empty; } set { category = value; } } /// <summary> /// Gets the base path for locating external files relative to the add-in. /// </summary> /// <value> /// The base path. /// </value> public string BasePath { get { return basePath != null ? basePath : string.Empty; } } internal void SetBasePath (string path) { basePath = path; } /// <summary> /// Gets or sets a value indicating whether this instance is an add-in root. /// </summary> /// <value> /// <c>true</c> if this instance is an add-in root; otherwise, <c>false</c>. /// </value> public bool IsRoot { get { return isroot; } set { isroot = value; } } /// <summary> /// Gets or sets a value indicating whether this add-in is enabled by default. /// </summary> /// <value> /// <c>true</c> if enabled by default; otherwise, <c>false</c>. /// </value> public bool EnabledByDefault { get { return defaultEnabled; } set { defaultEnabled = value; } } /// <summary> /// Gets or sets the add-in flags. /// </summary> /// <value> /// The flags. /// </value> public AddinFlags Flags { get { return flags; } set { flags = value; } } internal bool HasUserId { get { return hasUserId; } set { hasUserId = value; } } /// <summary> /// Gets a value indicating whether this add-in can be disabled. /// </summary> /// <value> /// <c>true</c> if this add-in can be disabled; otherwise, <c>false</c>. /// </value> public bool CanDisable { get { return (flags & AddinFlags.CantDisable) == 0 && !IsHidden; } } /// <summary> /// Gets a value indicating whether this add-in can be uninstalled. /// </summary> /// <value> /// <c>true</c> if this instance can be uninstalled; otherwise, <c>false</c>. /// </value> public bool CanUninstall { get { return (flags & AddinFlags.CantUninstall) == 0 && !IsHidden; } } /// <summary> /// Gets a value indicating whether this add-in is hidden. /// </summary> /// <value> /// <c>true</c> if this add-in is hidden; otherwise, <c>false</c>. /// </value> public bool IsHidden { get { return (flags & AddinFlags.Hidden) != 0; } } internal bool SupportsVersion (string ver) { return Addin.CompareVersions (ver, Version) >= 0 && (CompatVersion.Length == 0 || Addin.CompareVersions (ver, CompatVersion) <= 0); } /// <summary> /// Gets all external files /// </summary> /// <value> /// All files. /// </value> /// <remarks> /// External files are data files and assemblies explicitly referenced in the Runtime section of the add-in manifest. /// </remarks> public StringCollection AllFiles { get { StringCollection col = new StringCollection (); foreach (string s in MainModule.AllFiles) col.Add (s); foreach (ModuleDescription mod in OptionalModules) { foreach (string s in mod.AllFiles) col.Add (s); } return col; } } /// <summary> /// Gets all paths to be ignored by the add-in scanner. /// </summary> /// <value> /// All paths to be ignored. /// </value> public StringCollection AllIgnorePaths { get { StringCollection col = new StringCollection (); foreach (string s in MainModule.IgnorePaths) col.Add (s); foreach (ModuleDescription mod in OptionalModules) { foreach (string s in mod.IgnorePaths) col.Add (s); } return col; } } /// <summary> /// Gets the main module. /// </summary> /// <value> /// The main module. /// </value> public ModuleDescription MainModule { get { if (mainModule == null) { if (RootElement == null) mainModule = new ModuleDescription (); else mainModule = new ModuleDescription (RootElement); mainModule.SetParent (this); } return mainModule; } } /// <summary> /// Gets the optional modules. /// </summary> /// <value> /// The optional modules. /// </value> /// <remarks> /// Optional modules can be used to declare extensions which will be registered only if some specified /// add-in dependencies can be satisfied. Dependencies specified in optional modules are 'soft dependencies', /// which means that they don't need to be satisfied in order to load the add-in. /// </remarks> public ModuleCollection OptionalModules { get { if (optionalModules == null) { optionalModules = new ModuleCollection (this); if (RootElement != null) { foreach (XmlElement mod in RootElement.SelectNodes ("Module")) optionalModules.Add (new ModuleDescription (mod)); } } return optionalModules; } } /// <summary> /// Gets all modules (including the main module and all optional modules) /// </summary> /// <value> /// All modules. /// </value> public ModuleCollection AllModules { get { ModuleCollection col = new ModuleCollection (this); col.Add (MainModule); foreach (ModuleDescription mod in OptionalModules) col.Add (mod); return col; } } /// <summary> /// Gets the extension node sets. /// </summary> /// <value> /// The extension node sets. /// </value> public ExtensionNodeSetCollection ExtensionNodeSets { get { if (nodeSets == null) { nodeSets = new ExtensionNodeSetCollection (this); if (RootElement != null) { foreach (XmlElement elem in RootElement.SelectNodes ("ExtensionNodeSet")) nodeSets.Add (new ExtensionNodeSet (elem)); } } return nodeSets; } } /// <summary> /// Gets the extension points. /// </summary> /// <value> /// The extension points. /// </value> public ExtensionPointCollection ExtensionPoints { get { if (extensionPoints == null) { extensionPoints = new ExtensionPointCollection (this); if (RootElement != null) { foreach (XmlElement elem in RootElement.SelectNodes ("ExtensionPoint")) extensionPoints.Add (new ExtensionPoint (elem)); } } return extensionPoints; } } /// <summary> /// Gets the condition types. /// </summary> /// <value> /// The condition types. /// </value> public ConditionTypeDescriptionCollection ConditionTypes { get { if (conditionTypes == null) { conditionTypes = new ConditionTypeDescriptionCollection (this); if (RootElement != null) { foreach (XmlElement elem in RootElement.SelectNodes ("ConditionType")) conditionTypes.Add (new ConditionTypeDescription (elem)); } } return conditionTypes; } } /// <summary> /// Gets or sets the add-in localizer. /// </summary> /// <value> /// The description of the add-in localizer for this add-in. /// </value> public ExtensionNodeDescription Localizer { get { return localizer; } set { localizer = value; } } /// <summary> /// Custom properties specified in the add-in header /// </summary> public AddinPropertyCollection Properties { get { if (properties == null) properties = new AddinPropertyCollectionImpl (this); return properties; } } /// <summary> /// Adds an extension point. /// </summary> /// <returns> /// The extension point. /// </returns> /// <param name='path'> /// Path that identifies the new extension point. /// </param> public ExtensionPoint AddExtensionPoint (string path) { ExtensionPoint ep = new ExtensionPoint (); ep.Path = path; ExtensionPoints.Add (ep); return ep; } internal ExtensionNodeDescription FindExtensionNode (string path, bool lookInDeps) { // Look in the extensions of this add-in foreach (Extension ext in MainModule.Extensions) { if (path.StartsWith (ext.Path + "/")) { string subp = path.Substring (ext.Path.Length).Trim ('/'); ExtensionNodeDescriptionCollection nodes = ext.ExtensionNodes; ExtensionNodeDescription node = null; foreach (string p in subp.Split ('/')) { if (p.Length == 0) continue; node = nodes [p]; if (node == null) break; nodes = node.ChildNodes; } if (node != null) return node; } } if (!lookInDeps || OwnerDatabase == null) return null; // Look in dependencies foreach (Dependency dep in MainModule.Dependencies) { AddinDependency adep = dep as AddinDependency; if (adep == null) continue; Addin ad = OwnerDatabase.GetInstalledAddin (Domain, adep.FullAddinId); if (ad != null && ad.Description != null) { ExtensionNodeDescription node = ad.Description.FindExtensionNode (path, false); if (node != null) return node; } } return null; } XmlElement RootElement { get { if (configDoc != null) return configDoc.DocumentElement; else return null; } } internal void ResetXmlDoc () { configDoc = null; } /// <summary> /// Gets or sets file where this description is stored /// </summary> /// <value> /// The file path. /// </value> public string FileName { get { return configFile; } set { configFile = value; } } internal string Domain { get { return domain; } set { domain = value; } } internal void StoreFileInfo () { var allFiles = AllFiles; var list = new List<AddinFileInfo> (allFiles.Count); foreach (string f in allFiles) { string file = Path.Combine (this.BasePath, f); AddinFileInfo fi = new AddinFileInfo (); fi.FileName = f; fi.Timestamp = File.GetLastWriteTime (file); list.Add (fi); } fileInfo = list.ToArray (); } internal bool FilesChanged () { // Checks if the files of the add-in have changed. if (fileInfo == null) return true; foreach (AddinFileInfo f in fileInfo) { string file = Path.Combine (this.BasePath, f.FileName); if (!File.Exists (file)) return true; if (f.Timestamp != File.GetLastWriteTime (file)) return true; } return false; } void TransferCoreProperties (bool removeProperties) { if (properties == null) return; string val = properties.ExtractCoreProperty ("Id", removeProperties); if (val != null) id = val; val = properties.ExtractCoreProperty ("Namespace", removeProperties); if (val != null) ns = val; val = properties.ExtractCoreProperty ("Version", removeProperties); if (val != null) version = val; val = properties.ExtractCoreProperty ("CompatVersion", removeProperties); if (val != null) compatVersion = val; val = properties.ExtractCoreProperty ("DefaultEnabled", removeProperties); if (val != null) defaultEnabled = GetBool (val, true); val = properties.ExtractCoreProperty ("IsRoot", removeProperties); if (val != null) isroot = GetBool (val, true); val = properties.ExtractCoreProperty ("Flags", removeProperties); if (val != null) flags = (AddinFlags) Enum.Parse (typeof(AddinFlags), val); } bool TryGetVariableValue (string name, out string value) { if (variables != null && variables.TryGetValue (name, out value)) return true; switch (name) { case "Id": value = id; return true; case "Namespace": value = ns; return true; case "Version": value = version; return true; case "CompatVersion": value = compatVersion; return true; case "DefaultEnabled": value = defaultEnabled.ToString (); return true; case "IsRoot": value = isroot.ToString (); return true; case "Flags": value = flags.ToString (); return true; } if (properties != null && properties.HasProperty (name)) { value = properties.GetPropertyValue (name); return true; } value = null; return false; } /// <summary> /// Saves the add-in description. /// </summary> /// <param name='fileName'> /// File name where to save this instance /// </param> /// <remarks> /// Saves the add-in description to the specified file and sets the FileName property. /// </remarks> public void Save (string fileName) { configFile = fileName; Save (); } /// <summary> /// Saves the add-in description. /// </summary> /// <exception cref='InvalidOperationException'> /// It is thrown if FileName is not set /// </exception> /// <remarks> /// The description is saved to the file specified in the FileName property. /// </remarks> public void Save () { if (configFile == null) throw new InvalidOperationException ("File name not specified."); SaveXml (); using (StreamWriter sw = new StreamWriter (configFile)) { XmlTextWriter tw = new XmlTextWriter (sw); tw.Formatting = Formatting.Indented; configDoc.Save (tw); } } /// <summary> /// Generates an XML representation of the add-in description /// </summary> /// <returns> /// An XML manifest. /// </returns> public XmlDocument SaveToXml () { SaveXml (); return configDoc; } void SaveXml () { if (!canWrite) throw new InvalidOperationException ("Can't write incomplete description."); XmlElement elem; if (configDoc == null) { configDoc = new XmlDocument (); configDoc.AppendChild (configDoc.CreateElement ("Addin")); } elem = configDoc.DocumentElement; SaveCoreProperty (elem, HasUserId ? id : null, "id", "Id"); SaveCoreProperty (elem, version, "version", "Version"); SaveCoreProperty (elem, ns, "namespace", "Namespace"); SaveCoreProperty (elem, isroot ? "true" : null, "isroot", "IsRoot"); // Name will return the file name when HasUserId=false if (!string.IsNullOrEmpty (name)) elem.SetAttribute ("name", name); else elem.RemoveAttribute ("name"); SaveCoreProperty (elem, compatVersion, "compatVersion", "CompatVersion"); SaveCoreProperty (elem, defaultEnabled ? null : "false", "defaultEnabled", "DefaultEnabled"); SaveCoreProperty (elem, flags != AddinFlags.None ? flags.ToString () : null, "flags", "Flags"); if (author != null && author.Length > 0) elem.SetAttribute ("author", author); else elem.RemoveAttribute ("author"); if (url != null && url.Length > 0) elem.SetAttribute ("url", url); else elem.RemoveAttribute ("url"); if (copyright != null && copyright.Length > 0) elem.SetAttribute ("copyright", copyright); else elem.RemoveAttribute ("copyright"); if (description != null && description.Length > 0) elem.SetAttribute ("description", description); else elem.RemoveAttribute ("description"); if (category != null && category.Length > 0) elem.SetAttribute ("category", category); else elem.RemoveAttribute ("category"); if (localizer == null || localizer.Element == null) { // Remove old element if it exists XmlElement oldLoc = (XmlElement) elem.SelectSingleNode ("Localizer"); if (oldLoc != null) elem.RemoveChild (oldLoc); } if (localizer != null) localizer.SaveXml (elem); if (mainModule != null) { mainModule.Element = elem; mainModule.SaveXml (elem); } if (optionalModules != null) optionalModules.SaveXml (elem); if (nodeSets != null) nodeSets.SaveXml (elem); if (extensionPoints != null) extensionPoints.SaveXml (elem); XmlElement oldHeader = (XmlElement) elem.SelectSingleNode ("Header"); if (properties == null || properties.Count == 0) { if (oldHeader != null) elem.RemoveChild (oldHeader); } else { if (oldHeader == null) { oldHeader = elem.OwnerDocument.CreateElement ("Header"); if (elem.FirstChild != null) elem.InsertBefore (oldHeader, elem.FirstChild); else elem.AppendChild (oldHeader); } else oldHeader.RemoveAll (); foreach (var prop in properties) { XmlElement propElem = elem.OwnerDocument.CreateElement (prop.Name); if (!string.IsNullOrEmpty (prop.Locale)) propElem.SetAttribute ("locale", prop.Locale); propElem.InnerText = prop.Value ?? string.Empty; oldHeader.AppendChild (propElem); } } XmlElement oldVars = (XmlElement) elem.SelectSingleNode ("Variables"); if (variables == null || variables.Count == 0) { if (oldVars != null) elem.RemoveChild (oldVars); } else { if (oldVars == null) { oldVars = elem.OwnerDocument.CreateElement ("Variables"); if (elem.FirstChild != null) elem.InsertBefore (oldVars, elem.FirstChild); else elem.AppendChild (oldVars); } else oldVars.RemoveAll (); foreach (var prop in variables) { XmlElement propElem = elem.OwnerDocument.CreateElement (prop.Key); propElem.InnerText = prop.Value ?? string.Empty; oldVars.AppendChild (propElem); } } } public XmlDocument SaveToVsixXml () { if (!canWrite) throw new InvalidOperationException ("Can't write incomplete description."); XmlElement packageManifestEl; var vsixDoc = new XmlDocument (); vsixDoc.AppendChild (vsixDoc.CreateElement ("PackageManifest")); packageManifestEl = vsixDoc.DocumentElement; packageManifestEl.SetAttribute ("Version", "2.0.0"); packageManifestEl.SetAttribute ("xmlns", "http://schemas.microsoft.com/developer/vsx-schema/2011"); var metadata = vsixDoc.CreateElement ("Metadata"); var identity = vsixDoc.CreateElement ("Identity"); identity.SetAttribute ("Language", "en-US"); identity.SetAttribute ("Id", LocalId); identity.SetAttribute ("Version", Version); identity.SetAttribute ("Publisher", Properties.GetPropertyValue ("VisualStudio.Publisher")); metadata.AppendChild (identity); var displayNameEl = vsixDoc.CreateElement ("DisplayName"); displayNameEl.InnerText = Name; metadata.AppendChild (displayNameEl); var descriptionEl = vsixDoc.CreateElement ("Description"); descriptionEl.SetAttribute ("xml:space", "preserve"); descriptionEl.InnerText = Description; metadata.AppendChild (descriptionEl); var moreInfoEl = vsixDoc.CreateElement ("MoreInfo"); moreInfoEl.InnerText = Url; metadata.AppendChild (moreInfoEl); var tagsEl = vsixDoc.CreateElement ("Tags"); if (!string.IsNullOrEmpty (Properties.GetPropertyValue ("VisualStudio.Tags"))) tagsEl.InnerText = Properties.GetPropertyValue ("VisualStudio.Tags"); metadata.AppendChild (tagsEl); var categoriesEl = vsixDoc.CreateElement ("Categories"); categoriesEl.InnerText = Category; metadata.AppendChild (categoriesEl); var galleryFlagsEl = vsixDoc.CreateElement ("GalleryFlags"); var galleryFlags = Properties.GetPropertyValue ("VisualStudio.GalleryFlags"); if (string.IsNullOrEmpty (galleryFlags)) galleryFlags = "Public"; galleryFlagsEl.InnerText = galleryFlags; metadata.AppendChild (galleryFlagsEl); var badgesEl = vsixDoc.CreateElement ("Badges"); //TODO:Add Badges support metadata.AppendChild (badgesEl); var icon = Properties.GetPropertyValue ("Icon32"); if (!string.IsNullOrEmpty (icon)) { var iconEl = vsixDoc.CreateElement ("Icon"); iconEl.InnerText = icon; metadata.AppendChild (iconEl); } var license = Copyright; if (!string.IsNullOrEmpty (license)) { var licenseEl = vsixDoc.CreateElement ("License"); licenseEl.InnerText = license; metadata.AppendChild (licenseEl); } packageManifestEl.AppendChild (metadata); var installationEl = vsixDoc.CreateElement ("Installation"); var installationTargetEl = vsixDoc.CreateElement ("InstallationTarget"); installationTargetEl.SetAttribute ("Id", "Microsoft.VisualStudio.Mac"); installationEl.AppendChild (installationTargetEl); packageManifestEl.AppendChild (installationEl); packageManifestEl.AppendChild (vsixDoc.CreateElement ("Dependencies")); var assetsEl = vsixDoc.CreateElement ("Assets"); var addinInfoAsset = vsixDoc.CreateElement ("Asset"); addinInfoAsset.SetAttribute ("Type", "Microsoft.VisualStudio.Mac.AddinInfo"); addinInfoAsset.SetAttribute ("Path", "addin.info"); addinInfoAsset.SetAttribute ("Addressable", "true"); assetsEl.AppendChild (addinInfoAsset); if (!string.IsNullOrEmpty (icon)) { var iconAsset = vsixDoc.CreateElement ("Asset"); iconAsset.SetAttribute ("Type", "Microsoft.VisualStudio.Services.Icons.Default"); iconAsset.SetAttribute ("Path", icon); iconAsset.SetAttribute ("Addressable", "true"); assetsEl.AppendChild (iconAsset); } var propertyToAssetTypeMappings = new Dictionary<string, string>{ {"VisualStudio.License", "Microsoft.VisualStudio.Services.Content.License"}, {"VisualStudio.Details", "Microsoft.VisualStudio.Services.Content.Details"}, {"VisualStudio.Changelog", "Microsoft.VisualStudio.Services.Content.Changelog"}, }; foreach (var mapping in propertyToAssetTypeMappings) { if (!string.IsNullOrEmpty (Properties.GetPropertyValue (mapping.Key))) { var asset = vsixDoc.CreateElement ("Asset"); asset.SetAttribute ("Type", mapping.Value); asset.SetAttribute ("Path", icon); asset.SetAttribute ("Addressable", "true"); assetsEl.AppendChild (asset); } } packageManifestEl.AppendChild (assetsEl); return vsixDoc; } void SaveCoreProperty (XmlElement elem, string val, string attr, string prop) { if (properties != null && properties.HasProperty (prop)) { elem.RemoveAttribute (attr); if (!string.IsNullOrEmpty (val)) properties.SetPropertyValue (prop, val); else properties.RemoveProperty (prop); } else if (string.IsNullOrEmpty (val)) elem.RemoveAttribute (attr); else elem.SetAttribute (attr, val); } /// <summary> /// Load an add-in description from a file /// </summary> /// <param name='configFile'> /// The file. /// </param> public static AddinDescription Read (string configFile) { AddinDescription config; using (Stream s = File.OpenRead (configFile)) { config = Read (s, Path.GetDirectoryName (configFile)); } config.configFile = configFile; return config; } /// <summary> /// Load an add-in description from a stream /// </summary> /// <param name='stream'> /// The stream /// </param> /// <param name='basePath'> /// The path to be used to resolve relative file paths. /// </param> public static AddinDescription Read (Stream stream, string basePath) { return Read (new StreamReader (stream), basePath); } /// <summary> /// Load an add-in description from a text reader /// </summary> /// <param name='reader'> /// The text reader /// </param> /// <param name='basePath'> /// The path to be used to resolve relative file paths. /// </param> public static AddinDescription Read (TextReader reader, string basePath) { AddinDescription config = new AddinDescription (); try { config.configDoc = new XmlDocument (); config.configDoc.Load (reader); } catch (Exception ex) { throw new InvalidOperationException ("The add-in configuration file is invalid: " + ex.Message, ex); } XmlElement elem = config.configDoc.DocumentElement; if (elem.LocalName == "ExtensionModel") return config; XmlElement varsElem = (XmlElement) elem.SelectSingleNode ("Variables"); if (varsElem != null) { foreach (XmlNode node in varsElem.ChildNodes) { XmlElement prop = node as XmlElement; if (prop == null) continue; if (config.variables == null) config.variables = new Dictionary<string, string> (); config.variables [prop.LocalName] = prop.InnerText; } } config.id = elem.GetAttribute ("id"); config.ns = elem.GetAttribute ("namespace"); config.name = elem.GetAttribute ("name"); config.version = elem.GetAttribute ("version"); config.compatVersion = elem.GetAttribute ("compatVersion"); config.author = elem.GetAttribute ("author"); config.url = elem.GetAttribute ("url"); config.copyright = elem.GetAttribute ("copyright"); config.description = elem.GetAttribute ("description"); config.category = elem.GetAttribute ("category"); config.basePath = elem.GetAttribute ("basePath"); config.domain = "global"; string s = elem.GetAttribute ("isRoot"); if (s.Length == 0) s = elem.GetAttribute ("isroot"); config.isroot = GetBool (s, false); config.defaultEnabled = GetBool (elem.GetAttribute ("defaultEnabled"), true); string prot = elem.GetAttribute ("flags"); if (prot.Length == 0) config.flags = AddinFlags.None; else config.flags = (AddinFlags) Enum.Parse (typeof(AddinFlags), prot); XmlElement localizerElem = (XmlElement) elem.SelectSingleNode ("Localizer"); if (localizerElem != null) config.localizer = new ExtensionNodeDescription (localizerElem); XmlElement headerElem = (XmlElement) elem.SelectSingleNode ("Header"); if (headerElem != null) { foreach (XmlNode node in headerElem.ChildNodes) { XmlElement prop = node as XmlElement; if (prop == null) continue; config.Properties.SetPropertyValue (prop.LocalName, prop.InnerText, prop.GetAttribute ("locale")); } } config.TransferCoreProperties (false); if (config.id.Length > 0) config.hasUserId = true; return config; } internal string ParseString (string input) { if (input == null || input.Length < 4) return input; int i = input.IndexOf ("$("); if (i == -1) return input; StringBuilder result = new StringBuilder (input.Length); result.Append (input, 0, i); while (i < input.Length) { if (input [i] == '$') { i++; if (i >= input.Length || input[i] != '(') { result.Append ('$'); continue; } i++; int start = i; while (i < input.Length && input [i] != ')') i++; string tag = input.Substring (start, i - start); string tagValue; if (TryGetVariableValue (tag, out tagValue)) result.Append (tagValue); else { result.Append ('$'); i = start - 1; } } else { result.Append (input [i]); } i++; } return result.ToString (); } static bool GetBool (string s, bool defval) { if (s.Length == 0) return defval; else return s == "true" || s == "yes"; } internal static AddinDescription ReadBinary (FileDatabase fdb, string configFile) { AddinDescription description = (AddinDescription) fdb.ReadSharedObject (configFile, typeMap); if (description != null) { description.FileName = configFile; description.canWrite = !fdb.IgnoreDescriptionData; } return description; } internal void SaveBinary (FileDatabase fdb, string file) { configFile = file; SaveBinary (fdb); } internal void SaveBinary (FileDatabase fdb) { if (!canWrite) throw new InvalidOperationException ("Can't write incomplete description."); fdb.WriteSharedObject (AddinFile, FileName, typeMap, this); // BinaryXmlReader.DumpFile (configFile); } /// <summary> /// Verify this instance. /// </summary> /// <remarks> /// This method checks all the definitions in the description and returns a list of errors. /// If the returned list is empty, it means that the description is valid. /// </remarks> public StringCollection Verify () { return Verify (new AddinFileSystemExtension ()); } internal StringCollection Verify (AddinFileSystemExtension fs) { StringCollection errors = new StringCollection (); if (IsRoot) { if (OptionalModules.Count > 0) errors.Add ("Root add-in hosts can't have optional modules."); } if (AddinId.Length == 0 || Version.Length == 0) { if (ExtensionPoints.Count > 0) errors.Add ("Add-ins which define new extension points must have an Id and Version."); } MainModule.Verify ("", errors); OptionalModules.Verify ("", errors); ExtensionNodeSets.Verify ("", errors); ExtensionPoints.Verify ("", errors); ConditionTypes.Verify ("", errors); foreach (ExtensionNodeSet nset in ExtensionNodeSets) { if (nset.Id.Length == 0) errors.Add ("Attribute 'id' can't be empty for global node sets."); } string bp = null; if (BasePath.Length > 0) bp = BasePath; else if (sourceAddinFile != null && sourceAddinFile.Length > 0) bp = Path.GetDirectoryName (AddinFile); else if (configFile != null && configFile.Length > 0) bp = Path.GetDirectoryName (configFile); if (bp != null) { foreach (string file in AllFiles) { string asmFile = Path.Combine (bp, Util.NormalizePath (file)); if (!fs.FileExists (asmFile)) errors.Add ("The file '" + asmFile + "' referenced in the manifest could not be found."); } } if (localizer != null && localizer.GetAttribute ("type").Length == 0) { errors.Add ("The attribute 'type' in the Location element is required."); } // Ensure that there are no duplicated properties if (properties != null) { HashSet<string> props = new HashSet<string> (); foreach (var prop in properties) { if (!props.Add (prop.Name + " " + prop.Locale)) errors.Add (string.Format ("Property {0} specified more than once", prop.Name + (prop.Locale != null ? " (" + prop.Locale + ")" : ""))); } } return errors; } internal void SetExtensionsAddinId (string addinId) { foreach (ExtensionPoint ep in ExtensionPoints) ep.SetExtensionsAddinId (addinId); foreach (ExtensionNodeSet ns in ExtensionNodeSets) ns.SetExtensionsAddinId (addinId); } internal void UnmergeExternalData (Hashtable addins) { // Removes extension types and extension sets coming from other add-ins. foreach (ExtensionPoint ep in ExtensionPoints) ep.UnmergeExternalData (AddinId, addins); foreach (ExtensionNodeSet ns in ExtensionNodeSets) ns.UnmergeExternalData (AddinId, addins); } internal void MergeExternalData (AddinDescription other) { // Removes extension types and extension sets coming from other add-ins. foreach (ExtensionPoint ep in other.ExtensionPoints) { ExtensionPoint tep = ExtensionPoints [ep.Path]; if (tep != null) tep.MergeWith (AddinId, ep); } foreach (ExtensionNodeSet ns in other.ExtensionNodeSets) { ExtensionNodeSet tns = ExtensionNodeSets [ns.Id]; if (tns != null) tns.MergeWith (AddinId, ns); } } internal bool IsExtensionModel { get { return RootElement.LocalName == "ExtensionModel"; } } internal static AddinDescription Merge (AddinDescription desc1, AddinDescription desc2) { if (!desc2.IsExtensionModel) { AddinDescription tmp = desc1; desc1 = desc2; desc2 = tmp; } ((AddinPropertyCollectionImpl)desc1.Properties).AddRange (desc2.Properties); desc1.ExtensionPoints.AddRange (desc2.ExtensionPoints); desc1.ExtensionNodeSets.AddRange (desc2.ExtensionNodeSets); desc1.ConditionTypes.AddRange (desc2.ConditionTypes); desc1.OptionalModules.AddRange (desc2.OptionalModules); foreach (string s in desc2.MainModule.Assemblies) desc1.MainModule.Assemblies.Add (s); foreach (string s in desc2.MainModule.DataFiles) desc1.MainModule.DataFiles.Add (s); desc1.MainModule.MergeWith (desc2.MainModule); return desc1; } void IBinaryXmlElement.Write (BinaryXmlWriter writer) { TransferCoreProperties (true); writer.WriteValue ("id", ParseString (id)); writer.WriteValue ("ns", ParseString (ns)); writer.WriteValue ("isroot", isroot); writer.WriteValue ("name", ParseString (name)); writer.WriteValue ("version", ParseString (version)); writer.WriteValue ("compatVersion", ParseString (compatVersion)); writer.WriteValue ("hasUserId", hasUserId); writer.WriteValue ("author", ParseString (author)); writer.WriteValue ("url", ParseString (url)); writer.WriteValue ("copyright", ParseString (copyright)); writer.WriteValue ("description", ParseString (description)); writer.WriteValue ("category", ParseString (category)); writer.WriteValue ("basePath", basePath); writer.WriteValue ("sourceAddinFile", sourceAddinFile); writer.WriteValue ("defaultEnabled", defaultEnabled); writer.WriteValue ("domain", domain); writer.WriteValue ("MainModule", MainModule); writer.WriteValue ("OptionalModules", OptionalModules); writer.WriteValue ("NodeSets", ExtensionNodeSets); writer.WriteValue ("ExtensionPoints", ExtensionPoints); writer.WriteValue ("ConditionTypes", ConditionTypes); writer.WriteValue ("FilesInfo", fileInfo); writer.WriteValue ("Localizer", localizer); writer.WriteValue ("flags", (int)flags); writer.WriteValue ("Properties", properties); } void IBinaryXmlElement.Read (BinaryXmlReader reader) { id = reader.ReadStringValue ("id"); ns = reader.ReadStringValue ("ns"); isroot = reader.ReadBooleanValue ("isroot"); name = reader.ReadStringValue ("name"); version = reader.ReadStringValue ("version"); compatVersion = reader.ReadStringValue ("compatVersion"); hasUserId = reader.ReadBooleanValue ("hasUserId"); author = reader.ReadStringValue ("author"); url = reader.ReadStringValue ("url"); copyright = reader.ReadStringValue ("copyright"); description = reader.ReadStringValue ("description"); category = reader.ReadStringValue ("category"); basePath = reader.ReadStringValue ("basePath"); sourceAddinFile = reader.ReadStringValue ("sourceAddinFile"); defaultEnabled = reader.ReadBooleanValue ("defaultEnabled"); domain = reader.ReadStringValue ("domain"); mainModule = (ModuleDescription) reader.ReadValue ("MainModule"); optionalModules = (ModuleCollection) reader.ReadValue ("OptionalModules", new ModuleCollection (this)); nodeSets = (ExtensionNodeSetCollection) reader.ReadValue ("NodeSets", new ExtensionNodeSetCollection (this)); extensionPoints = (ExtensionPointCollection) reader.ReadValue ("ExtensionPoints", new ExtensionPointCollection (this)); conditionTypes = (ConditionTypeDescriptionCollection) reader.ReadValue ("ConditionTypes", new ConditionTypeDescriptionCollection (this)); fileInfo = (object[]) reader.ReadValue ("FilesInfo", null); localizer = (ExtensionNodeDescription) reader.ReadValue ("Localizer"); flags = (AddinFlags) reader.ReadInt32Value ("flags"); properties = (AddinPropertyCollectionImpl) reader.ReadValue ("Properties", new AddinPropertyCollectionImpl (this)); if (mainModule != null) mainModule.SetParent (this); } } class AddinFileInfo: IBinaryXmlElement { string fileName; DateTime timestamp; public string FileName { get { return fileName; } set { fileName = value; } } public System.DateTime Timestamp { get { return timestamp; } set { timestamp = value; } } public void Read (BinaryXmlReader reader) { fileName = reader.ReadStringValue ("fileName"); timestamp = reader.ReadDateTimeValue ("timestamp"); } public void Write (BinaryXmlWriter writer) { writer.WriteValue ("fileName", fileName); writer.WriteValue ("timestamp", timestamp); } } }
mono
mono-addins
F:\Projects\TestMap\Temp\mono-addins\Mono.Addins.sln
F:\Projects\TestMap\Temp\mono-addins\Test\UnitTests\UnitTests.csproj
F:\Projects\TestMap\Temp\mono-addins\Test\UnitTests\TestSetupService.cs
UnitTests
TestSetupService
['SetupService setup;', 'string addinsDir;', 'string repoDir;', 'string repoExtrasDir;', 'string baseDir;', 'ConsoleProgressStatus monitor;', 'bool repoBuilt;', 'string repoUrl;', 'string repoBaseUrl;']
['System', 'System.Linq', 'NUnit.Framework', 'Mono.Addins.Setup', 'Mono.Addins', 'System.IO', 'System.Globalization']
NUnit
net472;net6.0
[TestFixture] public class TestSetupService: TestBase { SetupService setup; string addinsDir; string repoDir; string repoExtrasDir; string baseDir; ConsoleProgressStatus monitor; bool repoBuilt; string repoUrl; string repoBaseUrl; [SetUp] public void TestSetup () { setup = new SetupService (); baseDir = Path.GetDirectoryName (new Uri (typeof(TestBase).Assembly.CodeBase).LocalPath); addinsDir = new DirectoryInfo (baseDir).Parent.Parent.Parent.Parent.FullName; addinsDir = Path.Combine (addinsDir, "lib"); repoDir = Path.Combine (TempDir, "repo"); repoExtrasDir = Path.Combine (repoDir,"extras"); monitor = new ConsoleProgressStatus (true); repoBaseUrl = new Uri (repoDir).ToString (); repoUrl = new Uri (Path.Combine (repoDir, "main.mrep")).ToString (); } [Test] public void AddinPackageCreation () { repoBuilt = false; if (Directory.Exists (repoDir)) Directory.Delete (repoDir, true); Directory.CreateDirectory (repoDir); Directory.CreateDirectory (repoExtrasDir); string asm = Path.Combine (baseDir, "SimpleApp.addin.xml"); string[] p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); asm = Path.Combine (addinsDir, "HelloWorldExtension.dll"); p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); asm = Path.Combine (addinsDir, "CommandExtension.addin.xml"); p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); asm = Path.Combine (addinsDir, "SystemInfoExtension.addin.xml"); p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); asm = Path.Combine (addinsDir, "MultiAssemblyAddin.dll"); p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); string extras = Path.Combine (addinsDir, "extras"); asm = Path.Combine (extras, "ExtraExtender.addin.xml"); p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); asm = Path.Combine (extras, "FileContentExtension.addin.xml"); p = setup.BuildPackage (monitor, repoDir, asm); Assert.IsTrue (File.Exists (p[0])); } public void InitRepository () { if (repoBuilt) return; if (Directory.Exists (repoDir)) Directory.Delete (repoDir, true); Directory.CreateDirectory (repoDir); Directory.CreateDirectory (repoExtrasDir); string asm = Path.Combine (baseDir, "SimpleApp.addin.xml"); setup.BuildPackage (monitor, repoDir, asm); asm = Path.Combine (addinsDir, "HelloWorldExtension.dll"); setup.BuildPackage (monitor, repoDir, asm); asm = Path.Combine (addinsDir, "CommandExtension.addin.xml"); setup.BuildPackage (monitor, repoDir, asm); asm = Path.Combine (addinsDir, "SystemInfoExtension.addin.xml"); setup.BuildPackage (monitor, repoDir, asm); asm = Path.Combine (addinsDir, "MultiAssemblyAddin.dll"); setup.BuildPackage (monitor, repoDir, asm); string extras = Path.Combine (addinsDir, "extras"); asm = Path.Combine (extras, "ExtraExtender.addin.xml"); setup.BuildPackage (monitor, repoExtrasDir, asm); asm = Path.Combine (extras, "FileContentExtension.addin.xml"); setup.BuildPackage (monitor, repoExtrasDir, asm); repoBuilt = true; } [Test] public void BuildRepository () { InitRepository (); setup.BuildRepository (monitor, repoDir); Assert.IsTrue (File.Exists (Path.Combine (repoDir, "main.mrep"))); Assert.IsTrue (File.Exists (Path.Combine (repoDir, "root.mrep"))); Assert.IsTrue (File.Exists (Path.Combine (repoExtrasDir, "main.mrep"))); } [Test] public void ManageRepository () { // Register without .mrep reference var ar = setup.Repositories.RegisterRepository (monitor, repoBaseUrl, false); Assert.IsTrue (ar.Enabled); Assert.AreEqual (repoUrl, ar.Url); Assert.IsTrue (setup.Repositories.ContainsRepository (repoUrl)); setup.Repositories.RemoveRepository (repoUrl); Assert.IsFalse (setup.Repositories.ContainsRepository (repoUrl)); // Register with .mrep reference ar = setup.Repositories.RegisterRepository (monitor, repoUrl, false); Assert.IsTrue (ar.Enabled); Assert.AreEqual (repoUrl, ar.Url); Assert.IsTrue (setup.Repositories.ContainsRepository (repoUrl)); var reps = setup.Repositories.GetRepositories (); Assert.AreEqual (1, reps.Length); Assert.IsTrue (reps[0].Enabled); Assert.AreEqual (repoUrl, reps[0].Url); setup.Repositories.RemoveRepository (repoUrl); Assert.IsFalse (setup.Repositories.ContainsRepository (repoUrl)); } [Test] public void QueryRepository () { InitRepository (); setup.BuildRepository (monitor, repoDir); setup.Repositories.RegisterRepository (monitor, repoUrl, true); var addins = setup.Repositories.GetAvailableAddins (); Assert.AreEqual (7, addins.Length); var oldc = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("ca-ES"); // CheckAddin (addins, "", "", "0.0.0.0", "", "", "", "", "", ""); CheckAddin (addins, "SimpleApp.CommandExtension,0.1.0", "SimpleApp", "0.1.0", "", "CommandExtension", "SimpleApp/Extensions", "Lluis Sanchez", "GPL", "CommandExtension"); CheckAddin (addins, "SimpleApp.Core,0.1.0", "SimpleApp", "0.1.0", "", "Una aplicació simple", "SimpleApp", "Lluis Sanchez", "GPL", "SimpleApp description"); CheckProperties (addins, "SimpleApp.Core,0.1.0", "Prop1", "Val1Cat", "Prop2", "Val2Cat"); CheckAddin (addins, "SimpleApp.HelloWorldExtension,0.1.0", "SimpleApp", "0.1.0", "", "SimpleApp.HelloWorldExtension", "", "", "", ""); CheckAddin (addins, "SimpleApp.SystemInfoExtension,0.1.0", "SimpleApp", "0.1.0", "", "SystemInfoExtension", "SimpleApp/Extensions", "Lluis Sanchez", "GPL", "SystemInfoExtension"); CheckAddin (addins, "SimpleApp.ExtraExtender,0.1.0", "SimpleApp", "0.1.0", "", "SimpleApp.ExtraExtender", "", "", "", ""); CheckAddin (addins, "SimpleApp.FileContentExtension,0.1.0", "SimpleApp", "0.1.0", "", "FileContentExtension", "SimpleApp/Extensions", "Lluis Sanchez", "GPL", "FileContentExtension"); System.Threading.Thread.CurrentThread.CurrentCulture = oldc; setup.Repositories.RemoveRepository (repoUrl); } void CheckAddin (AddinRepositoryEntry[] areps, string id, string ns, string version, string compat, string name, string category, string author, string copyright, string desc) { AddinRepositoryEntry arep = areps.FirstOrDefault (a => a.Addin.Id == id); Assert.IsNotNull (arep, "Add-in " + id + " not found"); Assert.AreEqual (id, arep.Addin.Id); Assert.AreEqual (ns, arep.Addin.Namespace); Assert.AreEqual (version, arep.Addin.Version); Assert.AreEqual (compat, arep.Addin.BaseVersion); Assert.AreEqual (name, arep.Addin.Name); Assert.AreEqual (category, arep.Addin.Category); Assert.AreEqual (author, arep.Addin.Author); Assert.AreEqual (copyright, arep.Addin.Copyright); Assert.AreEqual (desc, arep.Addin.Description); } void CheckProperties (AddinRepositoryEntry[] areps, string id, params string[] props) { AddinRepositoryEntry arep = areps.FirstOrDefault (a => a.Addin.Id == id); for (int n=0; n<props.Length; n+=2) Assert.AreEqual (props[n+1], arep.Addin.Properties.GetPropertyValue (props[n])); } [Test] public void GetSupportFile () { InitRepository (); setup.BuildRepository (monitor, repoDir); setup.Repositories.RegisterRepository (monitor, repoUrl, true); AddinRepositoryEntry arep = setup.Repositories.GetAvailableAddin ("SimpleApp.Core", "0.1.0")[0]; IAsyncResult res = arep.BeginDownloadSupportFile (arep.Addin.Properties.GetPropertyValue ("Prop3"), null, null); Stream s = arep.EndDownloadSupportFile (res); StreamReader sr = new StreamReader (s); Assert.AreEqual ("Some support file", sr.ReadToEnd ()); sr.Close (); setup.Repositories.RemoveRepository (repoUrl); } [Test] public void UpgradeCoreAddin () { InitRepository (); CreateTestPackage ("10.3"); CreateTestPackage ("10.4"); ExtensionNodeList list = AddinManager.GetExtensionNodes ("/SimpleApp/InstallUninstallTest"); Assert.AreEqual (1, list.Count); Assert.AreEqual ("10.2", ((ItemSetNode)list[0]).Label); Addin adn = AddinManager.Registry.GetAddin ("SimpleApp.AddRemoveTest,10.2"); Assert.IsTrue (adn.Enabled); Assert.IsFalse (adn.Description.CanUninstall); // Core add-in can't be uninstalled setup.Repositories.RegisterRepository (monitor, repoUrl, true); var pkg = setup.Repositories.GetAvailableAddinUpdates ("SimpleApp.AddRemoveTest", RepositorySearchFlags.LatestVersionsOnly).FirstOrDefault (); Assert.IsNotNull (pkg); Assert.AreEqual ("SimpleApp.AddRemoveTest,10.4", pkg.Addin.Id); // Install the add-in setup.Install (new ConsoleProgressStatus (true), pkg); adn = AddinManager.Registry.GetAddin ("SimpleApp.AddRemoveTest,10.2"); Assert.IsFalse (adn.Enabled); list = AddinManager.GetExtensionNodes ("/SimpleApp/InstallUninstallTest"); Assert.AreEqual (1, list.Count); Assert.AreEqual ("10.4", ((ItemSetNode)list[0]).Label); adn = AddinManager.Registry.GetAddin ("SimpleApp.AddRemoveTest"); Assert.IsTrue (adn.Enabled); Assert.IsTrue (adn.Description.CanUninstall); // Uninstall the add-in setup.Uninstall (new ConsoleProgressStatus (true), "SimpleApp.AddRemoveTest,10.4"); list = AddinManager.GetExtensionNodes ("/SimpleApp/InstallUninstallTest"); Assert.AreEqual (0, list.Count); adn = AddinManager.Registry.GetAddin ("SimpleApp.AddRemoveTest"); Assert.IsFalse (adn.Enabled); adn.Enabled = true; list = AddinManager.GetExtensionNodes ("/SimpleApp/InstallUninstallTest"); Assert.AreEqual (1, list.Count); Assert.AreEqual ("10.2", ((ItemSetNode)list[0]).Label); } void CreateTestPackage (string newVersion) { string file = AddinManager.CurrentAddin.GetFilePath (Path.Combine ("SampleAddins","AddRemoveTest1.addin.xml")); string txt = File.ReadAllText (file); txt = txt.Replace ("10.1", newVersion); string tmpFile = Path.Combine (TempDir, "AddRemoveTest_" + newVersion + ".addin.xml"); File.WriteAllText (tmpFile, txt); setup.BuildPackage (monitor, repoDir, tmpFile); setup.BuildRepository (monitor, repoDir); } }
1,434
12,202
// // SetupService.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using ICSharpCode.SharpZipLib.Zip; using Mono.Addins.Database; using Mono.Addins.Description; using Mono.Addins.Setup.ProgressMonitoring; using Mono.PkgConfig; namespace Mono.Addins.Setup { /// <summary> /// Provides tools for managing add-ins /// </summary> /// <remarks> /// This class can be used to manage the add-ins of an application. It allows installing and uninstalling /// add-ins, taking into account add-in dependencies. It provides methods for installing add-ins from on-line /// repositories and tools for generating those repositories. /// </remarks> public class SetupService { RepositoryRegistry repositories; string applicationNamespace; string installDirectory; AddinStore store; AddinSystemConfiguration config; const string addinFilesDir = "_addin_files"; AddinRegistry registry; /// <summary> /// Initializes a new instance /// </summary> /// <remarks> /// If the add-in manager is initialized (AddinManager.Initialize has been called), then this instance /// will manage the add-in registry of the initialized engine. /// </remarks> public SetupService () { if (AddinManager.IsInitialized) registry = AddinManager.Registry; else registry = AddinRegistry.GetGlobalRegistry (); repositories = new RepositoryRegistry (this); store = new AddinStore (this); AddAddinRepositoryProvider ("MonoAddins", new MonoAddinsRepositoryProvider (this)); } /// <summary> /// Initializes a new instance /// </summary> /// <param name="registry"> /// Add-in registry to manage /// </param> public SetupService (AddinRegistry registry) { this.registry = registry; repositories = new RepositoryRegistry (this); store = new AddinStore (this); AddAddinRepositoryProvider ("MonoAddins", new MonoAddinsRepositoryProvider (this)); } /// <summary> /// The add-in registry being managed /// </summary> public AddinRegistry Registry { get { return registry; } } internal string RepositoryCachePath { get { return Path.Combine (registry.RegistryPath, "repository-cache"); } } string RootConfigFile { get { return Path.Combine (registry.RegistryPath, "addins-setup-v2.config"); } } /// <summary> /// This should only be used for migration purposes /// </summary> string RootConfigFileOld { get { return Path.Combine (registry.RegistryPath, "addins-setup.config"); } } /// <summary> /// Default add-in namespace of the application (optional). If set, only add-ins that belong to that namespace /// will be shown in add-in lists. /// </summary> public string ApplicationNamespace { get { return applicationNamespace; } set { applicationNamespace = value; } } /// <summary> /// Directory where to install add-ins. If not specified, the 'addins' subdirectory of the /// registry location is used. /// </summary> public string InstallDirectory { get { if (installDirectory != null && installDirectory.Length > 0) return installDirectory; else return registry.DefaultAddinsFolder; } set { installDirectory = value; } } /// <summary> /// Returns a RepositoryRegistry which can be used to manage on-line repository references /// </summary> public RepositoryRegistry Repositories { get { return repositories; } } internal AddinStore Store { get { return store; } } /// <summary> /// Resolves add-in dependencies. /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="addins"> /// List of add-ins to check /// </param> /// <param name="resolved"> /// Packages that need to be installed. /// </param> /// <param name="toUninstall"> /// Packages that need to be uninstalled. /// </param> /// <param name="unresolved"> /// Add-in dependencies that could not be resolved. /// </param> /// <returns> /// True if all dependencies could be resolved. /// </returns> /// <remarks> /// This method can be used to get a list of all packages that have to be installed in order to install /// an add-in or set of add-ins. The list of packages to install will include the package that provides the /// add-in, and all packages that provide the add-in dependencies. In some cases, packages may need to /// be installed (for example, when an installed add-in needs to be upgraded). /// </remarks> public bool ResolveDependencies (IProgressStatus statusMonitor, AddinRepositoryEntry [] addins, out PackageCollection resolved, out PackageCollection toUninstall, out DependencyCollection unresolved) { return store.ResolveDependencies (statusMonitor, addins, out resolved, out toUninstall, out unresolved); } /// <summary> /// Resolves add-in dependencies. /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="packages"> /// Packages that need to be installed. /// </param> /// <param name="toUninstall"> /// Packages that need to be uninstalled. /// </param> /// <param name="unresolved"> /// Add-in dependencies that could not be resolved. /// </param> /// <returns> /// True if all dependencies could be resolved. /// </returns> /// <remarks> /// This method can be used to get a list of all packages that have to be installed in order to satisfy /// the dependencies of a package or set of packages. The 'packages' argument must have the list of packages /// to be resolved. When resolving dependencies, if there is any additional package that needs to be installed, /// it will be added to the same 'packages' collection. In some cases, packages may need to /// be installed (for example, when an installed add-in needs to be upgraded). Those packages will be added /// to the 'toUninstall' collection. Packages that could not be resolved are added to the 'unresolved' /// collection. /// </remarks> public bool ResolveDependencies (IProgressStatus statusMonitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved) { return store.ResolveDependencies (statusMonitor, packages, out toUninstall, out unresolved); } /// <summary> /// Installs add-in packages /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="files"> /// Paths to the packages to install /// </param> /// <returns> /// True if the installation succeeded /// </returns> public bool Install (IProgressStatus statusMonitor, params string [] files) { return store.Install (statusMonitor, files); } /// <summary> /// Installs add-in packages from on-line repositories /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="addins"> /// References to the add-ins to be installed /// </param> /// <returns> /// True if the installation succeeded /// </returns> public bool Install (IProgressStatus statusMonitor, params AddinRepositoryEntry [] addins) { return store.Install (statusMonitor, addins); } /// <summary> /// Installs add-in packages /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="packages"> /// Packages to install /// </param> /// <returns> /// True if the installation succeeded /// </returns> public bool Install (IProgressStatus statusMonitor, PackageCollection packages) { return store.Install (statusMonitor, packages); } /// <summary> /// Uninstalls an add-in. /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="id"> /// Full identifier of the add-in to uninstall. /// </param> public void Uninstall (IProgressStatus statusMonitor, string id) { store.Uninstall (statusMonitor, id); } /// <summary> /// Uninstalls a set of add-ins /// </summary> /// <param name='statusMonitor'> /// Progress monitor where to show progress status /// </param> /// <param name='ids'> /// Full identifiers of the add-ins to uninstall. /// </param> public void Uninstall (IProgressStatus statusMonitor, IEnumerable<string> ids) { store.Uninstall (statusMonitor, ids); } /// <summary> /// Gets information about an add-in /// </summary> /// <param name="addin"> /// The add-in /// </param> /// <returns> /// Add-in header data /// </returns> public static AddinHeader GetAddinHeader (Addin addin) { return AddinInfo.ReadFromDescription (addin.Description); } public static AddinHeader ReadAddinHeader (string mpack) { return AddinPackage.ReadAddinInfo(mpack); } Dictionary<string, AddinRepositoryProvider> providersList = new Dictionary<string, AddinRepositoryProvider> (); public AddinRepositoryProvider GetAddinRepositoryProvider (string providerId) { if (string.IsNullOrEmpty (providerId)) providerId = "MonoAddins"; if (providersList.TryGetValue (providerId, out var addinRepositoryProvider)) return addinRepositoryProvider; throw new KeyNotFoundException (providerId); } public void AddAddinRepositoryProvider (string providerId, AddinRepositoryProvider provider) { providersList [providerId] = provider; } public void RemoveAddinRepositoryProvider (string providerId) { providersList.Remove (providerId); } /// <summary> /// Gets a list of add-ins which depend on an add-in /// </summary> /// <param name="id"> /// Full identifier of an add-in. /// </param> /// <param name="recursive"> /// When set to True, dependencies will be gathered recursivelly /// </param> /// <returns> /// List of dependent add-ins. /// </returns> /// <remarks> /// This methods returns a list of add-ins which have the add-in identified by 'id' as a direct /// (or indirect if recursive=True) dependency. /// </remarks> public Addin [] GetDependentAddins (string id, bool recursive) { return store.GetDependentAddins (id, recursive); } /// <summary> /// Packages an add-in /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="targetDirectory"> /// Directory where to generate the package /// </param> /// <param name="filePaths"> /// Paths to the add-ins to be packaged. Paths can be either the main assembly of an add-in, or an add-in /// manifest (.addin or .addin.xml). /// </param> /// <remarks> /// This method can be used to create a package for an add-in, which can then be pushed to an on-line /// repository. The package will include the main assembly or manifest of the add-in and any external /// file declared in the add-in metadata. /// </remarks> public string [] BuildPackage (IProgressStatus statusMonitor, string targetDirectory, params string [] filePaths) { return BuildPackage (statusMonitor, false, targetDirectory, filePaths); } /// <summary> /// Packages an add-in /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="debugSymbols"> /// True if debug symbols (.pdb or .mdb) should be included in the package, if they exist /// </param> /// <param name="targetDirectory"> /// Directory where to generate the package /// </param> /// <param name="filePaths"> /// Paths to the add-ins to be packaged. Paths can be either the main assembly of an add-in, or an add-in /// manifest (.addin or .addin.xml). /// </param> /// <remarks> /// This method can be used to create a package for an add-in, which can then be pushed to an on-line /// repository. The package will include the main assembly or manifest of the add-in and any external /// file declared in the add-in metadata. /// </remarks> public string [] BuildPackage (IProgressStatus statusMonitor, bool debugSymbols, string targetDirectory, params string [] filePaths) { List<string> outFiles = new List<string> (); foreach (string file in filePaths) { string f = BuildPackageInternal (statusMonitor, debugSymbols, targetDirectory, file, PackageFormat.Mpack); if (f != null) outFiles.Add (f); } return outFiles.ToArray (); } /// <summary> /// Packages an add-in /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="debugSymbols"> /// True if debug symbols (.pdb or .mdb) should be included in the package, if they exist /// </param> /// <param name="targetDirectory"> /// Directory where to generate the package /// </param> /// <param name="format"> /// Which format to produce .mpack or .vsix /// </param> /// <param name="filePaths"> /// Paths to the add-ins to be packaged. Paths can be either the main assembly of an add-in, or an add-in /// manifest (.addin or .addin.xml). /// </param> /// <remarks> /// This method can be used to create a package for an add-in, which can then be pushed to an on-line /// repository. The package will include the main assembly or manifest of the add-in and any external /// file declared in the add-in metadata. /// </remarks> public string [] BuildPackage (IProgressStatus statusMonitor, bool debugSymbols, string targetDirectory, PackageFormat format, params string [] filePaths) { List<string> outFiles = new List<string> (); foreach (string file in filePaths) { string f = BuildPackageInternal (statusMonitor, debugSymbols, targetDirectory, file, format); if (f != null) outFiles.Add (f); } return outFiles.ToArray (); } string BuildPackageInternal (IProgressStatus monitor, bool debugSymbols, string targetDirectory, string filePath, PackageFormat format) { AddinDescription conf = registry.GetAddinDescription (monitor, filePath); if (conf == null) { monitor.ReportError ("Could not read add-in file: " + filePath, null); return null; } string basePath = Path.GetDirectoryName (Path.GetFullPath (filePath)); if (targetDirectory == null) targetDirectory = basePath; // Generate the file name string localId; if (conf.LocalId.Length == 0) localId = Path.GetFileNameWithoutExtension (filePath); else localId = conf.LocalId; string ext; var name = Addin.GetFullId (conf.Namespace, localId, null); string version = conf.Version; switch (format) { case PackageFormat.Mpack: ext = ".mpack"; break; case PackageFormat.Vsix: ext = ".vsix"; break; case PackageFormat.NuGet: ext = ".nupkg"; if (string.IsNullOrEmpty (version)) { monitor.ReportError ("Add-in doesn't have a version", null); return null; } version = GetNuGetVersion (version); break; default: throw new NotSupportedException (format.ToString ()); } string outFilePath = Path.Combine (targetDirectory, name); if (!string.IsNullOrEmpty (version)) outFilePath += "." + version; outFilePath += ext; ZipOutputStream s = new ZipOutputStream (File.Create (outFilePath)); s.SetLevel (5); if (format == PackageFormat.Vsix) { XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = false; doc.LoadXml (conf.SaveToVsixXml ().OuterXml); AddXmlFile (s, doc, "extension.vsixmanifest"); } if (format == PackageFormat.NuGet) { var doc = GenerateNuspec (conf); AddXmlFile (s, doc, Addin.GetIdName (conf.AddinId).ToLower () + ".nuspec"); } // Generate a stripped down description of the add-in in a file, since the complete // description may be declared as assembly attributes XmlDocument infoDoc = new XmlDocument (); infoDoc.PreserveWhitespace = false; infoDoc.LoadXml (conf.SaveToXml ().OuterXml); CleanDescription (infoDoc.DocumentElement); AddXmlFile (s, infoDoc, "addin.info"); // Now add the add-in files var files = new HashSet<string> (); files.Add (Path.GetFileName (Util.NormalizePath (filePath))); foreach (string f in conf.AllFiles) { var file = Util.NormalizePath (f); files.Add (file); if (debugSymbols) { if (File.Exists (Path.ChangeExtension (file, ".pdb"))) files.Add (Path.ChangeExtension (file, ".pdb")); else if (File.Exists (file + ".mdb")) files.Add (file + ".mdb"); } } foreach (var prop in conf.Properties) { try { var file = Util.NormalizePath (prop.Value); if (File.Exists (Path.Combine (basePath, file))) { files.Add (file); } } catch { // Ignore errors } } //add satellite assemblies for assemblies in the list var satelliteFinder = new SatelliteAssemblyFinder (); foreach (var f in files.ToList ()) { foreach (var satellite in satelliteFinder.FindSatellites (Path.Combine (basePath, f))) { var relativeSatellite = satellite.Substring (basePath.Length + 1); files.Add (relativeSatellite); } } monitor.Log ("Creating package " + Path.GetFileName (outFilePath)); foreach (string file in files) { string fp = Path.Combine (basePath, file); using (FileStream fs = File.OpenRead (fp)) { byte [] buffer = new byte [fs.Length]; fs.Read (buffer, 0, buffer.Length); var fileName = Path.DirectorySeparatorChar == '\\' ? file.Replace ('\\', '/') : file; if (format == PackageFormat.NuGet) fileName = Path.Combine ("addin", fileName); var entry = new ZipEntry (fileName) { Size = fs.Length }; s.PutNextEntry (entry); s.Write (buffer, 0, buffer.Length); s.CloseEntry (); } } if (format == PackageFormat.Vsix) { files.Add ("addin.info"); files.Add ("extension.vsixmanifest"); XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = false; XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration ("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore (xmlDeclaration, root); HashSet<string> alreadyAddedExtensions = new HashSet<string> (); var typesEl = doc.CreateElement ("Types"); typesEl.SetAttribute ("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types"); foreach (var file in files) { var extension = Path.GetExtension (file); if (string.IsNullOrEmpty (extension)) continue; if (extension.StartsWith (".", StringComparison.Ordinal)) extension = extension.Substring (1); if (alreadyAddedExtensions.Contains (extension)) continue; alreadyAddedExtensions.Add (extension); var typeEl = doc.CreateElement ("Default"); typeEl.SetAttribute ("Extension", extension); typeEl.SetAttribute ("ContentType", GetContentType (extension)); typesEl.AppendChild (typeEl); } doc.AppendChild (typesEl); AddXmlFile (s, doc, "[Content_Types].xml"); } s.Finish (); s.Close (); return outFilePath; } private static void AddXmlFile (ZipOutputStream s, XmlDocument doc, string fileName) { MemoryStream ms = new MemoryStream (); XmlTextWriter tw = new XmlTextWriter (ms, System.Text.Encoding.UTF8); tw.Formatting = Formatting.Indented; doc.WriteTo (tw); tw.Flush (); byte [] data = ms.ToArray (); var infoEntry = new ZipEntry (fileName) { Size = data.Length }; s.PutNextEntry (infoEntry); s.Write (data, 0, data.Length); s.CloseEntry (); } XmlDocument GenerateNuspec (AddinDescription conf) { XmlDocument doc = new XmlDocument (); var nugetNs = "http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"; var rootElement = doc.CreateElement ("package", nugetNs); doc.AppendChild (rootElement); var metadataElement = doc.CreateElement ("metadata", nugetNs); rootElement.AppendChild (metadataElement); var prop = doc.CreateElement ("id", nugetNs); prop.InnerText = Addin.GetIdName (conf.AddinId); metadataElement.AppendChild (prop); prop = doc.CreateElement ("version", nugetNs); prop.InnerText = GetNuGetVersion (conf.Version); metadataElement.AppendChild (prop); prop = doc.CreateElement ("packageTypes", nugetNs); prop.InnerText = "VisualStudioMacExtension"; metadataElement.AppendChild (prop); if (!string.IsNullOrEmpty (conf.Author)) { prop = doc.CreateElement ("authors", nugetNs); prop.InnerText = conf.Author; metadataElement.AppendChild (prop); } if (!string.IsNullOrEmpty (conf.Description)) { prop = doc.CreateElement ("description", nugetNs); prop.InnerText = conf.Description; metadataElement.AppendChild (prop); } if (!string.IsNullOrEmpty (conf.Name)) { prop = doc.CreateElement ("title", nugetNs); prop.InnerText = conf.Name; metadataElement.AppendChild (prop); } var depsElement = doc.CreateElement ("dependencies", nugetNs); metadataElement.AppendChild (depsElement); foreach (var dep in conf.MainModule.Dependencies.OfType<AddinDependency> ()) { var depElem = doc.CreateElement ("dependency", nugetNs); depElem.SetAttribute ("id", Addin.GetFullId (conf.Namespace, dep.AddinId, null)); depElem.SetAttribute ("version", GetNuGetVersion (dep.Version)); depsElement.AppendChild (depElem); } return doc; } static string GetNuGetVersion (string version) { if (Version.TryParse (version, out var parsedVersion)) { // NuGet versions always have at least 3 components if (parsedVersion.Build == -1) version += ".0"; } return version; } static string GetContentType (string extension) { switch (extension) { case "txt": return "text/plain"; case "pkgdef": return "text/plain"; case "xml": return "text/xml"; case "vsixmanifest": return "text/xml"; case "htm or html": return "text/html"; case "rtf": return "application/rtf"; case "pdf": return "application/pdf"; case "gif": return "image/gif"; case "jpg or jpeg": return "image/jpg"; case "tiff": return "image/tiff"; case "vsix": return "application/zip"; case "zip": return "application/zip"; case "dll": return "application/octet-stream"; case "info": return "text/xml";//Mono.Addins info file default: return "application/octet-stream"; } } class SatelliteAssemblyFinder { Dictionary<string, List<string>> cultureSubdirCache = new Dictionary<string, List<string>> (); HashSet<string> cultureNames = new HashSet<string> (StringComparer.OrdinalIgnoreCase); public SatelliteAssemblyFinder () { foreach (var cultureName in CultureInfo.GetCultures (CultureTypes.AllCultures)) { cultureNames.Add (cultureName.Name); } } List<string> GetCultureSubdirectories (string directory) { if (!cultureSubdirCache.TryGetValue (directory, out List<string> cultureDirs)) { cultureDirs = Directory.EnumerateDirectories (directory) .Where (d => cultureNames.Contains (Path.GetFileName ((d)))) .ToList (); cultureSubdirCache [directory] = cultureDirs; } return cultureDirs; } public IEnumerable<string> FindSatellites (string assemblyPath) { if (!assemblyPath.EndsWith (".dll", StringComparison.OrdinalIgnoreCase)) { yield break; } var satelliteName = Path.GetFileNameWithoutExtension (assemblyPath) + ".resources.dll"; foreach (var cultureDir in GetCultureSubdirectories (Path.GetDirectoryName (assemblyPath))) { string cultureName = Path.GetFileName (cultureDir); string satellitePath = Path.Combine (cultureDir, satelliteName); if (File.Exists (satellitePath)) { yield return satellitePath; } } } } void CleanDescription (XmlElement parent) { ArrayList todelete = new ArrayList (); foreach (XmlNode nod in parent.ChildNodes) { XmlElement elem = nod as XmlElement; if (elem == null) { todelete.Add (nod); continue; } if (elem.LocalName == "Module") CleanDescription (elem); else if (elem.LocalName != "Dependencies" && elem.LocalName != "Runtime" && elem.LocalName != "Header") todelete.Add (elem); } foreach (XmlNode e in todelete) parent.RemoveChild (e); } /// <summary> /// Generates an on-line repository /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="path"> /// Path to the directory that contains the add-ins and that is going to be published /// </param> /// <remarks> /// This method generates the index files required to publish a directory as an online repository /// of add-ins. /// </remarks> public void BuildRepository (IProgressStatus statusMonitor, string path) { string mainPath = Path.Combine (path, "main.mrep"); var allAddins = new List<PackageRepositoryEntry> (); Repository rootrep = (Repository)AddinStore.ReadObject (mainPath, typeof (Repository)); if (rootrep == null) rootrep = new Repository (); IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor (statusMonitor); BuildRepository (monitor, rootrep, path, "root.mrep", allAddins); AddinStore.WriteObject (mainPath, rootrep); GenerateIndexPage (rootrep, allAddins, path); monitor.Log.WriteLine ("Updated main.mrep"); } void BuildRepository (IProgressMonitor monitor, Repository rootrep, string rootPath, string relFilePath, List<PackageRepositoryEntry> allAddins) { DateTime lastModified = DateTime.MinValue; string mainFile = Path.Combine (rootPath, relFilePath); string mainPath = Path.GetDirectoryName (mainFile); string supportFileDir = Path.Combine (mainPath, addinFilesDir); if (File.Exists (mainFile)) lastModified = File.GetLastWriteTime (mainFile); Repository mainrep = (Repository)AddinStore.ReadObject (mainFile, typeof (Repository)); if (mainrep == null) { mainrep = new Repository (); } ReferenceRepositoryEntry repEntry = (ReferenceRepositoryEntry)rootrep.FindEntry (relFilePath); DateTime rootLastModified = repEntry != null ? repEntry.LastModified : DateTime.MinValue; bool modified = false; monitor.Log.WriteLine ("Checking directory: " + mainPath); foreach (string file in Directory.EnumerateFiles (mainPath, "*.mpack")) { DateTime date = File.GetLastWriteTime (file); string fname = Path.GetFileName (file); PackageRepositoryEntry entry = (PackageRepositoryEntry)mainrep.FindEntry (fname); if (entry != null && date > rootLastModified) { mainrep.RemoveEntry (entry); DeleteSupportFiles (supportFileDir, entry.Addin); entry = null; } if (entry == null) { entry = new PackageRepositoryEntry (); AddinPackage p = (AddinPackage)Package.FromFile (file); entry.Addin = (AddinInfo)p.Addin; entry.Url = fname; entry.Addin.Properties.SetPropertyValue ("DownloadSize", new FileInfo (file).Length.ToString ()); ExtractSupportFiles (supportFileDir, file, entry.Addin); mainrep.AddEntry (entry); modified = true; monitor.Log.WriteLine ("Added addin: " + fname); } allAddins.Add (entry); } var toRemove = new List<PackageRepositoryEntry> (); foreach (PackageRepositoryEntry entry in mainrep.Addins) { if (!File.Exists (Path.Combine (mainPath, entry.Url))) { toRemove.Add (entry); modified = true; } } foreach (PackageRepositoryEntry entry in toRemove) { DeleteSupportFiles (supportFileDir, entry.Addin); mainrep.RemoveEntry (entry); } if (modified) { AddinStore.WriteObject (mainFile, mainrep); monitor.Log.WriteLine ("Updated " + relFilePath); lastModified = File.GetLastWriteTime (mainFile); } if (repEntry != null) { if (repEntry.LastModified < lastModified) repEntry.LastModified = lastModified; } else if (modified) { repEntry = new ReferenceRepositoryEntry (); repEntry.LastModified = lastModified; repEntry.Url = relFilePath; rootrep.AddEntry (repEntry); } foreach (string dir in Directory.EnumerateDirectories (mainPath)) { if (Path.GetFileName (dir) == addinFilesDir) continue; string based = dir.Substring (rootPath.Length + 1); BuildRepository (monitor, rootrep, rootPath, Path.Combine (based, "main.mrep"), allAddins); } } void DeleteSupportFiles (string targetDir, AddinInfo ainfo) { foreach (var prop in ainfo.Properties) { if (prop.Value.StartsWith (addinFilesDir + Path.DirectorySeparatorChar)) { string file = Path.Combine (targetDir, Path.GetFileName (prop.Value)); if (File.Exists (file)) File.Delete (file); } } if (Directory.Exists (targetDir) && !Directory.EnumerateFileSystemEntries (targetDir).Any ()) Directory.Delete (targetDir, true); } void ExtractSupportFiles (string targetDir, string file, AddinInfo ainfo) { Random r = new Random (); ZipFile zfile = new ZipFile (file); try { foreach (var prop in ainfo.Properties) { ZipEntry ze = zfile.GetEntry (prop.Value); if (ze != null) { string fname; do { fname = Path.Combine (targetDir, r.Next ().ToString ("x") + Path.GetExtension (prop.Value)); } while (File.Exists (fname)); if (!Directory.Exists (targetDir)) Directory.CreateDirectory (targetDir); using (var f = File.OpenWrite (fname)) { using (Stream s = zfile.GetInputStream (ze)) { byte [] buffer = new byte [8092]; int nr = 0; while ((nr = s.Read (buffer, 0, buffer.Length)) > 0) f.Write (buffer, 0, nr); } } prop.Value = Path.Combine (addinFilesDir, Path.GetFileName (fname)); } } } finally { zfile.Close (); } } void GenerateIndexPage (Repository rep, List<PackageRepositoryEntry> addins, string basePath) { StreamWriter sw = new StreamWriter (Path.Combine (basePath, "index.html")); sw.WriteLine ("<html><body>"); sw.WriteLine ("<h1>Add-in Repository</h1>"); if (rep.Name != null && rep.Name != "") sw.WriteLine ("<h2>" + rep.Name + "</h2>"); sw.WriteLine ("<p>This is a list of add-ins available in this repository.</p>"); sw.WriteLine ("<table border=1><thead><tr><th>Add-in</th><th>Version</th><th>Description</th></tr></thead>"); foreach (PackageRepositoryEntry entry in addins) { sw.WriteLine ("<tr><td>" + entry.Addin.Name + "</td><td>" + entry.Addin.Version + "</td><td>" + entry.Addin.Description + "</td></tr>"); } sw.WriteLine ("</table>"); sw.WriteLine ("</body></html>"); sw.Close (); } internal AddinSystemConfiguration Configuration { get { if (config == null) { if (File.Exists (RootConfigFile)) config = (AddinSystemConfiguration)AddinStore.ReadObject (RootConfigFile, typeof (AddinSystemConfiguration)); else config = (AddinSystemConfiguration)AddinStore.ReadObject (RootConfigFileOld, typeof (AddinSystemConfiguration)); if (config == null) config = new AddinSystemConfiguration (); } return config; } } internal void SaveConfiguration () { if (config != null) { AddinStore.WriteObject (RootConfigFile, config); } } internal void ResetConfiguration () { if (File.Exists (RootConfigFile)) File.Delete (RootConfigFile); if (File.Exists (RootConfigFileOld)) File.Delete (RootConfigFileOld); ResetAddinInfo (); } internal void ResetAddinInfo () { if (Directory.Exists (RepositoryCachePath)) Directory.Delete (RepositoryCachePath, true); } /// <summary> /// Gets a reference to an extensible application /// </summary> /// <param name="name"> /// Name of the application /// </param> /// <returns> /// The Application object. Null if not found. /// </returns> public static Application GetExtensibleApplication (string name) { return GetExtensibleApplication (name, null); } /// <summary> /// Gets a reference to an extensible application /// </summary> /// <param name="name"> /// Name of the application /// </param> /// <param name="searchPaths"> /// Custom paths where to look for the application. /// </param> /// <returns> /// The Application object. Null if not found. /// </returns> public static Application GetExtensibleApplication (string name, IEnumerable<string> searchPaths) { AddinsPcFileCache pcc = GetAddinsPcFileCache (searchPaths); PackageInfo pi = pcc.GetPackageInfoByName (name, searchPaths); if (pi != null) return new Application (pi); else return null; } /// <summary> /// Gets a lis of all known extensible applications /// </summary> /// <returns> /// A list of applications. /// </returns> public static Application [] GetExtensibleApplications () { return GetExtensibleApplications (null); } /// <summary> /// Gets a lis of all known extensible applications /// </summary> /// <param name="searchPaths"> /// Custom paths where to look for applications. /// </param> /// <returns> /// A list of applications. /// </returns> public static Application [] GetExtensibleApplications (IEnumerable<string> searchPaths) { List<Application> list = new List<Application> (); AddinsPcFileCache pcc = GetAddinsPcFileCache (searchPaths); foreach (PackageInfo pinfo in pcc.GetPackages (searchPaths)) { if (pinfo.IsValidPackage) list.Add (new Application (pinfo)); } return list.ToArray (); } static AddinsPcFileCache pcFileCache; static AddinsPcFileCache GetAddinsPcFileCache (IEnumerable<string> searchPaths) { if (pcFileCache == null) { pcFileCache = new AddinsPcFileCache (); if (searchPaths != null) pcFileCache.Update (searchPaths); else pcFileCache.Update (); } return pcFileCache; } } class AddinsPcFileCacheContext : IPcFileCacheContext { public bool IsCustomDataComplete (string pcfile, PackageInfo pkg) { return true; } public void StoreCustomData (Mono.PkgConfig.PcFile pcfile, PackageInfo pkg) { } public void ReportError (string message, System.Exception ex) { Console.WriteLine (message); Console.WriteLine (ex); } } class AddinsPcFileCache : PcFileCache { public AddinsPcFileCache () : base (new AddinsPcFileCacheContext ()) { } protected override string CacheDirectory { get { string path = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); path = Path.Combine (path, "mono.addins"); return path; } } protected override void ParsePackageInfo (PcFile file, PackageInfo pinfo) { string rootPath = file.GetVariable ("MonoAddinsRoot"); string regPath = file.GetVariable ("MonoAddinsRegistry"); string addinsPath = file.GetVariable ("MonoAddinsInstallPath"); string databasePath = file.GetVariable ("MonoAddinsCachePath"); string testCmd = file.GetVariable ("MonoAddinsTestCommand"); if (string.IsNullOrEmpty (rootPath) || string.IsNullOrEmpty (regPath)) return; pinfo.SetData ("MonoAddinsRoot", rootPath); pinfo.SetData ("MonoAddinsRegistry", regPath); pinfo.SetData ("MonoAddinsInstallPath", addinsPath); pinfo.SetData ("MonoAddinsCachePath", databasePath); pinfo.SetData ("MonoAddinsTestCommand", testCmd); } } /// <summary> /// A registered extensible application /// </summary> public class Application { AddinRegistry registry; string description; string name; string testCommand; string startupPath; string registryPath; string addinsPath; string databasePath; internal Application (PackageInfo pinfo) { name = pinfo.Name; description = pinfo.Description; startupPath = pinfo.GetData ("MonoAddinsRoot"); registryPath = pinfo.GetData ("MonoAddinsRegistry"); addinsPath = pinfo.GetData ("MonoAddinsInstallPath"); databasePath = pinfo.GetData ("MonoAddinsCachePath"); testCommand = pinfo.GetData ("MonoAddinsTestCommand"); } /// <summary> /// Add-in registry of the application /// </summary> public AddinRegistry Registry { get { if (registry == null) registry = new AddinRegistry (RegistryPath, StartupPath, AddinsPath, AddinCachePath); return registry; } } /// <summary> /// Description of the application /// </summary> public string Description { get { return description; } } /// <summary> /// Name of the application /// </summary> public string Name { get { return name; } } /// <summary> /// Path to the add-in registry /// </summary> public string RegistryPath { get { return registryPath; } } /// <summary> /// Path to the directory that contains the main executable assembly of the application /// </summary> public string StartupPath { get { return startupPath; } } /// <summary> /// Command to be used to execute the application in add-in development mode. /// </summary> public string TestCommand { get { return testCommand; } } /// <summary> /// Path to the default add-ins directory for the aplpication /// </summary> public string AddinsPath { get { return addinsPath; } } /// <summary> /// Path to the add-in cache for the application /// </summary> public string AddinCachePath { get { return databasePath; } } } }
scottschluer
geolocation
F:\Projects\TestMap\Temp\geolocation\Geolocation.sln
F:\Projects\TestMap\Temp\geolocation\Geolocation.UnitTests\Geolocation.UnitTests.csproj
F:\Projects\TestMap\Temp\geolocation\Geolocation.UnitTests\ExtensionMethodTests.cs
Geolocation.UnitTests
ExtensionMethodTests
[]
['NUnit.Framework']
NUnit
null
[TestFixture] public class ExtensionMethodTests { [Test] public void ToRadianReturnsCorrectResult() { Coordinate coordinate = Constants.Coordinates.ValidCoordinate; double result = coordinate.Latitude.ToRadian(); const double expectedResult = 0.59459164513542162; Assert.AreEqual(result, expectedResult); } [Test] public void DiffRadianReturnsCorrectResult() { Coordinate coordinate = Constants.Coordinates.ValidCoordinate; Coordinate destinationCoordinate = Constants.Coordinates.ValidDestinationCoordinate; double result = coordinate.Latitude.DiffRadian(destinationCoordinate.Latitude); const double expectedResult = 0.017604127364559075; Assert.AreEqual(result, expectedResult); } [Test] public void ToBearingReturnsCorrectResult() { const double angleTangent = 1.8344799871616866; double result = angleTangent.ToBearing(); const double expectedResult = 105.10796086557809; Assert.AreEqual(result, expectedResult); } [Test] public void ToDegreesReturnsCorrectResult() { const double angleTangent = 1.8344799871616866; double result = angleTangent.ToDegrees(); const double expectedResult = 105.10796086557809; Assert.AreEqual(result, expectedResult); } }
66
1,625
/* Geolocation Class Library * Author: Scott Schluer ([email protected]) * May 29, 2012 * https://github.com/scottschluer/Geolocation */ using System; namespace Geolocation { /// <summary> /// Extension methods used by Geolocation. /// </summary> public static class ExtensionMethods { /// <summary> /// Gets the radian. /// </summary> /// <param name="d">The double.</param> /// <returns>Double.</returns> public static double ToRadian(this double d) { return d * (Math.PI / 180); } /// <summary> /// Diffs the radian. /// </summary> /// <param name="val1">First value.</param> /// <param name="val2">Second value.</param> /// <returns>Double.</returns> public static double DiffRadian(this double val1, double val2) { return val2.ToRadian() - val1.ToRadian(); } /// <summary> /// Gets the degrees. /// </summary> /// <param name="r">The radian.</param> /// <returns>Double.</returns> public static double ToDegrees(this double r) { return r * 180 / Math.PI; } /// <summary> /// Gets the bearing. /// </summary> /// <param name="r">The radian.</param> /// <returns>Double.</returns> public static double ToBearing(this double r) { double degrees = ToDegrees(r); return (degrees + 360) % 360; } } }
scottschluer
geolocation
F:\Projects\TestMap\Temp\geolocation\Geolocation.sln
F:\Projects\TestMap\Temp\geolocation\GeolocationNetStandard.UnitTests\GeolocationNetStandard.UnitTests.csproj
F:\Projects\TestMap\Temp\geolocation\GeolocationNetStandard.UnitTests\ExtensionMethodTests.cs
GeolocationNetStandard.UnitTests
ExtensionMethodTests
[]
['Geolocation', 'NUnit.Framework']
NUnit
netcoreapp2.1
[TestFixture] public class ExtensionMethodTests { [Test] public void ToRadianReturnsCorrectResult() { Coordinate coordinate = Constants.Coordinates.ValidCoordinate; double result = coordinate.Latitude.ToRadian(); const double expectedResult = 0.59459164513542162; Assert.AreEqual(expectedResult, result); } [Test] public void DiffRadianReturnsCorrectResult() { Coordinate coordinate = Constants.Coordinates.ValidCoordinate; Coordinate destinationCoordinate = Constants.Coordinates.ValidDestinationCoordinate; double result = coordinate.Latitude.DiffRadian(destinationCoordinate.Latitude); const double expectedResult = 0.017604127364559075; Assert.AreEqual(expectedResult, result); } [Test] public void ToBearingReturnsCorrectResult() { const double angleTangent = 1.8344799871616866; double result = angleTangent.ToBearing(); const double expectedResult = 105.10796086557809; Assert.AreEqual(expectedResult, result); } [Test] public void ToDegreesReturnsCorrectResult() { const double angleTangent = 1.8344799871616866; double result = angleTangent.ToDegrees(); const double expectedResult = 105.10796086557808; Assert.AreEqual(expectedResult, result); } }
97
1,656
/* Geolocation Class Library * Author: Scott Schluer ([email protected]) * May 29, 2012 * https://github.com/scottschluer/Geolocation */ using System; namespace Geolocation { /// <summary> /// Extension methods used by Geolocation. /// </summary> public static class ExtensionMethods { /// <summary> /// Gets the radian. /// </summary> /// <param name="d">The double.</param> /// <returns>Double.</returns> public static double ToRadian(this double d) { return d * (Math.PI / 180); } /// <summary> /// Diffs the radian. /// </summary> /// <param name="val1">First value.</param> /// <param name="val2">Second value.</param> /// <returns>Double.</returns> public static double DiffRadian(this double val1, double val2) { return val2.ToRadian() - val1.ToRadian(); } /// <summary> /// Gets the degrees. /// </summary> /// <param name="r">The radian.</param> /// <returns>Double.</returns> public static double ToDegrees(this double r) { return r * 180 / Math.PI; } /// <summary> /// Gets the bearing. /// </summary> /// <param name="r">The radian.</param> /// <returns>Double.</returns> public static double ToBearing(this double r) { double degrees = ToDegrees(r); return (degrees + 360) % 360; } } }
reactiveui
ReactiveUI.Samples
F:\Projects\TestMap\Temp\ReactiveUI.Samples\ReactiveUI.Samples.sln
F:\Projects\TestMap\Temp\ReactiveUI.Samples\testing\ReactiveUI.Samples.Testing.SimpleViewModels.Tests\ReactiveUI.Samples.Testing.SimpleViewModelsUnitTests.csproj
F:\Projects\TestMap\Temp\ReactiveUI.Samples\testing\ReactiveUI.Samples.Testing.SimpleViewModels.Tests\CalculatorViewModelTest.cs
ReactiveUI.Samples.Testing.SimpleViewModelsUnitTests
CalculatorViewModelTest
[]
['ReactiveUI.Samples.Testing.SimpleViewModels', 'Xunit']
xUnit
net7.0;net462
/// <summary> /// A few sample unit tests. Note how simple they are: since the concept of time /// is not involved we do not have to model it in our unit tests. We test these almost /// as if they were a non ReactiveUI object. /// </summary> public class CalculatorViewModelTest { [Fact] public void TestTypingStringGetsError() { CalculatorViewModel fixture = new() { InputText = "hi" }; Assert.Equal("Error", fixture.ErrorText); Assert.Equal("", fixture.ResultText); } [Fact] public void TestTypingInteger() { CalculatorViewModel fixture = new() { InputText = "50" }; Assert.Equal("", fixture.ErrorText); Assert.Equal("100", fixture.ResultText); } }
396
1,029
using System.Reactive.Linq; namespace ReactiveUI.Samples.Testing.SimpleViewModels { /// <summary> /// A view model with some straight forward calculations. There are no /// async operations involve, nor are there any delays or other time related /// calls. /// Operation: The user enters text into the input text field. /// If the text doesn't contain numbers, then an error message is shown in the ErrorText field /// Otherwise the number x2 is shown in the ResultText field. /// The ErrorText and ResultText fields should be empty when nothing is in InputText. /// </summary> public class CalculatorViewModel : ReactiveObject { private readonly ObservableAsPropertyHelper<string> _ErrorText; private readonly ObservableAsPropertyHelper<string> _ResultText; public string InputText { get => _InputText; set => this.RaiseAndSetIfChanged(ref _InputText, value); } string _InputText; public string ErrorText => _ErrorText.Value; public string ResultText => _ResultText.Value; public CalculatorViewModel() { var haveInput = this.WhenAny(x => x.InputText, x => x.Value) .Where(x => !string.IsNullOrEmpty(x)); // Convert into a stream of parsed integers, or null if we fail. var parsedIntegers = haveInput .Select(x => int.TryParse(x, out var val) ? (int?)val : null); // Now, the error text parsedIntegers .Select(x => x.HasValue ? "" : "Error") .ToProperty(this, x => x.ErrorText, out _ErrorText); // And the result, which is *2 of the input. parsedIntegers .Select(x => x.HasValue ? (x.Value * 2).ToString() : "") .ToProperty(this, x => x.ResultText, out _ResultText); } } }
reactiveui
ReactiveUI.Samples
F:\Projects\TestMap\Temp\ReactiveUI.Samples\ReactiveUI.Samples.sln
F:\Projects\TestMap\Temp\ReactiveUI.Samples\testing\ReactiveUI.Samples.Testing.SimpleViewModels.Tests\ReactiveUI.Samples.Testing.SimpleViewModelsUnitTests.csproj
F:\Projects\TestMap\Temp\ReactiveUI.Samples\testing\ReactiveUI.Samples.Testing.SimpleViewModels.Tests\WebCallViewModelTest.cs
ReactiveUI.Samples.Testing.SimpleViewModelsUnitTests
WebCallViewModelTest
[]
['Microsoft.Reactive.Testing', 'ReactiveUI.Samples.Testing.SimpleViewModels', 'ReactiveUI.Testing', 'System.Reactive.Linq', 'Xunit']
xUnit
net7.0;net462
/// <summary> /// The web call ViewModel is time dependent. There is the webservice time and there /// is the time that one waits for the user to stop typing. We could wait 800 ms, and test /// that way. Or we can time travel with some nifty tools from the System.Reactive.Testing /// namespace. /// </summary> public class WebCallViewModelTest { /// <summary> /// Make sure no webservice call is send off until 800 ms have passed. /// </summary> [Fact] public void TestNothingTill800ms() { // Run a test scheduler to put time under our control. new TestScheduler().With(s => { WebCallViewModel fixture = new(new immediateWebService()) { InputText = "hi" }; // Run the clock forward to 800 ms. At that point, nothing should have happened. s.AdvanceToMs(799); Assert.Equal("", fixture.ResultText); // Run the clock 1 tick past and the result should show up. s.AdvanceToMs(801); Assert.Equal("result hi", fixture.ResultText); }); } /// <summary> /// User types something, pauses, then types something again. /// </summary> [Fact] public void TestDelayAfterUpdate() { // Run a test scheduler to put time under our control. new TestScheduler().With(s => { WebCallViewModel fixture = new(new immediateWebService()) { InputText = "hi" }; // Run the clock forward 300 ms, where they type again. s.AdvanceToMs(300); fixture.InputText = "there"; // Now, at 800, there should be nothing! s.AdvanceToMs(799); Assert.Equal("", fixture.ResultText); // But, at 800+300+1, our result should appear! s.AdvanceToMs(800 + 300 + 1); Assert.Equal("result there", fixture.ResultText); }); } /// <summary> /// This dummy webservice takes zero time so we can isolate the timing tests for /// the typing above. /// </summary> class immediateWebService : IWebCaller { public System.IObservable<string> GetResult(string searchItems) { return Observable.Return("result " + searchItems); } } }
557
2,819
using System; using System.Reactive; using System.Reactive.Linq; namespace ReactiveUI.Samples.Testing.SimpleViewModels { /// <summary> /// A class that simulates a call to a web service, which is expected to /// take some time. We also do some work so that we don't flood the /// web service each time the user updates the input. /// </summary> public class WebCallViewModel : ReactiveObject { private readonly ObservableAsPropertyHelper<string> _ResultTextOAPH; private string _InputText; public string InputText { get => _InputText; set => this.RaiseAndSetIfChanged(ref _InputText, value); } public string ResultText => _ResultTextOAPH.Value; public ReactiveCommand<string, string> DoWebCall { get; } /// <summary> /// Setup the lookup logic, and use the interface to do the web call. /// </summary> /// <param name="caller"></param> public WebCallViewModel(IWebCaller caller) { // Do a search when nothing new has been entered for 800 ms and it isn't // an empty string... and don't search for the same thing twice. var newSearchNeeded = this.WhenAny(p => p.InputText, x => x.Value) .Throttle(TimeSpan.FromMilliseconds(800), RxApp.TaskpoolScheduler) .DistinctUntilChanged() .Where(x => !string.IsNullOrWhiteSpace(x)); DoWebCall = ReactiveCommand.CreateFromObservable<string, string>(x => caller.GetResult(x)); newSearchNeeded.InvokeCommand(DoWebCall); // The results are stuffed into the property, on the proper thread // (ToProperty takes care of that) when done. We never want the property to // be null, so we give it an initial value of "". DoWebCall.ToProperty(this, x => x.ResultText, out _ResultTextOAPH, ""); } } }
reactiveui
ReactiveUI
F:\Projects\TestMap\Temp\ReactiveUI\src\ReactiveUI.sln
F:\Projects\TestMap\Temp\ReactiveUI\src\ReactiveUI.Tests\ReactiveUI.Tests.csproj
F:\Projects\TestMap\Temp\ReactiveUI\src\ReactiveUI.Tests\Platforms\windows-xaml\DependencyObjectObservableForPropertyTest.cs
ReactiveUI.Tests.Xaml
DependencyObjectObservableForPropertyTest
[]
['DynamicData', 'System.Windows.Controls', 'Xunit.WpfFactAttribute']
xUnit
net6.0;net8.0
/// <summary> /// Tests for the dependency object property binding. /// </summary> public class DependencyObjectObservableForPropertyTest { /// <summary> /// Runs a smoke test for dependency object observables for property. /// </summary> [Fact] public void DependencyObjectObservableForPropertySmokeTest() { var fixture = new DepObjFixture(); var binder = new DependencyObjectObservableForProperty(); Assert.NotEqual(0, binder.GetAffinityForObject(typeof(DepObjFixture), "TestString")); Assert.Equal(0, binder.GetAffinityForObject(typeof(DepObjFixture), "DoesntExist")); var results = new List<IObservedChange<object, object?>>(); Expression<Func<DepObjFixture, object>> expression = x => x.TestString; var propertyName = expression.Body.GetMemberInfo()?.Name ?? throw new InvalidOperationException("There is no valid property name"); var disp1 = binder.GetNotificationForProperty(fixture, expression.Body, propertyName).WhereNotNull().Subscribe(results.Add); var disp2 = binder.GetNotificationForProperty(fixture, expression.Body, propertyName).WhereNotNull().Subscribe(results.Add); fixture.TestString = "Foo"; fixture.TestString = "Bar"; Assert.Equal(4, results.Count); disp1.Dispose(); disp2.Dispose(); } /// <summary> /// Runs a smoke test for derived dependency object observables for property. /// </summary> [Fact] public void DerivedDependencyObjectObservableForPropertySmokeTest() { var fixture = new DerivedDepObjFixture(); var binder = new DependencyObjectObservableForProperty(); Assert.NotEqual(0, binder.GetAffinityForObject(typeof(DerivedDepObjFixture), "TestString")); Assert.Equal(0, binder.GetAffinityForObject(typeof(DerivedDepObjFixture), "DoesntExist")); var results = new List<IObservedChange<object, object?>>(); Expression<Func<DerivedDepObjFixture, object>> expression = x => x.TestString; var propertyName = expression.Body.GetMemberInfo()?.Name ?? throw new InvalidOperationException("There is no valid property name"); var disp1 = binder.GetNotificationForProperty(fixture, expression.Body, propertyName).WhereNotNull().Subscribe(results.Add); var disp2 = binder.GetNotificationForProperty(fixture, expression.Body, propertyName).WhereNotNull().Subscribe(results.Add); fixture.TestString = "Foo"; fixture.TestString = "Bar"; Assert.Equal(4, results.Count); disp1.Dispose(); disp2.Dispose(); } /// <summary> /// Tests WhenAny with dependency object test. /// </summary> [Fact] public void WhenAnyWithDependencyObjectTest() { var inputs = new[] { "Foo", "Bar", "Baz" }; var fixture = new DepObjFixture(); fixture.WhenAnyValue(x => x.TestString).ToObservableChangeSet().Bind(out var outputs).Subscribe(); inputs.ForEach(x => fixture.TestString = x); Assert.Null(outputs.First()); Assert.Equal(4, outputs.Count); Assert.True(inputs.Zip(outputs.Skip(1), (expected, actual) => expected == actual).All(x => x)); } /// <summary> /// Tests ListBoxes the selected item test. /// </summary> [Fact] public void ListBoxSelectedItemTest() { var input = new ListBox(); input.Items.Add("Foo"); input.Items.Add("Bar"); input.Items.Add("Baz"); input.WhenAnyValue(x => x.SelectedItem).ToObservableChangeSet().Bind(out var output).Subscribe(); Assert.Equal(1, output.Count); input.SelectedIndex = 1; Assert.Equal(2, output.Count); input.SelectedIndex = 2; Assert.Equal(3, output.Count); } }
607
4,403
// Copyright (c) 2024 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System.Reflection; using System.Windows; namespace ReactiveUI; /// <summary> /// Creates a observable for a property if available that is based on a DependencyProperty. /// </summary> public class DependencyObjectObservableForProperty : ICreatesObservableForProperty { /// <inheritdoc/> public int GetAffinityForObject(Type type, string propertyName, bool beforeChanged = false) { if (!typeof(DependencyObject).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) { return 0; } return GetDependencyProperty(type, propertyName) is not null ? 4 : 0; } /// <inheritdoc/> public IObservable<IObservedChange<object, object?>> GetNotificationForProperty(object sender, System.Linq.Expressions.Expression expression, string propertyName, bool beforeChanged = false, bool suppressWarnings = false) { #if NET6_0_OR_GREATER ArgumentNullException.ThrowIfNull(sender); #else if (sender is null) { throw new ArgumentNullException(nameof(sender)); } #endif var type = sender.GetType(); var dependencyProperty = GetDependencyProperty(type, propertyName) ?? throw new ArgumentException( $"The property {propertyName} does not have a dependency property.", nameof(propertyName)); var dependencyPropertyDescriptor = DependencyPropertyDescriptor.FromProperty(dependencyProperty, type); if (dependencyPropertyDescriptor is null) { if (!suppressWarnings) { this.Log().Error("Couldn't find dependency property " + propertyName + " on " + type.Name); } throw new NullReferenceException("Couldn't find dependency property " + propertyName + " on " + type.Name); } return Observable.Create<IObservedChange<object, object?>>(subj => { var handler = new EventHandler((_, _) => subj.OnNext(new ObservedChange<object, object?>(sender, expression, default))); dependencyPropertyDescriptor.AddValueChanged(sender, handler); return Disposable.Create(() => dependencyPropertyDescriptor.RemoveValueChanged(sender, handler)); }); } private static DependencyProperty? GetDependencyProperty(Type type, string propertyName) { var fi = Array.Find(type.GetTypeInfo().GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public), x => x.Name == propertyName + "Property" && x.IsStatic); return (DependencyProperty?)fi?.GetValue(null); } }
jvukovich
bounce
F:\Projects\TestMap\Temp\bounce\Bounce.sln
F:\Projects\TestMap\Temp\bounce\Bounce.Tests\Bounce.Tests.csproj
F:\Projects\TestMap\Temp\bounce\Bounce.Tests\Framework\ParametersTest.cs
Bounce.Tests.Framework
ParametersTest
[]
['System', 'System.Collections.Generic', 'Bounce.Framework', 'Xunit']
xUnit
net6.0
public class ParametersTest { [Fact] public void CanParseDefaultStringParameter() { var p = new TaskParameters(new Dictionary<string, string> {{"file", "thefile.txt"}}); Assert.Equal("thefile.txt", p.Parameter("file", "afile.txt")); } [Fact] public void CanParseDefaultStringParameterIfNotPresent() { var p = new TaskParameters(new Dictionary<string, string>()); Assert.Equal("afile.txt", p.Parameter("file", "afile.txt")); } [Fact] public void CanParseStringParameter() { var p = new TaskParameters(new Dictionary<string, string> {{"file", "thefile.txt"}}); Assert.Equal("thefile.txt", p.Parameter("file", "afile.txt")); } [Fact] public void CanParseDefaultStringParameterWithType() { var p = new TaskParameters(new Dictionary<string, string> {{"file", "thefile.txt"}}); Assert.Equal("thefile.txt", p.Parameter(typeof(string), "file", "afile.txt")); } [Fact] public void CanParseDefaultStringParameterIfNotPresentWithType() { var p = new TaskParameters(new Dictionary<string, string>()); Assert.Equal("afile.txt", p.Parameter(typeof(string), "file", "afile.txt")); } [Fact] public void CanParseStringParameterWithType() { var p = new TaskParameters(new Dictionary<string, string> {{"file", "thefile.txt"}}); Assert.Equal("thefile.txt", p.Parameter(typeof(string), "file", "afile.txt")); } [Fact] public void ThrowsExceptionWhenStringParameterIsNotPresentWithType() { var p = new TaskParameters(new Dictionary<string, string>()); var ex = Assert.Throws<Exception>(() => p.Parameter(typeof(string), "file")); Assert.Equal("Required parameter 'file' must be provided.", ex.Message); } [Fact] public void ThrowsExceptionWhenStringParameterIsNotPresent() { var p = new TaskParameters(new Dictionary<string, string>()); var ex = Assert.Throws<Exception>(() => p.Parameter<string>("file")); Assert.Equal("Required parameter 'file' must be provided.", ex.Message); } [Fact] public void CanParseEnumeration() { var p = new TaskParameters(new Dictionary<string, string> {{"lake", "constance"}}); Assert.Equal(Lakes.Constance, p.Parameter<Lakes>("lake")); } private enum Lakes { Constance, Coniston, Consequence } }
132
2,919
namespace Bounce.Framework { public class Parameters { private readonly TaskParameters _params; public Parameters(TaskParameters parms) { _params = parms; } // ReSharper disable once UnusedAutoPropertyAccessor.Global public static Parameters Main { get; internal set; } // ReSharper disable once UnusedMember.Global public T Parameter<T>(string name) { return (T) _params.Parameter(typeof(T), name); } // ReSharper disable once UnusedMember.Global public T Parameter<T>(string name, T defaultValue) { return (T) _params.Parameter(typeof(T), name, defaultValue); } } }
jvukovich
bounce
F:\Projects\TestMap\Temp\bounce\Bounce.sln
F:\Projects\TestMap\Temp\bounce\Bounce.Tests\Bounce.Tests.csproj
F:\Projects\TestMap\Temp\bounce\Bounce.Tests\Framework\TaskMethodTest.cs
Bounce.Tests.Framework
TaskMethodTest
['private static StringWriter output;', 'private readonly IDependencyResolver resolver;']
['System', 'System.Collections.Generic', 'System.IO', 'System.Linq', 'System.Reflection', 'Bounce.Framework', 'Xunit']
xUnit
net6.0
public class TaskMethodTest { private static StringWriter output; private readonly IDependencyResolver resolver; public TaskMethodTest() { output = new StringWriter(); resolver = new SimpleDependencyResolver(); } [Fact] public void InvokesTaskMethodWithNoParameters() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Compile"), resolver); task.Invoke(new TaskParameters(new Dictionary<string, string>())); Assert.Equal("compiling", output.ToString().Trim()); } [Fact] public void InvokesTaskMethodWithStringParameter() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Deploy"), resolver); task.Invoke(new TaskParameters(new Dictionary<string, string> {{"dir", @"c:\sites"}})); Assert.Equal(@"deploying c:\sites", output.ToString().Trim()); } [Fact] public void InvokesTaskMethodWithBooleanParameter() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Test"), resolver); task.Invoke(new TaskParameters(new Dictionary<string, string> {{"fast", "true"}})); Assert.Equal("testing fast", output.ToString().Trim()); } [Fact] public void InvokesTaskMethodWithOptionalStringParameterNotGiven() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Optional"), resolver); task.Invoke(new TaskParameters(new Dictionary<string, string>())); Assert.Equal("optional fileName: stuff.txt", output.ToString().Trim()); } [Fact] public void InvokesTaskMethodWithOptionalStringParameterGiven() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Optional"), resolver); task.Invoke(new TaskParameters(new Dictionary<string, string> {{"fileName", "thefile.txt"}})); Assert.Equal("optional fileName: thefile.txt", output.ToString().Trim()); } [Fact] public void InvokesTaskMethodWithNullableIntParameterGiven() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Nullable"), resolver); task.Invoke(new TaskParameters(new Dictionary<string, string> {{"port", "80"}})); Assert.Equal("port: 80", output.ToString().Trim()); } [Fact] public void ThrowsExceptionWhenTaskRequiredParameterNotProvided() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Test"), resolver); var ex = Assert.Throws<Exception>(() => task.Invoke(new TaskParameters(new Dictionary<string, string>()))); Assert.Contains("Required parameter 'fast' must be provided.", ex.Message); } [Fact] public void ThrowsExceptionWhenCustomTypeCannotBeParsed() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Bad"), resolver); var ex = Assert.Throws<Exception>(() => task.Invoke(new TaskParameters(new Dictionary<string, string> {{"x", "something"}}))); Assert.Contains("Could not parse 'something' for type", ex.Message); } [Fact] public void NullableParameterIsNotRequired() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Nullable"), resolver); Assert.False(task.Parameters.ElementAt(0).IsRequired); } [Fact] public void TaskExceptionIsThrownWhenTaskThrows() { var task = new TaskMethod(typeof(FakeTaskClass).GetMethod("Throws"), resolver); var ex = Assert.Throws<TargetInvocationException>(() => task.Invoke(new TaskParameters(new Dictionary<string, string>()))); Assert.Contains("Exception has been thrown by the target", ex.Message); } public class FakeTaskClass { [Task] public void Compile() { output.WriteLine("compiling"); } [Task] public void Deploy(string dir) { output.WriteLine("deploying " + dir); } [Task] public void Test(bool fast) { output.WriteLine("testing " + (fast ? "fast" : "slow")); } [Task] public void Bad(CustomType x) { } [Task] public void Optional(string fileName = "stuff.txt") { output.WriteLine("optional fileName: " + fileName); } [Task] public void Nullable(int? port) { output.WriteLine("port: " + (port.HasValue ? port.Value.ToString() : "<nothing>")); } [Task] public void Throws() { throw new BadException(); } } private class BadException : Exception { } public abstract class CustomType { } }
196
5,497
using System.Collections.Generic; using System.Linq; using System.Reflection; using Serilog; namespace Bounce.Framework { public interface ITask { string FullName { get; } IEnumerable<ITaskParameter> Parameters { get; } void Invoke(TaskParameters taskParameters); } public class TaskMethod : ITask { private readonly MethodInfo _method; private readonly IDependencyResolver _resolver; public TaskMethod(MethodInfo method, IDependencyResolver resolver) { _method = method; _resolver = resolver; } public string FullName => _method.DeclaringType.FullName + "." + _method.Name; public void Invoke(TaskParameters taskParameters) { try { var taskObject = _resolver.Resolve(_method.DeclaringType); var methodArguments = MethodArgumentsFromCommandLineParameters(taskParameters); _method.Invoke(taskObject, methodArguments); } catch (TargetInvocationException e) { Log.Error(e.ToString()); if (e.InnerException != null) Log.Error(e.InnerException.ToString()); throw e; } } private object[] MethodArgumentsFromCommandLineParameters(TaskParameters taskParameters) { return Parameters.Select(x => ParseParameter(taskParameters, x)).ToArray(); } private static object ParseParameter(TaskParameters taskParameters, ITaskParameter p) { return taskParameters.Parameter(p); } public IEnumerable<ITaskParameter> Parameters { get { return _method.GetParameters().Select(x => (ITaskParameter) new TaskMethodParameter(x)); } } } }
jvukovich
bounce
F:\Projects\TestMap\Temp\bounce\Bounce.sln
F:\Projects\TestMap\Temp\bounce\Bounce.Tests\Bounce.Tests.csproj
F:\Projects\TestMap\Temp\bounce\Bounce.Tests\TargetsAssemblyArgumentsParser.cs
Bounce.Tests
TargetsAssemblyArgumentsParserTest
[]
['Xunit']
xUnit
net6.0
public class TargetsAssemblyArgumentsParserTest { [Fact] public void ShouldParseTargetsFromParameterWithColon() { var targetsAndArgs = TargetsAssemblyArgumentsParser.GetTargetsAssembly(new[] {"/bounceDir:adir", "other", "args"}); Assert.Equal(new[] {"other", "args"}, targetsAndArgs.RemainingArguments); Assert.Equal("adir", targetsAndArgs.BounceDirectory); } [Fact] public void ShouldParseTargetsFromParameter() { var targetsAndArgs = TargetsAssemblyArgumentsParser.GetTargetsAssembly(new[] {"/bounceDir", "adir", "other", "args"}); Assert.Equal(new[] {"other", "args"}, targetsAndArgs.RemainingArguments); Assert.Equal("adir", targetsAndArgs.BounceDirectory); } [Fact] public void ShouldFindTargetsIfNoTargetsParameterGiven() { var targetsAndArgs = TargetsAssemblyArgumentsParser.GetTargetsAssembly(new[] {"build", "SomeTarget", "/other", "args"}); Assert.Equal(new[] {"build", "SomeTarget", "/other", "args"}, targetsAndArgs.RemainingArguments); Assert.NotNull(targetsAndArgs.BounceDirectory); } [Fact] public void ShouldAttemptToFindAssemblyIfNoArgsGiven() { var targetsAndArgs = TargetsAssemblyArgumentsParser.GetTargetsAssembly(new string[0]); Assert.Empty(targetsAndArgs.RemainingArguments); Assert.NotNull(targetsAndArgs.BounceDirectory); } // todo: additional unit tests to cover multiple task invocation }
47
1,697
using System; using System.IO; namespace Bounce { public static class TargetsAssemblyArgumentsParser { private static void TryGetTargetsFromArguments(OptionsAndArguments optionsAndArguments) { var args = optionsAndArguments.RemainingArguments; if (args.Length <= 0) return; var firstArg = args[0]; const string bounceDir = "bounceDir"; if (firstArg.StartsWith("/" + bounceDir + ":")) { var remainingArgs = new string[args.Length - 1]; Array.Copy(args, 1, remainingArgs, 0, remainingArgs.Length); optionsAndArguments.BounceDirectory = firstArg.Substring(("/" + bounceDir + ":").Length); optionsAndArguments.RemainingArguments = remainingArgs; optionsAndArguments.WorkingDirectory = Directory.GetCurrentDirectory(); } else if (firstArg == "/" + bounceDir) { var remainingArgs = new string[args.Length - 2]; Array.Copy(args, 2, remainingArgs, 0, remainingArgs.Length); optionsAndArguments.BounceDirectory = args[1]; optionsAndArguments.RemainingArguments = remainingArgs; optionsAndArguments.WorkingDirectory = Directory.GetCurrentDirectory(); } } public static OptionsAndArguments GetTargetsAssembly(string[] args) { var optionsAndArguments = new OptionsAndArguments {RemainingArguments = args}; TryGetTargetsFromArguments(optionsAndArguments); if (optionsAndArguments.BounceDirectory != null) return optionsAndArguments; optionsAndArguments.BounceDirectory = Directory.GetCurrentDirectory(); optionsAndArguments.WorkingDirectory = Directory.GetCurrentDirectory(); return optionsAndArguments; } } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Integration\DatabaseTest.cs
Test.Integration
DatabaseTester
['private readonly TestDbHelper _dbHelper;', 'private readonly ILogger _logger;']
['SchemaZen.Library', 'SchemaZen.Library.Models', 'Test.Integration.Helpers', 'Xunit', 'Xunit.Abstractions', 'Microsoft.Extensions.Logging.ILogger']
xUnit
net6.0
[Trait("Category", "Integration")] public class DatabaseTester { private readonly TestDbHelper _dbHelper; private readonly ILogger _logger; public DatabaseTester(ITestOutputHelper output, TestDbHelper dbHelper) { _logger = output.BuildLogger(); _dbHelper = dbHelper; } [Fact] public async Task TestDescIndex() { await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(@"create table MyTable (Id int)"); await testDb.ExecSqlAsync(@"create nonclustered index MyIndex on MyTable (Id desc)"); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); var index = db.FindConstraint("MyIndex"); Assert.NotNull(index); Assert.True(index.Columns[0].Desc); } [Fact] public async Task TestTableIndexesWithFilter() { await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync( @"CREATE TABLE MyTable (Id int, EndDate datetime)"); await testDb.ExecSqlAsync( @"CREATE NONCLUSTERED INDEX MyIndex ON MyTable (Id) WHERE (EndDate) IS NULL"); var db = new Database("TEST") { Connection = testDb.GetConnString() }; db.Load(); var index = db.FindConstraint("MyIndex"); Assert.NotNull(index); Assert.Equal("([EndDate] IS NULL)", index.Filter); } [Fact] public async Task TestViewIndexes() { await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync( @"CREATE TABLE MyTable (Id int, Name nvarchar(250), EndDate datetime)"); await testDb.ExecSqlAsync( @"CREATE VIEW dbo.MyView WITH SCHEMABINDING as SELECT t.Id, t.Name, t.EndDate from dbo.MyTable t"); await testDb.ExecSqlAsync( @"CREATE UNIQUE CLUSTERED INDEX MyIndex ON MyView (Id, Name)"); var db = new Database("TEST") { Connection = testDb.GetConnString() }; db.Load(); var index = db.FindViewIndex("MyIndex"); Assert.NotNull(index); } [Fact] public async Task TestScript() { var db = new Database(_dbHelper.MakeTestDbName()); var t1 = new Table("dbo", "t1"); t1.Columns.Add(new Column("col1", "int", false, null) { Position = 1 }); t1.Columns.Add(new Column("col2", "int", false, null) { Position = 2 }); t1.AddConstraint( new Constraint("pk_t1", "PRIMARY KEY", "col1,col2") { IndexType = "CLUSTERED" }); var t2 = new Table("dbo", "t2"); t2.Columns.Add(new Column("col1", "int", false, null) { Position = 1 }); var col2 = new Column("col2", "int", false, null) { Position = 2 }; col2.Default = new Default(t2, col2, "df_col2", "((0))", false); t2.Columns.Add(col2); t2.Columns.Add(new Column("col3", "int", false, null) { Position = 3 }); t2.AddConstraint( new Constraint("pk_t2", "PRIMARY KEY", "col1") { IndexType = "CLUSTERED" }); t2.AddConstraint( Constraint.CreateCheckedConstraint("ck_col2", true, false, "([col2]>(0))")); t2.AddConstraint( new Constraint("IX_col3", "UNIQUE", "col3") { IndexType = "NONCLUSTERED" }); db.ForeignKeys.Add(new ForeignKey(t2, "fk_t2_t1", "col2,col3", t1, "col1,col2")); db.Tables.Add(t1); db.Tables.Add(t2); await using var testDb = await _dbHelper.CreateTestDb(db); var db2 = new Database(); db2.Connection = testDb.GetConnString(); db2.Load(); foreach (var t in db.Tables) { var copy = db2.FindTable(t.Name, t.Owner); Assert.NotNull(copy); Assert.False(copy.Compare(t).IsDiff); } } [Fact] public async Task TestScriptTableType() { var setupSQL1 = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [nvarchar](250) NULL, [Value] [numeric](5, 1) NULL, [LongNVarchar] [nvarchar](max) NULL ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(setupSQL1); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Equal(250, tt.Columns.Items[0].Length); Assert.Equal(1, tt.Columns.Items[1].Scale); Assert.Equal(5, tt.Columns.Items[1].Precision); Assert.Equal(-1, tt.Columns.Items[2].Length); Assert.Equal("MyTableType", tt.Name); var result = tt.ScriptCreate(); Assert.Contains( "CREATE TYPE [dbo].[MyTableType] AS TABLE", result); } [Fact] public async Task TestScriptTableTypePrimaryKey() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [int] NOT NULL, [Value] [varchar](50) NOT NULL, PRIMARY KEY CLUSTERED ( [ID] ) ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Single(tt.PrimaryKey.Columns); Assert.Equal("ID", tt.PrimaryKey.Columns[0].ColumnName); Assert.Equal(50, tt.Columns.Items[1].Length); Assert.Equal("MyTableType", tt.Name); var result = tt.ScriptCreate(); Assert.Contains("PRIMARY KEY", result); } [Fact] public async Task TestScriptTableTypeComputedColumn() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [Value1] [int] NOT NULL, [Value2] [int] NOT NULL, [ComputedValue] AS ([VALUE1]+[VALUE2]) ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Equal(3, tt.Columns.Items.Count()); Assert.Equal("ComputedValue", tt.Columns.Items[2].Name); Assert.Equal("([VALUE1]+[VALUE2])", tt.Columns.Items[2].ComputedDefinition); Assert.Equal("MyTableType", tt.Name); } [Fact] public async Task TestScriptTableTypeColumnCheckConstraint() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [nvarchar](250) NULL, [Value] [numeric](5, 1) NULL CHECK([Value]>(0)), [LongNVarchar] [nvarchar](max) NULL ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Single(tt.Constraints); var constraint = tt.Constraints.First(); Assert.Equal("([Value]>(0))", constraint.CheckConstraintExpression); Assert.Equal("MyTableType", db.TableTypes[0].Name); } [Fact] public async Task TestScriptTableTypeColumnDefaultConstraint() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [nvarchar](250) NULL, [Value] [numeric](5, 1) NULL DEFAULT 0, [LongNVarchar] [nvarchar](max) NULL ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); Assert.NotNull(db.TableTypes[0].Columns.Items[1].Default); Assert.Equal(" DEFAULT ((0))", db.TableTypes[0].Columns.Items[1].Default.ScriptCreate()); Assert.Equal("MyTableType", db.TableTypes[0].Name); } [Fact] public async Task TestScriptFKSameName() { var sql = @" CREATE SCHEMA [s2] AUTHORIZATION [dbo] CREATE TABLE [dbo].[t1a] ( a INT NOT NULL, CONSTRAINT [PK_1a] PRIMARY KEY (a) ) CREATE TABLE [dbo].[t1b] ( a INT NOT NULL, CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [dbo].[t1a] ([a]) ON UPDATE CASCADE ) CREATE TABLE [s2].[t2a] ( a INT NOT NULL, CONSTRAINT [PK_2a] PRIMARY KEY (a) ) CREATE TABLE [s2].[t2b] ( a INT NOT NULL, CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [s2].[t2a] ([a]) ON DELETE CASCADE ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Equal(2, db.ForeignKeys.Count()); Assert.Equal(db.ForeignKeys[0].Name, db.ForeignKeys[1].Name); Assert.NotEqual(db.ForeignKeys[0].Table.Owner, db.ForeignKeys[1].Table.Owner); Assert.Equal("CASCADE", db.FindForeignKey("FKName", "dbo").OnUpdate); Assert.Equal("NO ACTION", db.FindForeignKey("FKName", "s2").OnUpdate); Assert.Equal("NO ACTION", db.FindForeignKey("FKName", "dbo").OnDelete); Assert.Equal("CASCADE", db.FindForeignKey("FKName", "s2").OnDelete); } [Fact] public async Task TestScriptViewInsteadOfTrigger() { var setupSQL1 = @" CREATE TABLE [dbo].[t1] ( a INT NOT NULL, CONSTRAINT [PK] PRIMARY KEY (a) ) "; var setupSQL2 = @" CREATE VIEW [dbo].[v1] AS SELECT * FROM t1 "; var setupSQL3 = @" CREATE TRIGGER [dbo].[TR_v1] ON [dbo].[v1] INSTEAD OF DELETE AS DELETE FROM [dbo].[t1] FROM [dbo].[t1] INNER JOIN DELETED ON DELETED.a = [dbo].[t1].a "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(setupSQL1); await testDb.ExecSqlAsync(setupSQL2); await testDb.ExecSqlAsync(setupSQL3); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); var triggers = db.Routines.Where(x => x.RoutineType == Routine.RoutineKind.Trigger) .ToList(); Assert.Single(triggers); Assert.Equal("TR_v1", triggers[0].Name); } [Fact] public async Task TestScriptTriggerWithNoSets() { var setupSQL1 = @" CREATE TABLE [dbo].[t1] ( a INT NOT NULL, CONSTRAINT [PK] PRIMARY KEY (a) ) "; var setupSQL2 = @" CREATE TABLE [dbo].[t2] ( a INT NOT NULL ) "; var setupSQL3 = @" CREATE TRIGGER [dbo].[TR_1] ON [dbo].[t1] FOR UPDATE,INSERT AS INSERT INTO [dbo].[t2](a) SELECT a FROM INSERTED"; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(setupSQL1); await testDb.ExecSqlAsync(setupSQL2); await testDb.ExecSqlAsync(setupSQL3); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); // Set these properties to the defaults so they are not scripted db.FindProp("QUOTED_IDENTIFIER").Value = "ON"; db.FindProp("ANSI_NULLS").Value = "ON"; var trigger = db.FindRoutine("TR_1", "dbo"); var script = trigger.ScriptCreate(); Assert.DoesNotContain( "INSERTEDENABLE", script); } [Fact] public async Task TestScriptToDir() { var policy = new Table("dbo", "Policy"); policy.Columns.Add(new Column("id", "int", false, null) { Position = 1 }); policy.Columns.Add(new Column("form", "tinyint", false, null) { Position = 2 }); policy.AddConstraint( new Constraint("PK_Policy", "PRIMARY KEY", "id") { IndexType = "CLUSTERED", Unique = true }); policy.Columns.Items[0].Identity = new Identity(1, 1); var loc = new Table("dbo", "Location"); loc.Columns.Add(new Column("id", "int", false, null) { Position = 1 }); loc.Columns.Add(new Column("policyId", "int", false, null) { Position = 2 }); loc.Columns.Add(new Column("storage", "bit", false, null) { Position = 3 }); loc.Columns.Add(new Column("category", "int", false, null) { Position = 4 }); loc.AddConstraint( new Constraint("PK_Location", "PRIMARY KEY", "id") { IndexType = "CLUSTERED", Unique = true }); loc.Columns.Items[0].Identity = new Identity(1, 1); var formType = new Table("dbo", "FormType"); formType.Columns.Add(new Column("code", "tinyint", false, null) { Position = 1 }); formType.Columns.Add(new Column("desc", "varchar", 10, false, null) { Position = 2 }); formType.AddConstraint( new Constraint("PK_FormType", "PRIMARY KEY", "code") { IndexType = "CLUSTERED", Unique = true }); formType.AddConstraint( Constraint.CreateCheckedConstraint("CK_FormType", false, false, "([code]<(5))")); var categoryType = new Table("dbo", "CategoryType"); categoryType.Columns.Add(new Column("id", "int", false, null) { Position = 1 }); categoryType.Columns.Add( new Column("Category", "varchar", 10, false, null) { Position = 2 }); categoryType.AddConstraint( new Constraint("PK_CategoryType", "PRIMARY KEY", "id") { IndexType = "CLUSTERED", Unique = true }); var emptyTable = new Table("dbo", "EmptyTable"); emptyTable.Columns.Add(new Column("code", "tinyint", false, null) { Position = 1 }); emptyTable.AddConstraint( new Constraint("PK_EmptyTable", "PRIMARY KEY", "code") { IndexType = "CLUSTERED", Unique = true }); var fk_policy_formType = new ForeignKey("FK_Policy_FormType"); fk_policy_formType.Table = policy; fk_policy_formType.Columns.Add("form"); fk_policy_formType.RefTable = formType; fk_policy_formType.RefColumns.Add("code"); fk_policy_formType.OnUpdate = "NO ACTION"; fk_policy_formType.OnDelete = "NO ACTION"; var fk_location_policy = new ForeignKey("FK_Location_Policy"); fk_location_policy.Table = loc; fk_location_policy.Columns.Add("policyId"); fk_location_policy.RefTable = policy; fk_location_policy.RefColumns.Add("id"); fk_location_policy.OnUpdate = "NO ACTION"; fk_location_policy.OnDelete = "CASCADE"; var fk_location_category = new ForeignKey("FK_Location_category"); fk_location_category.Table = loc; fk_location_category.Columns.Add("category"); fk_location_category.RefTable = categoryType; fk_location_category.RefColumns.Add("id"); fk_location_category.OnUpdate = "NO ACTION"; fk_location_category.OnDelete = "CASCADE"; var tt_codedesc = new Table("dbo", "CodeDesc"); tt_codedesc.IsType = true; tt_codedesc.Columns.Add(new Column("code", "tinyint", false, null) { Position = 1 }); tt_codedesc.Columns.Add( new Column("desc", "varchar", 10, false, null) { Position = 2 }); tt_codedesc.AddConstraint( new Constraint("PK_CodeDesc", "PRIMARY KEY", "code") { IndexType = "NONCLUSTERED" }); var db = new Database("ScriptToDirTest"); db.Tables.Add(policy); db.Tables.Add(formType); db.Tables.Add(categoryType); db.Tables.Add(emptyTable); db.Tables.Add(loc); db.TableTypes.Add(tt_codedesc); db.ForeignKeys.Add(fk_policy_formType); db.ForeignKeys.Add(fk_location_policy); db.ForeignKeys.Add(fk_location_category); db.FindProp("COMPATIBILITY_LEVEL").Value = "110"; db.FindProp("COLLATE").Value = "SQL_Latin1_General_CP1_CI_AS"; db.FindProp("AUTO_CLOSE").Value = "OFF"; db.FindProp("AUTO_SHRINK").Value = "ON"; db.FindProp("ALLOW_SNAPSHOT_ISOLATION").Value = "ON"; db.FindProp("READ_COMMITTED_SNAPSHOT").Value = "OFF"; db.FindProp("RECOVERY").Value = "SIMPLE"; db.FindProp("PAGE_VERIFY").Value = "CHECKSUM"; db.FindProp("AUTO_CREATE_STATISTICS").Value = "ON"; db.FindProp("AUTO_UPDATE_STATISTICS").Value = "ON"; db.FindProp("AUTO_UPDATE_STATISTICS_ASYNC").Value = "ON"; db.FindProp("ANSI_NULL_DEFAULT").Value = "ON"; db.FindProp("ANSI_NULLS").Value = "ON"; db.FindProp("ANSI_PADDING").Value = "ON"; db.FindProp("ANSI_WARNINGS").Value = "ON"; db.FindProp("ARITHABORT").Value = "ON"; db.FindProp("CONCAT_NULL_YIELDS_NULL").Value = "ON"; db.FindProp("NUMERIC_ROUNDABORT").Value = "ON"; db.FindProp("QUOTED_IDENTIFIER").Value = "ON"; db.FindProp("RECURSIVE_TRIGGERS").Value = "ON"; db.FindProp("CURSOR_CLOSE_ON_COMMIT").Value = "ON"; db.FindProp("CURSOR_DEFAULT").Value = "LOCAL"; db.FindProp("TRUSTWORTHY").Value = "ON"; db.FindProp("DB_CHAINING").Value = "ON"; db.FindProp("PARAMETERIZATION").Value = "FORCED"; db.FindProp("DATE_CORRELATION_OPTIMIZATION").Value = "ON"; await _dbHelper.DropDbAsync(db.Name); await using var testDb = await _dbHelper.CreateTestDb(db); db.Connection = testDb.GetConnString(); DBHelper.ExecSql( db.Connection, " insert into formType ([code], [desc]) values (1, 'DP-1')\n" + "insert into formType ([code], [desc]) values (2, 'DP-2')\n" + "insert into formType ([code], [desc]) values (3, 'DP-3')"); db.DataTables.Add(formType); db.DataTables.Add(emptyTable); db.Dir = db.Name; if (Directory.Exists(db.Dir)) Directory.Delete(db.Dir, true); db.ScriptToDir(); Assert.True(Directory.Exists(db.Name)); Assert.True(Directory.Exists(db.Name + "/data")); Assert.True(Directory.Exists(db.Name + "/tables")); Assert.True(Directory.Exists(db.Name + "/foreign_keys")); foreach (var t in db.DataTables) if (t.Name == "EmptyTable") Assert.False(File.Exists(db.Name + "/data/" + t.Name + ".tsv")); else Assert.True(File.Exists(db.Name + "/data/" + t.Name + ".tsv")); foreach (var t in db.Tables) { var tblFile = db.Name + "/tables/" + t.Name + ".sql"; Assert.True(File.Exists(tblFile)); // Test that the constraints are ordered in the file var script = File.ReadAllText(tblFile); var cindex = -1; foreach (var ckobject in t.Constraints.Where(c => c.Type != "CHECK") .OrderBy(x => x.Name)) { var thisindex = script.IndexOf(ckobject.ScriptCreate()); Assert.True(thisindex > cindex, "Constraints are not ordered."); cindex = thisindex; } } foreach (var t in db.TableTypes) Assert.True(File.Exists(db.Name + "/table_types/TYPE_" + t.Name + ".sql")); foreach (var expected in db.ForeignKeys.Select( fk => db.Name + "/foreign_keys/" + fk.Table.Name + ".sql")) Assert.True(File.Exists(expected), "File does not exist" + expected); // Test that the foreign keys are ordered in the file foreach (var t in db.Tables) { var fksFile = db.Name + "/foreign_keys/" + t.Name + ".sql"; if (File.Exists(fksFile)) { var script = File.ReadAllText(fksFile); var fkindex = -1; foreach (var fkobject in db.ForeignKeys.Where(x => x.Table == t) .OrderBy(x => x.Name)) { var thisindex = script.IndexOf(fkobject.ScriptCreate()); Assert.True(thisindex > fkindex, "Foreign keys are not ordered."); fkindex = thisindex; } } } var copy = new Database("ScriptToDirTestCopy"); await _dbHelper.DropDbAsync("ScriptToDirTestCopy"); await using var testDb2 = await _dbHelper.CreateTestDb(copy); copy.Dir = db.Dir; copy.Connection = testDb2.GetConnString(); copy.CreateFromDir(true); copy.Load(); Assert.False(db.Compare(copy).IsDiff); } [Fact] public async Task TestScriptToDirOnlyCreatesNecessaryFolders() { var db = new Database("TestEmptyDB"); await _dbHelper.DropDbAsync(db.Name); await using var testDb = await _dbHelper.CreateTestDb(db); db.Load(); if (Directory.Exists(db.Dir)) Directory.Delete(db.Dir, true); db.ScriptToDir(); Assert.Empty(db.Assemblies); Assert.Empty(db.DataTables); Assert.Empty(db.ForeignKeys); Assert.Empty(db.Routines); Assert.Empty(db.Schemas); Assert.Empty(db.Synonyms); Assert.Empty(db.Tables); Assert.Empty(db.TableTypes); Assert.Empty(db.Users); Assert.Empty(db.ViewIndexes); Assert.True(Directory.Exists(db.Name)); Assert.True(File.Exists(db.Name + "/props.sql")); //Assert.IsFalse(File.Exists(db.Name + "/schemas.sql")); Assert.False(Directory.Exists(db.Name + "/assemblies")); Assert.False(Directory.Exists(db.Name + "/data")); Assert.False(Directory.Exists(db.Name + "/foreign_keys")); foreach (var routineType in Enum.GetNames(typeof(Routine.RoutineKind))) { var dir = routineType.ToLower() + "s"; Assert.False(Directory.Exists(db.Name + "/" + dir)); } Assert.False(Directory.Exists(db.Name + "/synonyms")); Assert.False(Directory.Exists(db.Name + "/tables")); Assert.False(Directory.Exists(db.Name + "/table_types")); Assert.False(Directory.Exists(db.Name + "/users")); } }
212
19,701
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using SchemaZen.Library.Models.Comparers; namespace SchemaZen.Library.Models; public class Database { #region Compare public DatabaseDiff Compare(Database db) { var diff = new DatabaseDiff { Db = db }; //compare database properties foreach (var p in from p in Props let p2 = db.FindProp(p.Name) where p.Script() != p2.Script() select p) diff.PropsChanged.Add(p); //get tables added and changed foreach (var tables in new[] { Tables, TableTypes }) foreach (var t in tables) { var t2 = db.FindTable(t.Name, t.Owner, t.IsType); if (t2 == null) { diff.TablesAdded.Add(t); } else { //compare mutual tables var tDiff = t.Compare(t2); if (!tDiff.IsDiff) continue; if (t.IsType) // types cannot be altered... diff.TableTypesDiff.Add(t); else diff.TablesDiff.Add(tDiff); } } //get deleted tables foreach (var t in db.Tables.Concat(db.TableTypes) .Where(t => FindTable(t.Name, t.Owner, t.IsType) == null)) diff.TablesDeleted.Add(t); //get procs added and changed foreach (var r in Routines) { var r2 = db.FindRoutine(r.Name, r.Owner); if (r2 == null) { diff.RoutinesAdded.Add(r); } else { //compare mutual procs if (r.Text.Trim() != r2.Text.Trim()) diff.RoutinesDiff.Add(r); } } //get procs deleted foreach (var r in db.Routines.Where(r => FindRoutine(r.Name, r.Owner) == null)) diff.RoutinesDeleted.Add(r); //get added and compare mutual foreign keys foreach (var fk in ForeignKeys) { var fk2 = db.FindForeignKey(fk.Name, fk.Table.Owner); if (fk2 == null) { diff.ForeignKeysAdded.Add(fk); } else { if (fk.ScriptCreate() != fk2.ScriptCreate()) diff.ForeignKeysDiff.Add(fk); } } //get deleted foreign keys foreach (var fk in db.ForeignKeys .Where(fk => FindForeignKey(fk.Name, fk.Table.Owner) == null)) diff.ForeignKeysDeleted.Add(fk); //get added and compare mutual assemblies foreach (var a in Assemblies) { var a2 = db.FindAssembly(a.Name); if (a2 == null) { diff.AssembliesAdded.Add(a); } else { if (a.ScriptCreate() != a2.ScriptCreate()) diff.AssembliesDiff.Add(a); } } //get deleted assemblies foreach (var a in db.Assemblies.Where(a => FindAssembly(a.Name) == null)) diff.AssembliesDeleted.Add(a); //get added and compare mutual users foreach (var u in Users) { var u2 = db.FindUser(u.Name); if (u2 == null) { diff.UsersAdded.Add(u); } else { if (u.ScriptCreate() != u2.ScriptCreate()) diff.UsersDiff.Add(u); } } //get deleted users foreach (var u in db.Users.Where(u => FindUser(u.Name) == null)) diff.UsersDeleted.Add(u); //get added and compare view indexes foreach (var c in ViewIndexes) { var c2 = db.FindViewIndex(c.Name); if (c2 == null) { diff.ViewIndexesAdded.Add(c); } else { if (c.ScriptCreate() != c2.ScriptCreate()) diff.ViewIndexesDiff.Add(c); } } //get deleted view indexes foreach (var c in db.ViewIndexes.Where(c => FindViewIndex(c.Name) == null)) diff.ViewIndexesDeleted.Add(c); //get added and compare synonyms foreach (var s in Synonyms) { var s2 = db.FindSynonym(s.Name, s.Owner); if (s2 == null) { diff.SynonymsAdded.Add(s); } else { if (s.BaseObjectName != s2.BaseObjectName) diff.SynonymsDiff.Add(s); } } //get deleted synonyms foreach (var s in db.Synonyms.Where(s => FindSynonym(s.Name, s.Owner) == null)) diff.SynonymsDeleted.Add(s); //get added and compare permissions foreach (var p in Permissions) { var p2 = db.FindPermission(p.Name); if (p2 == null) { diff.PermissionsAdded.Add(p); } else { if (p.ScriptCreate() != p2.ScriptCreate()) diff.PermissionsDiff.Add(p); } } //get deleted permissions foreach (var p in db.Permissions.Where(p => FindPermission(p.Name) == null)) diff.PermissionsDeleted.Add(p); return diff; } #endregion #region " Constructors " private readonly Microsoft.Extensions.Logging.ILogger _logger; public Database( IList<string> filteredTypes = null, Microsoft.Extensions.Logging.ILogger logger = null ) { // todo - make logger not nullable _logger = logger; ResetProps(); filteredTypes = filteredTypes ?? new List<string>(); foreach (var filteredType in filteredTypes) Dirs.Remove(filteredType); } public Database( string name, IList<string> filteredTypes = null, Microsoft.Extensions.Logging.ILogger logger = null ) : this(filteredTypes, logger) { Name = name; } #endregion #region " Properties " public const string SqlWhitespaceOrCommentRegex = @"(?>(?:\s+|--.*?(?:\r|\n)|/\*.*?\*/))"; public const string SqlEnclosedIdentifierRegex = @"\[.+?\]"; public const string SqlQuotedIdentifierRegex = "\".+?\""; public const string SqlRegularIdentifierRegex = @"(?!\d)[\w@$#]+"; // see rules for regular identifiers here https://msdn.microsoft.com/en-us/library/ms175874.aspx public List<SqlAssembly> Assemblies { get; set; } = new(); public string Connection { get; set; } = ""; public List<Table> DataTables { get; set; } = new(); public string Dir { get; set; } = ""; public List<ForeignKey> ForeignKeys { get; set; } = new(); public string Name { get; set; } public List<DbProp> Props { get; set; } = new(); public List<Routine> Routines { get; set; } = new(); public List<Schema> Schemas { get; set; } = new(); public List<Synonym> Synonyms { get; set; } = new(); public List<Table> TableTypes { get; set; } = new(); public List<Table> Tables { get; set; } = new(); public List<UserDefinedType> UserDefinedTypes { get; set; } = new(); public List<Role> Roles { get; set; } = new(); public List<SqlUser> Users { get; set; } = new(); public List<Constraint> ViewIndexes { get; set; } = new(); public List<Permission> Permissions { get; set; } = new(); public DbProp FindProp(string name) { return Props.FirstOrDefault( p => string.Equals(p.Name, name, StringComparison.CurrentCultureIgnoreCase)); } public Table FindTable(string name, string owner, bool isTableType = false) { return FindTableBase(isTableType ? TableTypes : Tables, name, owner); } private static Table FindTableBase(IEnumerable<Table> tables, string name, string owner) { return tables.FirstOrDefault(t => t.Name == name && t.Owner == owner); } public Constraint FindConstraint(string name) { return Tables.SelectMany(t => t.Constraints).FirstOrDefault(c => c.Name == name); } public ForeignKey FindForeignKey(string name, string owner) { return ForeignKeys.FirstOrDefault(fk => fk.Name == name && fk.Table.Owner == owner); } public Routine FindRoutine(string name, string schema) { return Routines.FirstOrDefault(r => r.Name == name && r.Owner == schema); } public SqlAssembly FindAssembly(string name) { return Assemblies.FirstOrDefault(a => a.Name == name); } public SqlUser FindUser(string name) { return Users.FirstOrDefault( u => string.Equals(u.Name, name, StringComparison.CurrentCultureIgnoreCase)); } public Constraint FindViewIndex(string name) { return ViewIndexes.FirstOrDefault(c => c.Name == name); } public Synonym FindSynonym(string name, string schema) { return Synonyms.FirstOrDefault(s => s.Name == name && s.Owner == schema); } public Permission FindPermission(string name) { return Permissions.FirstOrDefault(g => g.Name == name); } public List<Table> FindTablesRegEx(string pattern, string excludePattern = null) { return Tables.Where(t => FindTablesRegExPredicate(t, pattern, excludePattern)).ToList(); } private static bool FindTablesRegExPredicate( Table table, string pattern, string excludePattern) { var include = string.IsNullOrEmpty(pattern) || Regex.IsMatch(table.Name, pattern); var exclude = !string.IsNullOrEmpty(excludePattern) && Regex.IsMatch(table.Name, excludePattern); return include && !exclude; } public static HashSet<string> Dirs { get; } = new() { "user_defined_types", "tables", "foreign_keys", "assemblies", "functions", "procedures", "triggers", "views", "xmlschemacollections", "data", "roles", "users", "synonyms", "table_types", "schemas", "props", "permissions", "check_constraints", "defaults" }; public static string ValidTypes { get { return Dirs.Aggregate((x, y) => x + ", " + y); } } private void SetPropOnOff(string propName, object dbVal) { if (dbVal != DBNull.Value) FindProp(propName).Value = (bool)dbVal ? "ON" : "OFF"; } private void SetPropString(string propName, object dbVal) { if (dbVal != DBNull.Value) FindProp(propName).Value = dbVal.ToString(); } #endregion #region Load public void Load() { ResetProps(); Schemas.Clear(); Tables.Clear(); UserDefinedTypes.Clear(); TableTypes.Clear(); ForeignKeys.Clear(); Routines.Clear(); DataTables.Clear(); ViewIndexes.Clear(); Assemblies.Clear(); Users.Clear(); Synonyms.Clear(); Roles.Clear(); Permissions.Clear(); using (var cn = new SqlConnection(Connection)) { cn.Open(); using (var cm = cn.CreateCommand()) { LoadProps(cm); LoadSchemas(cm); LoadTables(cm); LoadUserDefinedTypes(cm); LoadColumns(cm); LoadColumnIdentities(cm); LoadColumnDefaults(cm); LoadColumnComputes(cm); LoadConstraintsAndIndexes(cm); LoadCheckConstraints(cm); LoadForeignKeys(cm); LoadRoutines(cm); LoadXmlSchemas(cm); LoadCLRAssemblies(cm); LoadUsersAndLogins(cm); LoadSynonyms(cm); LoadRoles(cm); LoadPermissions(cm); } } } private void ResetProps() { Props.Clear(); Props.Add(new DbProp("COMPATIBILITY_LEVEL", "")); Props.Add(new DbProp("COLLATE", "")); Props.Add(new DbProp("AUTO_CLOSE", "")); Props.Add(new DbProp("AUTO_SHRINK", "")); Props.Add(new DbProp("ALLOW_SNAPSHOT_ISOLATION", "")); Props.Add(new DbProp("READ_COMMITTED_SNAPSHOT", "")); Props.Add(new DbProp("RECOVERY", "")); Props.Add(new DbProp("PAGE_VERIFY", "")); Props.Add(new DbProp("AUTO_CREATE_STATISTICS", "")); Props.Add(new DbProp("AUTO_UPDATE_STATISTICS", "")); Props.Add(new DbProp("AUTO_UPDATE_STATISTICS_ASYNC", "")); Props.Add(new DbProp("ANSI_NULL_DEFAULT", "")); Props.Add(new DbProp("ANSI_NULLS", "")); Props.Add(new DbProp("ANSI_PADDING", "")); Props.Add(new DbProp("ANSI_WARNINGS", "")); Props.Add(new DbProp("ARITHABORT", "")); Props.Add(new DbProp("CONCAT_NULL_YIELDS_NULL", "")); Props.Add(new DbProp("NUMERIC_ROUNDABORT", "")); Props.Add(new DbProp("QUOTED_IDENTIFIER", "")); Props.Add(new DbProp("RECURSIVE_TRIGGERS", "")); Props.Add(new DbProp("CURSOR_CLOSE_ON_COMMIT", "")); Props.Add(new DbProp("CURSOR_DEFAULT", "")); Props.Add(new DbProp("TRUSTWORTHY", "")); Props.Add(new DbProp("DB_CHAINING", "")); Props.Add(new DbProp("PARAMETERIZATION", "")); Props.Add(new DbProp("DATE_CORRELATION_OPTIMIZATION", "")); } private void LoadSynonyms(SqlCommand cm) { cm.CommandText = @" select object_schema_name(object_id) as schema_name, name as synonym_name, base_object_name from sys.synonyms"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var synonym = new Synonym( (string)dr["synonym_name"], (string)dr["schema_name"]); synonym.BaseObjectName = (string)dr["base_object_name"]; Synonyms.Add(synonym); } } } private void LoadPermissions(SqlCommand cm) { cm.CommandText = @" select u.name as user_name, object_schema_name(o.id) as object_owner, o.name as object_name, p.permission_name as permission from sys.database_permissions p join sys.sysusers u on p.grantee_principal_id = u.uid join sys.sysobjects o on p.major_id = o.id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var permission = new Permission( (string)dr["user_name"], (string)dr["object_owner"], (string)dr["object_name"], (string)dr["permission"]); Permissions.Add(permission); } } } private void LoadRoles(SqlCommand cm) { cm.CommandText = @" select name from sys.database_principals where type = 'R' and name not in ( -- Ignore default roles, just look for custom ones 'db_accessadmin' , 'db_backupoperator' , 'db_datareader' , 'db_datawriter' , 'db_ddladmin' , 'db_denydatareader' , 'db_denydatawriter' , 'db_owner' , 'db_securityadmin' , 'public' ) "; Role r = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { r = new Role { Name = (string)dr["name"] }; Roles.Add(r); } } } private void LoadUsersAndLogins(SqlCommand cm) { // get users that have access to the database cm.CommandText = @" select dp.name as UserName, USER_NAME(drm.role_principal_id) as AssociatedDBRole, default_schema_name from sys.database_principals dp left outer join sys.database_role_members drm on dp.principal_id = drm.member_principal_id where (dp.type_desc = 'SQL_USER' or dp.type_desc = 'WINDOWS_USER') and dp.sid not in (0x00, 0x01) and dp.name not in ('dbo', 'guest') and dp.is_fixed_role = 0 order by dp.name"; SqlUser u = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { if (u == null || u.Name != (string)dr["UserName"]) u = new SqlUser((string)dr["UserName"], (string)dr["default_schema_name"]); if (!(dr["AssociatedDBRole"] is DBNull)) u.DatabaseRoles.Add((string)dr["AssociatedDBRole"]); if (!Users.Contains(u)) Users.Add(u); } } try { // get sql logins cm.CommandText = @" select sp.name, sl.password_hash from sys.server_principals sp inner join sys.sql_logins sl on sp.principal_id = sl.principal_id and sp.type_desc = 'SQL_LOGIN' where sp.name not like '##%##' and sp.name != 'SA' order by sp.name"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { u = FindUser((string)dr["name"]); if (u != null && !(dr["password_hash"] is DBNull)) u.PasswordHash = (byte[])dr["password_hash"]; } } } catch (SqlException ex) { // todo detect this before query and get rid of try catch _logger?.LogWarning("assumed logins not supported by sql version, ignored ex:"); _logger?.LogWarning(ex.Message); } } private void LoadCLRAssemblies(SqlCommand cm) { try { // get CLR assemblies cm.CommandText = @"select a.name as AssemblyName, a.permission_set_desc, af.name as FileName, af.content from sys.assemblies a inner join sys.assembly_files af on a.assembly_id = af.assembly_id where a.is_user_defined = 1 order by a.name, af.file_id"; SqlAssembly a = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { if (a == null || a.Name != (string)dr["AssemblyName"]) a = new SqlAssembly( (string)dr["permission_set_desc"], (string)dr["AssemblyName"]); a.Files.Add( new KeyValuePair<string, byte[]>( (string)dr["FileName"], (byte[])dr["content"])); if (!Assemblies.Contains(a)) Assemblies.Add(a); } } } catch (SqlException ex) { // todo detect this before query and get rid of try catch _logger?.LogWarning("assumed assemblies not supported by sql version, ignored ex:"); _logger?.LogWarning(ex.Message); } } private void LoadXmlSchemas(SqlCommand cm) { try { // get xml schemas cm.CommandText = @" select s.name as DBSchemaName, x.name as XMLSchemaCollectionName, xml_schema_namespace(s.name, x.name) as definition from sys.xml_schema_collections x inner join sys.schemas s on s.schema_id = x.schema_id where s.name != 'sys'"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var r = new Routine( (string)dr["DBSchemaName"], (string)dr["XMLSchemaCollectionName"], this) { Text = string.Format( "CREATE XML SCHEMA COLLECTION {0}.{1} AS N'{2}'", dr["DBSchemaName"], dr["XMLSchemaCollectionName"], dr["definition"]), RoutineType = Routine.RoutineKind.XmlSchemaCollection }; Routines.Add(r); } } } catch (SqlException ex) { // todo detect this before query and get rid of try catch _logger?.LogWarning("assumed xml schemas not supported by sql version, ignored ex:"); _logger?.LogWarning(ex.Message); } } private void LoadRoutines(SqlCommand cm) { //get routines cm.CommandText = @" select s.name as schemaName, o.name as routineName, o.type_desc, m.definition, m.uses_ansi_nulls, m.uses_quoted_identifier, isnull(s2.name, s3.name) as tableSchema, isnull(t.name, v.name) as tableName, tr.is_disabled as trigger_disabled from sys.sql_modules m inner join sys.objects o on m.object_id = o.object_id inner join sys.schemas s on s.schema_id = o.schema_id left join sys.triggers tr on m.object_id = tr.object_id left join sys.tables t on tr.parent_id = t.object_id left join sys.views v on tr.parent_id = v.object_id left join sys.schemas s2 on s2.schema_id = t.schema_id left join sys.schemas s3 on s3.schema_id = v.schema_id where objectproperty(o.object_id, 'IsMSShipped') = 0 "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var r = new Routine((string)dr["schemaName"], (string)dr["routineName"], this); r.Text = dr["definition"] is DBNull ? string.Empty : (string)dr["definition"]; r.AnsiNull = (bool)dr["uses_ansi_nulls"]; r.QuotedId = (bool)dr["uses_quoted_identifier"]; Routines.Add(r); switch ((string)dr["type_desc"]) { case "SQL_STORED_PROCEDURE": r.RoutineType = Routine.RoutineKind.Procedure; break; case "SQL_TRIGGER": r.RoutineType = Routine.RoutineKind.Trigger; r.RelatedTableName = (string)dr["tableName"]; r.RelatedTableSchema = (string)dr["tableSchema"]; r.Disabled = (bool)dr["trigger_disabled"]; break; case "SQL_SCALAR_FUNCTION": case "SQL_INLINE_TABLE_VALUED_FUNCTION": case "SQL_TABLE_VALUED_FUNCTION": r.RoutineType = Routine.RoutineKind.Function; break; case "VIEW": r.RoutineType = Routine.RoutineKind.View; break; } } } } private void LoadCheckConstraints(SqlCommand cm) { cm.CommandText = @" SELECT OBJECT_NAME(o.OBJECT_ID) AS CONSTRAINT_NAME, SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA, OBJECT_NAME(o.parent_object_id) AS TABLE_NAME, CAST(0 AS bit) AS IS_TYPE, objectproperty(o.object_id, 'CnstIsNotRepl') AS NotForReplication, 'CHECK' AS ConstraintType, cc.definition as CHECK_CLAUSE, cc.is_system_named FROM sys.objects o inner join sys.check_constraints cc on cc.object_id = o.object_id inner join sys.tables t on t.object_id = o.parent_object_id WHERE o.type_desc = 'CHECK_CONSTRAINT' UNION ALL SELECT OBJECT_NAME(o.OBJECT_ID) AS CONSTRAINT_NAME, SCHEMA_NAME(tt.schema_id) AS TABLE_SCHEMA, tt.name AS TABLE_NAME, CAST(1 AS bit) AS IS_TYPE, objectproperty(o.object_id, 'CnstIsNotRepl') AS NotForReplication, 'CHECK' AS ConstraintType, cc.definition as CHECK_CLAUSE, cc.is_system_named FROM sys.objects o inner join sys.check_constraints cc on cc.object_id = o.object_id inner join sys.table_types tt on tt.type_table_object_id = o.parent_object_id WHERE o.type_desc = 'CHECK_CONSTRAINT' ORDER BY TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable( (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var constraint = Constraint.CreateCheckedConstraint( (string)dr["CONSTRAINT_NAME"], Convert.ToBoolean(dr["NotForReplication"]), Convert.ToBoolean(dr["is_system_named"]), (string)dr["CHECK_CLAUSE"] ); t.AddConstraint(constraint); } } } } private void LoadForeignKeys(SqlCommand cm) { //get foreign keys cm.CommandText = @" select TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY'"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); var fk = new ForeignKey((string)dr["CONSTRAINT_NAME"]); fk.Table = t; ForeignKeys.Add(fk); } } //get foreign key props cm.CommandText = @" select CONSTRAINT_NAME, OBJECT_SCHEMA_NAME(fk.parent_object_id) as TABLE_SCHEMA, UPDATE_RULE, DELETE_RULE, fk.is_disabled, fk.is_system_named from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc inner join sys.foreign_keys fk on rc.CONSTRAINT_NAME = fk.name and rc.CONSTRAINT_SCHEMA = OBJECT_SCHEMA_NAME(fk.parent_object_id)"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey( (string)dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]); fk.OnUpdate = (string)dr["UPDATE_RULE"]; fk.OnDelete = (string)dr["DELETE_RULE"]; fk.Check = !(bool)dr["is_disabled"]; fk.IsSystemNamed = (bool)dr["is_system_named"]; } } //get foreign key columns and ref table cm.CommandText = @" select fk.name as CONSTRAINT_NAME, OBJECT_SCHEMA_NAME(fk.parent_object_id) as TABLE_SCHEMA, c1.name as COLUMN_NAME, OBJECT_SCHEMA_NAME(fk.referenced_object_id) as REF_TABLE_SCHEMA, OBJECT_NAME(fk.referenced_object_id) as REF_TABLE_NAME, c2.name as REF_COLUMN_NAME from sys.foreign_keys fk inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id inner join sys.columns c1 on fkc.parent_column_id = c1.column_id and fkc.parent_object_id = c1.object_id inner join sys.columns c2 on fkc.referenced_column_id = c2.column_id and fkc.referenced_object_id = c2.object_id order by fk.name, fkc.constraint_column_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey( (string)dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]); if (fk == null) continue; fk.Columns.Add((string)dr["COLUMN_NAME"]); fk.RefColumns.Add((string)dr["REF_COLUMN_NAME"]); if (fk.RefTable == null) fk.RefTable = FindTable( (string)dr["REF_TABLE_NAME"], (string)dr["REF_TABLE_SCHEMA"]); } } } private void LoadConstraintsAndIndexes(SqlCommand cm) { //get constraints & indexes cm.CommandText = @" select s.name as schemaName, t.name as tableName, t.baseType, i.name as indexName, c.name as columnName, i.is_primary_key, i.is_unique_constraint, i.is_unique, i.type_desc, i.filter_definition, isnull(ic.is_included_column, 0) as is_included_column, ic.is_descending_key, i.type from ( select object_id, name, schema_id, 'T' as baseType from sys.tables union select object_id, name, schema_id, 'V' as baseType from sys.views union select type_table_object_id, name, schema_id, 'TVT' as baseType from sys.table_types ) t inner join sys.indexes i on i.object_id = t.object_id inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id = i.index_id inner join sys.columns c on c.object_id = t.object_id and c.column_id = ic.column_id inner join sys.schemas s on s.schema_id = t.schema_id where i.type_desc != 'HEAP' order by s.name, t.name, i.name, ic.key_ordinal, ic.index_column_id"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var schemaName = (string)dr["schemaName"]; var tableName = (string)dr["tableName"]; var indexName = (string)dr["indexName"]; var isView = (string)dr["baseType"] == "V"; var t = isView ? new Table(schemaName, tableName) : FindTable(tableName, schemaName, (string)dr["baseType"] == "TVT"); var c = t.FindConstraint(indexName); if (c == null) { c = new Constraint(indexName, "", ""); t.AddConstraint(c); } if (isView) { if (ViewIndexes.Any(v => v.Name == indexName)) c = ViewIndexes.First(v => v.Name == indexName); else ViewIndexes.Add(c); } c.IndexType = dr["type_desc"] as string; c.Unique = (bool)dr["is_unique"]; c.Filter = dr["filter_definition"] as string; if ((bool)dr["is_included_column"]) c.IncludedColumns.Add((string)dr["columnName"]); else c.Columns.Add( new ConstraintColumn( (string)dr["columnName"], (bool)dr["is_descending_key"])); c.Type = "INDEX"; if ((bool)dr["is_primary_key"]) c.Type = "PRIMARY KEY"; if ((bool)dr["is_unique_constraint"]) c.Type = "UNIQUE"; } } } private void LoadColumnComputes(SqlCommand cm) { //get computed column definitions cm.CommandText = @" select object_schema_name(t.object_id) as TABLE_SCHEMA, object_name(t.object_id) as TABLE_NAME, cc.name as COLUMN_NAME, cc.definition as DEFINITION, cc.is_persisted as PERSISTED, cc.is_nullable as NULLABLE, cast(0 as bit) as IS_TYPE from sys.computed_columns cc inner join sys.tables t on cc.object_id = t.object_id UNION ALL select SCHEMA_NAME(tt.schema_id) as TABLE_SCHEMA, tt.name as TABLE_NAME, cc.name as COLUMN_NAME, cc.definition as DEFINITION, cc.is_persisted as PERSISTED, cc.is_nullable as NULLABLE, cast(1 as bit) AS IS_TYPE from sys.computed_columns cc inner join sys.table_types tt on cc.object_id = tt.type_table_object_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable( (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var column = t.Columns.Find((string)dr["COLUMN_NAME"]); if (column != null) { column.ComputedDefinition = (string)dr["DEFINITION"]; column.Persisted = (bool)dr["PERSISTED"]; } } } } } private void LoadColumnDefaults(SqlCommand cm) { //get column defaults cm.CommandText = @" select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, c.name as COLUMN_NAME, d.name as DEFAULT_NAME, d.definition as DEFAULT_VALUE, d.is_system_named as IS_SYSTEM_NAMED, cast(0 AS bit) AS IS_TYPE from sys.tables t inner join sys.columns c on c.object_id = t.object_id inner join sys.default_constraints d on c.column_id = d.parent_column_id and d.parent_object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id UNION ALL select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME, c.name as COLUMN_NAME, d.name as DEFAULT_NAME, d.definition as DEFAULT_VALUE, d.is_system_named as IS_SYSTEM_NAMED, cast(1 AS bit) AS IS_TYPE from sys.table_types tt inner join sys.columns c on c.object_id = tt.type_table_object_id inner join sys.default_constraints d on c.column_id = d.parent_column_id and d.parent_object_id = c.object_id inner join sys.schemas s on s.schema_id = tt.schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable( (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var c = t.Columns.Find((string)dr["COLUMN_NAME"]); if (c != null) c.Default = new Default( t, c, (string)dr["DEFAULT_NAME"], (string)dr["DEFAULT_VALUE"], (bool)dr["IS_SYSTEM_NAMED"]); } } } } private void LoadColumnIdentities(SqlCommand cm) { //get column identities cm.CommandText = @" select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, c.name AS COLUMN_NAME, i.SEED_VALUE, i.INCREMENT_VALUE from sys.tables t inner join sys.columns c on c.object_id = t.object_id inner join sys.identity_columns i on i.object_id = c.object_id and i.column_id = c.column_id inner join sys.schemas s on s.schema_id = t.schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) try { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); var c = t.Columns.Find((string)dr["COLUMN_NAME"]); var seed = dr["SEED_VALUE"].ToString(); var increment = dr["INCREMENT_VALUE"].ToString(); c.Identity = new Identity(seed, increment); } catch (Exception ex) { throw new ApplicationException( string.Format( "{0}.{1} : {2}", dr["TABLE_SCHEMA"], dr["TABLE_NAME"], ex.Message), ex); } } } private void LoadColumns(SqlCommand cm) { //get columns cm.CommandText = @" select t.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.ORDINAL_POSITION, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE, CASE WHEN COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsRowGuidCol') = 1 THEN 'YES' ELSE 'NO' END AS IS_ROW_GUID_COL from INFORMATION_SCHEMA.COLUMNS c inner join INFORMATION_SCHEMA.TABLES t on t.TABLE_NAME = c.TABLE_NAME and t.TABLE_SCHEMA = c.TABLE_SCHEMA and t.TABLE_CATALOG = c.TABLE_CATALOG where t.TABLE_TYPE = 'BASE TABLE' order by t.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION "; using (var dr = cm.ExecuteReader()) { LoadColumnsBase(dr, Tables); } try { cm.CommandText = @" select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME, c.name as COLUMN_NAME, t.name as DATA_TYPE, c.column_id as ORDINAL_POSITION, CASE WHEN c.is_nullable = 1 THEN 'YES' ELSE 'NO' END as IS_NULLABLE, CASE WHEN t.name = 'nvarchar' and c.max_length > 0 THEN CAST(c.max_length as int)/2 ELSE CAST(c.max_length as int) END as CHARACTER_MAXIMUM_LENGTH, c.precision as NUMERIC_PRECISION, CAST(c.scale as int) as NUMERIC_SCALE, CASE WHEN c.is_rowguidcol = 1 THEN 'YES' ELSE 'NO' END as IS_ROW_GUID_COL from sys.columns c inner join sys.table_types tt on tt.type_table_object_id = c.object_id inner join sys.schemas s on tt.schema_id = s.schema_id inner join sys.types t on t.system_type_id = c.system_type_id and t.user_type_id = c.user_type_id where tt.is_user_defined = 1 order by s.name, tt.name, c.column_id "; using (var dr = cm.ExecuteReader()) { LoadColumnsBase(dr, TableTypes); } } catch (SqlException ex) { // todo - detect this before query and get rid of try catch _logger.LogError( "Assuming sql server version doesn't support table types because" + $"the followign error occurred: {ex.Message}"); } } private static void LoadColumnsBase(IDataReader dr, List<Table> tables) { Table table = null; while (dr.Read()) { var c = new Column { Name = (string)dr["COLUMN_NAME"], Type = (string)dr["DATA_TYPE"], IsNullable = (string)dr["IS_NULLABLE"] == "YES", Position = (int)dr["ORDINAL_POSITION"], IsRowGuidCol = (string)dr["IS_ROW_GUID_COL"] == "YES" }; switch (c.Type) { case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": c.Length = (int)dr["CHARACTER_MAXIMUM_LENGTH"]; break; case "decimal": case "numeric": c.Precision = (byte)dr["NUMERIC_PRECISION"]; c.Scale = (int)dr["NUMERIC_SCALE"]; break; } if (table == null || table.Name != (string)dr["TABLE_NAME"] || table.Owner != (string)dr["TABLE_SCHEMA"]) // only do a lookup if the table we have isn't already the relevant one table = FindTableBase( tables, (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); table.Columns.Add(c); } } private void LoadTables(SqlCommand cm) { //get tables cm.CommandText = @" select TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'"; using (var dr = cm.ExecuteReader()) { LoadTablesBase(dr, false, Tables); } cm.CommandText = @" select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME from sys.table_types tt inner join sys.schemas s on tt.schema_id = s.schema_id where tt.is_user_defined = 1 order by s.name, tt.name"; using (var dr = cm.ExecuteReader()) { LoadTablesBase(dr, true, TableTypes); } } private void LoadUserDefinedTypes(SqlCommand cm) { //get types cm.CommandText = @" select s.name as 'Type_Schema', t.name as 'Type_Name', tt.name as 'Base_Type_Name', t.max_length as 'Max_Length', t.is_nullable as 'Nullable' from sys.types t inner join sys.schemas s on s.schema_id = t.schema_id inner join sys.types tt on t.system_type_id = tt.user_type_id where t.is_user_defined = 1 and t.is_table_type = 0"; using (var dr = cm.ExecuteReader()) { LoadUserDefinedTypesBase(dr, UserDefinedTypes); } } private void LoadUserDefinedTypesBase( SqlDataReader dr, List<UserDefinedType> userDefinedTypes) { while (dr.Read()) userDefinedTypes.Add( new UserDefinedType( (string)dr["Type_Schema"], (string)dr["Type_Name"], (string)dr["Base_Type_Name"], Convert.ToInt16(dr["Max_Length"]), (bool)dr["Nullable"])); } private static void LoadTablesBase( SqlDataReader dr, bool areTableTypes, List<Table> tables) { while (dr.Read()) tables.Add( new Table((string)dr["TABLE_SCHEMA"], (string)dr["TABLE_NAME"]) { IsType = areTableTypes }); } private void LoadSchemas(SqlCommand cm) { //get schemas cm.CommandText = @" select s.name as schemaName, p.name as principalName from sys.schemas s inner join sys.database_principals p on s.principal_id = p.principal_id where s.schema_id < 16384 and s.name not in ('dbo','guest','sys','INFORMATION_SCHEMA') order by schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) Schemas.Add(new Schema((string)dr["schemaName"], (string)dr["principalName"])); } } private void LoadProps(SqlCommand cm) { var cnStrBuilder = new SqlConnectionStringBuilder(Connection); // query schema for database properties cm.CommandText = @" select [compatibility_level], [collation_name], [is_auto_close_on], [is_auto_shrink_on], [snapshot_isolation_state], [is_read_committed_snapshot_on], [recovery_model_desc], [page_verify_option_desc], [is_auto_create_stats_on], [is_auto_update_stats_on], [is_auto_update_stats_async_on], [is_ansi_null_default_on], [is_ansi_nulls_on], [is_ansi_padding_on], [is_ansi_warnings_on], [is_arithabort_on], [is_concat_null_yields_null_on], [is_numeric_roundabort_on], [is_quoted_identifier_on], [is_recursive_triggers_on], [is_cursor_close_on_commit_on], [is_local_cursor_default], [is_trustworthy_on], [is_db_chaining_on], [is_parameterization_forced], [is_date_correlation_on] from sys.databases where name = @dbname "; cm.Parameters.AddWithValue("@dbname", cnStrBuilder.InitialCatalog); using (IDataReader dr = cm.ExecuteReader()) { if (dr.Read()) { SetPropString("COMPATIBILITY_LEVEL", dr["compatibility_level"]); SetPropString("COLLATE", dr["collation_name"]); SetPropOnOff("AUTO_CLOSE", dr["is_auto_close_on"]); SetPropOnOff("AUTO_SHRINK", dr["is_auto_shrink_on"]); if (dr["snapshot_isolation_state"] != DBNull.Value) FindProp("ALLOW_SNAPSHOT_ISOLATION").Value = (byte)dr["snapshot_isolation_state"] == 0 || (byte)dr["snapshot_isolation_state"] == 2 ? "OFF" : "ON"; SetPropOnOff("READ_COMMITTED_SNAPSHOT", dr["is_read_committed_snapshot_on"]); SetPropString("RECOVERY", dr["recovery_model_desc"]); SetPropString("PAGE_VERIFY", dr["page_verify_option_desc"]); SetPropOnOff("AUTO_CREATE_STATISTICS", dr["is_auto_create_stats_on"]); SetPropOnOff("AUTO_UPDATE_STATISTICS", dr["is_auto_update_stats_on"]); SetPropOnOff( "AUTO_UPDATE_STATISTICS_ASYNC", dr["is_auto_update_stats_async_on"]); SetPropOnOff("ANSI_NULL_DEFAULT", dr["is_ansi_null_default_on"]); SetPropOnOff("ANSI_NULLS", dr["is_ansi_nulls_on"]); SetPropOnOff("ANSI_PADDING", dr["is_ansi_padding_on"]); SetPropOnOff("ANSI_WARNINGS", dr["is_ansi_warnings_on"]); SetPropOnOff("ARITHABORT", dr["is_arithabort_on"]); SetPropOnOff("CONCAT_NULL_YIELDS_NULL", dr["is_concat_null_yields_null_on"]); SetPropOnOff("NUMERIC_ROUNDABORT", dr["is_numeric_roundabort_on"]); SetPropOnOff("QUOTED_IDENTIFIER", dr["is_quoted_identifier_on"]); SetPropOnOff("RECURSIVE_TRIGGERS", dr["is_recursive_triggers_on"]); SetPropOnOff("CURSOR_CLOSE_ON_COMMIT", dr["is_cursor_close_on_commit_on"]); if (dr["is_local_cursor_default"] != DBNull.Value) FindProp("CURSOR_DEFAULT").Value = (bool)dr["is_local_cursor_default"] ? "LOCAL" : "GLOBAL"; SetPropOnOff("TRUSTWORTHY", dr["is_trustworthy_on"]); SetPropOnOff("DB_CHAINING", dr["is_db_chaining_on"]); if (dr["is_parameterization_forced"] != DBNull.Value) FindProp("PARAMETERIZATION").Value = (bool)dr["is_parameterization_forced"] ? "FORCED" : "SIMPLE"; SetPropOnOff("DATE_CORRELATION_OPTIMIZATION", dr["is_date_correlation_on"]); } } } #endregion #region Script public void ScriptToDir(string tableHint = null, Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; if (Directory.Exists(Dir)) { // delete the existing script files log(TraceLevel.Verbose, "Deleting existing files..."); var files = Dirs.Select(dir => Path.Combine(Dir, dir)) .Where(Directory.Exists) .SelectMany(Directory.GetFiles); foreach (var f in files) File.Delete(f); log(TraceLevel.Verbose, "Existing files deleted."); } else { Directory.CreateDirectory(Dir); } WritePropsScript(log); WriteScriptDir("schemas", Schemas.ToArray(), log); WriteScriptDir("tables", Tables.ToArray(), log); foreach (var table in Tables) { WriteScriptDir( "check_constraints", table.Constraints.Where(c => c.Type == "CHECK").ToArray(), log); var defaults = (from c in table.Columns.Items where c.Default != null select c.Default).ToArray(); if (defaults.Any()) WriteScriptDir("defaults", defaults, log); } WriteScriptDir("table_types", TableTypes.ToArray(), log); WriteScriptDir("user_defined_types", UserDefinedTypes.ToArray(), log); WriteScriptDir( "foreign_keys", ForeignKeys.OrderBy(x => x, ForeignKeyComparer.Instance).ToArray(), log); foreach (var routineType in Routines.GroupBy(x => x.RoutineType)) { var dir = routineType.Key.ToString().ToLower() + "s"; WriteScriptDir(dir, routineType.ToArray(), log); } WriteScriptDir("views", ViewIndexes.ToArray(), log); WriteScriptDir("assemblies", Assemblies.ToArray(), log); WriteScriptDir("roles", Roles.ToArray(), log); WriteScriptDir("users", Users.ToArray(), log); WriteScriptDir("synonyms", Synonyms.ToArray(), log); WriteScriptDir("permissions", Permissions.ToArray(), log); ExportData(tableHint, log); } private void WritePropsScript(Action<TraceLevel, string> log) { if (!Dirs.Contains("props")) return; log(TraceLevel.Verbose, "Scripting database properties..."); var text = new StringBuilder(); text.Append(ScriptPropList(Props)); text.AppendLine("GO"); text.AppendLine(); File.WriteAllText($"{Dir}/props.sql", text.ToString()); } private void WriteScriptDir( string name, ICollection<IScriptable> objects, Action<TraceLevel, string> log) { if (!objects.Any()) return; if (!Dirs.Contains(name)) return; var dir = Path.Combine(Dir, name); Directory.CreateDirectory(dir); var index = 0; foreach (var o in objects) { log( TraceLevel.Verbose, $"Scripting {name} {++index} of {objects.Count}...{(index < objects.Count ? "\r" : string.Empty)}"); var filePath = Path.Combine(dir, MakeFileName(o) + ".sql"); var script = o.ScriptCreate() + "\r\nGO\r\n"; File.AppendAllText(filePath, script); } } private static string MakeFileName(object o) { // combine foreign keys into one script per table var fk = o as ForeignKey; if (fk != null) return MakeFileName(fk.Table); // combine defaults into one script per table if (o is Default) return MakeFileName((o as Default).Table); // combine check constraints into one script per table if (o is Constraint && (o as Constraint).Type == "CHECK") return MakeFileName((o as Constraint).Table); var schema = o as IHasOwner == null ? "" : (o as IHasOwner).Owner; var name = o as INameable == null ? "" : (o as INameable).Name; var fileName = MakeFileName(schema, name); // prefix user defined types with TYPE_ var prefix = o as Table == null ? "" : (o as Table).IsType ? "TYPE_" : ""; return string.Concat(prefix, fileName); } private static string MakeFileName(string schema, string name) { // Dont' include schema name for objects in the dbo schema. // This maintains backward compatability for those who use // SchemaZen to keep their schemas under version control. var fileName = name; if (!string.IsNullOrEmpty(schema) && schema.ToLower() != "dbo") fileName = $"{schema}.{name}"; return Path.GetInvalidFileNameChars() .Aggregate( fileName, (current, invalidChar) => current.Replace(invalidChar, '-')); } public void ExportData(string tableHint = null, Action<TraceLevel, string> log = null) { if (!DataTables.Any()) return; var dataDir = Dir + "/data"; if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); log?.Invoke(TraceLevel.Info, "Exporting data..."); var index = 0; foreach (var t in DataTables) { log?.Invoke( TraceLevel.Verbose, $"Exporting data from {t.Owner + "." + t.Name} (table {++index} of {DataTables.Count})..."); var filePathAndName = dataDir + "/" + MakeFileName(t) + ".tsv"; var sw = File.CreateText(filePathAndName); t.ExportData(Connection, sw, tableHint); sw.Flush(); if (sw.BaseStream.Length == 0) { log?.Invoke( TraceLevel.Verbose, $" No data to export for {t.Owner + "." + t.Name}, deleting file..."); sw.Close(); File.Delete(filePathAndName); } else { sw.Close(); } } } public static string ScriptPropList(IList<DbProp> props) { var text = new StringBuilder(); text.AppendLine("DECLARE @DB VARCHAR(255)"); text.AppendLine("SET @DB = DB_NAME()"); foreach (var p in props.Select(p => p.Script()).Where(p => !string.IsNullOrEmpty(p))) text.AppendLine(p); return text.ToString(); } #endregion #region Create public void ImportData(Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; var dataDir = Dir + "\\data"; if (!Directory.Exists(dataDir)) { log(TraceLevel.Verbose, "No data to import."); return; } log(TraceLevel.Verbose, "Loading database schema..."); Load(); // load the schema first so we can import data log(TraceLevel.Verbose, "Database schema loaded."); log(TraceLevel.Info, "Importing data..."); foreach (var f in Directory.GetFiles(dataDir)) { var fi = new FileInfo(f); var schema = "dbo"; var table = Path.GetFileNameWithoutExtension(fi.Name); if (table.Contains(".")) { schema = fi.Name.Split('.')[0]; table = fi.Name.Split('.')[1]; } var t = FindTable(table, schema); if (t == null) { log( TraceLevel.Warning, $"Warning: found data file '{fi.Name}', but no corresponding table in database..."); continue; } try { log(TraceLevel.Verbose, $"Importing data for table {schema}.{table}..."); t.ImportData(Connection, fi.FullName); } catch (SqlBatchException ex) { throw new DataFileException(ex.Message, fi.FullName, ex.LineNumber); } catch (Exception ex) { throw new DataFileException(ex.Message, fi.FullName, -1); } } log(TraceLevel.Info, "Data imported successfully."); } public void CreateFromDir( bool overwrite, string databaseFilesPath = null, Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; if (DBHelper.DbExists(Connection)) { _logger?.LogTrace("Dropping existing database..."); DBHelper.DropDb(Connection); _logger?.LogTrace("Existing database dropped."); } _logger?.LogTrace("Creating database..."); DBHelper.CreateDb(Connection, databaseFilesPath); //run scripts if (File.Exists(Dir + "/props.sql")) { _logger?.LogTrace("Setting database properties..."); try { DBHelper.ExecBatchSql(Connection, File.ReadAllText(Dir + "/props.sql")); } catch (SqlBatchException ex) { throw new SqlFileException(Dir + "/props.sql", ex); } // COLLATE can cause connection to be reset // so clear the pool so we get a new connection DBHelper.ClearPool(Connection); } // stage 0: everything not in another stage // stage 1: after_data & foreign keys _logger?.LogTrace("Creating database objects..."); var stages = GetScriptStages(); for (var i = 0; i < stages.Count; i++) { if (i == 2) ImportData(log); // load data before stage 2 _logger?.LogTrace($"running stage {i}"); var errors = RunStage(GetScripts(stages[i])); if (errors.Count > 0) { _logger?.LogCritical("Aborting due to unresolved errors"); var ex = new BatchSqlFileException { Exceptions = errors }; throw ex; } } } private List<HashSet<string>> GetScriptStages() { // stage zero objects must never have dependencies var stage0 = new HashSet<string> { "roles" }; // runs after most objects have been created // permissions are inlcued here because they tie a user to another object var stage2 = new HashSet<string> { "permissions" }; // stage3 runs after data has been imported var stage3 = new HashSet<string> { "after_data", "foreign_keys" }; var stage1 = Dirs .Except(stage0) .Except(stage2) .Except(stage3) .ToHashSet(); var itemsByStage = new List<HashSet<string>> { stage0, stage1, stage2, stage3 }; foreach (var stage in itemsByStage) stage.RemoveWhere( x => { var path = Path.Combine(Dir, x); return !Directory.Exists(path) && !File.Exists(path); }); return itemsByStage; } private List<string> GetScripts(HashSet<string> items) { var scripts = new List<string>(); foreach (var item in items) { var path = Path.Combine(Dir, item); if (item.EndsWith(".sql")) scripts.Add(path); else scripts.AddRange(Directory.GetFiles(path, "*.sql")); } return scripts; } private List<SqlFileException> RunStage(List<string> scripts) { // resolve dependencies by trying over and over // if the number of failures stops decreasing then give up var errors = new List<SqlFileException>(); var prevCount = -1; var attempt = 1; while (scripts.Count > 0 && (prevCount == -1 || errors.Count < prevCount)) { if (errors.Count > 0) { prevCount = errors.Count; attempt++; _logger?.LogTrace($"{errors.Count} errors occurred, retrying..."); } errors.Clear(); var index = 0; var total = scripts.Count; foreach (var f in scripts.ToArray()) { _logger?.LogTrace( $"Executing script {++index} of {total}...{(index < total ? "\r" : string.Empty)}"); _logger?.LogTrace($"file name: {f}"); try { DBHelper.ExecBatchSql(Connection, File.ReadAllText(f)); scripts.Remove(f); } catch (SqlBatchException ex) { _logger?.LogTrace($"attempt {attempt}: {f}@{ex.LineNumber} {ex.Message}"); errors.Add(new SqlFileException(f, ex)); } } } if (errors.Any()) foreach (var error in errors) _logger?.LogError(error.Message); return errors; } #endregion }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Integration\ForeignKeyTest.cs
Test.Integration
ForeignKeyTest
['private readonly TestDbHelper _dbHelper;', 'private readonly ILogger _logger;']
['Microsoft.Extensions.Logging', 'SchemaZen.Library.Models', 'Test.Integration.Helpers', 'Xunit', 'Xunit.Abstractions']
xUnit
net6.0
[Trait("Category", "Integration")] public class ForeignKeyTest { private readonly TestDbHelper _dbHelper; private readonly ILogger _logger; public ForeignKeyTest(ITestOutputHelper output, TestDbHelper dbHelper) { _logger = output.BuildLogger(); _dbHelper = dbHelper; } [Fact] public async Task TestMultiColumnKey() { var t1 = new Table("dbo", "t1"); t1.Columns.Add(new Column("c2", "varchar", 10, false, null)); t1.Columns.Add(new Column("c1", "int", false, null)); t1.AddConstraint(new Constraint("pk_t1", "PRIMARY KEY", "c1,c2")); var t2 = new Table("dbo", "t2"); t2.Columns.Add(new Column("c1", "int", false, null)); t2.Columns.Add(new Column("c2", "varchar", 10, false, null)); t2.Columns.Add(new Column("c3", "int", false, null)); var fk = new ForeignKey(t2, "fk_test", "c3,c2", t1, "c1,c2"); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t1.ScriptCreate()); await testDb.ExecSqlAsync(t2.ScriptCreate()); await testDb.ExecSqlAsync(fk.ScriptCreate()); var db = new Database("TESTDB"); db.Connection = testDb.GetConnString(); db.Load(); Assert.Equal("c3", db.FindForeignKey("fk_test", "dbo").Columns[0]); Assert.Equal("c2", db.FindForeignKey("fk_test", "dbo").Columns[1]); Assert.Equal("c1", db.FindForeignKey("fk_test", "dbo").RefColumns[0]); Assert.Equal("c2", db.FindForeignKey("fk_test", "dbo").RefColumns[1]); } [Fact] public async Task TestScript() { var person = new Table("dbo", "Person"); person.Columns.Add(new Column("id", "int", false, null)); person.Columns.Add(new Column("name", "varchar", 50, false, null)); person.Columns.Find("id").Identity = new Identity(1, 1); person.AddConstraint(new Constraint("PK_Person", "PRIMARY KEY", "id")); var address = new Table("dbo", "Address"); address.Columns.Add(new Column("id", "int", false, null)); address.Columns.Add(new Column("personId", "int", false, null)); address.Columns.Add(new Column("street", "varchar", 50, false, null)); address.Columns.Add(new Column("city", "varchar", 50, false, null)); address.Columns.Add(new Column("state", "char", 2, false, null)); address.Columns.Add(new Column("zip", "varchar", 5, false, null)); address.Columns.Find("id").Identity = new Identity(1, 1); address.AddConstraint(new Constraint("PK_Address", "PRIMARY KEY", "id")); var fk = new ForeignKey( address, "FK_Address_Person", "personId", person, "id", "", "CASCADE"); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(person.ScriptCreate()); await testDb.ExecSqlAsync(address.ScriptCreate()); await testDb.ExecSqlAsync(fk.ScriptCreate()); var db = new Database("TESTDB"); db.Connection = testDb.GetConnString(); db.Load(); Assert.NotNull(db.FindTable("Person", "dbo")); Assert.NotNull(db.FindTable("Address", "dbo")); Assert.NotNull(db.FindForeignKey("FK_Address_Person", "dbo")); } [Fact] public async Task TestScriptForeignKeyWithNoName() { var t1 = new Table("dbo", "t1"); t1.Columns.Add(new Column("c2", "varchar", 10, false, null)); t1.Columns.Add(new Column("c1", "int", false, null)); t1.AddConstraint(new Constraint("pk_t1", "PRIMARY KEY", "c1,c2")); var t2 = new Table("dbo", "t2"); t2.Columns.Add(new Column("c1", "int", false, null)); t2.Columns.Add(new Column("c2", "varchar", 10, false, null)); t2.Columns.Add(new Column("c3", "int", false, null)); var fk = new ForeignKey(t2, "fk_ABCDEF", "c3,c2", t1, "c1,c2"); fk.IsSystemNamed = true; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t1.ScriptCreate()); await testDb.ExecSqlAsync(t2.ScriptCreate()); await testDb.ExecSqlAsync(fk.ScriptCreate()); var db = new Database("TESTDB"); db.Connection = testDb.GetConnString(); db.Load(); Assert.Single(db.ForeignKeys); var fkCopy = db.ForeignKeys.Single(); Assert.Equal("c3", fkCopy.Columns[0]); Assert.Equal("c2", fkCopy.Columns[1]); Assert.Equal("c1", fkCopy.RefColumns[0]); Assert.Equal("c2", fkCopy.RefColumns[1]); Assert.True(fkCopy.IsSystemNamed); } }
169
4,307
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SchemaZen.Library.Models; public class ForeignKey : INameable, IScriptable { private const string _defaultRules = "NO ACTION|RESTRICT"; public ForeignKey(string name) { Name = name; } public ForeignKey( Table table, string name, string columns, Table refTable, string refColumns) : this(table, name, columns, refTable, refColumns, "", "") { } public ForeignKey( Table table, string name, string columns, Table refTable, string refColumns, string onUpdate, string onDelete) { Table = table; Name = name; Columns = new List<string>(columns.Split(',')); RefTable = refTable; RefColumns = new List<string>(refColumns.Split(',')); OnUpdate = onUpdate; OnDelete = onDelete; } public bool Check { get; set; } public bool IsSystemNamed { get; set; } public List<string> Columns { get; set; } = new(); public string OnDelete { get; set; } public string OnUpdate { get; set; } public List<string> RefColumns { get; set; } = new(); public Table RefTable { get; set; } public Table Table { get; set; } public string CheckText => Check ? "CHECK" : "NOCHECK"; public string Name { get; set; } public string ScriptCreate() { AssertArgNotNull(Table, "Table"); AssertArgNotNull(Columns, "Columns"); AssertArgNotNull(RefTable, "RefTable"); AssertArgNotNull(RefColumns, "RefColumns"); var text = new StringBuilder(); var constraintName = IsSystemNamed ? string.Empty : $"CONSTRAINT [{Name}]"; text.Append( $"ALTER TABLE [{Table.Owner}].[{Table.Name}] WITH {CheckText} ADD {constraintName}\r\n"); text.Append( $" FOREIGN KEY([{string.Join("], [", Columns.ToArray())}]) REFERENCES [{RefTable.Owner}].[{RefTable.Name}] ([{string.Join("], [", RefColumns.ToArray())}])\r\n"); if (!string.IsNullOrEmpty(OnUpdate) && !_defaultRules.Split('|').Contains(OnUpdate)) text.Append($" ON UPDATE {OnUpdate}\r\n"); if (!string.IsNullOrEmpty(OnDelete) && !_defaultRules.Split('|').Contains(OnDelete)) text.Append($" ON DELETE {OnDelete}\r\n"); if (!Check && !IsSystemNamed) text.Append( $" ALTER TABLE [{Table.Owner}].[{Table.Name}] NOCHECK CONSTRAINT [{Name}]\r\n"); return text.ToString(); } private void AssertArgNotNull(object arg, string argName) { if (arg == null) throw new ArgumentNullException( $"Unable to Script FK {Name} on table {Table.Owner}.{Table.Name}. {argName} must not be null."); } public string ScriptDrop() { return $"ALTER TABLE [{Table.Owner}].[{Table.Name}] DROP CONSTRAINT [{Name}]\r\n"; } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Integration\TableTest.cs
Test.Integration
TableTest
['private readonly TestDbHelper _dbHelper;', 'private readonly ILogger _logger;']
['System.Text', 'Microsoft.Extensions.Logging', 'SchemaZen.Library.Models', 'Test.Integration.Helpers', 'Xunit', 'Xunit.Abstractions']
xUnit
net6.0
[Trait("Category", "Integration")] public class TableTest { private readonly TestDbHelper _dbHelper; private readonly ILogger _logger; public TableTest(ITestOutputHelper output, TestDbHelper dbHelper) { _logger = output.BuildLogger(); _dbHelper = dbHelper; } [Fact] public async Task TestExportData() { var t = new Table("dbo", "Status"); t.Columns.Add(new Column("id", "int", false, null)); t.Columns.Add(new Column("code", "char", 1, false, null)); t.Columns.Add(new Column("description", "varchar", 20, false, null)); t.Columns.Find("id").Identity = new Identity(1, 1); t.AddConstraint(new Constraint("PK_Status", "PRIMARY KEY", "id")); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); var dataIn = @"1 R Ready" + Environment.NewLine + @"2 P Processing" + Environment.NewLine + @"3 F Frozen" + Environment.NewLine; var filename = Path.GetTempFileName(); var writer = File.AppendText(filename); writer.Write(dataIn); writer.Flush(); writer.Close(); t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); File.Delete(filename); } [Fact] public async Task TestImportAndExportIgnoringComputedData() { var t = new Table("dbo", "Status"); t.Columns.Add(new Column("id", "int", false, null)); t.Columns.Add(new Column("code", "char", 1, false, null)); t.Columns.Add(new Column("description", "varchar", 20, false, null)); var computedCol = new Column("computed", "varchar", false, null) { ComputedDefinition = "code + ' : ' + description" }; t.Columns.Add(computedCol); t.Columns.Find("id").Identity = new Identity(1, 1); t.AddConstraint(new Constraint("PK_Status", "PRIMARY KEY", "id")); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); var dataIn = @"1 R Ready" + Environment.NewLine + @"2 P Processing" + Environment.NewLine + @"3 F Frozen" + Environment.NewLine; var filename = Path.GetTempFileName(); var writer = File.AppendText(filename); writer.Write(dataIn); writer.Flush(); writer.Close(); try { t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); } finally { File.Delete(filename); } } [Fact] public async Task TestImportAndExportDateTimeWithoutLosePrecision() { var t = new Table("dbo", "Dummy"); t.Columns.Add(new Column("id", "int", false, null)); t.Columns.Add(new Column("createdTime", "datetime", false, null)); t.Columns.Find("id").Identity = new Identity(1, 1); t.AddConstraint(new Constraint("PK_Status", "PRIMARY KEY", "id")); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); var dataIn = @"1 2017-02-21 11:20:30.1" + Environment.NewLine + @"2 2017-02-22 11:20:30.12" + Environment.NewLine + @"3 2017-02-23 11:20:30.123" + Environment.NewLine; var filename = Path.GetTempFileName(); var writer = File.AppendText(filename); writer.Write(dataIn); writer.Flush(); writer.Close(); try { t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); } finally { File.Delete(filename); } } [Fact] public async Task TestImportAndExportNonDefaultSchema() { var s = new Schema("example", "dbo"); var t = new Table(s.Name, "Example"); t.Columns.Add(new Column("id", "int", false, null)); t.Columns.Add(new Column("code", "char", 1, false, null)); t.Columns.Add(new Column("description", "varchar", 20, false, null)); t.Columns.Find("id").Identity = new Identity(1, 1); t.AddConstraint(new Constraint("PK_Example", "PRIMARY KEY", "id")); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(s.ScriptCreate()); await testDb.ExecSqlAsync(t.ScriptCreate()); var dataIn = @"1 R Ready" + Environment.NewLine + @"2 P Processing" + Environment.NewLine + @"3 F Frozen" + Environment.NewLine; var filename = Path.GetTempFileName(); var writer = File.AppendText(filename); writer.Write(dataIn); writer.Flush(); writer.Close(); try { t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); } finally { File.Delete(filename); } } [Fact] public async Task TestLargeAmountOfRowsImportAndExport() { var t = new Table("dbo", "TestData"); t.Columns.Add(new Column("test_field", "int", false, null)); t.AddConstraint( new Constraint("PK_TestData", "PRIMARY KEY", "test_field") { IndexType = "NONCLUSTERED" }); t.AddConstraint( new Constraint("IX_TestData_PK", "INDEX", "test_field") { // clustered index is required to ensure the row order is the same as what we import IndexType = "CLUSTERED", Table = t, Unique = true }); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); var filename = Path.GetTempFileName(); var writer = File.CreateText(filename); var sb = new StringBuilder(); for (var i = 0; i < Table.RowsInBatch * 4.2; i++) { sb.AppendLine(i.ToString()); writer.WriteLine(i.ToString()); } writer.Flush(); writer.Close(); var dataIn = sb.ToString(); Assert.Equal( dataIn, File.ReadAllText( filename)); // just prove that the file and the string are the same, to make the next assertion meaningful! try { t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); } finally { File.Delete(filename); } } [Fact] public async Task TestScript() { //create a table with all known types, script it, and execute the script var t = new Table("dbo", "AllTypesTest"); t.Columns.Add(new Column("a", "bigint", false, null)); t.Columns.Add(new Column("b", "binary", 50, false, null)); t.Columns.Add(new Column("c", "bit", false, null)); t.Columns.Add(new Column("d", "char", 10, false, null)); t.Columns.Add(new Column("e", "datetime", false, null)); t.Columns.Add(new Column("f", "decimal", 18, 0, false, null)); t.Columns.Add(new Column("g", "float", false, null)); t.Columns.Add(new Column("h", "image", false, null)); t.Columns.Add(new Column("i", "int", false, null)); t.Columns.Add(new Column("j", "money", false, null)); t.Columns.Add(new Column("k", "nchar", 10, false, null)); t.Columns.Add(new Column("l", "ntext", false, null)); t.Columns.Add(new Column("m", "numeric", 18, 0, false, null)); t.Columns.Add(new Column("n", "nvarchar", 50, false, null)); t.Columns.Add(new Column("o", "nvarchar", -1, false, null)); t.Columns.Add(new Column("p", "real", false, null)); t.Columns.Add(new Column("q", "smalldatetime", false, null)); t.Columns.Add(new Column("r", "smallint", false, null)); t.Columns.Add(new Column("s", "smallmoney", false, null)); t.Columns.Add(new Column("t", "sql_variant", false, null)); t.Columns.Add(new Column("u", "text", false, null)); t.Columns.Add(new Column("v", "timestamp", false, null)); t.Columns.Add(new Column("w", "tinyint", false, null)); t.Columns.Add(new Column("x", "uniqueidentifier", false, null)); t.Columns.Add(new Column("y", "varbinary", 50, false, null)); t.Columns.Add(new Column("z", "varbinary", -1, false, null)); t.Columns.Add( new Column( "aa", "varchar", 50, true, new Default("DF_AllTypesTest_aa", "'asdf'", false))); t.Columns.Add(new Column("bb", "varchar", -1, true, null)); t.Columns.Add(new Column("cc", "xml", true, null)); t.Columns.Add(new Column("dd", "hierarchyid", false, null)); t.Columns.Add(new Column("ee", "geometry", false, null)); t.Columns.Add(new Column("ff", "geography", false, null)); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); } [Fact] public async Task TestImportExportGeometryData() { var t = new Table("dbo", "Shape"); t.Columns.Add(new Column("id", "int", false, null)); t.Columns.Add(new Column("shape", "geometry", false, null)); t.Columns.Find("id").Identity = new Identity(1, 1); t.AddConstraint(new Constraint("PK_Shape", "PRIMARY KEY", "id")); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); var dataIn = @"1 0000000001040300000000000000000059400000000000005940000000000000344000000000008066400000000000806640000000000080664001000000010000000001000000FFFFFFFF0000000002" + Environment.NewLine + @"2 00000000010405000000000000000000000000000000000000000000000000C0624000000000000000000000000000C062400000000000C0624000000000000000000000000000C062400000000000000000000000000000000001000000020000000001000000FFFFFFFF0000000003" + Environment.NewLine; var filename = Path.GetTempFileName(); var writer = File.AppendText(filename); writer.Write(dataIn); writer.Flush(); writer.Close(); try { t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); } finally { File.Delete(filename); } } [Fact] public async Task TestImportExportGeographyData() { var t = new Table("dbo", "PointsOfInterest"); t.Columns.Add(new Column("id", "int", false, null)); t.Columns.Add(new Column("location", "geography", false, null)); t.Columns.Find("id").Identity = new Identity(1, 1); t.AddConstraint(new Constraint("PK_PointsOfInterest", "PRIMARY KEY", "id")); await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(t.ScriptCreate()); var dataIn = @"1 E610000001148716D9CEF7D34740D7A3703D0A975EC08716D9CEF7D34740CBA145B6F3955EC0" + Environment.NewLine; var filename = Path.GetTempFileName(); var writer = File.AppendText(filename); writer.Write(dataIn); writer.Flush(); writer.Close(); try { t.ImportData(testDb.GetConnString(), filename); var sw = new StringWriter(); t.ExportData(testDb.GetConnString(), sw); Assert.Equal(dataIn, sw.ToString()); } finally { File.Delete(filename); } } }
188
10,660
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace SchemaZen.Library.Models; public class Table : INameable, IHasOwner, IScriptable { private const string _tab = "\t"; private const string _escapeTab = "--SchemaZenTAB--"; private const string _carriageReturn = "\r"; private const string _escapeCarriageReturn = "--SchemaZenCR--"; private const string _lineFeed = "\n"; private const string _escapeLineFeed = "--SchemaZenLF--"; private const string _nullValue = "--SchemaZenNull--"; private const string _dateTimeFormat = "yyyy-MM-dd HH:mm:ss.FFFFFFF"; public const int RowsInBatch = 15000; // TODO allow users to configure these private static readonly string _rowSeparator = Environment.NewLine; private readonly List<Constraint> _constraints = new(); public ColumnList Columns = new(); public bool IsType; public Table(string owner, string name) { Owner = owner; Name = name; } public Constraint PrimaryKey { get { return _constraints.FirstOrDefault(c => c.Type == "PRIMARY KEY"); } } public IEnumerable<Constraint> Constraints => _constraints.AsEnumerable(); public string Owner { get; set; } public string Name { get; set; } public string ScriptCreate() { var text = new StringBuilder(); text.Append( $"CREATE {(IsType ? "TYPE" : "TABLE")} [{Owner}].[{Name}] {(IsType ? "AS TABLE " : string.Empty)}(\r\n"); text.Append(Columns.Script()); if (_constraints.Count > 0) text.AppendLine(); if (!IsType) foreach (var c in _constraints.OrderBy(x => x.Name) .Where(c => c.Type == "PRIMARY KEY" || c.Type == "UNIQUE")) text.AppendLine(" ," + c.ScriptCreate()); else foreach (var c in _constraints.OrderBy(x => x.Name).Where(c => c.Type != "INDEX")) text.AppendLine(" ," + c.ScriptCreate()); text.AppendLine(")"); text.AppendLine(); foreach (var c in _constraints.Where(c => c.Type == "INDEX")) text.AppendLine(c.ScriptCreate()); return text.ToString(); } public Constraint FindConstraint(string name) { return _constraints.FirstOrDefault(c => c.Name == name); } public void AddConstraint(Constraint constraint) { constraint.Table = this; _constraints.Add(constraint); } public void RemoveContraint(Constraint constraint) { _constraints.Remove(constraint); } public TableDiff Compare(Table t) { var diff = new TableDiff { Owner = t.Owner, Name = t.Name }; //get additions and compare mutual columns foreach (var c in Columns.Items) { var c2 = t.Columns.Find(c.Name); if (c2 == null) { diff.ColumnsAdded.Add(c); } else { //compare mutual columns var cDiff = c.Compare(c2); if (cDiff.IsDiff) diff.ColumnsDiff.Add(cDiff); } } //get deletions foreach (var c in t.Columns.Items.Where(c => Columns.Find(c.Name) == null)) diff.ColumnsDropped.Add(c); if (!t.IsType) { //get added and compare mutual constraints foreach (var c in Constraints) { var c2 = t.FindConstraint(c.Name); if (c2 == null) { diff.ConstraintsAdded.Add(c); } else { if (c.ScriptCreate() != c2.ScriptCreate()) diff.ConstraintsChanged.Add(c); } } //get deleted constraints foreach (var c in t.Constraints.Where(c => FindConstraint(c.Name) == null)) diff.ConstraintsDeleted.Add(c); } else { // compare constraints on table types, which can't be named in the script, but have names in the DB var dest = Constraints.ToList(); var src = t.Constraints.ToList(); var j = from c1 in dest join c2 in src on c1.ScriptCreate() equals c2.ScriptCreate() into match //new { c1.Type, c1.Unique, c1.Clustered, Columns = string.Join(",", c1.Columns.ToArray()), IncludedColumns = string.Join(",", c1.IncludedColumns.ToArray()) } equals new { c2.Type, c2.Unique, c2.Clustered, Columns = string.Join(",", c2.Columns.ToArray()), IncludedColumns = string.Join(",", c2.IncludedColumns.ToArray()) } into match from m in match.DefaultIfEmpty() select new { c1, m }; foreach (var c in j) if (c.m == null) diff.ConstraintsAdded.Add(c.c1); else src.Remove(c.m); foreach (var c in src) diff.ConstraintsDeleted.Add(c); } return diff; } public string ScriptDrop() { return $"DROP {(IsType ? "TYPE" : "TABLE")} [{Owner}].[{Name}]"; } public void ExportData(string conn, TextWriter data, string tableHint = null) { if (IsType) throw new InvalidOperationException(); var sql = new StringBuilder(); sql.Append("select "); var cols = Columns.Items.Where(c => string.IsNullOrEmpty(c.ComputedDefinition)) .ToArray(); foreach (var c in cols) sql.Append($"[{c.Name}],"); sql.Remove(sql.Length - 1, 1); sql.Append($" from [{Owner}].[{Name}]"); if (!string.IsNullOrEmpty(tableHint)) sql.Append($" WITH ({tableHint})"); AppendOrderBy(sql, cols); using (var cn = new SqlConnection(conn)) { cn.Open(); using (var cm = cn.CreateCommand()) { cm.CommandText = sql.ToString(); using (var dr = cm.ExecuteReader()) { while (dr.Read()) { foreach (var c in cols) { var ordinal = dr.GetOrdinal(c.Name); if (dr.IsDBNull(ordinal)) data.Write(_nullValue); else if (dr.GetDataTypeName(ordinal).EndsWith(".sys.geometry") || dr.GetDataTypeName(ordinal).EndsWith(".sys.geography")) // https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2012/ms143179(v=sql.110)?redirectedfrom=MSDN#sql-clr-data-types-geometry-geography-and-hierarchyid data.Write(StringUtil.ToHexString(dr.GetSqlBytes(ordinal).Value)); else if (dr[c.Name] is byte[]) data.Write(StringUtil.ToHexString((byte[])dr[c.Name])); else if (dr[c.Name] is DateTime) data.Write( ((DateTime)dr[c.Name]) .ToString(_dateTimeFormat, CultureInfo.InvariantCulture)); else if (dr[c.Name] is float || dr[c.Name] is double || dr[c.Name] is decimal) data.Write( Convert.ToString( dr[c.Name], CultureInfo.InvariantCulture)); else data.Write( dr[c.Name] .ToString() .Replace(_tab, _escapeTab) .Replace(_lineFeed, _escapeLineFeed) .Replace(_carriageReturn, _escapeCarriageReturn)); if (c != cols.Last()) data.Write(_tab); } data.WriteLine(); } } } } } public void ImportData(string conn, string filename) { if (IsType) throw new InvalidOperationException(); var dt = new DataTable(); var cols = Columns.Items.Where(c => string.IsNullOrEmpty(c.ComputedDefinition)) .ToArray(); foreach (var c in cols) dt.Columns.Add(new DataColumn(c.Name, c.SqlTypeToNativeType())); var linenumber = 0; var batch_rows = 0; using (var bulk = new SqlBulkCopy( conn, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.TableLock)) { foreach (var colName in dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName)) bulk.ColumnMappings.Add(colName, colName); bulk.DestinationTableName = $"[{Owner}].[{Name}]"; using (var file = new StreamReader(filename)) { var line = new List<char>(); while (file.Peek() >= 0) { var rowsep_cnt = 0; line.Clear(); while (file.Peek() >= 0) { var ch = (char)file.Read(); line.Add(ch); if (ch == _rowSeparator[rowsep_cnt]) rowsep_cnt++; else rowsep_cnt = 0; if (rowsep_cnt == _rowSeparator.Length) { // Remove rowseparator from line line.RemoveRange( line.Count - _rowSeparator.Length, _rowSeparator.Length); break; } } linenumber++; // Skip empty lines if (line.Count == 0) continue; batch_rows++; var row = dt.NewRow(); var fields = new string(line.ToArray()).Split( new[] { _tab }, StringSplitOptions.None); if (fields.Length != dt.Columns.Count) throw new DataFileException( "Incorrect number of columns", filename, linenumber); for (var j = 0; j < fields.Length; j++) try { row[j] = ConvertType( cols[j].Type, fields[j] .Replace(_escapeLineFeed, _lineFeed) .Replace(_escapeCarriageReturn, _carriageReturn) .Replace(_escapeTab, _tab)); } catch (FormatException ex) { throw new DataFileException( $"{ex.Message} at column {j + 1}", filename, linenumber); } dt.Rows.Add(row); if (batch_rows == RowsInBatch) { batch_rows = 0; bulk.WriteToServer(dt); dt.Clear(); } } } bulk.WriteToServer(dt); bulk.Close(); } } public static object ConvertType(string sqlType, string val) { if (val == _nullValue) return DBNull.Value; switch (sqlType.ToLower()) { case "bit": //added for compatibility with bcp if (val == "0") val = "False"; if (val == "1") val = "True"; return bool.Parse(val); case "datetime": case "smalldatetime": return DateTime.Parse(val, CultureInfo.InvariantCulture); case "int": return int.Parse(val); case "float": return double.Parse(val, CultureInfo.InvariantCulture); case "decimal": return decimal.Parse(val, CultureInfo.InvariantCulture); case "uniqueidentifier": return new Guid(val); case "binary": case "varbinary": case "image": case "geometry": case "geography": return StringUtil.FromHexString(val); default: return val; } } private void AppendOrderBy(StringBuilder sql, IEnumerable<Column> cols) { sql.Append(" ORDER BY "); if (PrimaryKey != null) { var pkColumns = PrimaryKey.Columns.Select(c => $"[{c.ColumnName}]"); sql.Append(string.Join(",", pkColumns.ToArray())); return; } var uk = Constraints.Where(c => c.Unique) .OrderBy(c => c.Columns.Count) .ThenBy(c => c.Name) .FirstOrDefault(); if (uk != null) { var ukColumns = uk.Columns.Select(c => $"[{c.ColumnName}]"); sql.Append(string.Join(",", ukColumns.ToArray())); return; } var allColumns = cols.Select(c => $"[{c.Name}]"); sql.Append(string.Join(",", allColumns.ToArray())); } } public class TableDiff { public List<Column> ColumnsAdded = new(); public List<ColumnDiff> ColumnsDiff = new(); public List<Column> ColumnsDropped = new(); public List<Constraint> ConstraintsAdded = new(); public List<Constraint> ConstraintsChanged = new(); public List<Constraint> ConstraintsDeleted = new(); public string Name; public string Owner; public bool IsDiff => ColumnsAdded.Count + ColumnsDropped.Count + ColumnsDiff.Count + ConstraintsAdded.Count + ConstraintsChanged.Count + ConstraintsDeleted.Count > 0; public string Script() { var text = new StringBuilder(); foreach (var c in ColumnsAdded) text.Append($"ALTER TABLE [{Owner}].[{Name}] ADD {c.ScriptCreate()}\r\n"); foreach (var c in ColumnsDropped) text.Append($"ALTER TABLE [{Owner}].[{Name}] DROP COLUMN [{c.Name}]\r\n"); foreach (var c in ColumnsDiff) { if (c.DefaultIsDiff) { if (c.Source.Default != null) text.Append( $"ALTER TABLE [{Owner}].[{Name}] {c.Source.Default.ScriptDrop()}\r\n"); if (c.Target.Default != null) text.Append( $"ALTER TABLE [{Owner}].[{Name}] {c.Target.Default.ScriptCreate(c.Target)}\r\n"); } if (!c.OnlyDefaultIsDiff) text.Append( $"ALTER TABLE [{Owner}].[{Name}] ALTER COLUMN {c.Target.ScriptAlter()}\r\n"); } void ScriptUnspported(Constraint c) { text.AppendLine("-- constraint added that SchemaZen doesn't support yet"); text.AppendLine("/*"); text.AppendLine(c.ScriptCreate()); text.AppendLine("*/"); } foreach (var c in ConstraintsAdded) switch (c.Type) { case "CHECK": case "INDEX": text.Append($"ALTER TABLE [{Owner}].[{Name}] ADD {c.ScriptCreate()}\r\n"); break; default: ScriptUnspported(c); break; } foreach (var c in ConstraintsChanged) switch (c.Type) { case "CHECK": text.Append($"-- Check constraint {c.Name} changed\r\n"); text.Append($"ALTER TABLE [{Owner}].[{Name}] DROP CONSTRAINT {c.Name}\r\n"); text.Append($"ALTER TABLE [{Owner}].[{Name}] ADD {c.ScriptCreate()}\r\n"); break; case "INDEX": text.Append($"-- Index {c.Name} changed\r\n"); text.Append($"DROP INDEX {c.Name} ON [{Owner}].[{Name}]\r\n"); text.Append($"{c.ScriptCreate()}\r\n"); break; default: ScriptUnspported(c); break; } foreach (var c in ConstraintsDeleted) text.Append( c.Type != "INDEX" ? $"ALTER TABLE [{Owner}].[{Name}] DROP CONSTRAINT {c.Name}\r\n" : $"DROP INDEX {c.Name} ON [{Owner}].[{Name}]\r\n"); return text.ToString(); } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Integration\UserTest.cs
Test.Integration
UserTest
['private readonly TestDbHelper _dbHelper;', 'private readonly ILogger _logger;']
['Microsoft.Extensions.Logging', 'SchemaZen.Library.Models', 'Test.Integration.Helpers', 'Xunit', 'Xunit.Abstractions']
xUnit
net6.0
[Trait("Category", "Integration")] public class UserTest { private readonly TestDbHelper _dbHelper; private readonly ILogger _logger; public UserTest(ITestOutputHelper output, TestDbHelper dbHelper) { _logger = output.BuildLogger(); _dbHelper = dbHelper; } [Fact] public async Task TestScriptUserAssignedToRole() { var testSchema = @" CREATE VIEW a_view AS SELECT 1 AS N GO CREATE ROLE [MyRole] GO GRANT SELECT ON [dbo].[a_view] TO [MyRole] GO IF SUSER_ID('usr') IS NULL BEGIN CREATE LOGIN usr WITH PASSWORD = 0x0100A92164F026C6EFC652DE59D9DEF79AC654E4E8EFA8E01A9B HASHED END CREATE USER [usr] FOR LOGIN usr WITH DEFAULT_SCHEMA = dbo exec sp_addrolemember 'MyRole', 'usr' exec sp_addrolemember 'db_datareader', 'usr' GO "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecBatchSqlAsync(testSchema); var db = new Database(_dbHelper.MakeTestDbName()); db.Connection = testDb.GetConnString(); db.Load(); db.Dir = db.Name; db.ScriptToDir(); db.Load(); var ex = Record.Exception(() => db.CreateFromDir(true)); Assert.Null(ex); } [Fact] public async Task TestScriptUserAssignedToSchema() { // when this test was written it would fail // because of a circular dependency... // user depends on role // schema depends on user // view depends on schema // role depends on view // // .> role -, // | v // user view // ^ | // \ schema < // var testSchema = @" CREATE ROLE [MyRole] GO IF SUSER_ID('usr') IS NULL BEGIN CREATE LOGIN usr WITH PASSWORD = 0x0100A92164F026C6EFC652DE59D9DEF79AC654E4E8EFA8E01A9B HASHED END CREATE USER [usr] FOR LOGIN usr WITH DEFAULT_SCHEMA = dbo exec sp_addrolemember 'MyRole', 'usr' exec sp_addrolemember 'db_datareader', 'usr' GO create schema [TestSchema] authorization [usr] GO CREATE VIEW TestSchema.a_view AS SELECT 1 AS N GO GRANT SELECT ON [TestSchema].[a_view] TO [MyRole] GO "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecBatchSqlAsync(testSchema); var db = new Database(_dbHelper.MakeTestDbName(), logger: _logger); db.Connection = testDb.GetConnString(); db.Load(); db.Dir = db.Name; db.ScriptToDir(); var ex = Record.Exception(() => db.CreateFromDir(true)); Assert.Null(ex); Assert.NotNull(db.Routines.FirstOrDefault(x => x.Name == "a_view")); Assert.NotNull(db.Roles.FirstOrDefault(x => x.Name == "MyRole")); Assert.NotNull(db.Users.FirstOrDefault(x => x.Name == "usr")); Assert.NotNull(db.Schemas.FirstOrDefault(x => x.Name == "TestSchema")); } }
169
2,775
using System; using System.Collections.Generic; using System.Linq; namespace SchemaZen.Library.Models; public class SqlUser : INameable, IHasOwner, IScriptable { public List<string> DatabaseRoles = new(); public SqlUser(string name, string owner) { Name = name; Owner = owner; } public byte[] PasswordHash { get; set; } public string Owner { get; set; } public string Name { get; set; } public string ScriptCreate() { var login = PasswordHash == null ? string.Empty : $@"IF SUSER_ID('{Name}') IS NULL BEGIN CREATE LOGIN [{Name}] WITH PASSWORD = {"0x" + StringUtil.ToHexString(PasswordHash)} HASHED END "; return login + $"CREATE USER [{Name}] {(PasswordHash == null ? "WITHOUT LOGIN" : "FOR LOGIN " + $"[{Name}]")} {(string.IsNullOrEmpty(Owner) ? string.Empty : "WITH DEFAULT_SCHEMA = ")}[{Owner}]" + "\r\n" + string.Join( "\r\n", DatabaseRoles.Select( r => $"/*ALTER ROLE {r} ADD MEMBER {Name}*/ exec sp_addrolemember '{r}', '{Name}'") .ToArray()); } public string ScriptDrop() { return $"DROP USER [{Name}]"; // NOTE: login is deliberately not dropped } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\AssemblyTest.cs
Test.Unit
AssemblyTest
[]
['SchemaZen.Library.Models', 'Xunit']
xUnit
net6.0
public class AssemblyTest { [Theory] [InlineData("SAFE_ACCESS", "SAFE")] [InlineData("UNSAFE_ACCESS", "UNSAFE")] [InlineData("EXTERNAL_ACCESS", "EXTERNAL_ACCESS")] public void Assembly_WithPermissionSetCases( string permissionSet, string scriptedPermissionSet ) { var assembly = new SqlAssembly(permissionSet, "SchemazenAssembly"); assembly.Files.Add(new KeyValuePair<string, byte[]>("mydll", new byte[0])); var expected = @"CREATE ASSEMBLY [SchemazenAssembly] FROM 0x WITH PERMISSION_SET = " + scriptedPermissionSet; Assert.Equal(expected, assembly.ScriptCreate()); } }
68
659
using System; using System.Collections.Generic; using System.Linq; namespace SchemaZen.Library.Models; public class SqlAssembly : INameable, IScriptable { public List<KeyValuePair<string, byte[]>> Files = new(); public string PermissionSet; public SqlAssembly(string permissionSet, string name) { PermissionSet = permissionSet; Name = name; if (PermissionSet == "SAFE_ACCESS") PermissionSet = "SAFE"; if (PermissionSet == "UNSAFE_ACCESS") PermissionSet = "UNSAFE"; } public string Name { get; set; } public string ScriptCreate() { var commands = Files.Select( (kvp, index) => { if (index == 0) return $@"CREATE ASSEMBLY [{Name}] {string.Empty}FROM {"0x" + StringUtil.ToHexString(kvp.Value)} {"WITH PERMISSION_SET = " + PermissionSet}"; return $@"ALTER ASSEMBLY [{Name}] ADD FILE FROM {"0x" + StringUtil.ToHexString(kvp.Value)} AS N\'{kvp.Key}\'"; }); var go = Environment.NewLine + "GO" + Environment.NewLine; var script = string.Join(go, commands.ToArray()); return script; } public string ScriptDrop() { return $"DROP ASSEMBLY [{Name}]"; } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\BatchSqlParserTest.cs
Test.Unit
BatchSqlParserTest
[]
['SchemaZen.Library', 'Xunit']
xUnit
net6.0
public class BatchSqlParserTest { [Fact] public void CanParseCommentBeforeGoStatement() { const string script = @"SELECT FOO /*TEST*/ GO BAR"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(2, scripts.Length); } [Fact] public void CanParseCommentWithQuoteChar() { const string script = @"/* Add the Url column to the subtext_Log table if it doesn't exist */ ADD [Url] VARCHAR(255) NULL GO AND COLUMN_NAME = 'BlogGroup') IS NULL"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(2, scripts.Length); } [Fact] public void CanParseDashDashCommentWithQuoteChar() { const string script = @"-- Add the Url column to the subtext_Log table if it doesn't exist SELECT * FROM BLAH GO PRINT 'FOO'"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(2, scripts.Length); } [Fact] public void CanParseGoWithDashDashCommentAfter() { const string script = @"SELECT * FROM foo; GO -- Hello Phil CREATE PROCEDURE dbo.Test AS SELECT * FROM foo"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(2, scripts.Length); } [Fact] public void CanParseLineEndingInDashDashComment() { const string script = @"SELECT * FROM BLAH -- Comment GO FOOBAR GO"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(2, scripts.Length); } [Fact] public void CanParseNestedComments() { const string script = @"/* select 1 /* nested comment */ go delete from users -- */"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Single(scripts); } [Fact] public void CanParseQuotedCorrectly() { const string script = @"INSERT INTO #Indexes EXEC sp_helpindex 'dbo.subtext_URLs'"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(script, scripts[0]); } [Fact] public void CanParseSimpleScript() { var script = "Test" + Environment.NewLine + "go"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Single(scripts); Assert.Equal("Test" + Environment.NewLine, scripts[0]); } [Fact] public void CanParseSimpleScriptEndingInNewLine() { var script = "Test" + Environment.NewLine + "GO" + Environment.NewLine; var scripts = BatchSqlParser.SplitBatch(script); Assert.Single(scripts); Assert.Equal("Test" + Environment.NewLine, scripts[0]); } [Fact] public void CanParseSuccessiveGoStatements() { const string script = @"GO GO"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Empty(scripts); } [Fact] public void MultiLineQuoteShouldNotBeSplitByGoKeyword() { var script = "PRINT '" + Environment.NewLine + "GO" + Environment.NewLine + "SELECT * FROM BLAH" + Environment.NewLine + "GO" + Environment.NewLine + "'"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(script, scripts[0]); Assert.Single(scripts); } [Fact] public void MultiLineQuoteShouldNotIgnoreDoubleQuote() { var script = "PRINT '" + Environment.NewLine + "''" + Environment.NewLine + "GO" + Environment.NewLine + "/*" + Environment.NewLine + "GO" + "'"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Single(scripts); Assert.Equal(script, scripts[0]); } /// <summary> /// Makes sure that ParseScript parses correctly. /// </summary> [Fact] public void ParseScriptParsesCorrectly() { const string script = @"SET QUOTED_IDENTIFIER OFF -- Comment Go SET ANSI_NULLS ON GO GO SET ANSI_NULLS ON CREATE TABLE [<username,varchar,dbo>].[blog_Gost] ( [HostUserName] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Password] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Salt] [nvarchar] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [DateCreated] [datetime] NOT NULL ) ON [PRIMARY] gO "; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(3, scripts.Length); } [Fact] public void SemiColonDoesNotSplitScript() { const string script = "CREATE PROC Blah AS SELECT FOO; SELECT Bar;"; var scripts = BatchSqlParser.SplitBatch(script); Assert.Single(scripts); } [Fact] public void SlashStarCommentAfterGoThrowsException() { const string script = @"PRINT 'blah' GO /* blah */"; Assert.Equal(2, BatchSqlParser.SplitBatch(script).Length); //why should this throw an exception? } [Fact] public void TestCommentFollowingGO() { var scripts = BatchSqlParser.SplitBatch("/*script1*/GO/*script2*/"); Assert.Equal(2, scripts.Length); Assert.Equal("/*script1*/", scripts[0]); Assert.Equal("/*script2*/", scripts[1]); } [Fact] public void TestCommentPrecedingGO() { var scripts = BatchSqlParser.SplitBatch("/*script1*/GO--script2"); Assert.Equal(2, scripts.Length); Assert.Equal("/*script1*/", scripts[0]); Assert.Equal("--script2", scripts[1]); } [Fact] public void TestLeadingTablsDashDash() { string[] scripts; scripts = BatchSqlParser.SplitBatch("\t\t\t\t-- comment"); Assert.Equal("\t\t\t\t-- comment", scripts[0]); } [Fact] public void TestLeadingTabsParameter() { string[] scripts; scripts = BatchSqlParser.SplitBatch("\t\t\t\t@param"); Assert.Equal("\t\t\t\t@param", scripts[0]); } [Fact] public void TestLeadingTabsSingleQuotes() { string[] scripts; scripts = BatchSqlParser.SplitBatch("\t\t\t\t'AddProjectToSourceSafe',"); Assert.Equal("\t\t\t\t'AddProjectToSourceSafe',", scripts[0]); } [Fact] public void TestLeadingTabsSlashStar() { string[] scripts; scripts = BatchSqlParser.SplitBatch("\t\t\t\t/* comment */"); Assert.Equal("\t\t\t\t/* comment */", scripts[0]); } [Fact] public void TestScriptWithGOTO() { var script = @"script 1 GO script 2 GOTO <-- not a GO <-- niether is this NOGO <-- also not a GO <-- still no "; var scripts = BatchSqlParser.SplitBatch(script); Assert.Equal(2, scripts.Length); } [Fact] public void TestSplitGOInComment() { string[] scripts; scripts = BatchSqlParser.SplitBatch( @" 1:1 -- GO ride a bike 1:2 "); //shoud be 1 script Assert.Single(scripts); } [Fact] public void TestSplitGOInQuotes() { string[] scripts; scripts = BatchSqlParser.SplitBatch( @" 1:1 ' GO ' 1:2 "); //should be 1 script Assert.Single(scripts); } [Fact] public void TestSplitGONoEndLine() { string[] scripts; scripts = BatchSqlParser.SplitBatch( @" 1:1 1:2 GO"); //should be 1 script with no 'GO' Assert.Single(scripts); Assert.DoesNotContain("GO", scripts[0]); } [Fact] public void TestSplitMultipleGOs() { string[] scripts; scripts = BatchSqlParser.SplitBatch( @" 1:1 GO GO GO GO 2:1 "); //should be 2 scripts Assert.Equal(2, scripts.Length); } [Fact] public void IgnoresSlashStarInsideQuotedIdentifier() { var scripts = BatchSqlParser.SplitBatch( @" select 1 as ""/*"" GO SET ANSI_NULLS OFF GO "); //should be 2 scripts Assert.Equal(2, scripts.Length); } [Fact] public void IgnoresGoInsideBrackets() { var scripts = BatchSqlParser.SplitBatch( @" 1:1 select 1 as [GO] SET ANSI_NULLS OFF GO "); Assert.Single(scripts); } [Fact] public void IgnoresGoInsideQuotedIdentifier() { var scripts = BatchSqlParser.SplitBatch( @" 1:1 select 1 as ""GO"" SET ANSI_NULLS OFF GO "); Assert.Single(scripts); } }
61
7,236
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace SchemaZen.Library; internal enum State { Searching, InOneLineComment, InMultiLineComment, InBrackets, InQuotes, InDoubleQuotes } public class BatchSqlParser { private static bool IsWhitespace(char c) { return Regex.Match(c.ToString(), "\\s", RegexOptions.Multiline).Success; } private static bool IsOneLineComment(char c0, char c1) { return c0 == '-' && c1 == '-'; } private static bool IsMultiLineComment(char c0, char c1) { return c0 == '/' && c1 == '*'; } private static bool IsEndMultiLineComment(char c0, char c1) { return c0 == '*' && c1 == '/'; } private static bool IsGO(char p3, char p2, char p, char c, char n, char n2) { /* valid GO is preceded by whitespace or the end of a multi-line * comment, and followed by whitespace or the beginning of a single * line or multi line comment. */ if (char.ToUpper(p) != 'G' || char.ToUpper(c) != 'O') return false; if (!IsWhitespace(p2) && !IsEndMultiLineComment(p3, p2)) return false; if (!IsWhitespace(n) && !IsOneLineComment(n, n2) && !IsMultiLineComment(n, n2)) return false; return true; } public static string[] SplitBatch(string batchSql) { var scripts = new List<string>(); var state = State.Searching; var foundGO = false; var commentDepth = 0; // previous 3, current, & next 2 chars char p3 = ' ', p2 = ' ', p = ' ', c = ' ', n = ' ', n2 = ' '; var scriptStartIndex = 0; for (var i = 0; i < batchSql.Length; i++) { // previous 3, current, & next 2 chars // out of bounds chars are treated as whitespace p3 = i > 2 ? batchSql[i - 3] : ' '; p2 = i > 1 ? batchSql[i - 2] : ' '; p = i > 0 ? batchSql[i - 1] : ' '; c = batchSql[i]; n = batchSql.Length > i + 1 ? batchSql[i + 1] : ' '; n2 = batchSql.Length > i + 2 ? batchSql[i + 2] : ' '; switch (state) { case State.Searching: if (IsMultiLineComment(p, c)) state = State.InMultiLineComment; else if (IsOneLineComment(p, c)) state = State.InOneLineComment; else if (c == '[') state = State.InBrackets; else if (c == '\'') state = State.InQuotes; else if (c == '\"') state = State.InDoubleQuotes; else if (IsGO(p3, p2, p, c, n, n2)) foundGO = true; break; case State.InOneLineComment: if (c == '\n') state = State.Searching; break; case State.InMultiLineComment: if (IsEndMultiLineComment(p, c)) commentDepth--; else if (IsMultiLineComment(p, c)) commentDepth++; if (commentDepth < 0) { commentDepth = 0; state = State.Searching; } break; case State.InBrackets: if (c == ']') state = State.Searching; break; case State.InQuotes: if (c == '\'') state = State.Searching; break; case State.InDoubleQuotes: if (c == '\"') state = State.Searching; break; } if (foundGO) { // store the current script and continue searching // set length -1 so 'G' is not included in the script var length = i - scriptStartIndex - 1; scripts.Add(batchSql.Substring(scriptStartIndex, length)); // start the next script after the 'O' in "GO" scriptStartIndex = i + 1; foundGO = false; } else if (i == batchSql.Length - 1) { // end of batch // set lenght +1 to include the current char var length = i - scriptStartIndex + 1; scripts.Add(batchSql.Substring(scriptStartIndex, length)); } } // return scripts that contain non-whitespace return scripts.Where(s => Regex.Match(s, "\\S", RegexOptions.Multiline).Success) .ToArray(); } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\ColumnTest.cs
Test.Unit
ColumnTest
[]
['SchemaZen.Library.Models', 'Xunit']
xUnit
net6.0
public class ColumnTest { public class ScriptCreate { [Fact] public void int_no_trailing_space() { var c = new Column("test", "int", false, null); Assert.Equal("[test] [int] NOT NULL", c.ScriptCreate()); } [Fact] public void varchar_no_trailing_space() { var c = new Column("test", "varchar", 10, false, null); Assert.Equal("[test] [varchar](10) NOT NULL", c.ScriptCreate()); } [Fact] public void decimal_no_trailing_space() { var c = new Column("test", "decimal", 4, 2, false, null); Assert.Equal("[test] [decimal](4,2) NOT NULL", c.ScriptCreate()); } [Fact] public void no_trailing_space_with_default() { var c = new Column("test", "int", true, new Default("df_test", "0", false)); var lines = c.ScriptCreate() .Split(new[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("[test] [int] NULL", lines[0]); Assert.Equal(" CONSTRAINT [df_test] DEFAULT 0", lines[1]); } [Fact] public void no_trailing_space_with_no_name_default() { var c = new Column("test", "int", true, new Default("df_ABCDEF", "0", true)); var lines = c.ScriptCreate() .Split(new[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("[test] [int] NULL", lines[0]); Assert.Equal(" DEFAULT 0", lines[1]); } [Fact] public void computed_column() { var c = new Column("test", "int", false, null) { ComputedDefinition = "(A + B)" }; Assert.Equal("[test] AS (A + B)", c.ScriptCreate()); } [Fact] public void computed_column_persisted() { var c = new Column("test", "int", false, null) { ComputedDefinition = "(A + B)", Persisted = true }; Assert.Equal("[test] AS (A + B) PERSISTED", c.ScriptCreate()); } } }
68
1,793
using System; using System.Text; namespace SchemaZen.Library.Models; public class Column { public Column() { } public Column(string name, string type, bool nullable, Default defaultValue) { Name = name; Type = type; Default = defaultValue; IsNullable = nullable; } public Column(string name, string type, int length, bool nullable, Default defaultValue) : this(name, type, nullable, defaultValue) { Length = length; } public Column( string name, string type, byte precision, int scale, bool nullable, Default defaultValue) : this(name, type, nullable, defaultValue) { Precision = precision; Scale = scale; } public Default Default { get; set; } public Identity Identity { get; set; } public bool IsNullable { get; set; } public int Length { get; set; } public string Name { get; set; } public int Position { get; set; } public byte Precision { get; set; } public int Scale { get; set; } public string Type { get; set; } public string ComputedDefinition { get; set; } public bool IsRowGuidCol { get; set; } public bool IncludeDefaultConstraint => Default != null && Default.ScriptInline; private string IsNullableText { get { if (IsNullable || !string.IsNullOrEmpty(ComputedDefinition)) return "NULL"; return "NOT NULL"; } } public string DefaultText { get { if (Default == null || !string.IsNullOrEmpty(ComputedDefinition)) return ""; return Environment.NewLine + " " + Default.ScriptCreate(); } } public string IdentityText { get { if (Identity == null) return ""; return Environment.NewLine + " " + Identity.Script(); } } public string RowGuidColText => IsRowGuidCol ? " ROWGUIDCOL " : string.Empty; public bool Persisted { get; set; } public ColumnDiff Compare(Column c) { return new ColumnDiff(this, c); } private string ScriptBase() { if (!string.IsNullOrEmpty(ComputedDefinition)) { var persistedSetting = Persisted ? " PERSISTED" : string.Empty; return $"[{Name}] AS {ComputedDefinition}{persistedSetting}"; } var val = new StringBuilder($"[{Name}] [{Type}]"); switch (Type) { case "bigint": case "bit": case "date": case "datetime": case "datetime2": case "datetimeoffset": case "float": case "hierarchyid": case "image": case "int": case "money": case "ntext": case "real": case "smalldatetime": case "smallint": case "smallmoney": case "sql_variant": case "text": case "time": case "timestamp": case "tinyint": case "uniqueidentifier": case "geography": case "xml": case "sysname": case "geometry": val.Append($" {IsNullableText}"); if (IncludeDefaultConstraint) val.Append(DefaultText); if (Identity != null) val.Append(IdentityText); if (IsRowGuidCol) val.Append(RowGuidColText); return val.ToString(); case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": var lengthString = Length.ToString(); if (lengthString == "-1") lengthString = "max"; val.Append($"({lengthString}) {IsNullableText}"); if (IncludeDefaultConstraint) val.Append(DefaultText); return val.ToString(); case "decimal": case "numeric": val.Append($"({Precision},{Scale}) {IsNullableText}"); if (IncludeDefaultConstraint) val.Append(DefaultText); if (Identity != null) val.Append(IdentityText); return val.ToString(); default: throw new NotSupportedException( "Error scripting column " + Name + ". SQL data type " + Type + " is not supported."); } } public string ScriptCreate() { return ScriptBase(); } public string ScriptAlter() { return ScriptBase(); } internal static Type SqlTypeToNativeType(string sqlType) { switch (sqlType.ToLower()) { case "bit": return typeof(bool); case "datetime": case "smalldatetime": return typeof(DateTime); case "int": return typeof(int); case "uniqueidentifier": return typeof(Guid); case "binary": case "varbinary": case "image": case "geometry": case "geography": return typeof(byte[]); default: return typeof(string); } } public Type SqlTypeToNativeType() { return SqlTypeToNativeType(Type); } } public class ColumnDiff { public ColumnDiff(Column target, Column source) { Source = source; Target = target; } public Column Source { get; set; } public Column Target { get; set; } public bool IsDiff => IsDiffBase || DefaultIsDiff; private bool IsDiffBase => Source.IsNullable != Target.IsNullable || Source.Length != Target.Length || Source.Position != Target.Position || Source.Type != Target.Type || Source.Precision != Target.Precision || Source.Scale != Target.Scale || Source.ComputedDefinition != Target.ComputedDefinition || Source.Persisted != Target.Persisted; public bool DefaultIsDiff => Source.DefaultText != Target.DefaultText; public bool OnlyDefaultIsDiff => DefaultIsDiff && !IsDiffBase; /*public string Script() { return Target.Script(); }*/ }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\ColumnTest.cs
Test.Unit
ScriptCreate
[]
['SchemaZen.Library.Models', 'Xunit']
xUnit
net6.0
public class ScriptCreate { [Fact] public void int_no_trailing_space() { var c = new Column("test", "int", false, null); Assert.Equal("[test] [int] NOT NULL", c.ScriptCreate()); } [Fact] public void varchar_no_trailing_space() { var c = new Column("test", "varchar", 10, false, null); Assert.Equal("[test] [varchar](10) NOT NULL", c.ScriptCreate()); } [Fact] public void decimal_no_trailing_space() { var c = new Column("test", "decimal", 4, 2, false, null); Assert.Equal("[test] [decimal](4,2) NOT NULL", c.ScriptCreate()); } [Fact] public void no_trailing_space_with_default() { var c = new Column("test", "int", true, new Default("df_test", "0", false)); var lines = c.ScriptCreate() .Split(new[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("[test] [int] NULL", lines[0]); Assert.Equal(" CONSTRAINT [df_test] DEFAULT 0", lines[1]); } [Fact] public void no_trailing_space_with_no_name_default() { var c = new Column("test", "int", true, new Default("df_ABCDEF", "0", true)); var lines = c.ScriptCreate() .Split(new[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("[test] [int] NULL", lines[0]); Assert.Equal(" DEFAULT 0", lines[1]); } [Fact] public void computed_column() { var c = new Column("test", "int", false, null) { ComputedDefinition = "(A + B)" }; Assert.Equal("[test] AS (A + B)", c.ScriptCreate()); } [Fact] public void computed_column_persisted() { var c = new Column("test", "int", false, null) { ComputedDefinition = "(A + B)", Persisted = true }; Assert.Equal("[test] AS (A + B) PERSISTED", c.ScriptCreate()); } }
95
1,791
using System; using System.Text; namespace SchemaZen.Library.Models; public class Column { public Column() { } public Column(string name, string type, bool nullable, Default defaultValue) { Name = name; Type = type; Default = defaultValue; IsNullable = nullable; } public Column(string name, string type, int length, bool nullable, Default defaultValue) : this(name, type, nullable, defaultValue) { Length = length; } public Column( string name, string type, byte precision, int scale, bool nullable, Default defaultValue) : this(name, type, nullable, defaultValue) { Precision = precision; Scale = scale; } public Default Default { get; set; } public Identity Identity { get; set; } public bool IsNullable { get; set; } public int Length { get; set; } public string Name { get; set; } public int Position { get; set; } public byte Precision { get; set; } public int Scale { get; set; } public string Type { get; set; } public string ComputedDefinition { get; set; } public bool IsRowGuidCol { get; set; } public bool IncludeDefaultConstraint => Default != null && Default.ScriptInline; private string IsNullableText { get { if (IsNullable || !string.IsNullOrEmpty(ComputedDefinition)) return "NULL"; return "NOT NULL"; } } public string DefaultText { get { if (Default == null || !string.IsNullOrEmpty(ComputedDefinition)) return ""; return Environment.NewLine + " " + Default.ScriptCreate(); } } public string IdentityText { get { if (Identity == null) return ""; return Environment.NewLine + " " + Identity.Script(); } } public string RowGuidColText => IsRowGuidCol ? " ROWGUIDCOL " : string.Empty; public bool Persisted { get; set; } public ColumnDiff Compare(Column c) { return new ColumnDiff(this, c); } private string ScriptBase() { if (!string.IsNullOrEmpty(ComputedDefinition)) { var persistedSetting = Persisted ? " PERSISTED" : string.Empty; return $"[{Name}] AS {ComputedDefinition}{persistedSetting}"; } var val = new StringBuilder($"[{Name}] [{Type}]"); switch (Type) { case "bigint": case "bit": case "date": case "datetime": case "datetime2": case "datetimeoffset": case "float": case "hierarchyid": case "image": case "int": case "money": case "ntext": case "real": case "smalldatetime": case "smallint": case "smallmoney": case "sql_variant": case "text": case "time": case "timestamp": case "tinyint": case "uniqueidentifier": case "geography": case "xml": case "sysname": case "geometry": val.Append($" {IsNullableText}"); if (IncludeDefaultConstraint) val.Append(DefaultText); if (Identity != null) val.Append(IdentityText); if (IsRowGuidCol) val.Append(RowGuidColText); return val.ToString(); case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": var lengthString = Length.ToString(); if (lengthString == "-1") lengthString = "max"; val.Append($"({lengthString}) {IsNullableText}"); if (IncludeDefaultConstraint) val.Append(DefaultText); return val.ToString(); case "decimal": case "numeric": val.Append($"({Precision},{Scale}) {IsNullableText}"); if (IncludeDefaultConstraint) val.Append(DefaultText); if (Identity != null) val.Append(IdentityText); return val.ToString(); default: throw new NotSupportedException( "Error scripting column " + Name + ". SQL data type " + Type + " is not supported."); } } public string ScriptCreate() { return ScriptBase(); } public string ScriptAlter() { return ScriptBase(); } internal static Type SqlTypeToNativeType(string sqlType) { switch (sqlType.ToLower()) { case "bit": return typeof(bool); case "datetime": case "smalldatetime": return typeof(DateTime); case "int": return typeof(int); case "uniqueidentifier": return typeof(Guid); case "binary": case "varbinary": case "image": case "geometry": case "geography": return typeof(byte[]); default: return typeof(string); } } public Type SqlTypeToNativeType() { return SqlTypeToNativeType(Type); } } public class ColumnDiff { public ColumnDiff(Column target, Column source) { Source = source; Target = target; } public Column Source { get; set; } public Column Target { get; set; } public bool IsDiff => IsDiffBase || DefaultIsDiff; private bool IsDiffBase => Source.IsNullable != Target.IsNullable || Source.Length != Target.Length || Source.Position != Target.Position || Source.Type != Target.Type || Source.Precision != Target.Precision || Source.Scale != Target.Scale || Source.ComputedDefinition != Target.ComputedDefinition || Source.Persisted != Target.Persisted; public bool DefaultIsDiff => Source.DefaultText != Target.DefaultText; public bool OnlyDefaultIsDiff => DefaultIsDiff && !IsDiffBase; /*public string Script() { return Target.Script(); }*/ }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\ConstraintTest.cs
Test.Unit
ConstraintTest
[]
['SchemaZen.Library.Models', 'Xunit']
xUnit
net6.0
public class ConstraintTest { public class ScriptCreate { private static Constraint SetUp() { return new Constraint("test", "INDEX", "a,b") { Table = new Table("dbo", "test") }; } [Fact] public void clustered_index() { var c = SetUp(); c.IndexType = "CLUSTERED"; Assert.Equal( "CREATE CLUSTERED INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void nonclustered_index() { var c = SetUp(); c.IndexType = "NONCLUSTERED"; Assert.Equal( "CREATE NONCLUSTERED INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void clustered_columnstore_index() { var c = SetUp(); c.IndexType = "CLUSTERED COLUMNSTORE"; Assert.Equal( "CREATE CLUSTERED COLUMNSTORE INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void nonclustered_columnstore_index() { var c = SetUp(); c.IndexType = "NONCLUSTERED COLUMNSTORE"; Assert.Equal( "CREATE NONCLUSTERED COLUMNSTORE INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void primary_key() { var c = SetUp(); c.Type = "PRIMARY KEY"; c.IndexType = "NONCLUSTERED"; Assert.Equal( "CONSTRAINT [test] PRIMARY KEY NONCLUSTERED ([a], [b])", c.ScriptCreate()); } [Fact] public void foreign_key() { var c = SetUp(); c.Type = "FOREIGN KEY"; c.IndexType = "NONCLUSTERED"; Assert.Equal( "CONSTRAINT [test] FOREIGN KEY NONCLUSTERED ([a], [b])", c.ScriptCreate()); } [Fact] public void check_constraint() { var c = Constraint.CreateCheckedConstraint("test", true, false, "[a]>(1)"); Assert.Equal( "CHECK NOT FOR REPLICATION [a]>(1)", c.ScriptCreate()); } } }
68
1,824
using System.Collections.Generic; using System.Linq; using SchemaZen.Library.Extensions; namespace SchemaZen.Library.Models; public class Constraint : INameable, IScriptable { private bool _isNotForReplication; private bool _isSystemNamed; public Constraint(string name, string type, string columns) { Name = name; Type = type; if (!string.IsNullOrEmpty(columns)) Columns = new List<ConstraintColumn>( columns.Split(',') .Select(x => new ConstraintColumn(x, false))); } public string IndexType { get; set; } public List<ConstraintColumn> Columns { get; set; } = new(); public List<string> IncludedColumns { get; set; } = new(); public Table Table { get; set; } public string Type { get; set; } public string Filter { get; set; } public bool Unique { get; set; } public string CheckConstraintExpression { get; private set; } public bool ScriptInline => Table == null || Table != null && Table.IsType; public string UniqueText => Type != " PRIMARY KEY" && !Unique ? "" : " UNIQUE"; public string Name { get; set; } public string ScriptCreate() { switch (Type) { case "CHECK": var notForReplicationOption = _isNotForReplication ? "NOT FOR REPLICATION" : ""; if (ScriptInline) return $"CHECK {notForReplicationOption} {CheckConstraintExpression}"; else return $"ALTER TABLE [{Table.Owner}].[{Table.Name}] WITH CHECK ADD {(_isSystemNamed ? string.Empty : $"CONSTRAINT [{Name}]")} CHECK {notForReplicationOption} {CheckConstraintExpression}"; case "INDEX": var sql = $"CREATE{UniqueText}{IndexType.Space()} INDEX [{Name}] ON [{Table.Owner}].[{Table.Name}] ({string.Join(", ", Columns.Select(c => c.Script()).ToArray())})"; if (IncludedColumns.Count > 0) sql += $" INCLUDE ([{string.Join("], [", IncludedColumns.ToArray())}])"; if (!string.IsNullOrEmpty(Filter)) sql += $" WHERE {Filter}"; return sql; } return (Table.IsType || _isSystemNamed ? string.Empty : $"CONSTRAINT [{Name}] ") + $"{Type}{IndexType.Space()} ({string.Join(", ", Columns.Select(c => c.Script()).ToArray())})"; } public static Constraint CreateCheckedConstraint( string name, bool isNotForReplication, bool isSystemNamed, string checkConstraintExpression) { var constraint = new Constraint(name, "CHECK", "") { _isNotForReplication = isNotForReplication, _isSystemNamed = isSystemNamed, CheckConstraintExpression = checkConstraintExpression }; return constraint; } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\ConstraintTest.cs
Test.Unit
ScriptCreate
[]
['SchemaZen.Library.Models', 'Xunit']
xUnit
net6.0
public class ScriptCreate { private static Constraint SetUp() { return new Constraint("test", "INDEX", "a,b") { Table = new Table("dbo", "test") }; } [Fact] public void clustered_index() { var c = SetUp(); c.IndexType = "CLUSTERED"; Assert.Equal( "CREATE CLUSTERED INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void nonclustered_index() { var c = SetUp(); c.IndexType = "NONCLUSTERED"; Assert.Equal( "CREATE NONCLUSTERED INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void clustered_columnstore_index() { var c = SetUp(); c.IndexType = "CLUSTERED COLUMNSTORE"; Assert.Equal( "CREATE CLUSTERED COLUMNSTORE INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void nonclustered_columnstore_index() { var c = SetUp(); c.IndexType = "NONCLUSTERED COLUMNSTORE"; Assert.Equal( "CREATE NONCLUSTERED COLUMNSTORE INDEX [test] ON [dbo].[test] ([a], [b])", c.ScriptCreate()); } [Fact] public void primary_key() { var c = SetUp(); c.Type = "PRIMARY KEY"; c.IndexType = "NONCLUSTERED"; Assert.Equal( "CONSTRAINT [test] PRIMARY KEY NONCLUSTERED ([a], [b])", c.ScriptCreate()); } [Fact] public void foreign_key() { var c = SetUp(); c.Type = "FOREIGN KEY"; c.IndexType = "NONCLUSTERED"; Assert.Equal( "CONSTRAINT [test] FOREIGN KEY NONCLUSTERED ([a], [b])", c.ScriptCreate()); } [Fact] public void check_constraint() { var c = Constraint.CreateCheckedConstraint("test", true, false, "[a]>(1)"); Assert.Equal( "CHECK NOT FOR REPLICATION [a]>(1)", c.ScriptCreate()); } }
99
1,822
using System.Collections.Generic; using System.Linq; using SchemaZen.Library.Extensions; namespace SchemaZen.Library.Models; public class Constraint : INameable, IScriptable { private bool _isNotForReplication; private bool _isSystemNamed; public Constraint(string name, string type, string columns) { Name = name; Type = type; if (!string.IsNullOrEmpty(columns)) Columns = new List<ConstraintColumn>( columns.Split(',') .Select(x => new ConstraintColumn(x, false))); } public string IndexType { get; set; } public List<ConstraintColumn> Columns { get; set; } = new(); public List<string> IncludedColumns { get; set; } = new(); public Table Table { get; set; } public string Type { get; set; } public string Filter { get; set; } public bool Unique { get; set; } public string CheckConstraintExpression { get; private set; } public bool ScriptInline => Table == null || Table != null && Table.IsType; public string UniqueText => Type != " PRIMARY KEY" && !Unique ? "" : " UNIQUE"; public string Name { get; set; } public string ScriptCreate() { switch (Type) { case "CHECK": var notForReplicationOption = _isNotForReplication ? "NOT FOR REPLICATION" : ""; if (ScriptInline) return $"CHECK {notForReplicationOption} {CheckConstraintExpression}"; else return $"ALTER TABLE [{Table.Owner}].[{Table.Name}] WITH CHECK ADD {(_isSystemNamed ? string.Empty : $"CONSTRAINT [{Name}]")} CHECK {notForReplicationOption} {CheckConstraintExpression}"; case "INDEX": var sql = $"CREATE{UniqueText}{IndexType.Space()} INDEX [{Name}] ON [{Table.Owner}].[{Table.Name}] ({string.Join(", ", Columns.Select(c => c.Script()).ToArray())})"; if (IncludedColumns.Count > 0) sql += $" INCLUDE ([{string.Join("], [", IncludedColumns.ToArray())}])"; if (!string.IsNullOrEmpty(Filter)) sql += $" WHERE {Filter}"; return sql; } return (Table.IsType || _isSystemNamed ? string.Empty : $"CONSTRAINT [{Name}] ") + $"{Type}{IndexType.Space()} ({string.Join(", ", Columns.Select(c => c.Script()).ToArray())})"; } public static Constraint CreateCheckedConstraint( string name, bool isNotForReplication, bool isSystemNamed, string checkConstraintExpression) { var constraint = new Constraint(name, "CHECK", "") { _isNotForReplication = isNotForReplication, _isSystemNamed = isSystemNamed, CheckConstraintExpression = checkConstraintExpression }; return constraint; } }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\DatabaseTest.cs
Test.Unit
DatabaseTest
['private readonly ILogger _logger;']
['Microsoft.Extensions.Logging', 'SchemaZen.Library.Models', 'Xunit', 'Xunit.Abstractions']
xUnit
net6.0
public class DatabaseTest { private readonly ILogger _logger; public DatabaseTest(ITestOutputHelper output) { _logger = output.BuildLogger(); } [Fact] public void TestFindTableRegEx() { var db = CreateSampleDataForRegExTests(); Assert.Equal(3, db.FindTablesRegEx("^cmic").Count); Assert.Single(db.FindTablesRegEx("Location")); } [Fact] public void TestFindTableRegEx_ExcludeOnly() { var db = CreateSampleDataForRegExTests(); Assert.Equal(3, db.FindTablesRegEx(null, "^cmic").Count); Assert.Equal(5, db.FindTablesRegEx(null, "Location").Count); } [Fact] public void TestFindTableRegEx_BothIncludeExclude() { var db = CreateSampleDataForRegExTests(); Assert.Equal(2, db.FindTablesRegEx("^cmic", "Code$").Count); Assert.Empty(db.FindTablesRegEx("Location", "Location")); } private static Database CreateSampleDataForRegExTests() { var db = new Database(); db.Tables.Add(new Table("dbo", "cmicDeductible")); db.Tables.Add(new Table("dbo", "cmicZipCode")); db.Tables.Add(new Table("dbo", "cmicState")); db.Tables.Add(new Table("dbo", "Policy")); db.Tables.Add(new Table("dbo", "Location")); db.Tables.Add(new Table("dbo", "Rate")); return db; } [Fact] public void TestScriptDeletedProc() { var source = new Database(); source.Routines.Add(new Routine("dbo", "test", null)); source.FindRoutine("test", "dbo").RoutineType = Routine.RoutineKind.Procedure; source.FindRoutine("test", "dbo").Text = @" create procedure [dbo].[test] as select * from Table1 "; var target = new Database(); var scriptUp = target.Compare(source).Script(); var scriptDown = source.Compare(target).Script(); Assert.Contains( "drop procedure [dbo].[test]", scriptUp.ToLower()); Assert.Contains( "create procedure [dbo].[test]", scriptDown.ToLower()); } }
130
1,947
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using SchemaZen.Library.Models.Comparers; namespace SchemaZen.Library.Models; public class Database { #region Compare public DatabaseDiff Compare(Database db) { var diff = new DatabaseDiff { Db = db }; //compare database properties foreach (var p in from p in Props let p2 = db.FindProp(p.Name) where p.Script() != p2.Script() select p) diff.PropsChanged.Add(p); //get tables added and changed foreach (var tables in new[] { Tables, TableTypes }) foreach (var t in tables) { var t2 = db.FindTable(t.Name, t.Owner, t.IsType); if (t2 == null) { diff.TablesAdded.Add(t); } else { //compare mutual tables var tDiff = t.Compare(t2); if (!tDiff.IsDiff) continue; if (t.IsType) // types cannot be altered... diff.TableTypesDiff.Add(t); else diff.TablesDiff.Add(tDiff); } } //get deleted tables foreach (var t in db.Tables.Concat(db.TableTypes) .Where(t => FindTable(t.Name, t.Owner, t.IsType) == null)) diff.TablesDeleted.Add(t); //get procs added and changed foreach (var r in Routines) { var r2 = db.FindRoutine(r.Name, r.Owner); if (r2 == null) { diff.RoutinesAdded.Add(r); } else { //compare mutual procs if (r.Text.Trim() != r2.Text.Trim()) diff.RoutinesDiff.Add(r); } } //get procs deleted foreach (var r in db.Routines.Where(r => FindRoutine(r.Name, r.Owner) == null)) diff.RoutinesDeleted.Add(r); //get added and compare mutual foreign keys foreach (var fk in ForeignKeys) { var fk2 = db.FindForeignKey(fk.Name, fk.Table.Owner); if (fk2 == null) { diff.ForeignKeysAdded.Add(fk); } else { if (fk.ScriptCreate() != fk2.ScriptCreate()) diff.ForeignKeysDiff.Add(fk); } } //get deleted foreign keys foreach (var fk in db.ForeignKeys .Where(fk => FindForeignKey(fk.Name, fk.Table.Owner) == null)) diff.ForeignKeysDeleted.Add(fk); //get added and compare mutual assemblies foreach (var a in Assemblies) { var a2 = db.FindAssembly(a.Name); if (a2 == null) { diff.AssembliesAdded.Add(a); } else { if (a.ScriptCreate() != a2.ScriptCreate()) diff.AssembliesDiff.Add(a); } } //get deleted assemblies foreach (var a in db.Assemblies.Where(a => FindAssembly(a.Name) == null)) diff.AssembliesDeleted.Add(a); //get added and compare mutual users foreach (var u in Users) { var u2 = db.FindUser(u.Name); if (u2 == null) { diff.UsersAdded.Add(u); } else { if (u.ScriptCreate() != u2.ScriptCreate()) diff.UsersDiff.Add(u); } } //get deleted users foreach (var u in db.Users.Where(u => FindUser(u.Name) == null)) diff.UsersDeleted.Add(u); //get added and compare view indexes foreach (var c in ViewIndexes) { var c2 = db.FindViewIndex(c.Name); if (c2 == null) { diff.ViewIndexesAdded.Add(c); } else { if (c.ScriptCreate() != c2.ScriptCreate()) diff.ViewIndexesDiff.Add(c); } } //get deleted view indexes foreach (var c in db.ViewIndexes.Where(c => FindViewIndex(c.Name) == null)) diff.ViewIndexesDeleted.Add(c); //get added and compare synonyms foreach (var s in Synonyms) { var s2 = db.FindSynonym(s.Name, s.Owner); if (s2 == null) { diff.SynonymsAdded.Add(s); } else { if (s.BaseObjectName != s2.BaseObjectName) diff.SynonymsDiff.Add(s); } } //get deleted synonyms foreach (var s in db.Synonyms.Where(s => FindSynonym(s.Name, s.Owner) == null)) diff.SynonymsDeleted.Add(s); //get added and compare permissions foreach (var p in Permissions) { var p2 = db.FindPermission(p.Name); if (p2 == null) { diff.PermissionsAdded.Add(p); } else { if (p.ScriptCreate() != p2.ScriptCreate()) diff.PermissionsDiff.Add(p); } } //get deleted permissions foreach (var p in db.Permissions.Where(p => FindPermission(p.Name) == null)) diff.PermissionsDeleted.Add(p); return diff; } #endregion #region " Constructors " private readonly Microsoft.Extensions.Logging.ILogger _logger; public Database( IList<string> filteredTypes = null, Microsoft.Extensions.Logging.ILogger logger = null ) { // todo - make logger not nullable _logger = logger; ResetProps(); filteredTypes = filteredTypes ?? new List<string>(); foreach (var filteredType in filteredTypes) Dirs.Remove(filteredType); } public Database( string name, IList<string> filteredTypes = null, Microsoft.Extensions.Logging.ILogger logger = null ) : this(filteredTypes, logger) { Name = name; } #endregion #region " Properties " public const string SqlWhitespaceOrCommentRegex = @"(?>(?:\s+|--.*?(?:\r|\n)|/\*.*?\*/))"; public const string SqlEnclosedIdentifierRegex = @"\[.+?\]"; public const string SqlQuotedIdentifierRegex = "\".+?\""; public const string SqlRegularIdentifierRegex = @"(?!\d)[\w@$#]+"; // see rules for regular identifiers here https://msdn.microsoft.com/en-us/library/ms175874.aspx public List<SqlAssembly> Assemblies { get; set; } = new(); public string Connection { get; set; } = ""; public List<Table> DataTables { get; set; } = new(); public string Dir { get; set; } = ""; public List<ForeignKey> ForeignKeys { get; set; } = new(); public string Name { get; set; } public List<DbProp> Props { get; set; } = new(); public List<Routine> Routines { get; set; } = new(); public List<Schema> Schemas { get; set; } = new(); public List<Synonym> Synonyms { get; set; } = new(); public List<Table> TableTypes { get; set; } = new(); public List<Table> Tables { get; set; } = new(); public List<UserDefinedType> UserDefinedTypes { get; set; } = new(); public List<Role> Roles { get; set; } = new(); public List<SqlUser> Users { get; set; } = new(); public List<Constraint> ViewIndexes { get; set; } = new(); public List<Permission> Permissions { get; set; } = new(); public DbProp FindProp(string name) { return Props.FirstOrDefault( p => string.Equals(p.Name, name, StringComparison.CurrentCultureIgnoreCase)); } public Table FindTable(string name, string owner, bool isTableType = false) { return FindTableBase(isTableType ? TableTypes : Tables, name, owner); } private static Table FindTableBase(IEnumerable<Table> tables, string name, string owner) { return tables.FirstOrDefault(t => t.Name == name && t.Owner == owner); } public Constraint FindConstraint(string name) { return Tables.SelectMany(t => t.Constraints).FirstOrDefault(c => c.Name == name); } public ForeignKey FindForeignKey(string name, string owner) { return ForeignKeys.FirstOrDefault(fk => fk.Name == name && fk.Table.Owner == owner); } public Routine FindRoutine(string name, string schema) { return Routines.FirstOrDefault(r => r.Name == name && r.Owner == schema); } public SqlAssembly FindAssembly(string name) { return Assemblies.FirstOrDefault(a => a.Name == name); } public SqlUser FindUser(string name) { return Users.FirstOrDefault( u => string.Equals(u.Name, name, StringComparison.CurrentCultureIgnoreCase)); } public Constraint FindViewIndex(string name) { return ViewIndexes.FirstOrDefault(c => c.Name == name); } public Synonym FindSynonym(string name, string schema) { return Synonyms.FirstOrDefault(s => s.Name == name && s.Owner == schema); } public Permission FindPermission(string name) { return Permissions.FirstOrDefault(g => g.Name == name); } public List<Table> FindTablesRegEx(string pattern, string excludePattern = null) { return Tables.Where(t => FindTablesRegExPredicate(t, pattern, excludePattern)).ToList(); } private static bool FindTablesRegExPredicate( Table table, string pattern, string excludePattern) { var include = string.IsNullOrEmpty(pattern) || Regex.IsMatch(table.Name, pattern); var exclude = !string.IsNullOrEmpty(excludePattern) && Regex.IsMatch(table.Name, excludePattern); return include && !exclude; } public static HashSet<string> Dirs { get; } = new() { "user_defined_types", "tables", "foreign_keys", "assemblies", "functions", "procedures", "triggers", "views", "xmlschemacollections", "data", "roles", "users", "synonyms", "table_types", "schemas", "props", "permissions", "check_constraints", "defaults" }; public static string ValidTypes { get { return Dirs.Aggregate((x, y) => x + ", " + y); } } private void SetPropOnOff(string propName, object dbVal) { if (dbVal != DBNull.Value) FindProp(propName).Value = (bool)dbVal ? "ON" : "OFF"; } private void SetPropString(string propName, object dbVal) { if (dbVal != DBNull.Value) FindProp(propName).Value = dbVal.ToString(); } #endregion #region Load public void Load() { ResetProps(); Schemas.Clear(); Tables.Clear(); UserDefinedTypes.Clear(); TableTypes.Clear(); ForeignKeys.Clear(); Routines.Clear(); DataTables.Clear(); ViewIndexes.Clear(); Assemblies.Clear(); Users.Clear(); Synonyms.Clear(); Roles.Clear(); Permissions.Clear(); using (var cn = new SqlConnection(Connection)) { cn.Open(); using (var cm = cn.CreateCommand()) { LoadProps(cm); LoadSchemas(cm); LoadTables(cm); LoadUserDefinedTypes(cm); LoadColumns(cm); LoadColumnIdentities(cm); LoadColumnDefaults(cm); LoadColumnComputes(cm); LoadConstraintsAndIndexes(cm); LoadCheckConstraints(cm); LoadForeignKeys(cm); LoadRoutines(cm); LoadXmlSchemas(cm); LoadCLRAssemblies(cm); LoadUsersAndLogins(cm); LoadSynonyms(cm); LoadRoles(cm); LoadPermissions(cm); } } } private void ResetProps() { Props.Clear(); Props.Add(new DbProp("COMPATIBILITY_LEVEL", "")); Props.Add(new DbProp("COLLATE", "")); Props.Add(new DbProp("AUTO_CLOSE", "")); Props.Add(new DbProp("AUTO_SHRINK", "")); Props.Add(new DbProp("ALLOW_SNAPSHOT_ISOLATION", "")); Props.Add(new DbProp("READ_COMMITTED_SNAPSHOT", "")); Props.Add(new DbProp("RECOVERY", "")); Props.Add(new DbProp("PAGE_VERIFY", "")); Props.Add(new DbProp("AUTO_CREATE_STATISTICS", "")); Props.Add(new DbProp("AUTO_UPDATE_STATISTICS", "")); Props.Add(new DbProp("AUTO_UPDATE_STATISTICS_ASYNC", "")); Props.Add(new DbProp("ANSI_NULL_DEFAULT", "")); Props.Add(new DbProp("ANSI_NULLS", "")); Props.Add(new DbProp("ANSI_PADDING", "")); Props.Add(new DbProp("ANSI_WARNINGS", "")); Props.Add(new DbProp("ARITHABORT", "")); Props.Add(new DbProp("CONCAT_NULL_YIELDS_NULL", "")); Props.Add(new DbProp("NUMERIC_ROUNDABORT", "")); Props.Add(new DbProp("QUOTED_IDENTIFIER", "")); Props.Add(new DbProp("RECURSIVE_TRIGGERS", "")); Props.Add(new DbProp("CURSOR_CLOSE_ON_COMMIT", "")); Props.Add(new DbProp("CURSOR_DEFAULT", "")); Props.Add(new DbProp("TRUSTWORTHY", "")); Props.Add(new DbProp("DB_CHAINING", "")); Props.Add(new DbProp("PARAMETERIZATION", "")); Props.Add(new DbProp("DATE_CORRELATION_OPTIMIZATION", "")); } private void LoadSynonyms(SqlCommand cm) { cm.CommandText = @" select object_schema_name(object_id) as schema_name, name as synonym_name, base_object_name from sys.synonyms"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var synonym = new Synonym( (string)dr["synonym_name"], (string)dr["schema_name"]); synonym.BaseObjectName = (string)dr["base_object_name"]; Synonyms.Add(synonym); } } } private void LoadPermissions(SqlCommand cm) { cm.CommandText = @" select u.name as user_name, object_schema_name(o.id) as object_owner, o.name as object_name, p.permission_name as permission from sys.database_permissions p join sys.sysusers u on p.grantee_principal_id = u.uid join sys.sysobjects o on p.major_id = o.id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var permission = new Permission( (string)dr["user_name"], (string)dr["object_owner"], (string)dr["object_name"], (string)dr["permission"]); Permissions.Add(permission); } } } private void LoadRoles(SqlCommand cm) { cm.CommandText = @" select name from sys.database_principals where type = 'R' and name not in ( -- Ignore default roles, just look for custom ones 'db_accessadmin' , 'db_backupoperator' , 'db_datareader' , 'db_datawriter' , 'db_ddladmin' , 'db_denydatareader' , 'db_denydatawriter' , 'db_owner' , 'db_securityadmin' , 'public' ) "; Role r = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { r = new Role { Name = (string)dr["name"] }; Roles.Add(r); } } } private void LoadUsersAndLogins(SqlCommand cm) { // get users that have access to the database cm.CommandText = @" select dp.name as UserName, USER_NAME(drm.role_principal_id) as AssociatedDBRole, default_schema_name from sys.database_principals dp left outer join sys.database_role_members drm on dp.principal_id = drm.member_principal_id where (dp.type_desc = 'SQL_USER' or dp.type_desc = 'WINDOWS_USER') and dp.sid not in (0x00, 0x01) and dp.name not in ('dbo', 'guest') and dp.is_fixed_role = 0 order by dp.name"; SqlUser u = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { if (u == null || u.Name != (string)dr["UserName"]) u = new SqlUser((string)dr["UserName"], (string)dr["default_schema_name"]); if (!(dr["AssociatedDBRole"] is DBNull)) u.DatabaseRoles.Add((string)dr["AssociatedDBRole"]); if (!Users.Contains(u)) Users.Add(u); } } try { // get sql logins cm.CommandText = @" select sp.name, sl.password_hash from sys.server_principals sp inner join sys.sql_logins sl on sp.principal_id = sl.principal_id and sp.type_desc = 'SQL_LOGIN' where sp.name not like '##%##' and sp.name != 'SA' order by sp.name"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { u = FindUser((string)dr["name"]); if (u != null && !(dr["password_hash"] is DBNull)) u.PasswordHash = (byte[])dr["password_hash"]; } } } catch (SqlException ex) { // todo detect this before query and get rid of try catch _logger?.LogWarning("assumed logins not supported by sql version, ignored ex:"); _logger?.LogWarning(ex.Message); } } private void LoadCLRAssemblies(SqlCommand cm) { try { // get CLR assemblies cm.CommandText = @"select a.name as AssemblyName, a.permission_set_desc, af.name as FileName, af.content from sys.assemblies a inner join sys.assembly_files af on a.assembly_id = af.assembly_id where a.is_user_defined = 1 order by a.name, af.file_id"; SqlAssembly a = null; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { if (a == null || a.Name != (string)dr["AssemblyName"]) a = new SqlAssembly( (string)dr["permission_set_desc"], (string)dr["AssemblyName"]); a.Files.Add( new KeyValuePair<string, byte[]>( (string)dr["FileName"], (byte[])dr["content"])); if (!Assemblies.Contains(a)) Assemblies.Add(a); } } } catch (SqlException ex) { // todo detect this before query and get rid of try catch _logger?.LogWarning("assumed assemblies not supported by sql version, ignored ex:"); _logger?.LogWarning(ex.Message); } } private void LoadXmlSchemas(SqlCommand cm) { try { // get xml schemas cm.CommandText = @" select s.name as DBSchemaName, x.name as XMLSchemaCollectionName, xml_schema_namespace(s.name, x.name) as definition from sys.xml_schema_collections x inner join sys.schemas s on s.schema_id = x.schema_id where s.name != 'sys'"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var r = new Routine( (string)dr["DBSchemaName"], (string)dr["XMLSchemaCollectionName"], this) { Text = string.Format( "CREATE XML SCHEMA COLLECTION {0}.{1} AS N'{2}'", dr["DBSchemaName"], dr["XMLSchemaCollectionName"], dr["definition"]), RoutineType = Routine.RoutineKind.XmlSchemaCollection }; Routines.Add(r); } } } catch (SqlException ex) { // todo detect this before query and get rid of try catch _logger?.LogWarning("assumed xml schemas not supported by sql version, ignored ex:"); _logger?.LogWarning(ex.Message); } } private void LoadRoutines(SqlCommand cm) { //get routines cm.CommandText = @" select s.name as schemaName, o.name as routineName, o.type_desc, m.definition, m.uses_ansi_nulls, m.uses_quoted_identifier, isnull(s2.name, s3.name) as tableSchema, isnull(t.name, v.name) as tableName, tr.is_disabled as trigger_disabled from sys.sql_modules m inner join sys.objects o on m.object_id = o.object_id inner join sys.schemas s on s.schema_id = o.schema_id left join sys.triggers tr on m.object_id = tr.object_id left join sys.tables t on tr.parent_id = t.object_id left join sys.views v on tr.parent_id = v.object_id left join sys.schemas s2 on s2.schema_id = t.schema_id left join sys.schemas s3 on s3.schema_id = v.schema_id where objectproperty(o.object_id, 'IsMSShipped') = 0 "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var r = new Routine((string)dr["schemaName"], (string)dr["routineName"], this); r.Text = dr["definition"] is DBNull ? string.Empty : (string)dr["definition"]; r.AnsiNull = (bool)dr["uses_ansi_nulls"]; r.QuotedId = (bool)dr["uses_quoted_identifier"]; Routines.Add(r); switch ((string)dr["type_desc"]) { case "SQL_STORED_PROCEDURE": r.RoutineType = Routine.RoutineKind.Procedure; break; case "SQL_TRIGGER": r.RoutineType = Routine.RoutineKind.Trigger; r.RelatedTableName = (string)dr["tableName"]; r.RelatedTableSchema = (string)dr["tableSchema"]; r.Disabled = (bool)dr["trigger_disabled"]; break; case "SQL_SCALAR_FUNCTION": case "SQL_INLINE_TABLE_VALUED_FUNCTION": case "SQL_TABLE_VALUED_FUNCTION": r.RoutineType = Routine.RoutineKind.Function; break; case "VIEW": r.RoutineType = Routine.RoutineKind.View; break; } } } } private void LoadCheckConstraints(SqlCommand cm) { cm.CommandText = @" SELECT OBJECT_NAME(o.OBJECT_ID) AS CONSTRAINT_NAME, SCHEMA_NAME(t.schema_id) AS TABLE_SCHEMA, OBJECT_NAME(o.parent_object_id) AS TABLE_NAME, CAST(0 AS bit) AS IS_TYPE, objectproperty(o.object_id, 'CnstIsNotRepl') AS NotForReplication, 'CHECK' AS ConstraintType, cc.definition as CHECK_CLAUSE, cc.is_system_named FROM sys.objects o inner join sys.check_constraints cc on cc.object_id = o.object_id inner join sys.tables t on t.object_id = o.parent_object_id WHERE o.type_desc = 'CHECK_CONSTRAINT' UNION ALL SELECT OBJECT_NAME(o.OBJECT_ID) AS CONSTRAINT_NAME, SCHEMA_NAME(tt.schema_id) AS TABLE_SCHEMA, tt.name AS TABLE_NAME, CAST(1 AS bit) AS IS_TYPE, objectproperty(o.object_id, 'CnstIsNotRepl') AS NotForReplication, 'CHECK' AS ConstraintType, cc.definition as CHECK_CLAUSE, cc.is_system_named FROM sys.objects o inner join sys.check_constraints cc on cc.object_id = o.object_id inner join sys.table_types tt on tt.type_table_object_id = o.parent_object_id WHERE o.type_desc = 'CHECK_CONSTRAINT' ORDER BY TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable( (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var constraint = Constraint.CreateCheckedConstraint( (string)dr["CONSTRAINT_NAME"], Convert.ToBoolean(dr["NotForReplication"]), Convert.ToBoolean(dr["is_system_named"]), (string)dr["CHECK_CLAUSE"] ); t.AddConstraint(constraint); } } } } private void LoadForeignKeys(SqlCommand cm) { //get foreign keys cm.CommandText = @" select TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY'"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); var fk = new ForeignKey((string)dr["CONSTRAINT_NAME"]); fk.Table = t; ForeignKeys.Add(fk); } } //get foreign key props cm.CommandText = @" select CONSTRAINT_NAME, OBJECT_SCHEMA_NAME(fk.parent_object_id) as TABLE_SCHEMA, UPDATE_RULE, DELETE_RULE, fk.is_disabled, fk.is_system_named from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc inner join sys.foreign_keys fk on rc.CONSTRAINT_NAME = fk.name and rc.CONSTRAINT_SCHEMA = OBJECT_SCHEMA_NAME(fk.parent_object_id)"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey( (string)dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]); fk.OnUpdate = (string)dr["UPDATE_RULE"]; fk.OnDelete = (string)dr["DELETE_RULE"]; fk.Check = !(bool)dr["is_disabled"]; fk.IsSystemNamed = (bool)dr["is_system_named"]; } } //get foreign key columns and ref table cm.CommandText = @" select fk.name as CONSTRAINT_NAME, OBJECT_SCHEMA_NAME(fk.parent_object_id) as TABLE_SCHEMA, c1.name as COLUMN_NAME, OBJECT_SCHEMA_NAME(fk.referenced_object_id) as REF_TABLE_SCHEMA, OBJECT_NAME(fk.referenced_object_id) as REF_TABLE_NAME, c2.name as REF_COLUMN_NAME from sys.foreign_keys fk inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id inner join sys.columns c1 on fkc.parent_column_id = c1.column_id and fkc.parent_object_id = c1.object_id inner join sys.columns c2 on fkc.referenced_column_id = c2.column_id and fkc.referenced_object_id = c2.object_id order by fk.name, fkc.constraint_column_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var fk = FindForeignKey( (string)dr["CONSTRAINT_NAME"], (string)dr["TABLE_SCHEMA"]); if (fk == null) continue; fk.Columns.Add((string)dr["COLUMN_NAME"]); fk.RefColumns.Add((string)dr["REF_COLUMN_NAME"]); if (fk.RefTable == null) fk.RefTable = FindTable( (string)dr["REF_TABLE_NAME"], (string)dr["REF_TABLE_SCHEMA"]); } } } private void LoadConstraintsAndIndexes(SqlCommand cm) { //get constraints & indexes cm.CommandText = @" select s.name as schemaName, t.name as tableName, t.baseType, i.name as indexName, c.name as columnName, i.is_primary_key, i.is_unique_constraint, i.is_unique, i.type_desc, i.filter_definition, isnull(ic.is_included_column, 0) as is_included_column, ic.is_descending_key, i.type from ( select object_id, name, schema_id, 'T' as baseType from sys.tables union select object_id, name, schema_id, 'V' as baseType from sys.views union select type_table_object_id, name, schema_id, 'TVT' as baseType from sys.table_types ) t inner join sys.indexes i on i.object_id = t.object_id inner join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id = i.index_id inner join sys.columns c on c.object_id = t.object_id and c.column_id = ic.column_id inner join sys.schemas s on s.schema_id = t.schema_id where i.type_desc != 'HEAP' order by s.name, t.name, i.name, ic.key_ordinal, ic.index_column_id"; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var schemaName = (string)dr["schemaName"]; var tableName = (string)dr["tableName"]; var indexName = (string)dr["indexName"]; var isView = (string)dr["baseType"] == "V"; var t = isView ? new Table(schemaName, tableName) : FindTable(tableName, schemaName, (string)dr["baseType"] == "TVT"); var c = t.FindConstraint(indexName); if (c == null) { c = new Constraint(indexName, "", ""); t.AddConstraint(c); } if (isView) { if (ViewIndexes.Any(v => v.Name == indexName)) c = ViewIndexes.First(v => v.Name == indexName); else ViewIndexes.Add(c); } c.IndexType = dr["type_desc"] as string; c.Unique = (bool)dr["is_unique"]; c.Filter = dr["filter_definition"] as string; if ((bool)dr["is_included_column"]) c.IncludedColumns.Add((string)dr["columnName"]); else c.Columns.Add( new ConstraintColumn( (string)dr["columnName"], (bool)dr["is_descending_key"])); c.Type = "INDEX"; if ((bool)dr["is_primary_key"]) c.Type = "PRIMARY KEY"; if ((bool)dr["is_unique_constraint"]) c.Type = "UNIQUE"; } } } private void LoadColumnComputes(SqlCommand cm) { //get computed column definitions cm.CommandText = @" select object_schema_name(t.object_id) as TABLE_SCHEMA, object_name(t.object_id) as TABLE_NAME, cc.name as COLUMN_NAME, cc.definition as DEFINITION, cc.is_persisted as PERSISTED, cc.is_nullable as NULLABLE, cast(0 as bit) as IS_TYPE from sys.computed_columns cc inner join sys.tables t on cc.object_id = t.object_id UNION ALL select SCHEMA_NAME(tt.schema_id) as TABLE_SCHEMA, tt.name as TABLE_NAME, cc.name as COLUMN_NAME, cc.definition as DEFINITION, cc.is_persisted as PERSISTED, cc.is_nullable as NULLABLE, cast(1 as bit) AS IS_TYPE from sys.computed_columns cc inner join sys.table_types tt on cc.object_id = tt.type_table_object_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable( (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var column = t.Columns.Find((string)dr["COLUMN_NAME"]); if (column != null) { column.ComputedDefinition = (string)dr["DEFINITION"]; column.Persisted = (bool)dr["PERSISTED"]; } } } } } private void LoadColumnDefaults(SqlCommand cm) { //get column defaults cm.CommandText = @" select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, c.name as COLUMN_NAME, d.name as DEFAULT_NAME, d.definition as DEFAULT_VALUE, d.is_system_named as IS_SYSTEM_NAMED, cast(0 AS bit) AS IS_TYPE from sys.tables t inner join sys.columns c on c.object_id = t.object_id inner join sys.default_constraints d on c.column_id = d.parent_column_id and d.parent_object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id UNION ALL select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME, c.name as COLUMN_NAME, d.name as DEFAULT_NAME, d.definition as DEFAULT_VALUE, d.is_system_named as IS_SYSTEM_NAMED, cast(1 AS bit) AS IS_TYPE from sys.table_types tt inner join sys.columns c on c.object_id = tt.type_table_object_id inner join sys.default_constraints d on c.column_id = d.parent_column_id and d.parent_object_id = c.object_id inner join sys.schemas s on s.schema_id = tt.schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) { var t = FindTable( (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"], (bool)dr["IS_TYPE"]); if (t != null) { var c = t.Columns.Find((string)dr["COLUMN_NAME"]); if (c != null) c.Default = new Default( t, c, (string)dr["DEFAULT_NAME"], (string)dr["DEFAULT_VALUE"], (bool)dr["IS_SYSTEM_NAMED"]); } } } } private void LoadColumnIdentities(SqlCommand cm) { //get column identities cm.CommandText = @" select s.name as TABLE_SCHEMA, t.name as TABLE_NAME, c.name AS COLUMN_NAME, i.SEED_VALUE, i.INCREMENT_VALUE from sys.tables t inner join sys.columns c on c.object_id = t.object_id inner join sys.identity_columns i on i.object_id = c.object_id and i.column_id = c.column_id inner join sys.schemas s on s.schema_id = t.schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) try { var t = FindTable((string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); var c = t.Columns.Find((string)dr["COLUMN_NAME"]); var seed = dr["SEED_VALUE"].ToString(); var increment = dr["INCREMENT_VALUE"].ToString(); c.Identity = new Identity(seed, increment); } catch (Exception ex) { throw new ApplicationException( string.Format( "{0}.{1} : {2}", dr["TABLE_SCHEMA"], dr["TABLE_NAME"], ex.Message), ex); } } } private void LoadColumns(SqlCommand cm) { //get columns cm.CommandText = @" select t.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, c.ORDINAL_POSITION, c.IS_NULLABLE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.NUMERIC_SCALE, CASE WHEN COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsRowGuidCol') = 1 THEN 'YES' ELSE 'NO' END AS IS_ROW_GUID_COL from INFORMATION_SCHEMA.COLUMNS c inner join INFORMATION_SCHEMA.TABLES t on t.TABLE_NAME = c.TABLE_NAME and t.TABLE_SCHEMA = c.TABLE_SCHEMA and t.TABLE_CATALOG = c.TABLE_CATALOG where t.TABLE_TYPE = 'BASE TABLE' order by t.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION "; using (var dr = cm.ExecuteReader()) { LoadColumnsBase(dr, Tables); } try { cm.CommandText = @" select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME, c.name as COLUMN_NAME, t.name as DATA_TYPE, c.column_id as ORDINAL_POSITION, CASE WHEN c.is_nullable = 1 THEN 'YES' ELSE 'NO' END as IS_NULLABLE, CASE WHEN t.name = 'nvarchar' and c.max_length > 0 THEN CAST(c.max_length as int)/2 ELSE CAST(c.max_length as int) END as CHARACTER_MAXIMUM_LENGTH, c.precision as NUMERIC_PRECISION, CAST(c.scale as int) as NUMERIC_SCALE, CASE WHEN c.is_rowguidcol = 1 THEN 'YES' ELSE 'NO' END as IS_ROW_GUID_COL from sys.columns c inner join sys.table_types tt on tt.type_table_object_id = c.object_id inner join sys.schemas s on tt.schema_id = s.schema_id inner join sys.types t on t.system_type_id = c.system_type_id and t.user_type_id = c.user_type_id where tt.is_user_defined = 1 order by s.name, tt.name, c.column_id "; using (var dr = cm.ExecuteReader()) { LoadColumnsBase(dr, TableTypes); } } catch (SqlException ex) { // todo - detect this before query and get rid of try catch _logger.LogError( "Assuming sql server version doesn't support table types because" + $"the followign error occurred: {ex.Message}"); } } private static void LoadColumnsBase(IDataReader dr, List<Table> tables) { Table table = null; while (dr.Read()) { var c = new Column { Name = (string)dr["COLUMN_NAME"], Type = (string)dr["DATA_TYPE"], IsNullable = (string)dr["IS_NULLABLE"] == "YES", Position = (int)dr["ORDINAL_POSITION"], IsRowGuidCol = (string)dr["IS_ROW_GUID_COL"] == "YES" }; switch (c.Type) { case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": c.Length = (int)dr["CHARACTER_MAXIMUM_LENGTH"]; break; case "decimal": case "numeric": c.Precision = (byte)dr["NUMERIC_PRECISION"]; c.Scale = (int)dr["NUMERIC_SCALE"]; break; } if (table == null || table.Name != (string)dr["TABLE_NAME"] || table.Owner != (string)dr["TABLE_SCHEMA"]) // only do a lookup if the table we have isn't already the relevant one table = FindTableBase( tables, (string)dr["TABLE_NAME"], (string)dr["TABLE_SCHEMA"]); table.Columns.Add(c); } } private void LoadTables(SqlCommand cm) { //get tables cm.CommandText = @" select TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'"; using (var dr = cm.ExecuteReader()) { LoadTablesBase(dr, false, Tables); } cm.CommandText = @" select s.name as TABLE_SCHEMA, tt.name as TABLE_NAME from sys.table_types tt inner join sys.schemas s on tt.schema_id = s.schema_id where tt.is_user_defined = 1 order by s.name, tt.name"; using (var dr = cm.ExecuteReader()) { LoadTablesBase(dr, true, TableTypes); } } private void LoadUserDefinedTypes(SqlCommand cm) { //get types cm.CommandText = @" select s.name as 'Type_Schema', t.name as 'Type_Name', tt.name as 'Base_Type_Name', t.max_length as 'Max_Length', t.is_nullable as 'Nullable' from sys.types t inner join sys.schemas s on s.schema_id = t.schema_id inner join sys.types tt on t.system_type_id = tt.user_type_id where t.is_user_defined = 1 and t.is_table_type = 0"; using (var dr = cm.ExecuteReader()) { LoadUserDefinedTypesBase(dr, UserDefinedTypes); } } private void LoadUserDefinedTypesBase( SqlDataReader dr, List<UserDefinedType> userDefinedTypes) { while (dr.Read()) userDefinedTypes.Add( new UserDefinedType( (string)dr["Type_Schema"], (string)dr["Type_Name"], (string)dr["Base_Type_Name"], Convert.ToInt16(dr["Max_Length"]), (bool)dr["Nullable"])); } private static void LoadTablesBase( SqlDataReader dr, bool areTableTypes, List<Table> tables) { while (dr.Read()) tables.Add( new Table((string)dr["TABLE_SCHEMA"], (string)dr["TABLE_NAME"]) { IsType = areTableTypes }); } private void LoadSchemas(SqlCommand cm) { //get schemas cm.CommandText = @" select s.name as schemaName, p.name as principalName from sys.schemas s inner join sys.database_principals p on s.principal_id = p.principal_id where s.schema_id < 16384 and s.name not in ('dbo','guest','sys','INFORMATION_SCHEMA') order by schema_id "; using (var dr = cm.ExecuteReader()) { while (dr.Read()) Schemas.Add(new Schema((string)dr["schemaName"], (string)dr["principalName"])); } } private void LoadProps(SqlCommand cm) { var cnStrBuilder = new SqlConnectionStringBuilder(Connection); // query schema for database properties cm.CommandText = @" select [compatibility_level], [collation_name], [is_auto_close_on], [is_auto_shrink_on], [snapshot_isolation_state], [is_read_committed_snapshot_on], [recovery_model_desc], [page_verify_option_desc], [is_auto_create_stats_on], [is_auto_update_stats_on], [is_auto_update_stats_async_on], [is_ansi_null_default_on], [is_ansi_nulls_on], [is_ansi_padding_on], [is_ansi_warnings_on], [is_arithabort_on], [is_concat_null_yields_null_on], [is_numeric_roundabort_on], [is_quoted_identifier_on], [is_recursive_triggers_on], [is_cursor_close_on_commit_on], [is_local_cursor_default], [is_trustworthy_on], [is_db_chaining_on], [is_parameterization_forced], [is_date_correlation_on] from sys.databases where name = @dbname "; cm.Parameters.AddWithValue("@dbname", cnStrBuilder.InitialCatalog); using (IDataReader dr = cm.ExecuteReader()) { if (dr.Read()) { SetPropString("COMPATIBILITY_LEVEL", dr["compatibility_level"]); SetPropString("COLLATE", dr["collation_name"]); SetPropOnOff("AUTO_CLOSE", dr["is_auto_close_on"]); SetPropOnOff("AUTO_SHRINK", dr["is_auto_shrink_on"]); if (dr["snapshot_isolation_state"] != DBNull.Value) FindProp("ALLOW_SNAPSHOT_ISOLATION").Value = (byte)dr["snapshot_isolation_state"] == 0 || (byte)dr["snapshot_isolation_state"] == 2 ? "OFF" : "ON"; SetPropOnOff("READ_COMMITTED_SNAPSHOT", dr["is_read_committed_snapshot_on"]); SetPropString("RECOVERY", dr["recovery_model_desc"]); SetPropString("PAGE_VERIFY", dr["page_verify_option_desc"]); SetPropOnOff("AUTO_CREATE_STATISTICS", dr["is_auto_create_stats_on"]); SetPropOnOff("AUTO_UPDATE_STATISTICS", dr["is_auto_update_stats_on"]); SetPropOnOff( "AUTO_UPDATE_STATISTICS_ASYNC", dr["is_auto_update_stats_async_on"]); SetPropOnOff("ANSI_NULL_DEFAULT", dr["is_ansi_null_default_on"]); SetPropOnOff("ANSI_NULLS", dr["is_ansi_nulls_on"]); SetPropOnOff("ANSI_PADDING", dr["is_ansi_padding_on"]); SetPropOnOff("ANSI_WARNINGS", dr["is_ansi_warnings_on"]); SetPropOnOff("ARITHABORT", dr["is_arithabort_on"]); SetPropOnOff("CONCAT_NULL_YIELDS_NULL", dr["is_concat_null_yields_null_on"]); SetPropOnOff("NUMERIC_ROUNDABORT", dr["is_numeric_roundabort_on"]); SetPropOnOff("QUOTED_IDENTIFIER", dr["is_quoted_identifier_on"]); SetPropOnOff("RECURSIVE_TRIGGERS", dr["is_recursive_triggers_on"]); SetPropOnOff("CURSOR_CLOSE_ON_COMMIT", dr["is_cursor_close_on_commit_on"]); if (dr["is_local_cursor_default"] != DBNull.Value) FindProp("CURSOR_DEFAULT").Value = (bool)dr["is_local_cursor_default"] ? "LOCAL" : "GLOBAL"; SetPropOnOff("TRUSTWORTHY", dr["is_trustworthy_on"]); SetPropOnOff("DB_CHAINING", dr["is_db_chaining_on"]); if (dr["is_parameterization_forced"] != DBNull.Value) FindProp("PARAMETERIZATION").Value = (bool)dr["is_parameterization_forced"] ? "FORCED" : "SIMPLE"; SetPropOnOff("DATE_CORRELATION_OPTIMIZATION", dr["is_date_correlation_on"]); } } } #endregion #region Script public void ScriptToDir(string tableHint = null, Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; if (Directory.Exists(Dir)) { // delete the existing script files log(TraceLevel.Verbose, "Deleting existing files..."); var files = Dirs.Select(dir => Path.Combine(Dir, dir)) .Where(Directory.Exists) .SelectMany(Directory.GetFiles); foreach (var f in files) File.Delete(f); log(TraceLevel.Verbose, "Existing files deleted."); } else { Directory.CreateDirectory(Dir); } WritePropsScript(log); WriteScriptDir("schemas", Schemas.ToArray(), log); WriteScriptDir("tables", Tables.ToArray(), log); foreach (var table in Tables) { WriteScriptDir( "check_constraints", table.Constraints.Where(c => c.Type == "CHECK").ToArray(), log); var defaults = (from c in table.Columns.Items where c.Default != null select c.Default).ToArray(); if (defaults.Any()) WriteScriptDir("defaults", defaults, log); } WriteScriptDir("table_types", TableTypes.ToArray(), log); WriteScriptDir("user_defined_types", UserDefinedTypes.ToArray(), log); WriteScriptDir( "foreign_keys", ForeignKeys.OrderBy(x => x, ForeignKeyComparer.Instance).ToArray(), log); foreach (var routineType in Routines.GroupBy(x => x.RoutineType)) { var dir = routineType.Key.ToString().ToLower() + "s"; WriteScriptDir(dir, routineType.ToArray(), log); } WriteScriptDir("views", ViewIndexes.ToArray(), log); WriteScriptDir("assemblies", Assemblies.ToArray(), log); WriteScriptDir("roles", Roles.ToArray(), log); WriteScriptDir("users", Users.ToArray(), log); WriteScriptDir("synonyms", Synonyms.ToArray(), log); WriteScriptDir("permissions", Permissions.ToArray(), log); ExportData(tableHint, log); } private void WritePropsScript(Action<TraceLevel, string> log) { if (!Dirs.Contains("props")) return; log(TraceLevel.Verbose, "Scripting database properties..."); var text = new StringBuilder(); text.Append(ScriptPropList(Props)); text.AppendLine("GO"); text.AppendLine(); File.WriteAllText($"{Dir}/props.sql", text.ToString()); } private void WriteScriptDir( string name, ICollection<IScriptable> objects, Action<TraceLevel, string> log) { if (!objects.Any()) return; if (!Dirs.Contains(name)) return; var dir = Path.Combine(Dir, name); Directory.CreateDirectory(dir); var index = 0; foreach (var o in objects) { log( TraceLevel.Verbose, $"Scripting {name} {++index} of {objects.Count}...{(index < objects.Count ? "\r" : string.Empty)}"); var filePath = Path.Combine(dir, MakeFileName(o) + ".sql"); var script = o.ScriptCreate() + "\r\nGO\r\n"; File.AppendAllText(filePath, script); } } private static string MakeFileName(object o) { // combine foreign keys into one script per table var fk = o as ForeignKey; if (fk != null) return MakeFileName(fk.Table); // combine defaults into one script per table if (o is Default) return MakeFileName((o as Default).Table); // combine check constraints into one script per table if (o is Constraint && (o as Constraint).Type == "CHECK") return MakeFileName((o as Constraint).Table); var schema = o as IHasOwner == null ? "" : (o as IHasOwner).Owner; var name = o as INameable == null ? "" : (o as INameable).Name; var fileName = MakeFileName(schema, name); // prefix user defined types with TYPE_ var prefix = o as Table == null ? "" : (o as Table).IsType ? "TYPE_" : ""; return string.Concat(prefix, fileName); } private static string MakeFileName(string schema, string name) { // Dont' include schema name for objects in the dbo schema. // This maintains backward compatability for those who use // SchemaZen to keep their schemas under version control. var fileName = name; if (!string.IsNullOrEmpty(schema) && schema.ToLower() != "dbo") fileName = $"{schema}.{name}"; return Path.GetInvalidFileNameChars() .Aggregate( fileName, (current, invalidChar) => current.Replace(invalidChar, '-')); } public void ExportData(string tableHint = null, Action<TraceLevel, string> log = null) { if (!DataTables.Any()) return; var dataDir = Dir + "/data"; if (!Directory.Exists(dataDir)) Directory.CreateDirectory(dataDir); log?.Invoke(TraceLevel.Info, "Exporting data..."); var index = 0; foreach (var t in DataTables) { log?.Invoke( TraceLevel.Verbose, $"Exporting data from {t.Owner + "." + t.Name} (table {++index} of {DataTables.Count})..."); var filePathAndName = dataDir + "/" + MakeFileName(t) + ".tsv"; var sw = File.CreateText(filePathAndName); t.ExportData(Connection, sw, tableHint); sw.Flush(); if (sw.BaseStream.Length == 0) { log?.Invoke( TraceLevel.Verbose, $" No data to export for {t.Owner + "." + t.Name}, deleting file..."); sw.Close(); File.Delete(filePathAndName); } else { sw.Close(); } } } public static string ScriptPropList(IList<DbProp> props) { var text = new StringBuilder(); text.AppendLine("DECLARE @DB VARCHAR(255)"); text.AppendLine("SET @DB = DB_NAME()"); foreach (var p in props.Select(p => p.Script()).Where(p => !string.IsNullOrEmpty(p))) text.AppendLine(p); return text.ToString(); } #endregion #region Create public void ImportData(Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; var dataDir = Dir + "\\data"; if (!Directory.Exists(dataDir)) { log(TraceLevel.Verbose, "No data to import."); return; } log(TraceLevel.Verbose, "Loading database schema..."); Load(); // load the schema first so we can import data log(TraceLevel.Verbose, "Database schema loaded."); log(TraceLevel.Info, "Importing data..."); foreach (var f in Directory.GetFiles(dataDir)) { var fi = new FileInfo(f); var schema = "dbo"; var table = Path.GetFileNameWithoutExtension(fi.Name); if (table.Contains(".")) { schema = fi.Name.Split('.')[0]; table = fi.Name.Split('.')[1]; } var t = FindTable(table, schema); if (t == null) { log( TraceLevel.Warning, $"Warning: found data file '{fi.Name}', but no corresponding table in database..."); continue; } try { log(TraceLevel.Verbose, $"Importing data for table {schema}.{table}..."); t.ImportData(Connection, fi.FullName); } catch (SqlBatchException ex) { throw new DataFileException(ex.Message, fi.FullName, ex.LineNumber); } catch (Exception ex) { throw new DataFileException(ex.Message, fi.FullName, -1); } } log(TraceLevel.Info, "Data imported successfully."); } public void CreateFromDir( bool overwrite, string databaseFilesPath = null, Action<TraceLevel, string> log = null) { if (log == null) log = (tl, s) => { }; if (DBHelper.DbExists(Connection)) { _logger?.LogTrace("Dropping existing database..."); DBHelper.DropDb(Connection); _logger?.LogTrace("Existing database dropped."); } _logger?.LogTrace("Creating database..."); DBHelper.CreateDb(Connection, databaseFilesPath); //run scripts if (File.Exists(Dir + "/props.sql")) { _logger?.LogTrace("Setting database properties..."); try { DBHelper.ExecBatchSql(Connection, File.ReadAllText(Dir + "/props.sql")); } catch (SqlBatchException ex) { throw new SqlFileException(Dir + "/props.sql", ex); } // COLLATE can cause connection to be reset // so clear the pool so we get a new connection DBHelper.ClearPool(Connection); } // stage 0: everything not in another stage // stage 1: after_data & foreign keys _logger?.LogTrace("Creating database objects..."); var stages = GetScriptStages(); for (var i = 0; i < stages.Count; i++) { if (i == 2) ImportData(log); // load data before stage 2 _logger?.LogTrace($"running stage {i}"); var errors = RunStage(GetScripts(stages[i])); if (errors.Count > 0) { _logger?.LogCritical("Aborting due to unresolved errors"); var ex = new BatchSqlFileException { Exceptions = errors }; throw ex; } } } private List<HashSet<string>> GetScriptStages() { // stage zero objects must never have dependencies var stage0 = new HashSet<string> { "roles" }; // runs after most objects have been created // permissions are inlcued here because they tie a user to another object var stage2 = new HashSet<string> { "permissions" }; // stage3 runs after data has been imported var stage3 = new HashSet<string> { "after_data", "foreign_keys" }; var stage1 = Dirs .Except(stage0) .Except(stage2) .Except(stage3) .ToHashSet(); var itemsByStage = new List<HashSet<string>> { stage0, stage1, stage2, stage3 }; foreach (var stage in itemsByStage) stage.RemoveWhere( x => { var path = Path.Combine(Dir, x); return !Directory.Exists(path) && !File.Exists(path); }); return itemsByStage; } private List<string> GetScripts(HashSet<string> items) { var scripts = new List<string>(); foreach (var item in items) { var path = Path.Combine(Dir, item); if (item.EndsWith(".sql")) scripts.Add(path); else scripts.AddRange(Directory.GetFiles(path, "*.sql")); } return scripts; } private List<SqlFileException> RunStage(List<string> scripts) { // resolve dependencies by trying over and over // if the number of failures stops decreasing then give up var errors = new List<SqlFileException>(); var prevCount = -1; var attempt = 1; while (scripts.Count > 0 && (prevCount == -1 || errors.Count < prevCount)) { if (errors.Count > 0) { prevCount = errors.Count; attempt++; _logger?.LogTrace($"{errors.Count} errors occurred, retrying..."); } errors.Clear(); var index = 0; var total = scripts.Count; foreach (var f in scripts.ToArray()) { _logger?.LogTrace( $"Executing script {++index} of {total}...{(index < total ? "\r" : string.Empty)}"); _logger?.LogTrace($"file name: {f}"); try { DBHelper.ExecBatchSql(Connection, File.ReadAllText(f)); scripts.Remove(f); } catch (SqlBatchException ex) { _logger?.LogTrace($"attempt {attempt}: {f}@{ex.LineNumber} {ex.Message}"); errors.Add(new SqlFileException(f, ex)); } } } if (errors.Any()) foreach (var error in errors) _logger?.LogError(error.Message); return errors; } #endregion }
sethreno
schemazen
F:\Projects\TestMap\Temp\schemazen\SchemaZen.sln
F:\Projects\TestMap\Temp\schemazen\Test\Test.csproj
F:\Projects\TestMap\Temp\schemazen\Test\Unit\TableTest.cs
Test.Unit
TableTest
['private readonly ILogger _logger;']
['Microsoft.Extensions.Logging', 'SchemaZen.Library.Models', 'Xunit', 'Xunit.Abstractions']
xUnit
net6.0
public class TableTest { private readonly ILogger _logger; public TableTest(ITestOutputHelper output) { _logger = output.BuildLogger(); } [Fact] public void CompareConstraints() { var t1 = new Table("dbo", "Test"); var t2 = new Table("dbo", "Test"); var diff = default(TableDiff); //test equal t1.Columns.Add(new Column("first", "varchar", 30, false, null)); t2.Columns.Add(new Column("first", "varchar", 30, false, null)); t1.AddConstraint( Constraint.CreateCheckedConstraint("IsTomorrow", true, false, "fnTomorrow()")); t2.AddConstraint( Constraint.CreateCheckedConstraint("IsTomorrow", false, false, "Tomorrow <> 1")); diff = t1.Compare(t2); Assert.Single(diff.ConstraintsChanged); Assert.NotNull(diff); Assert.True(diff.IsDiff); } [Fact] public void TestCompare() { var t1 = new Table("dbo", "Test"); var t2 = new Table("dbo", "Test"); var diff = default(TableDiff); //test equal t1.Columns.Add(new Column("first", "varchar", 30, false, null)); t2.Columns.Add(new Column("first", "varchar", 30, false, null)); t1.AddConstraint(new Constraint("PK_Test", "PRIMARY KEY", "first")); t2.AddConstraint(new Constraint("PK_Test", "PRIMARY KEY", "first")); diff = t1.Compare(t2); Assert.NotNull(diff); Assert.False(diff.IsDiff); //test add t1.Columns.Add(new Column("second", "varchar", 30, false, null)); diff = t1.Compare(t2); Assert.True(diff.IsDiff); Assert.Single(diff.ColumnsAdded); //test delete diff = t2.Compare(t1); Assert.True(diff.IsDiff); Assert.Single(diff.ColumnsDropped); //test diff t1.Columns.Items[0].Length = 20; diff = t1.Compare(t2); Assert.True(diff.IsDiff); Assert.Single(diff.ColumnsDiff); _logger.LogTrace("--- create ----"); _logger.LogTrace(t1.ScriptCreate()); _logger.LogTrace("--- migrate up ---"); _logger.LogTrace(t1.Compare(t2).Script()); _logger.LogTrace("--- migrate down ---"); _logger.LogTrace(t2.Compare(t1).Script()); } [Fact] public void TestScriptNonSupportedColumn() { Assert.Throws<NotSupportedException>( () => { var t = new Table("dbo", "bla"); t.Columns.Add(new Column("a", "madeuptype", true, null)); t.ScriptCreate(); }); } }
130
2,338
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace SchemaZen.Library.Models; public class Table : INameable, IHasOwner, IScriptable { private const string _tab = "\t"; private const string _escapeTab = "--SchemaZenTAB--"; private const string _carriageReturn = "\r"; private const string _escapeCarriageReturn = "--SchemaZenCR--"; private const string _lineFeed = "\n"; private const string _escapeLineFeed = "--SchemaZenLF--"; private const string _nullValue = "--SchemaZenNull--"; private const string _dateTimeFormat = "yyyy-MM-dd HH:mm:ss.FFFFFFF"; public const int RowsInBatch = 15000; // TODO allow users to configure these private static readonly string _rowSeparator = Environment.NewLine; private readonly List<Constraint> _constraints = new(); public ColumnList Columns = new(); public bool IsType; public Table(string owner, string name) { Owner = owner; Name = name; } public Constraint PrimaryKey { get { return _constraints.FirstOrDefault(c => c.Type == "PRIMARY KEY"); } } public IEnumerable<Constraint> Constraints => _constraints.AsEnumerable(); public string Owner { get; set; } public string Name { get; set; } public string ScriptCreate() { var text = new StringBuilder(); text.Append( $"CREATE {(IsType ? "TYPE" : "TABLE")} [{Owner}].[{Name}] {(IsType ? "AS TABLE " : string.Empty)}(\r\n"); text.Append(Columns.Script()); if (_constraints.Count > 0) text.AppendLine(); if (!IsType) foreach (var c in _constraints.OrderBy(x => x.Name) .Where(c => c.Type == "PRIMARY KEY" || c.Type == "UNIQUE")) text.AppendLine(" ," + c.ScriptCreate()); else foreach (var c in _constraints.OrderBy(x => x.Name).Where(c => c.Type != "INDEX")) text.AppendLine(" ," + c.ScriptCreate()); text.AppendLine(")"); text.AppendLine(); foreach (var c in _constraints.Where(c => c.Type == "INDEX")) text.AppendLine(c.ScriptCreate()); return text.ToString(); } public Constraint FindConstraint(string name) { return _constraints.FirstOrDefault(c => c.Name == name); } public void AddConstraint(Constraint constraint) { constraint.Table = this; _constraints.Add(constraint); } public void RemoveContraint(Constraint constraint) { _constraints.Remove(constraint); } public TableDiff Compare(Table t) { var diff = new TableDiff { Owner = t.Owner, Name = t.Name }; //get additions and compare mutual columns foreach (var c in Columns.Items) { var c2 = t.Columns.Find(c.Name); if (c2 == null) { diff.ColumnsAdded.Add(c); } else { //compare mutual columns var cDiff = c.Compare(c2); if (cDiff.IsDiff) diff.ColumnsDiff.Add(cDiff); } } //get deletions foreach (var c in t.Columns.Items.Where(c => Columns.Find(c.Name) == null)) diff.ColumnsDropped.Add(c); if (!t.IsType) { //get added and compare mutual constraints foreach (var c in Constraints) { var c2 = t.FindConstraint(c.Name); if (c2 == null) { diff.ConstraintsAdded.Add(c); } else { if (c.ScriptCreate() != c2.ScriptCreate()) diff.ConstraintsChanged.Add(c); } } //get deleted constraints foreach (var c in t.Constraints.Where(c => FindConstraint(c.Name) == null)) diff.ConstraintsDeleted.Add(c); } else { // compare constraints on table types, which can't be named in the script, but have names in the DB var dest = Constraints.ToList(); var src = t.Constraints.ToList(); var j = from c1 in dest join c2 in src on c1.ScriptCreate() equals c2.ScriptCreate() into match //new { c1.Type, c1.Unique, c1.Clustered, Columns = string.Join(",", c1.Columns.ToArray()), IncludedColumns = string.Join(",", c1.IncludedColumns.ToArray()) } equals new { c2.Type, c2.Unique, c2.Clustered, Columns = string.Join(",", c2.Columns.ToArray()), IncludedColumns = string.Join(",", c2.IncludedColumns.ToArray()) } into match from m in match.DefaultIfEmpty() select new { c1, m }; foreach (var c in j) if (c.m == null) diff.ConstraintsAdded.Add(c.c1); else src.Remove(c.m); foreach (var c in src) diff.ConstraintsDeleted.Add(c); } return diff; } public string ScriptDrop() { return $"DROP {(IsType ? "TYPE" : "TABLE")} [{Owner}].[{Name}]"; } public void ExportData(string conn, TextWriter data, string tableHint = null) { if (IsType) throw new InvalidOperationException(); var sql = new StringBuilder(); sql.Append("select "); var cols = Columns.Items.Where(c => string.IsNullOrEmpty(c.ComputedDefinition)) .ToArray(); foreach (var c in cols) sql.Append($"[{c.Name}],"); sql.Remove(sql.Length - 1, 1); sql.Append($" from [{Owner}].[{Name}]"); if (!string.IsNullOrEmpty(tableHint)) sql.Append($" WITH ({tableHint})"); AppendOrderBy(sql, cols); using (var cn = new SqlConnection(conn)) { cn.Open(); using (var cm = cn.CreateCommand()) { cm.CommandText = sql.ToString(); using (var dr = cm.ExecuteReader()) { while (dr.Read()) { foreach (var c in cols) { var ordinal = dr.GetOrdinal(c.Name); if (dr.IsDBNull(ordinal)) data.Write(_nullValue); else if (dr.GetDataTypeName(ordinal).EndsWith(".sys.geometry") || dr.GetDataTypeName(ordinal).EndsWith(".sys.geography")) // https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2012/ms143179(v=sql.110)?redirectedfrom=MSDN#sql-clr-data-types-geometry-geography-and-hierarchyid data.Write(StringUtil.ToHexString(dr.GetSqlBytes(ordinal).Value)); else if (dr[c.Name] is byte[]) data.Write(StringUtil.ToHexString((byte[])dr[c.Name])); else if (dr[c.Name] is DateTime) data.Write( ((DateTime)dr[c.Name]) .ToString(_dateTimeFormat, CultureInfo.InvariantCulture)); else if (dr[c.Name] is float || dr[c.Name] is double || dr[c.Name] is decimal) data.Write( Convert.ToString( dr[c.Name], CultureInfo.InvariantCulture)); else data.Write( dr[c.Name] .ToString() .Replace(_tab, _escapeTab) .Replace(_lineFeed, _escapeLineFeed) .Replace(_carriageReturn, _escapeCarriageReturn)); if (c != cols.Last()) data.Write(_tab); } data.WriteLine(); } } } } } public void ImportData(string conn, string filename) { if (IsType) throw new InvalidOperationException(); var dt = new DataTable(); var cols = Columns.Items.Where(c => string.IsNullOrEmpty(c.ComputedDefinition)) .ToArray(); foreach (var c in cols) dt.Columns.Add(new DataColumn(c.Name, c.SqlTypeToNativeType())); var linenumber = 0; var batch_rows = 0; using (var bulk = new SqlBulkCopy( conn, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.TableLock)) { foreach (var colName in dt.Columns.OfType<DataColumn>().Select(c => c.ColumnName)) bulk.ColumnMappings.Add(colName, colName); bulk.DestinationTableName = $"[{Owner}].[{Name}]"; using (var file = new StreamReader(filename)) { var line = new List<char>(); while (file.Peek() >= 0) { var rowsep_cnt = 0; line.Clear(); while (file.Peek() >= 0) { var ch = (char)file.Read(); line.Add(ch); if (ch == _rowSeparator[rowsep_cnt]) rowsep_cnt++; else rowsep_cnt = 0; if (rowsep_cnt == _rowSeparator.Length) { // Remove rowseparator from line line.RemoveRange( line.Count - _rowSeparator.Length, _rowSeparator.Length); break; } } linenumber++; // Skip empty lines if (line.Count == 0) continue; batch_rows++; var row = dt.NewRow(); var fields = new string(line.ToArray()).Split( new[] { _tab }, StringSplitOptions.None); if (fields.Length != dt.Columns.Count) throw new DataFileException( "Incorrect number of columns", filename, linenumber); for (var j = 0; j < fields.Length; j++) try { row[j] = ConvertType( cols[j].Type, fields[j] .Replace(_escapeLineFeed, _lineFeed) .Replace(_escapeCarriageReturn, _carriageReturn) .Replace(_escapeTab, _tab)); } catch (FormatException ex) { throw new DataFileException( $"{ex.Message} at column {j + 1}", filename, linenumber); } dt.Rows.Add(row); if (batch_rows == RowsInBatch) { batch_rows = 0; bulk.WriteToServer(dt); dt.Clear(); } } } bulk.WriteToServer(dt); bulk.Close(); } } public static object ConvertType(string sqlType, string val) { if (val == _nullValue) return DBNull.Value; switch (sqlType.ToLower()) { case "bit": //added for compatibility with bcp if (val == "0") val = "False"; if (val == "1") val = "True"; return bool.Parse(val); case "datetime": case "smalldatetime": return DateTime.Parse(val, CultureInfo.InvariantCulture); case "int": return int.Parse(val); case "float": return double.Parse(val, CultureInfo.InvariantCulture); case "decimal": return decimal.Parse(val, CultureInfo.InvariantCulture); case "uniqueidentifier": return new Guid(val); case "binary": case "varbinary": case "image": case "geometry": case "geography": return StringUtil.FromHexString(val); default: return val; } } private void AppendOrderBy(StringBuilder sql, IEnumerable<Column> cols) { sql.Append(" ORDER BY "); if (PrimaryKey != null) { var pkColumns = PrimaryKey.Columns.Select(c => $"[{c.ColumnName}]"); sql.Append(string.Join(",", pkColumns.ToArray())); return; } var uk = Constraints.Where(c => c.Unique) .OrderBy(c => c.Columns.Count) .ThenBy(c => c.Name) .FirstOrDefault(); if (uk != null) { var ukColumns = uk.Columns.Select(c => $"[{c.ColumnName}]"); sql.Append(string.Join(",", ukColumns.ToArray())); return; } var allColumns = cols.Select(c => $"[{c.Name}]"); sql.Append(string.Join(",", allColumns.ToArray())); } } public class TableDiff { public List<Column> ColumnsAdded = new(); public List<ColumnDiff> ColumnsDiff = new(); public List<Column> ColumnsDropped = new(); public List<Constraint> ConstraintsAdded = new(); public List<Constraint> ConstraintsChanged = new(); public List<Constraint> ConstraintsDeleted = new(); public string Name; public string Owner; public bool IsDiff => ColumnsAdded.Count + ColumnsDropped.Count + ColumnsDiff.Count + ConstraintsAdded.Count + ConstraintsChanged.Count + ConstraintsDeleted.Count > 0; public string Script() { var text = new StringBuilder(); foreach (var c in ColumnsAdded) text.Append($"ALTER TABLE [{Owner}].[{Name}] ADD {c.ScriptCreate()}\r\n"); foreach (var c in ColumnsDropped) text.Append($"ALTER TABLE [{Owner}].[{Name}] DROP COLUMN [{c.Name}]\r\n"); foreach (var c in ColumnsDiff) { if (c.DefaultIsDiff) { if (c.Source.Default != null) text.Append( $"ALTER TABLE [{Owner}].[{Name}] {c.Source.Default.ScriptDrop()}\r\n"); if (c.Target.Default != null) text.Append( $"ALTER TABLE [{Owner}].[{Name}] {c.Target.Default.ScriptCreate(c.Target)}\r\n"); } if (!c.OnlyDefaultIsDiff) text.Append( $"ALTER TABLE [{Owner}].[{Name}] ALTER COLUMN {c.Target.ScriptAlter()}\r\n"); } void ScriptUnspported(Constraint c) { text.AppendLine("-- constraint added that SchemaZen doesn't support yet"); text.AppendLine("/*"); text.AppendLine(c.ScriptCreate()); text.AppendLine("*/"); } foreach (var c in ConstraintsAdded) switch (c.Type) { case "CHECK": case "INDEX": text.Append($"ALTER TABLE [{Owner}].[{Name}] ADD {c.ScriptCreate()}\r\n"); break; default: ScriptUnspported(c); break; } foreach (var c in ConstraintsChanged) switch (c.Type) { case "CHECK": text.Append($"-- Check constraint {c.Name} changed\r\n"); text.Append($"ALTER TABLE [{Owner}].[{Name}] DROP CONSTRAINT {c.Name}\r\n"); text.Append($"ALTER TABLE [{Owner}].[{Name}] ADD {c.ScriptCreate()}\r\n"); break; case "INDEX": text.Append($"-- Index {c.Name} changed\r\n"); text.Append($"DROP INDEX {c.Name} ON [{Owner}].[{Name}]\r\n"); text.Append($"{c.ScriptCreate()}\r\n"); break; default: ScriptUnspported(c); break; } foreach (var c in ConstraintsDeleted) text.Append( c.Type != "INDEX" ? $"ALTER TABLE [{Owner}].[{Name}] DROP CONSTRAINT {c.Name}\r\n" : $"DROP INDEX {c.Name} ON [{Owner}].[{Name}]\r\n"); return text.ToString(); } }
kthompson
glob
F:\Projects\TestMap\Temp\glob\Glob.sln
F:\Projects\TestMap\Temp\glob\test\Glob.Tests\Glob.Tests.csproj
F:\Projects\TestMap\Temp\glob\test\Glob.Tests\GlobExtensionTests.cs
GlobExpressions.Tests
GlobExtensionTests
[]
['System', 'System.IO', 'System.Linq', 'Xunit', 'GlobExpressions.Tests.TestHelpers']
xUnit
null
public class GlobExtensionTests { [Fact] public void CanMatchBinFolderGlob() { var root = new DirectoryInfo(SourceRoot); var allBinFolders = root.GlobDirectories("**/bin"); Assert.True(allBinFolders.Any(), "There should be some bin folders"); } [Fact] public void CanMatchBinFolderGlobCaseInsensitive() { var root = new DirectoryInfo(SourceRoot); var allBinFolders = root.GlobDirectories("**/BIN", GlobOptions.CaseInsensitive); Assert.True(allBinFolders.Any(), "There should be some BIN folders"); } [Fact] public void CanMatchDllExtension() { var root = new DirectoryInfo(SourceRoot); var allDllFiles = root.GlobFiles("**/*.dll"); Assert.True(allDllFiles.Any(), "There should be some DLL files"); } [Fact] public void CanMatchDllExtensionCaseInsensitive() { var root = new DirectoryInfo(SourceRoot); var allDllFiles = root.GlobFiles("**/*.DLL", GlobOptions.CaseInsensitive); Assert.True(allDllFiles.Any(), "There should be some DLL files"); } [Fact] public void CanMatchInfoInFileSystemInfo() { var root = new DirectoryInfo(SourceRoot); var allInfoFilesAndFolders = root.GlobFileSystemInfos("**/*info"); Assert.True(allInfoFilesAndFolders.Any(), "There should be some 'allInfoFilesAndFolders'"); } [Fact] public void CanMatchInfoInFileSystemInfoCaseInsensitive() { var root = new DirectoryInfo(SourceRoot); var allInfoFilesAndFolders = root.GlobFileSystemInfos("**/*INFO", GlobOptions.CaseInsensitive); Assert.True(allInfoFilesAndFolders.Any(), "There should be some 'allINFOFilesAndFolders'"); } [Fact] public void CanMatchConfigFilesInMsDirectory() { var globPattern = @"**/*.sln"; var root = new DirectoryInfo(SourceRoot); var result = root.GlobFiles(globPattern).ToList(); Assert.NotNull(result); Assert.True(result.Any(x => x.Name == "Glob.sln"), $"There should be some Glob.sln files in '{root.FullName}'"); } [Fact] public void CanMatchStarThenPath() { var globPattern = @"*/*/*.csproj"; var root = new DirectoryInfo(SourceRoot); var result = root.GlobFiles(globPattern).OrderBy(x => x.Name.ToLower()).ToList(); Assert.Collection( result, file => Assert.Equal("Glob.Benchmarks.csproj", file.Name), file => Assert.Equal("Glob.csproj", file.Name), file => Assert.Equal("Glob.Tests.csproj", file.Name), file => Assert.Equal("GlobApp.csproj", file.Name) ); } [Fact] public void CanMatchConfigFilesOrFoldersInMsDirectory() { var globPattern = @"**/*[Tt]est*"; var root = new DirectoryInfo(SourceRoot); var result = root.GlobFileSystemInfos(globPattern).ToList(); Assert.NotNull(result); Assert.True(result.Any(x => x.Name == "GlobTests.cs"), $"There should be some GlobTests.cs files in '{root.FullName}'"); Assert.True(result.Any(x => x.Name == "test"), $"There should some folder with 'test' in '{root.FullName}'"); } [Fact] public void CanMatchDirectoriesInMsDirectory() { var globPattern = @"**/*Gl*.Te*"; var root = new DirectoryInfo(SourceRoot); var result = root.GlobDirectories(globPattern).ToList(); Assert.NotNull(result); Assert.True(result.Any(), $"There should be some directories that match glob: {globPattern} in '{root.FullName}'"); } [Fact] public void CanMatchFilesInDirectoriesWithTrailingSlash() { var globPattern = @"test/**/*Gl*.Te*"; var root = new DirectoryInfo(SourceRoot + Path.DirectorySeparatorChar).FullName; var result = Glob.Files(root, globPattern).ToList(); Assert.NotNull(result); Assert.All(result, path => Assert.StartsWith("test", path)); Assert.True(result.Any(), $"There should be some directories that match glob: {globPattern} in '{root}'"); } [Fact] public void CanMatchFilesInDirectoriesWithoutTrailingSlash() { var globPattern = @"test/**/*Gl*.Te*"; var root = new DirectoryInfo(SourceRoot).FullName; var result = Glob.Files(root, globPattern).ToList(); Assert.NotNull(result); Assert.All(result, path => Assert.StartsWith("test", path)); Assert.True(result.Any(), $"There should be some directories that match glob: {globPattern} in '{root}'"); } }
154
5,142
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace GlobExpressions; public static class GlobExtensions { public static IEnumerable<DirectoryInfo> GlobDirectories(this DirectoryInfo di, string pattern) { return Glob.Directories(di, pattern); } public static IEnumerable<DirectoryInfo> GlobDirectories(this DirectoryInfo di, string pattern, GlobOptions options) { return Glob.Directories(di, pattern, options); } public static IEnumerable<FileInfo> GlobFiles(this DirectoryInfo di, string pattern) { return Glob.Files(di, pattern); } public static IEnumerable<FileInfo> GlobFiles(this DirectoryInfo di, string pattern, GlobOptions options) { return Glob.Files(di, pattern, options); } public static IEnumerable<FileSystemInfo> GlobFileSystemInfos(this DirectoryInfo di, string pattern) { return Glob.FilesAndDirectories(di, pattern); } public static IEnumerable<FileSystemInfo> GlobFileSystemInfos(this DirectoryInfo di, string pattern, GlobOptions options) { return Glob.FilesAndDirectories(di, pattern, options); } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\CqlFunctions\Tests\Token.cs
Cassandra.IntegrationTests.CqlFunctions.Tests
Token
['private ISession _session = null;', 'private List<EntityWithTimeUuid> _expectedTimeUuidObjectList;', 'private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName();', 'private Table<EntityWithTimeUuid> _tableEntityWithTimeUuid;', 'private Table<EntityWithNullableTimeUuid> _tableEntityWithNullableTimeUuid;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.CqlFunctions.Structures', 'Cassandra.IntegrationTests.TestBase', 'Cassandra.Mapping', 'Cassandra.Tests', 'NUnit.Framework']
NUnit
net8
[Category(TestCategory.Short), Category(TestCategory.RealCluster)] public class Token : SharedClusterTest { private ISession _session = null; private List<EntityWithTimeUuid> _expectedTimeUuidObjectList; private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName(); private Table<EntityWithTimeUuid> _tableEntityWithTimeUuid; private Table<EntityWithNullableTimeUuid> _tableEntityWithNullableTimeUuid; public override void OneTimeSetUp() { base.OneTimeSetUp(); _session = Session; _session.CreateKeyspace(_uniqueKsName); _session.ChangeKeyspace(_uniqueKsName); // Create necessary tables MappingConfiguration config1 = new MappingConfiguration(); config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof (EntityWithTimeUuid), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof (EntityWithTimeUuid))); _tableEntityWithTimeUuid = new Table<EntityWithTimeUuid>(_session, config1); _tableEntityWithTimeUuid.Create(); MappingConfiguration config2 = new MappingConfiguration(); config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof (EntityWithNullableTimeUuid), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof (EntityWithNullableTimeUuid))); _tableEntityWithNullableTimeUuid = new Table<EntityWithNullableTimeUuid>(_session, config2); _tableEntityWithNullableTimeUuid.Create(); _expectedTimeUuidObjectList = EntityWithTimeUuid.GetDefaultObjectList(); for (int i=0; i<_expectedTimeUuidObjectList.Count; i++) { _expectedTimeUuidObjectList[i].StringType = i.ToString(); } } /// <summary> /// Validate that the LinqUtility function Token, which corresponds to the CQL query token /// functions as expected when using a 'equals' comparison, comparing string values /// </summary> [Test] public void Token_EqualTo_String() { EntityWithTimeUuid.SetupEntity(_tableEntityWithTimeUuid, _expectedTimeUuidObjectList); foreach (EntityWithTimeUuid singleEntity in _expectedTimeUuidObjectList) { var whereQuery = _tableEntityWithTimeUuid.Where(s => CqlFunction.Token(s.StringType) == CqlFunction.Token(singleEntity.StringType)); List<EntityWithTimeUuid> objectsReturned1 = whereQuery.ExecuteAsync().Result.ToList(); Assert.AreEqual(1, objectsReturned1.Count); EntityWithTimeUuid.AssertEquals(singleEntity, objectsReturned1.First()); foreach (var actualObj in objectsReturned1) EntityWithTimeUuid.AssertListContains(_expectedTimeUuidObjectList, actualObj); } // change to query that returns nothing var whereQueryReturnsNothing =_tableEntityWithTimeUuid.Where(s => CqlFunction.Token(s.StringType) == CqlFunction.Token(Guid.NewGuid().ToString())); List<EntityWithTimeUuid> objectsReturned2 = whereQueryReturnsNothing.ExecuteAsync().Result.ToList(); Assert.AreEqual(0, objectsReturned2.Count); } /// <summary> /// Validate that the LinqUtility function Token, which corresponds to the CQL query token /// functions as expected when using a 'less than' comparison, comparing string values /// </summary> [Test] public void Token_LessThan_String() { EntityWithTimeUuid.SetupEntity(_tableEntityWithTimeUuid, _expectedTimeUuidObjectList); List<EntityWithTimeUuid> listAsTheyAreInCassandra = _tableEntityWithTimeUuid.Execute().ToList(); Assert.AreEqual(_expectedTimeUuidObjectList.Count, listAsTheyAreInCassandra.Count); for (int i = 0; i < listAsTheyAreInCassandra.Count; i++) { EntityWithTimeUuid singleEntity = listAsTheyAreInCassandra[i]; var whereQuery = _tableEntityWithTimeUuid.Where(s => CqlFunction.Token(s.StringType) < CqlFunction.Token(singleEntity.StringType)); List<EntityWithTimeUuid> objectsReturned1 = whereQuery.ExecuteAsync().Result.ToList(); Assert.AreEqual(i, objectsReturned1.Count); foreach (var actualObj in objectsReturned1) EntityWithTimeUuid.AssertListContains(_expectedTimeUuidObjectList, actualObj); } } /// <summary> /// Validate that the LinqUtility function Token, which corresponds to the CQL query token /// functions as expected when using a 'greater than' comparison, comparing string values /// </summary> [Test] public void Token_GreaterThan_String() { EntityWithTimeUuid.SetupEntity(_tableEntityWithTimeUuid, _expectedTimeUuidObjectList); List<EntityWithTimeUuid> listAsTheyAreInCassandra = _tableEntityWithTimeUuid.Execute().ToList(); Assert.AreEqual(_expectedTimeUuidObjectList.Count, listAsTheyAreInCassandra.Count); int independentInterator = 5; for (int i = 0; i < listAsTheyAreInCassandra.Count; i++) { EntityWithTimeUuid singleEntity = listAsTheyAreInCassandra[i]; var whereQuery = _tableEntityWithTimeUuid.Where(s => CqlFunction.Token(s.StringType) > CqlFunction.Token(singleEntity.StringType)); List<EntityWithTimeUuid> objectsReturned1 = whereQuery.ExecuteAsync().Result.ToList(); Assert.AreEqual(independentInterator, objectsReturned1.Count); foreach (var actualObj in objectsReturned1) EntityWithTimeUuid.AssertListContains(_expectedTimeUuidObjectList, actualObj); independentInterator--; } } }
1,004
7,101
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; namespace Cassandra.Data.Linq { public class CqlToken { public readonly object[] Values; private CqlToken(object[] v) { Values = v; } public static CqlToken Create<T>(T v) { return new CqlToken(new object[] {v}); } public static CqlToken Create<T1, T2>(T1 v1, T2 v2) { return new CqlToken(new object[] {v1, v2}); } public static CqlToken Create<T1, T2, T3>(T1 v1, T2 v2, T3 v3) { return new CqlToken(new object[] {v1, v2, v3}); } public static CqlToken Create<T1, T2, T3, T4>(T1 v1, T2 v2, T3 v3, T4 v4) { return new CqlToken(new object[] {v1, v2, v3, v4}); } public static CqlToken Create<T1, T2, T3, T4, T5>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return new CqlToken(new object[] {v1, v2, v3, v4, v5}); } public static CqlToken Create<T1, T2, T3, T4, T5, T6>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { return new CqlToken(new object[] {v1, v2, v3, v4, v5, v6}); } public override int GetHashCode() { throw new InvalidOperationException(); } public static bool operator ==(CqlToken a, object b) { throw new InvalidOperationException(); } public static bool operator !=(CqlToken a, object b) { throw new InvalidOperationException(); } public static bool operator <=(CqlToken a, object b) { throw new InvalidOperationException(); } public static bool operator >=(CqlToken a, object b) { throw new InvalidOperationException(); } public static bool operator <(CqlToken a, object b) { throw new InvalidOperationException(); } public static bool operator >(CqlToken a, object b) { throw new InvalidOperationException(); } public static bool operator !=(CqlToken a, CqlToken b) { throw new InvalidOperationException(); } public override bool Equals(object obj) { throw new InvalidOperationException(); } public static bool operator ==(CqlToken a, CqlToken b) { throw new InvalidOperationException(); } public static bool operator <=(CqlToken a, CqlToken b) { throw new InvalidOperationException(); } public static bool operator >=(CqlToken a, CqlToken b) { throw new InvalidOperationException(); } public static bool operator <(CqlToken a, CqlToken b) { throw new InvalidOperationException(); } public static bool operator >(CqlToken a, CqlToken b) { throw new InvalidOperationException(); } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Linq\LinqMethods\Counter.cs
Cassandra.IntegrationTests.Linq.LinqMethods
Counter
['[Cassandra.Data.Linq.Counter]\n public long Counter;', '[Cassandra.Data.Linq.PartitionKey(1)]\n public Guid KeyPart1;', '[Cassandra.Data.Linq.PartitionKey(2)]\n public Decimal KeyPart2;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.SimulacronAPI', 'Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then', 'Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.When', 'Cassandra.Mapping', 'NUnit.Framework']
NUnit
net8
public class Counter : SimulacronTest { private void PrimeLinqCounterQuery(CounterEntityWithLinqAttributes counter) { TestCluster.PrimeDelete(); TestCluster.PrimeFluent( b => b.WhenQuery( "SELECT \"Counter\", \"KeyPart1\", \"KeyPart2\" " + "FROM \"CounterEntityWithLinqAttributes\" " + "WHERE \"KeyPart1\" = ? AND \"KeyPart2\" = ?", when => counter.WithParams(when, "KeyPart1", "KeyPart2")) .ThenRowsSuccess(counter.CreateRowsResult())); } private RowsResult AddRows(IEnumerable<CounterEntityWithLinqAttributes> counters) { return counters.Aggregate(CounterEntityWithLinqAttributes.GetEmptyRowsResult(), (current, c) => c.AddRow(current)); } private void PrimeLinqCounterRangeQuery( IEnumerable<CounterEntityWithLinqAttributes> counters, string tableName = "CounterEntityWithLinqAttributes", bool caseSensitive = true) { var cql = caseSensitive ? $"SELECT \"Counter\", \"KeyPart1\", \"KeyPart2\" FROM \"{tableName}\"" : $"SELECT Counter, KeyPart1, KeyPart2 FROM {tableName}"; TestCluster.PrimeDelete(); TestCluster.PrimeFluent(b => b.WhenQuery(cql).ThenRowsSuccess(AddRows(counters))); } [Test] public void LinqAttributes_Counter_SelectRange() { //var mapping = new Map<PocoWithCounter>(); var mappingConfig = new MappingConfiguration(); mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(CounterEntityWithLinqAttributes), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(CounterEntityWithLinqAttributes))); var table = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); table.Create(); var expectedCounters = new List<CounterEntityWithLinqAttributes>(); for (var i = 0; i < 10; i++) { expectedCounters.Add( new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = Guid.NewGuid().GetHashCode(), Counter = Guid.NewGuid().GetHashCode() }); } PrimeLinqCounterRangeQuery(expectedCounters); var countersQueried = table.Select(m => m).Execute().ToList(); Assert.AreEqual(10, countersQueried.Count); foreach (var expectedCounter in expectedCounters) { var actualCounter = countersQueried.Single(c => c.KeyPart1 == expectedCounter.KeyPart1); Assert.AreEqual(expectedCounter.KeyPart2, actualCounter.KeyPart2); Assert.AreEqual(expectedCounter.Counter, actualCounter.Counter); } } /// <summary> /// Validate expected error message when attempting to insert a row that contains a counter /// </summary> [Test] public void LinqAttributes_Counter_AttemptInsert() { // Create config that uses linq based attributes var mappingConfig = new MappingConfiguration(); mappingConfig.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(CounterEntityWithLinqAttributes), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(CounterEntityWithLinqAttributes))); var table = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); CounterEntityWithLinqAttributes pocoAndLinqAttributesLinqPocos = new CounterEntityWithLinqAttributes() { KeyPart1 = Guid.NewGuid(), KeyPart2 = (decimal)123, }; var expectedErrMsg = "INSERT statement(s)? are not allowed on counter tables, use UPDATE instead"; TestCluster.PrimeFluent( b => b.WhenQuery( "INSERT INTO \"CounterEntityWithLinqAttributes\" (\"Counter\", \"KeyPart1\", \"KeyPart2\") VALUES (?, ?, ?)", when => pocoAndLinqAttributesLinqPocos.WithParams(when)) .ThenServerError( ServerError.Invalid, expectedErrMsg)); var e = Assert.Throws<InvalidQueryException>(() => Session.Execute(table.Insert(pocoAndLinqAttributesLinqPocos))); Assert.AreEqual(expectedErrMsg, e.Message); } [TestCase(-21)] [TestCase(-13)] [TestCase(-8)] [TestCase(-5)] [TestCase(-3)] [TestCase(-2)] [TestCase(-1)] [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(5)] [TestCase(8)] [TestCase(13)] [TestCase(21)] public void LinqAttributes_Counter_Increments(int increment) { // Create config that uses linq based attributes var mappingConfig = new MappingConfiguration(); var counterTable = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); var counter = new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = 1 }; var updateCounterCql = "UPDATE \"CounterEntityWithLinqAttributes\" " + "SET \"Counter\" = \"Counter\" + ? " + "WHERE \"KeyPart1\" = ? AND \"KeyPart2\" = ?"; // first update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update() .Execute(); VerifyBoundStatement(updateCounterCql, 1, (long)increment, counter.KeyPart1, counter.KeyPart2); counter.Counter = increment; // counter = increment PrimeLinqCounterQuery(counter); var updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute() .First(); Assert.AreEqual(increment, updatedCounter.Counter); // second update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 2, (long)increment, counter.KeyPart1, counter.KeyPart2); counter.Counter += increment; // counter = increment*2; PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment * 2, updatedCounter.Counter); // third update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 3, (long)increment, counter.KeyPart1, counter.KeyPart2); counter.Counter += increment; // counter = increment*3; PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment * 3, updatedCounter.Counter); // testing negative values var negativeIncrement = -1 * increment; // first negative update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 1, (long)negativeIncrement, counter.KeyPart1, counter.KeyPart2); counter.Counter += negativeIncrement; PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment * 2, updatedCounter.Counter); // second negative update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 2, (long)negativeIncrement, counter.KeyPart1, counter.KeyPart2); counter.Counter += negativeIncrement; // counter -= increment = increment PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(increment, updatedCounter.Counter); // third negative update counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); VerifyBoundStatement(updateCounterCql, 3, (long)negativeIncrement, counter.KeyPart1, counter.KeyPart2); counter.Counter += negativeIncrement; // counter -= increment = 0 PrimeLinqCounterQuery(counter); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Execute().First(); Assert.AreEqual(0, updatedCounter.Counter); } [Test] public void LinqCounter_BatchTest() { var mappingConfig = new MappingConfiguration(); mappingConfig.Define(new Map<CounterEntityWithLinqAttributes>() .ExplicitColumns() .Column(t => t.KeyPart1) .Column(t => t.KeyPart2) .Column(t => t.Counter, map => map.AsCounter()) .PartitionKey(t => t.KeyPart1, t => t.KeyPart2) .TableName("linqcounter_batchtest_table") ); var counterTable = new Table<CounterEntityWithLinqAttributes>(Session, mappingConfig); counterTable.CreateIfNotExists(); var counter = new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = 1, Counter = 1 }; var counter2 = new CounterEntityWithLinqAttributes { KeyPart1 = counter.KeyPart1, KeyPart2 = 2, Counter = 2 }; var batch = counterTable.GetSession().CreateBatch(BatchType.Counter); var update1 = counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = 1 }) .Update(); var update2 = counterTable .Where(t => t.KeyPart1 == counter2.KeyPart1 && t.KeyPart2 == counter2.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = 2 }) .Update(); batch.Append(update1); batch.Append(update2); batch.Execute(); VerifyBatchStatement( 1, new[] { "UPDATE linqcounter_batchtest_table SET Counter = Counter + ? WHERE KeyPart1 = ? AND KeyPart2 = ?", "UPDATE linqcounter_batchtest_table SET Counter = Counter + ? WHERE KeyPart1 = ? AND KeyPart2 = ?" }, new[] { new object[] { 1L, counter.KeyPart1, counter.KeyPart2 }, new object[] { 2L, counter2.KeyPart1, counter2.KeyPart2 } }); var expectedCounters = new[] { counter, counter2 }; PrimeLinqCounterRangeQuery(expectedCounters, "linqcounter_batchtest_table", false); var counters = counterTable.Execute().ToList(); Assert.AreEqual(2, counters.Count); Assert.IsTrue(counters.Contains(counter)); Assert.IsTrue(counters.Contains(counter2)); } [Cassandra.Data.Linq.Table] private class CounterEntityWithLinqAttributes { [Cassandra.Data.Linq.Counter] public long Counter; [Cassandra.Data.Linq.PartitionKey(1)] public Guid KeyPart1; [Cassandra.Data.Linq.PartitionKey(2)] public Decimal KeyPart2; public static IWhenQueryBuilder WithParams(IWhenQueryBuilder builder, params (string, CounterEntityWithLinqAttributes)[] parameters) { foreach (var (name, value) in parameters) { switch (name) { case nameof(CounterEntityWithLinqAttributes.Counter): builder = builder.WithParam(DataType.Counter, value.Counter); break; case nameof(CounterEntityWithLinqAttributes.KeyPart1): builder = builder.WithParam(DataType.Uuid, value.KeyPart1); break; case nameof(CounterEntityWithLinqAttributes.KeyPart2): builder = builder.WithParam(DataType.Decimal, value.KeyPart2); break; default: throw new ArgumentException("parameter not found"); } } return builder; } public IWhenQueryBuilder WithParams(IWhenQueryBuilder builder, params string[] parameters) { return WithParams(builder, parameters.Select(p => (p, this)).ToArray()); } public IWhenQueryBuilder WithParams(IWhenQueryBuilder builder) { return WithParams(builder, new string[0]); } public RowsResult CreateRowsResult() { return (RowsResult)AddRow(CounterEntityWithLinqAttributes.GetEmptyRowsResult()); } public static RowsResult GetEmptyRowsResult() { return new RowsResult( (nameof(CounterEntityWithLinqAttributes.Counter), DataType.Counter), (nameof(CounterEntityWithLinqAttributes.KeyPart1), DataType.Uuid), (nameof(CounterEntityWithLinqAttributes.KeyPart2), DataType.Decimal)); } public RowsResult AddRow(RowsResult rows) { return (RowsResult)rows.WithRow(Counter, KeyPart1, KeyPart2); } public override bool Equals(object obj) { if (obj == null) { return false; } var comp = (CounterEntityWithLinqAttributes)obj; return (this.Counter == comp.Counter && this.KeyPart1.Equals(comp.KeyPart1) && this.KeyPart2.Equals(comp.KeyPart2)); } public override int GetHashCode() { var hash = KeyPart1.GetHashCode(); hash += KeyPart2.GetHashCode() * 1000; hash += (int)Counter * 100000; return hash; } } }
1,093
17,555
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Cassandra.Metrics.Abstractions { /// <summary> /// Represents a metric of type Counter. /// </summary> public interface IDriverCounter : IDriverMetric { void Increment(); void Increment(long value); } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Linq\LinqMethods\Delete.cs
Cassandra.IntegrationTests.Linq.LinqMethods
Delete
['private List<AllDataTypesEntity> _entityList;', 'private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName();', 'private Table<AllDataTypesEntity> _table;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.Linq.Structures', 'Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then', 'Cassandra.IntegrationTests.TestBase', 'Cassandra.Mapping', 'NUnit.Framework']
NUnit
net8
public class Delete : SimulacronTest { private List<AllDataTypesEntity> _entityList; private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName(); private Table<AllDataTypesEntity> _table; [SetUp] public override void SetUp() { base.SetUp(); _entityList = AllDataTypesEntity.GetDefaultAllDataTypesList(); _table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); } [TestCase(true)] [TestCase(false)] [Test] public void Delete_DeleteOneEquals(bool async) { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); AllDataTypesEntity.PrimeCountQuery(TestCluster, _entityList.Count); var count = table.Count().Execute(); Assert.AreEqual(_entityList.Count, count); AllDataTypesEntity entityToDelete = _entityList[0]; var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType); var deleteQuery = selectQuery.Delete(); if (async) { deleteQuery.ExecuteAsync().GetAwaiter().GetResult(); } else { deleteQuery.Execute(); } VerifyBoundStatement( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?", 1, entityToDelete.StringType); TestCluster.PrimeDelete(); AllDataTypesEntity.PrimeCountQuery(TestCluster, _entityList.Count - 1); count = table.Count().Execute(); Assert.AreEqual(_entityList.Count - 1, count); TestCluster.PrimeFluent(b => entityToDelete.When(TestCluster, b).ThenVoidSuccess()); Assert.AreEqual(0, selectQuery.Execute().ToList().Count); } [TestCase(true)] [TestCase(false)] [Test] public void Delete_DeleteMultipleContains(bool async) { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); var uniqueStringKeys = _entityList.Select(m => m.StringType).ToList(); var deleteRequest = table.Where(m => uniqueStringKeys.Contains(m.StringType)).Delete(); if (async) { deleteRequest.ExecuteAsync().GetAwaiter().GetResult(); } else { deleteRequest.Execute(); } VerifyBoundStatement( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" IN ?", 1, uniqueStringKeys); } [Test] public void Delete_MissingKey_Sync() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"boolean_type\" = ?", when => when.WithParam(true)) .ThenServerError(ServerError.Invalid, "invalid")); var selectQuery = table.Select(m => m).Where(m => m.BooleanType == true); var deleteQuery = selectQuery.Delete(); Assert.Throws<InvalidQueryException>(() => deleteQuery.Execute()); } [Test] public void Delete_NoSuchRecord() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); var entityToDelete = _entityList[0]; var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType + Randomm.RandomAlphaNum(16)); var deleteQuery = selectQuery.Delete(); deleteQuery.Execute(); // make sure record was not deleted var listOfExecutionParameters = GetBoundStatementExecutionParameters( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?").ToList(); Assert.AreEqual(1, listOfExecutionParameters.Count); var parameter = Convert.FromBase64String((string)listOfExecutionParameters.Single().Single()); var actualParameter = (string) Session.Cluster.Metadata.ControlConnection.Serializer.GetCurrentSerializer().Deserialize(parameter, 0, parameter.Length, ColumnTypeCode.Text, null); Assert.AreNotEqual(entityToDelete.StringType, actualParameter); Assert.IsTrue(actualParameter.StartsWith(entityToDelete.StringType)); Assert.IsTrue(actualParameter.Length > entityToDelete.StringType.Length); } /// <summary> /// Attempt to delete from a table without specifying a WHERE limiter. Assert expected failure. /// NOTE: Not specifying a 'where' clause in C* is like Delete * in SQL, which is not allowed. /// </summary> [Test] public void Delete_MissingWhereAndSelectClause_Sync() { TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\"", when => when.WithParam(true)) .ThenSyntaxError("invalid")); Assert.Throws<SyntaxError>(() => _table.Delete().Execute()); } /// <summary> /// Attempt to delete from a table without specifying a WHERE limiter. Assert expected failure. /// NOTE: Not specifying a 'where' clause in C* is like Delete * in SQL, which is not allowed. /// </summary> [Test] public void Delete_MissingWhereClause_Sync() { TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\"", when => when.WithParam(true)) .ThenSyntaxError("invalid")); Assert.Throws<SyntaxError>(() => _table.Select(m => m).Delete().Execute()); } /// <summary> /// Successfully delete a record using the IfExists condition /// </summary> [Test, TestCassandraVersion(2, 0)] public void Delete_IfExists() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); AllDataTypesEntity entityToDelete = _entityList[0]; var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType && m.GuidType == entityToDelete.GuidType); var deleteQuery = selectQuery.Delete().IfExists(); deleteQuery.Execute(); VerifyBoundStatement( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", 1, entityToDelete.StringType, entityToDelete.GuidType); } /// <summary> /// Successfully delete a record using the IfExists condition, when the row doesn't exist. /// </summary> [Test, TestCassandraVersion(2, 0)] public void Delete_IfExists_RowDoesntExist() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); AllDataTypesEntity entityToDelete = _entityList[0]; var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType && m.GuidType == entityToDelete.GuidType); var deleteQuery = selectQuery.Delete().IfExists(); deleteQuery.Execute(); VerifyBoundStatement( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", 1, entityToDelete.StringType, entityToDelete.GuidType); // Executing again should not fail, should just be a no-op deleteQuery.Execute(); VerifyBoundStatement( $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? AND \"guid_type\" = ? IF EXISTS", 2, entityToDelete.StringType, entityToDelete.GuidType); } /// <summary> /// /// </summary> [Test, TestCassandraVersion(2, 1, 2)] public void Delete_IfExists_ClusteringKeyOmitted() { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); AllDataTypesEntity entityToDelete = _entityList[0]; TestCluster.PrimeFluent( b => b.WhenQuery($"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ? IF EXISTS", when => when.WithParam(entityToDelete.StringType)) .ThenServerError(ServerError.Invalid, "invalid")); var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType); var deleteQuery = selectQuery.Delete().IfExists(); Assert.Throws<InvalidQueryException>(() => deleteQuery.Execute()); } [TestCase(BatchType.Unlogged)] [TestCase(BatchType.Logged)] [TestCase(default(BatchType))] [TestCassandraVersion(2, 0)] public void Delete_BatchType(BatchType batchType) { var table = new Table<AllDataTypesEntity>(Session, new MappingConfiguration()); AllDataTypesEntity entityToDelete = _entityList[0]; AllDataTypesEntity entityToDelete2 = _entityList[1]; var selectQuery = table.Select(m => m).Where(m => m.StringType == entityToDelete.StringType); var deleteQuery = selectQuery.Delete(); var selectQuery2 = table.Select(m => m).Where(m => m.StringType == entityToDelete2.StringType); var deleteQuery2 = selectQuery2.Delete(); var batch = table.GetSession().CreateBatch(batchType); batch.Append(deleteQuery); batch.Append(deleteQuery2); batch.Execute(); VerifyBatchStatement( 1, new [] { $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?", $"DELETE FROM \"{AllDataTypesEntity.TableName}\" WHERE \"string_type\" = ?" }, new[] { new object [] { entityToDelete.StringType }, new object [] { entityToDelete2.StringType }}); } }
1,010
11,742
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Linq.Expressions; using Cassandra.Mapping; using Cassandra.Mapping.Statements; namespace Cassandra.Data.Linq { public class CqlDelete : CqlCommand { private bool _ifExists = false; internal CqlDelete(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData) : base(expression, table, stmtFactory, pocoData) { } public CqlDelete IfExists() { _ifExists = true; return this; } protected internal override string GetCql(out object[] values) { var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); return visitor.GetDelete(Expression, out values, _timestamp, _ifExists); } public override string ToString() { object[] _; return GetCql(out _); } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Linq\LinqMethods\Update.cs
Cassandra.IntegrationTests.Linq.LinqMethods
Update
['private readonly List<Movie> _movieList = Movie.GetDefaultMovieList();', 'private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName();']
['System.Collections.Generic', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.Linq.Structures', 'Cassandra.IntegrationTests.TestBase', 'Cassandra.Mapping', 'NUnit.Framework']
NUnit
net8
public class Update : SimulacronTest { private readonly List<Movie> _movieList = Movie.GetDefaultMovieList(); private readonly string _uniqueKsName = TestUtils.GetUniqueKeyspaceName(); public override void SetUp() { base.SetUp(); Session.ChangeKeyspace(_uniqueKsName); } /// <summary> /// Successfully update multiple records using a single (non-batch) update /// </summary> [TestCase(true), TestCase(false)] [Test] public void LinqUpdate_Single(bool async) { // Setup var table = new Table<Movie>(Session, new MappingConfiguration()); var movieToUpdate = _movieList[1]; var expectedMovie = new Movie(movieToUpdate.Title, movieToUpdate.Director, "something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate.MovieMaker, 1212); var updateQuery = table.Where(m => m.Title == movieToUpdate.Title && m.MovieMaker == movieToUpdate.MovieMaker && m.Director == movieToUpdate.Director) .Select(m => new Movie { Year = expectedMovie.Year, MainActor = expectedMovie.MainActor }) .Update(); if (async) { updateQuery.ExecuteAsync().GetAwaiter().GetResult(); } else { updateQuery.Execute(); } VerifyBoundStatement( $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ?", 1, expectedMovie.Year, expectedMovie.MainActor, movieToUpdate.Title, movieToUpdate.MovieMaker, movieToUpdate.Director); } /// <summary> /// Try to update a non existing record /// </summary> [Test, TestCassandraVersion(2, 0)] public void LinqUpdate_IfExists() { // Setup var table = new Table<Movie>(Session, new MappingConfiguration()); var unexistingMovie = new Movie("Unexisting movie title", "Unexisting movie director", "Unexisting movie actor", "Unexisting movie maker", 1212); TestCluster.PrimeFluent( b => b.WhenQuery( $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ? IF EXISTS", when => when.WithParams(unexistingMovie.Year, unexistingMovie.MainActor, unexistingMovie.Title, unexistingMovie.MovieMaker, unexistingMovie.Director)) .ThenRowsSuccess(Movie.CreateAppliedInfoRowsResultWithoutMovie(false))); var cql = table.Where(m => m.Title == unexistingMovie.Title && m.MovieMaker == unexistingMovie.MovieMaker && m.Director == unexistingMovie.Director) .Select(m => new Movie { Year = unexistingMovie.Year, MainActor = unexistingMovie.MainActor }) .UpdateIfExists(); var appliedInfo = cql.Execute(); Assert.IsFalse(appliedInfo.Applied); VerifyBoundStatement( $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ? IF EXISTS", 1, unexistingMovie.Year, unexistingMovie.MainActor, unexistingMovie.Title, unexistingMovie.MovieMaker, unexistingMovie.Director); } /// <summary> /// Successfully update multiple records using a Batch update /// </summary> [Test, TestCassandraVersion(2, 0)] public void LinqUpdate_Batch() { // Setup var table = new Table<Movie>(Session, new MappingConfiguration()); var movieToUpdate1 = _movieList[1]; var movieToUpdate2 = _movieList[2]; var batch = new BatchStatement(); var expectedMovie1 = new Movie(movieToUpdate1.Title, movieToUpdate1.Director, "something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate1.MovieMaker, 1212); var update1 = table.Where(m => m.Title == movieToUpdate1.Title && m.MovieMaker == movieToUpdate1.MovieMaker && m.Director == movieToUpdate1.Director) .Select(m => new Movie { Year = expectedMovie1.Year, MainActor = expectedMovie1.MainActor }) .Update(); batch.Add(update1); var expectedMovie2 = new Movie(movieToUpdate2.Title, movieToUpdate2.Director, "also_something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate2.MovieMaker, 1212); var update2 = table.Where(m => m.Title == movieToUpdate2.Title && m.MovieMaker == movieToUpdate2.MovieMaker && m.Director == movieToUpdate2.Director) .Select(m => new Movie { Year = expectedMovie2.Year, MainActor = expectedMovie2.MainActor }) .Update(); batch.Add(update2); table.GetSession().Execute(batch); VerifyBatchStatement( 1, new[] { $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ?", $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ?" }, new[] { new object[] { expectedMovie1.Year, expectedMovie1.MainActor, movieToUpdate1.Title, movieToUpdate1.MovieMaker, movieToUpdate1.Director }, new object[] { expectedMovie2.Year, expectedMovie2.MainActor, movieToUpdate2.Title, movieToUpdate2.MovieMaker, movieToUpdate2.Director } }); } [TestCase(BatchType.Unlogged)] [TestCase(BatchType.Logged)] [TestCase(default(BatchType))] [TestCassandraVersion(2, 0)] public void LinqUpdate_UpdateBatchType(BatchType batchType) { // Setup var table = new Table<Movie>(Session, new MappingConfiguration()); var movieToUpdate1 = _movieList[1]; var movieToUpdate2 = _movieList[2]; var batch = table.GetSession().CreateBatch(batchType); var expectedMovie1 = new Movie(movieToUpdate1.Title, movieToUpdate1.Director, "something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate1.MovieMaker, 1212); var update1 = table.Where(m => m.Title == movieToUpdate1.Title && m.MovieMaker == movieToUpdate1.MovieMaker && m.Director == movieToUpdate1.Director) .Select(m => new Movie { Year = expectedMovie1.Year, MainActor = expectedMovie1.MainActor }) .Update(); batch.Append(update1); var expectedMovie2 = new Movie(movieToUpdate2.Title, movieToUpdate2.Director, "also_something_different_" + Randomm.RandomAlphaNum(10), movieToUpdate2.MovieMaker, 1212); var update2 = table.Where(m => m.Title == movieToUpdate2.Title && m.MovieMaker == movieToUpdate2.MovieMaker && m.Director == movieToUpdate2.Director) .Select(m => new Movie { Year = expectedMovie2.Year, MainActor = expectedMovie2.MainActor }) .Update(); batch.Append(update2); batch.Execute(); VerifyBatchStatement( 1, new[] { $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ?", $"UPDATE \"{Movie.TableName}\" " + "SET \"yearMade\" = ?, \"mainGuy\" = ? " + "WHERE \"unique_movie_title\" = ? AND \"movie_maker\" = ? AND \"director\" = ?" }, new[] { new object[] { expectedMovie1.Year, expectedMovie1.MainActor, movieToUpdate1.Title, movieToUpdate1.MovieMaker, movieToUpdate1.Director }, new object[] { expectedMovie2.Year, expectedMovie2.MainActor, movieToUpdate2.Title, movieToUpdate2.MovieMaker, movieToUpdate2.Director } }); } }
939
9,960
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Linq.Expressions; using Cassandra.Mapping; using Cassandra.Mapping.Statements; namespace Cassandra.Data.Linq { public class CqlUpdate : CqlCommand { private readonly MapperFactory _mapperFactory; internal CqlUpdate(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData, MapperFactory mapperFactory) : base(expression, table, stmtFactory, pocoData) { _mapperFactory = mapperFactory; } protected internal override string GetCql(out object[] values) { var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); return visitor.GetUpdate(Expression, out values, _ttl, _timestamp, _mapperFactory); } public override string ToString() { object[] _; return GetCql(out _); } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Mapping\Tests\Attributes.cs
Cassandra.IntegrationTests.Mapping.Tests
Attributes
['private const string IgnoredStringAttribute = "ignoredstringattribute";', '[Column("someCaseSensitivePartitionKey")]\n [PartitionKey]\n public string SomePartitionKey = "defaultPartitionKeyVal";', '[Column("some_column_label_thats_different")]\n public int SomeColumn = 191991919;', '[PartitionKey]\n public string SomePartitionKey = "defaultPartitionKeyVal";', '[Column]\n public int SomeColumn = 121212121;', '[PartitionKey]\n public string SomePartitionKey;', '[SecondaryIndex]\n public int SomeSecondaryIndex = 1;', 'public string StringTyp = "someStringValue";', '[PartitionKey]\n public string StringType = "someStringValue";', 'public string StringTypeNotPartitionKey = "someStringValueNotPk";', '[PartitionKey]\n public string SomePartitionKey = "somePartitionKeyDefaultValue";', 'public double SomeNonIgnoredDouble = 123456;', '[Cassandra.Mapping.Attributes.Ignore]\n public string IgnoredStringAttribute = "someIgnoredString";', '[Linq::PartitionKey]\n [PartitionKey]\n [Linq::Column("somepartitionkey")]\n public string SomePartitionKey = "somePartitionKeyDefaultValue";', '[Linq::Column("somenonignoreddouble")]\n public double SomeNonIgnoredDouble = 123456;', '[Cassandra.Mapping.Attributes.Ignore]\n [Linq::Column(Attributes.IgnoredStringAttribute)]\n public string IgnoredStringAttribute = "someIgnoredString";', '[Linq::PartitionKey]\n [Linq::Column("somepartitionkey")]\n public string SomePartitionKey = "somePartitionKeyDefaultValue";', '[Linq::Column("somenonignoreddouble")]\n public double SomeNonIgnoredDouble = 123456;', '[PartitionKey]\n [Linq::Column("someotherstring")]\n public string SomeOtherString = "someOtherString";', 'public string SomeString = "somestring_value";', 'public string SomeString = "somestring_value";', 'public string SomeOtherString = "someotherstring_value";', '[ClusteringKey]\n public string SomeString = "someStringValue";', 'public double SomeDouble = 123456;', 'public List<string> SomeList = new List<string>();', '[PartitionKey]\n public string SomeString = "somePartitionKeyDefaultValue";', 'public double SomeDouble = 123456;', 'public List<string> SomeList = new List<string>();', '[Linq::PartitionKey(1)]\n [PartitionKey(1)]\n [Linq::Column("somepartitionkey1")]\n public string SomePartitionKey1 = "somepartitionkey1_val";', '[Linq::PartitionKey(2)]\n [PartitionKey(2)]\n [Linq::Column("somepartitionkey2")]\n public string SomePartitionKey2 = "somepartitionkey2_val";', '[Linq::Column("listofguids")]\n public List<Guid> ListOfGuids;', '[Cassandra.Mapping.Attributes.Ignore]\n [Linq::Column("ignoredstring")]\n public string IgnoredString = "someIgnoredString_val";', '[Linq::PartitionKey(1)]\n [PartitionKey(1)]\n [Linq::Column("somepartitionkey1")]\n public string SomePartitionKey1 = "somepartitionkey1_val";', '[Linq::PartitionKey(2)]\n [PartitionKey(2)]\n [Linq::Column("somepartitionkey2")]\n public string SomePartitionKey2 = "somepartitionkey2_val";', '[Linq::ClusteringKey(1)]\n [ClusteringKey(1)]\n [Linq::Column("guid1")]\n public Guid Guid1;', '[Linq::ClusteringKey(2)]\n [ClusteringKey(2)]\n [Linq::Column("guid2")]\n public Guid Guid2;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.IntegrationTests.Linq.Structures', 'Cassandra.IntegrationTests.Mapping.Structures', 'Cassandra.IntegrationTests.SimulacronAPI', 'Cassandra.IntegrationTests.SimulacronAPI.Models.Logs', 'Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then', 'Cassandra.IntegrationTests.TestBase', 'Cassandra.Mapping', 'Cassandra.Mapping.Attributes', 'NUnit.Framework', 'Cassandra.Data.Linq']
NUnit
net8
public class Attributes : SimulacronTest { private const string IgnoredStringAttribute = "ignoredstringattribute"; private Linq::Table<T> GetTable<T>() { return new Linq::Table<T>(Session, new MappingConfiguration()); } private IMapper GetMapper() { return new Mapper(Session, new MappingConfiguration()); } /// <summary> /// Validate that the mapping mechanism ignores the field marked with mapping attribute "Ignore" /// </summary> [Test] public void Attributes_Ignore_TableCreatedWithMappingAttributes() { var definition = new AttributeBasedTypeDefinition(typeof(PocoWithIgnoredAttributes)); var table = new Linq::Table<PocoWithIgnoredAttributes>(Session, new MappingConfiguration().Define(definition)); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE PocoWithIgnoredAttributes " + "(SomeNonIgnoredDouble double, SomePartitionKey text, " + "PRIMARY KEY (SomePartitionKey))", 1); //var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); var mapper = new Mapper(Session, new MappingConfiguration()); var pocoToUpload = new PocoWithIgnoredAttributes { SomePartitionKey = Guid.NewGuid().ToString(), IgnoredStringAttribute = Guid.NewGuid().ToString(), }; mapper.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO PocoWithIgnoredAttributes (SomeNonIgnoredDouble, SomePartitionKey) " + "VALUES (?, ?)", 1, pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"somepartitionkey\"='{pocoToUpload.SomePartitionKey}'"; // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { "somenonignoreddouble", "somepartitionkey" }, r => r.WithRow(pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey))); var records = mapper.Fetch<PocoWithIgnoredAttributes>(cqlSelect).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey); var defaultPoco = new PocoWithIgnoredAttributes(); Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute); Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute); Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey")); Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble")); // Verify there was no column created for the ignored column var e = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>(IgnoredStringAttribute)); var expectedErrMsg = "Column " + IgnoredStringAttribute + " not found"; Assert.AreEqual(expectedErrMsg, e.Message); } /// <summary> /// Validate that the mapping mechanism ignores the field marked with mapping attribute "Ignore" /// </summary> [Test] public void Attributes_Ignore() { var table = GetTable<PocoWithIgnoredAttributes>(); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE PocoWithIgnoredAttributes " + "(SomeNonIgnoredDouble double, SomePartitionKey text, " + "PRIMARY KEY (SomePartitionKey))", 1); var mapper = GetMapper(); var pocoToUpload = new PocoWithIgnoredAttributes { SomePartitionKey = Guid.NewGuid().ToString(), IgnoredStringAttribute = Guid.NewGuid().ToString(), }; mapper.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO PocoWithIgnoredAttributes (SomeNonIgnoredDouble, SomePartitionKey) " + "VALUES (?, ?)", 1, pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"{"somepartitionkey"}\"='{pocoToUpload.SomePartitionKey}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { "somenonignoreddouble", "somepartitionkey" }, r => r.WithRow(pocoToUpload.SomeNonIgnoredDouble, pocoToUpload.SomePartitionKey))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = mapper.Fetch<PocoWithIgnoredAttributes>(cqlSelect).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, records[0].SomePartitionKey); var defaultPoco = new PocoWithIgnoredAttributes(); Assert.AreNotEqual(defaultPoco.IgnoredStringAttribute, pocoToUpload.IgnoredStringAttribute); Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute); Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoToUpload.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey")); Assert.AreEqual(pocoToUpload.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble")); // Verify there was no column created for the ignored column var e = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>(IgnoredStringAttribute)); var expectedErrMsg = "Column " + IgnoredStringAttribute + " not found"; Assert.AreEqual(expectedErrMsg, e.Message); } /// <summary> /// Validate that the mapping mechanism ignores the class variable marked as "Ignore" /// The fact that the request does not fail trying to find a non-existing custom named column proves that /// the request is not looking for the column for reads or writes. /// /// This also validates that attributes from Cassandra.Mapping and Cassandra.Data.Linq can be used successfully on the same object /// </summary> [Test] public void Attributes_Ignore_LinqAndMappingAttributes() { var config = new MappingConfiguration(); config.MapperFactory.PocoDataFactory.AddDefinitionDefault( typeof(PocoWithIgnrdAttr_LinqAndMapping), () => Linq::LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithIgnrdAttr_LinqAndMapping))); var table = new Linq::Table<PocoWithIgnrdAttr_LinqAndMapping>(Session, config); table.Create(); VerifyQuery( "CREATE TABLE \"pocowithignrdattr_linqandmapping\" " + "(\"ignoredstringattribute\" text, \"somenonignoreddouble\" double, " + "\"somepartitionkey\" text, PRIMARY KEY (\"somepartitionkey\"))", 1); var cqlClient = GetMapper(); var pocoToInsert = new PocoWithIgnrdAttr_LinqAndMapping { SomePartitionKey = Guid.NewGuid().ToString(), IgnoredStringAttribute = Guid.NewGuid().ToString(), }; cqlClient.Insert(pocoToInsert); VerifyBoundStatement( "INSERT INTO PocoWithIgnrdAttr_LinqAndMapping (SomeNonIgnoredDouble, SomePartitionKey) " + "VALUES (?, ?)", 1, pocoToInsert.SomeNonIgnoredDouble, pocoToInsert.SomePartitionKey); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var cqlSelect = "SELECT * from " + table.Name; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("somenonignoreddouble", DataType.Double), ("somepartitionkey", DataType.Text), ("ignoredstringattribute", DataType.Text) }, r => r.WithRow( pocoToInsert.SomeNonIgnoredDouble, pocoToInsert.SomePartitionKey, null))); var records = cqlClient.Fetch<PocoWithIgnrdAttr_LinqAndMapping>(cqlSelect).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoToInsert.SomePartitionKey, records[0].SomePartitionKey); var defaultPoco = new PocoWithIgnrdAttr_LinqAndMapping(); Assert.AreEqual(defaultPoco.IgnoredStringAttribute, records[0].IgnoredStringAttribute); Assert.AreEqual(defaultPoco.SomeNonIgnoredDouble, records[0].SomeNonIgnoredDouble); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoToInsert.SomePartitionKey, rows[0].GetValue<string>("somepartitionkey")); Assert.AreEqual(pocoToInsert.SomeNonIgnoredDouble, rows[0].GetValue<double>("somenonignoreddouble")); Assert.AreEqual(null, rows[0].GetValue<string>(IgnoredStringAttribute)); } /// <summary> /// Verify that inserting a mapped object that totally omits the Cassandra.Mapping.Attributes.PartitionKey silently fails. /// However, using mapping and a different Poco that has the key, records can be inserted and fetched into the same table /// </summary> [Test] public void Attributes_InsertFailsWhenPartitionKeyAttributeOmitted_FixedWithMapping() { // Setup var tableName = typeof(PocoWithPartitionKeyOmitted).Name.ToLower(); var selectAllCql = "SELECT * from " + tableName; var stringList = new List<string> { "string1", "string2" }; // Instantiate CqlClient with mapping rule that resolves the missing key issue var cqlClientWithMappping = new Mapper(Session, new MappingConfiguration().Define(new PocoWithPartitionKeyIncludedMapping())); // insert new record var pocoWithCustomAttributesKeyIncluded = new PocoWithPartitionKeyIncluded(); pocoWithCustomAttributesKeyIncluded.SomeList = stringList; // make it not empty cqlClientWithMappping.Insert(pocoWithCustomAttributesKeyIncluded); VerifyBoundStatement( $"INSERT INTO {tableName} (SomeDouble, SomeList, somestring) " + "VALUES (?, ?, ?)", 1, pocoWithCustomAttributesKeyIncluded.SomeDouble, pocoWithCustomAttributesKeyIncluded.SomeList, pocoWithCustomAttributesKeyIncluded.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery(selectAllCql) .ThenRowsSuccess( new[] { "somedouble", "somelist", "somestring" }, r => r.WithRow( pocoWithCustomAttributesKeyIncluded.SomeDouble, pocoWithCustomAttributesKeyIncluded.SomeList, pocoWithCustomAttributesKeyIncluded.SomeString))); var records1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList(); Assert.AreEqual(1, records1.Count); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, records1[0].SomeString); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeList, records1[0].SomeList); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, records1[0].SomeDouble); records1.Clear(); var rows = Session.Execute(selectAllCql).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeString, rows[0].GetValue<string>("somestring")); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeList, rows[0].GetValue<List<string>>("somelist")); Assert.AreEqual(pocoWithCustomAttributesKeyIncluded.SomeDouble, rows[0].GetValue<double>("somedouble")); // try to Select new record using poco that does not contain partition key, validate that the mapping mechanism matches what it can var cqlClientNomapping = GetMapper(); var records2 = cqlClientNomapping.Fetch<PocoWithPartitionKeyOmitted>(selectAllCql).ToList(); Assert.AreEqual(1, records2.Count); records2.Clear(); // try again with the old CqlClient instance records1 = cqlClientWithMappping.Fetch<PocoWithPartitionKeyIncluded>(selectAllCql).ToList(); Assert.AreEqual(1, records1.Count); } /// <summary> /// Verify that inserting a mapped object without specifying Cassandra.Mapping.Attributes.PartitionKey does not fail /// This also validates that not all columns need to be included for the Poco insert / fetch to succeed /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_PartitionKeyNotLabeled() { var tableName = typeof(PocoWithOnlyPartitionKeyNotLabeled).Name; var cqlClient = GetMapper(); var pocoWithOnlyCustomAttributes = new PocoWithOnlyPartitionKeyNotLabeled(); cqlClient.Insert(pocoWithOnlyCustomAttributes); VerifyBoundStatement( $"INSERT INTO {tableName} (SomeString) " + "VALUES (?)", 1, pocoWithOnlyCustomAttributes.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("somedouble", DataType.Double), ("somelist", DataType.List(DataType.Text)), ("somestring", DataType.Text) }, r => r.WithRow( null, null, pocoWithOnlyCustomAttributes.SomeString))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoWithOnlyPartitionKeyNotLabeled>("SELECT * from " + tableName).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithOnlyCustomAttributes.SomeString, records[0].SomeString); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute("SELECT * from " + tableName).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithOnlyCustomAttributes.SomeString, rows[0].GetValue<string>("somestring")); } /// <summary> /// Verify that inserting a mapped object without including PartitionKey succeeds when it is not the only field in the Poco class /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_PartitionKeyNotLabeled_AnotherNonLabelFieldIncluded() { var tableName = typeof(PocoWithPartitionKeyNotLabeledAndOtherField).Name; var cqlClient = GetMapper(); var pocoWithOnlyCustomAttributes = new PocoWithPartitionKeyNotLabeledAndOtherField(); cqlClient.Insert(pocoWithOnlyCustomAttributes); VerifyBoundStatement( $"INSERT INTO {tableName} (SomeOtherString, SomeString) " + "VALUES (?, ?)", 1, pocoWithOnlyCustomAttributes.SomeOtherString, pocoWithOnlyCustomAttributes.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("somedouble", DataType.Double), ("somelist", DataType.List(DataType.Text)), ("somestring", DataType.Text), ("someotherstring", DataType.Text) }, r => r.WithRow( null, null, pocoWithOnlyCustomAttributes.SomeString, pocoWithOnlyCustomAttributes.SomeOtherString))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoWithPartitionKeyNotLabeledAndOtherField>("SELECT * from " + tableName).ToList(); Assert.AreEqual(1, records.Count); } /// <summary> /// Verify that inserting a mapped object, mislabeling the PartitionKey as a Clustering Key does not fail /// </summary> [Test] public void Attributes_MislabledClusteringKey() { var tableName = typeof(PocoMislabeledClusteringKey).Name; var cqlClient = GetMapper(); var pocoWithCustomAttributes = new PocoMislabeledClusteringKey(); cqlClient.Insert(pocoWithCustomAttributes); // TODO: Should this fail? VerifyBoundStatement( $"INSERT INTO {tableName} (SomeString) " + "VALUES (?)", 1, pocoWithCustomAttributes.SomeString); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("somestring", DataType.Varchar) }, r => r.WithRow(pocoWithCustomAttributes.SomeString))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoMislabeledClusteringKey>("SELECT * from " + tableName).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithCustomAttributes.SomeString, records[0].SomeString); } /// <summary> /// Successfully insert Poco object which have values that are part of a composite key /// </summary> [Test] public void Attributes_CompositeKey() { var tableName = typeof(PocoWithCompositeKey).Name; var definition = new AttributeBasedTypeDefinition(typeof(PocoWithCompositeKey)); var table = new Linq::Table<PocoWithCompositeKey>(Session, new MappingConfiguration().Define(definition)); table.Create(); VerifyQuery( $"CREATE TABLE {tableName} (ListOfGuids list<uuid>, SomePartitionKey1 text, SomePartitionKey2 text, " + "PRIMARY KEY ((SomePartitionKey1, SomePartitionKey2)))", 1); var listOfGuids = new List<Guid> { new Guid(), new Guid() }; var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); var pocoWithCustomAttributes = new PocoWithCompositeKey { ListOfGuids = listOfGuids, SomePartitionKey1 = Guid.NewGuid().ToString(), SomePartitionKey2 = Guid.NewGuid().ToString(), IgnoredString = Guid.NewGuid().ToString(), }; mapper.Insert(pocoWithCustomAttributes); VerifyBoundStatement( $"INSERT INTO {tableName} (ListOfGuids, SomePartitionKey1, SomePartitionKey2) VALUES (?, ?, ?)", 1, pocoWithCustomAttributes.ListOfGuids, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + tableName) .ThenRowsSuccess( new[] { ("listofguids", DataType.List(DataType.Uuid)), ("somepartitionkey1", DataType.Text), ("somepartitionkey2", DataType.Text) }, r => r.WithRow( pocoWithCustomAttributes.ListOfGuids, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = mapper.Fetch<PocoWithCompositeKey>("SELECT * from " + table.Name).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, records[0].SomePartitionKey1); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, records[0].SomePartitionKey2); Assert.AreEqual(pocoWithCustomAttributes.ListOfGuids, records[0].ListOfGuids); Assert.AreEqual(new PocoWithCompositeKey().IgnoredString, records[0].IgnoredString); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute("SELECT * from " + table.Name).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, rows[0].GetValue<string>("somepartitionkey1")); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, rows[0].GetValue<string>("somepartitionkey2")); Assert.AreEqual(pocoWithCustomAttributes.ListOfGuids, rows[0].GetValue<List<Guid>>("listofguids")); var ex = Assert.Throws<ArgumentException>(() => rows[0].GetValue<string>("ignoredstring")); Assert.AreEqual("Column ignoredstring not found", ex.Message); } /// <summary> /// Successfully insert Poco object which have values that are part of a composite key /// </summary> [Test] public void Attributes_MultipleClusteringKeys() { var config = new MappingConfiguration(); config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(PocoWithClusteringKeys), () => Linq::LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(PocoWithClusteringKeys))); var table = new Linq::Table<PocoWithClusteringKeys>(Session, config); table.Create(); VerifyQuery( "CREATE TABLE \"pocowithclusteringkeys\" (" + "\"guid1\" uuid, \"guid2\" uuid, \"somepartitionkey1\" text, \"somepartitionkey2\" text, " + "PRIMARY KEY ((\"somepartitionkey1\", \"somepartitionkey2\"), \"guid1\", \"guid2\"))", 1); var cqlClient = new Mapper(Session, config); var pocoWithCustomAttributes = new PocoWithClusteringKeys { SomePartitionKey1 = Guid.NewGuid().ToString(), SomePartitionKey2 = Guid.NewGuid().ToString(), Guid1 = Guid.NewGuid(), Guid2 = Guid.NewGuid(), }; cqlClient.Insert(pocoWithCustomAttributes); VerifyBoundStatement( "INSERT INTO \"pocowithclusteringkeys\" (" + "\"guid1\", \"guid2\", \"somepartitionkey1\", \"somepartitionkey2\") " + "VALUES (?, ?, ?, ?)", 1, pocoWithCustomAttributes.Guid1, pocoWithCustomAttributes.Guid2, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2); TestCluster.PrimeFluent( b => b.WhenQuery("SELECT * from " + table.Name) .ThenRowsSuccess( new[] { ("guid1", DataType.Uuid), ("guid2", DataType.Uuid), ("somepartitionkey1", DataType.Text), ("somepartitionkey2", DataType.Text) }, r => r.WithRow( pocoWithCustomAttributes.Guid1, pocoWithCustomAttributes.Guid2, pocoWithCustomAttributes.SomePartitionKey1, pocoWithCustomAttributes.SomePartitionKey2))); // Get records using mapped object, validate that the value from Cassandra was ignored in favor of the default val var records = cqlClient.Fetch<PocoWithClusteringKeys>("SELECT * from " + table.Name).ToList(); Assert.AreEqual(1, records.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, records[0].SomePartitionKey1); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, records[0].SomePartitionKey2); Assert.AreEqual(pocoWithCustomAttributes.Guid1, records[0].Guid1); Assert.AreEqual(pocoWithCustomAttributes.Guid2, records[0].Guid2); // Query for the column that the Linq table create created, verify no value was uploaded to it var rows = Session.Execute("SELECT * from " + table.Name).GetRows().ToList(); Assert.AreEqual(1, rows.Count); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey1, rows[0].GetValue<string>("somepartitionkey1")); Assert.AreEqual(pocoWithCustomAttributes.SomePartitionKey2, rows[0].GetValue<string>("somepartitionkey2")); Assert.AreEqual(pocoWithCustomAttributes.Guid1, rows[0].GetValue<Guid>("guid1")); Assert.AreEqual(pocoWithCustomAttributes.Guid2, rows[0].GetValue<Guid>("guid2")); } /// <summary> /// Expect a "missing partition key" failure upon create since there was no field specific to the class being created /// that was marked as partition key. /// This happens despite the matching partition key names since they reside in different classes. /// </summary> [Test] public void Attributes_Mapping_MisMatchedClassTypesButTheSamePartitionKeyName() { var mapping = new Map<SimplePocoWithPartitionKey>(); mapping.CaseSensitive(); mapping.PartitionKey(u => u.StringType); var table = new Linq::Table<ManyDataTypesPoco>(Session, new MappingConfiguration().Define(mapping)); // Validate expected Exception var ex = Assert.Throws<InvalidOperationException>(table.Create); StringAssert.Contains("No partition key defined", ex.Message); } /// <summary> /// The Partition key Attribute from the Poco class is used to create a table with a partition key /// </summary> [Test] public void Attributes_ClusteringKey_NoName() { var table = GetTable<EmptyClusteringColumnName>(); table.Create(); VerifyQuery( "CREATE TABLE \"test_map_empty_clust_column_name\" (\"cluster\" text, \"id\" int, \"value\" text, " + "PRIMARY KEY (\"id\", \"cluster\"))", 1); var definition = new AttributeBasedTypeDefinition(typeof(EmptyClusteringColumnName)); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); var pocoToUpload = new EmptyClusteringColumnName { Id = 1, cluster = "c2", value = "v2" }; mapper.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO test_map_empty_clust_column_name (cluster, id, value) VALUES (?, ?, ?)", 1, pocoToUpload.cluster, pocoToUpload.Id, pocoToUpload.value); var cqlSelect = $"SELECT * from {table.Name} where id={pocoToUpload.Id}"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("cluster", DataType.Text), ("id", DataType.Int), ("value", DataType.Text) }, r => r.WithRow(pocoToUpload.cluster, pocoToUpload.Id, pocoToUpload.value))); var instancesQueried = mapper.Fetch<EmptyClusteringColumnName>(cqlSelect).ToList(); Assert.AreEqual(1, instancesQueried.Count); Assert.AreEqual(pocoToUpload.Id, instancesQueried[0].Id); Assert.AreEqual(pocoToUpload.cluster, instancesQueried[0].cluster); Assert.AreEqual(pocoToUpload.value, instancesQueried[0].value); } /// <summary> /// The Partition key Attribute from the Poco class is used to create a table with a partition key /// </summary> [Test] public void Attributes_PartitionKey() { var table = GetTable<SimplePocoWithPartitionKey>(); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithPartitionKey (StringTyp text, StringType text, StringTypeNotPartitionKey text, " + "PRIMARY KEY (StringType))", 1); var cqlClient = GetMapper(); var pocoToUpload = new SimplePocoWithPartitionKey(); cqlClient.Insert(pocoToUpload); VerifyBoundStatement( "INSERT INTO SimplePocoWithPartitionKey (StringTyp, StringType, StringTypeNotPartitionKey) VALUES (?, ?, ?)", 1, pocoToUpload.StringTyp, pocoToUpload.StringType, pocoToUpload.StringTypeNotPartitionKey); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where \"{"stringtype"}\"='{pocoToUpload.StringType}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("StringTyp", DataType.Text), ("StringType", DataType.Text), ("StringTypeNotPartitionKey", DataType.Text) }, r => r.WithRow( pocoToUpload.StringTyp, pocoToUpload.StringType, pocoToUpload.StringTypeNotPartitionKey))); var instancesQueried = cqlClient.Fetch<SimplePocoWithPartitionKey>(cqlSelect).ToList(); Assert.AreEqual(1, instancesQueried.Count); Assert.AreEqual(pocoToUpload.StringType, instancesQueried[0].StringType); Assert.AreEqual(pocoToUpload.StringTyp, instancesQueried[0].StringTyp); Assert.AreEqual(pocoToUpload.StringTypeNotPartitionKey, instancesQueried[0].StringTypeNotPartitionKey); } /// <summary> /// Expect the mapping mechanism to recognize / use the Partition key Attribute from /// the Poco class it's derived from /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_SecondaryIndex() { var table = GetTable<SimplePocoWithSecondaryIndex>(); table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithSecondaryIndex (SomePartitionKey text, SomeSecondaryIndex int, " + "PRIMARY KEY (SomePartitionKey))", 1); VerifyQuery("CREATE INDEX ON SimplePocoWithSecondaryIndex (SomeSecondaryIndex)", 1); var cqlClient = GetMapper(); var expectedTotalRecords = 10; var defaultInstance = new SimplePocoWithSecondaryIndex(); var entities = new List<SimplePocoWithSecondaryIndex>(); for (var i = 0; i < expectedTotalRecords; i++) { var entity = new SimplePocoWithSecondaryIndex(i); entities.Add(entity); cqlClient.Insert(entity); } var logs = TestCluster.GetQueries(null, QueryType.Execute); foreach (var entity in entities) { VerifyStatement( logs, "INSERT INTO SimplePocoWithSecondaryIndex (SomePartitionKey, SomeSecondaryIndex) VALUES (?, ?)", 1, entity.SomePartitionKey, entity.SomeSecondaryIndex); } // Select using basic cql var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where {"somesecondaryindex"}={defaultInstance.SomeSecondaryIndex} order by {"somepartitionkey"} desc"; TestCluster.PrimeFluent( b => b.WhenQuery("SELECT SomePartitionKey, SomeSecondaryIndex FROM SimplePocoWithSecondaryIndex") .ThenRowsSuccess( new[] { ("somepartitionkey", DataType.Text), ("somesecondaryindex", DataType.Int) }, r => r.WithRows(entities.Select(entity => new object[] { entity.SomePartitionKey, entity.SomeSecondaryIndex }).ToArray()))); TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenServerError(ServerError.Invalid, "ORDER BY with 2ndary indexes is not supported.")); var instancesQueried = cqlClient.Fetch<SimplePocoWithSecondaryIndex>().ToList(); Assert.AreEqual(expectedTotalRecords, instancesQueried.Count); var ex = Assert.Throws<InvalidQueryException>(() => cqlClient.Fetch<SimplePocoWithSecondaryIndex>(cqlSelect)); Assert.AreEqual("ORDER BY with 2ndary indexes is not supported.", ex.Message); } /// <summary> /// Expect the mapping mechanism to recognize / use the Column Attribute from /// the Poco class it's derived from /// </summary> [Test] public void Attributes_Column_NoCustomLabel() { // Setup var expectedTotalRecords = 1; var definition = new AttributeBasedTypeDefinition(typeof(SimplePocoWithColumnAttribute)); var table = new Linq::Table<SimplePocoWithColumnAttribute>(Session, new MappingConfiguration().Define(definition)); Assert.AreNotEqual(table.Name, table.Name.ToLower()); table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithColumnAttribute (SomeColumn int, SomePartitionKey text, PRIMARY KEY (SomePartitionKey))", 1); var defaultInstance = new SimplePocoWithColumnAttribute(); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); mapper.Insert(defaultInstance); VerifyBoundStatement( "INSERT INTO SimplePocoWithColumnAttribute (SomeColumn, SomePartitionKey) VALUES (?, ?)", 1, defaultInstance.SomeColumn, defaultInstance.SomePartitionKey); // Validate using mapped Fetch var cqlSelectAll = "select * from " + table.Name.ToLower(); TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelectAll) .ThenRowsSuccess( new[] { ("somecolumn", DataType.Int), ("somepartitionkey", DataType.Text) }, r => r.WithRow(defaultInstance.SomeColumn, defaultInstance.SomePartitionKey))); var instancesQueried = mapper.Fetch<SimplePocoWithColumnAttribute>(cqlSelectAll).ToList(); Assert.AreEqual(expectedTotalRecords, instancesQueried.Count); var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where {"somepartitionkey"}='{defaultInstance.SomePartitionKey}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("somecolumn", DataType.Int), ("somepartitionkey", DataType.Text) }, r => r.WithRow(defaultInstance.SomeColumn, defaultInstance.SomePartitionKey))); var actualObjectsInOrder = mapper.Fetch<SimplePocoWithColumnAttribute>(cqlSelect).ToList(); Assert.AreEqual(expectedTotalRecords, actualObjectsInOrder.Count); // Validate using straight cql to verify column names var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(expectedTotalRecords, rows.Count); Assert.AreEqual(defaultInstance.SomeColumn, rows[0].GetValue<int>("somecolumn")); } /// <summary> /// Expect the mapping mechanism to recognize / use the Column Attribute from /// the Poco class it's derived from, including the custom label option /// </summary> [Test, TestCassandraVersion(2, 0)] public void Attributes_Column_CustomLabels() { // Setup var expectedTotalRecords = 1; var definition = new AttributeBasedTypeDefinition(typeof(SimplePocoWithColumnLabel_CustomColumnName)); var table = new Linq::Table<SimplePocoWithColumnLabel_CustomColumnName>(Session, new MappingConfiguration().Define(definition)); Assert.AreEqual(typeof(SimplePocoWithColumnLabel_CustomColumnName).Name, table.Name); // Assert table name is case sensitive now Assert.AreNotEqual(typeof(SimplePocoWithColumnLabel_CustomColumnName).Name, typeof(SimplePocoWithColumnLabel_CustomColumnName).Name.ToLower()); // Assert table name is case senstive table.Create(); VerifyQuery( "CREATE TABLE SimplePocoWithColumnLabel_CustomColumnName (someCaseSensitivePartitionKey text, some_column_label_thats_different int, " + "PRIMARY KEY (someCaseSensitivePartitionKey))", 1); var defaultInstance = new SimplePocoWithColumnLabel_CustomColumnName(); var mapper = new Mapper(Session, new MappingConfiguration().Define(definition)); mapper.Insert(defaultInstance); VerifyBoundStatement( "INSERT INTO SimplePocoWithColumnLabel_CustomColumnName (someCaseSensitivePartitionKey, some_column_label_thats_different) " + "VALUES (?, ?)", 1, defaultInstance.SomePartitionKey, defaultInstance.SomeColumn); // Validate using mapped Fetch var cqlSelect = $"SELECT * from \"{table.Name.ToLower()}\" where {"someCaseSensitivePartitionKey"}='{defaultInstance.SomePartitionKey}'"; TestCluster.PrimeFluent( b => b.WhenQuery(cqlSelect) .ThenRowsSuccess( new[] { ("some_column_label_thats_different", DataType.Int), ("someCaseSensitivePartitionKey", DataType.Text) }, r => r.WithRow(defaultInstance.SomeColumn, defaultInstance.SomePartitionKey))); var actualObjectsInOrder = mapper.Fetch<SimplePocoWithColumnLabel_CustomColumnName>(cqlSelect).ToList(); Assert.AreEqual(expectedTotalRecords, actualObjectsInOrder.Count); Assert.AreEqual(defaultInstance.SomeColumn, actualObjectsInOrder[0].SomeColumn); // Validate using straight cql to verify column names var rows = Session.Execute(cqlSelect).GetRows().ToList(); Assert.AreEqual(expectedTotalRecords, rows.Count); Assert.AreEqual(defaultInstance.SomeColumn, rows[0].GetValue<int>("some_column_label_thats_different")); } ///////////////////////////////////////// /// Private test classes ///////////////////////////////////////// [Table("SimplePocoWithColumnLabel_CustomColumnName")] public class SimplePocoWithColumnLabel_CustomColumnName { [Column("someCaseSensitivePartitionKey")] [PartitionKey] public string SomePartitionKey = "defaultPartitionKeyVal"; [Column("some_column_label_thats_different")] public int SomeColumn = 191991919; } public class SimplePocoWithColumnAttribute { [PartitionKey] public string SomePartitionKey = "defaultPartitionKeyVal"; [Column] public int SomeColumn = 121212121; } public class SimplePocoWithSecondaryIndex { [PartitionKey] public string SomePartitionKey; [SecondaryIndex] public int SomeSecondaryIndex = 1; public SimplePocoWithSecondaryIndex() { } public SimplePocoWithSecondaryIndex(int i) { SomePartitionKey = "partitionKey_" + i; } } private class SimplePocoWithPartitionKey { public string StringTyp = "someStringValue"; [PartitionKey] public string StringType = "someStringValue"; public string StringTypeNotPartitionKey = "someStringValueNotPk"; } private class PocoWithIgnoredAttributes { [PartitionKey] public string SomePartitionKey = "somePartitionKeyDefaultValue"; public double SomeNonIgnoredDouble = 123456; [Cassandra.Mapping.Attributes.Ignore] public string IgnoredStringAttribute = "someIgnoredString"; } /// <summary> /// Test poco class that uses both Linq and Cassandra.Mapping attributes at the same time /// </summary> [Linq::Table("pocowithignrdattr_linqandmapping")] private class PocoWithIgnrdAttr_LinqAndMapping { [Linq::PartitionKey] [PartitionKey] [Linq::Column("somepartitionkey")] public string SomePartitionKey = "somePartitionKeyDefaultValue"; [Linq::Column("somenonignoreddouble")] public double SomeNonIgnoredDouble = 123456; [Cassandra.Mapping.Attributes.Ignore] [Linq::Column(Attributes.IgnoredStringAttribute)] public string IgnoredStringAttribute = "someIgnoredString"; } /// <summary> /// See PocoWithIgnoredAttributes for correctly implemented counterpart /// </summary> [Linq::Table("pocowithwrongfieldlabeledpk")] private class PocoWithWrongFieldLabeledPk { [Linq::PartitionKey] [Linq::Column("somepartitionkey")] public string SomePartitionKey = "somePartitionKeyDefaultValue"; [Linq::Column("somenonignoreddouble")] public double SomeNonIgnoredDouble = 123456; [PartitionKey] [Linq::Column("someotherstring")] public string SomeOtherString = "someOtherString"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted /// </summary> private class PocoWithOnlyPartitionKeyNotLabeled { public string SomeString = "somestring_value"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted, as well as another field that is not labeled /// </summary> private class PocoWithPartitionKeyNotLabeledAndOtherField { public string SomeString = "somestring_value"; public string SomeOtherString = "someotherstring_value"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted /// </summary> private class PocoMislabeledClusteringKey { [ClusteringKey] public string SomeString = "someStringValue"; } /// <summary> /// Class with Mapping.Attributes.Partition key ommitted /// </summary> private class PocoWithPartitionKeyOmitted { public double SomeDouble = 123456; public List<string> SomeList = new List<string>(); } /// <summary> /// Class with Mapping.Attributes.Partition key included, which was missing from PocoWithPartitionKeyOmitted /// </summary> private class PocoWithPartitionKeyIncluded { [PartitionKey] public string SomeString = "somePartitionKeyDefaultValue"; public double SomeDouble = 123456; public List<string> SomeList = new List<string>(); } /// <summary> /// Class designed to fix the issue with PocoWithPartitionKeyOmitted, which is implied by the name /// </summary> private class PocoWithPartitionKeyIncludedMapping : Map<PocoWithPartitionKeyIncluded> { public PocoWithPartitionKeyIncludedMapping() { TableName(typeof(PocoWithPartitionKeyOmitted).Name.ToLower()); PartitionKey(u => u.SomeString); Column(u => u.SomeString, cm => cm.WithName("somestring")); } } [Linq::Table("pocowithcompositekey")] private class PocoWithCompositeKey { [Linq::PartitionKey(1)] [PartitionKey(1)] [Linq::Column("somepartitionkey1")] public string SomePartitionKey1 = "somepartitionkey1_val"; [Linq::PartitionKey(2)] [PartitionKey(2)] [Linq::Column("somepartitionkey2")] public string SomePartitionKey2 = "somepartitionkey2_val"; [Linq::Column("listofguids")] public List<Guid> ListOfGuids; [Cassandra.Mapping.Attributes.Ignore] [Linq::Column("ignoredstring")] public string IgnoredString = "someIgnoredString_val"; } [Linq::Table("pocowithclusteringkeys")] private class PocoWithClusteringKeys { [Linq::PartitionKey(1)] [PartitionKey(1)] [Linq::Column("somepartitionkey1")] public string SomePartitionKey1 = "somepartitionkey1_val"; [Linq::PartitionKey(2)] [PartitionKey(2)] [Linq::Column("somepartitionkey2")] public string SomePartitionKey2 = "somepartitionkey2_val"; [Linq::ClusteringKey(1)] [ClusteringKey(1)] [Linq::Column("guid1")] public Guid Guid1; [Linq::ClusteringKey(2)] [ClusteringKey(2)] [Linq::Column("guid2")] public Guid Guid2; } }
1,308
51,379
// <autogenerated /> using System; using System.Reflection; [assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Mapping\Tests\Counter.cs
Cassandra.IntegrationTests.Mapping.Tests
Counter
['[Cassandra.Mapping.Attributes.Counter]\n public long Counter;', '[Cassandra.Mapping.Attributes.PartitionKey(1)]\n public Guid KeyPart1;', '[Cassandra.Mapping.Attributes.PartitionKey(2)]\n public Decimal KeyPart2;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.SimulacronAPI', 'Cassandra.IntegrationTests.SimulacronAPI.PrimeBuilder.Then', 'Cassandra.Mapping', 'Cassandra.Mapping.Attributes', 'NUnit.Framework']
NUnit
net8
public class Counter : SimulacronTest { [Test] public void Counter_Success() { var config = new AttributeBasedTypeDefinition(typeof(PocoWithCounterAttribute)); var table = new Table<PocoWithCounterAttribute>(Session, new MappingConfiguration().Define(config)); table.CreateIfNotExists(); VerifyQuery( "CREATE TABLE PocoWithCounterAttribute (Counter counter, KeyPart1 uuid, KeyPart2 decimal, " + "PRIMARY KEY ((KeyPart1, KeyPart2)))", 1); var cqlClient = new Mapper(Session, new MappingConfiguration().Define(config)); var counterPocos = new List<PocoWithCounterAttribute>(); for (var i = 0; i < 10; i++) { counterPocos.Add( new PocoWithCounterAttribute() { KeyPart1 = Guid.NewGuid(), KeyPart2 = (decimal)123, }); } var counterIncrements = 100; foreach (var pocoWithCounter in counterPocos) { pocoWithCounter.Counter += counterIncrements; } TestCluster.PrimeFluent( b => b.WhenQuery("SELECT Counter, KeyPart1, KeyPart2 FROM PocoWithCounterAttribute") .ThenRowsSuccess(new[] { ("Counter", DataType.Counter), ("KeyPart1", DataType.Uuid), ("KeyPart2", DataType.Decimal) }, r => r.WithRows(counterPocos.Select(c => new object [] { c.Counter, c.KeyPart1, c.KeyPart2 }).ToArray()))); var countersQueried = cqlClient.Fetch<PocoWithCounterAttribute>().ToList(); foreach (var pocoWithCounterExpected in counterPocos) { var counterFound = false; foreach (var pocoWithCounterActual in countersQueried) { if (pocoWithCounterExpected.KeyPart1 == pocoWithCounterActual.KeyPart1) { Assert.AreEqual(pocoWithCounterExpected.KeyPart2, pocoWithCounterExpected.KeyPart2); Assert.AreEqual(pocoWithCounterExpected.Counter, pocoWithCounterExpected.Counter); counterFound = true; } } Assert.IsTrue(counterFound, "Counter with first key part: " + pocoWithCounterExpected.KeyPart1 + " was not found!"); } } /// <summary> /// Validate expected error message when attempting to insert a row that contains a counter /// </summary> [Test] public void Counter_LinqAttributes_AttemptInsert() { var table = new Table<PocoWithCounterAttribute>(Session, new MappingConfiguration()); table.Create(); VerifyQuery( "CREATE TABLE PocoWithCounterAttribute (Counter counter, KeyPart1 uuid, KeyPart2 decimal, " + "PRIMARY KEY ((KeyPart1, KeyPart2)))", 1); PocoWithCounterAttribute pocoAndLinqAttributesPocos = new PocoWithCounterAttribute() { KeyPart1 = Guid.NewGuid(), KeyPart2 = (decimal)123, }; string expectedErrMsg = "INSERT statement(s)? are not allowed on counter tables, use UPDATE instead"; TestCluster.PrimeFluent( b => b.WhenQuery( "INSERT INTO PocoWithCounterAttribute (Counter, KeyPart1, KeyPart2) VALUES (?, ?, ?)", when => when.WithParams( pocoAndLinqAttributesPocos.Counter, pocoAndLinqAttributesPocos.KeyPart1, pocoAndLinqAttributesPocos.KeyPart2)) .ThenServerError(ServerError.Invalid, expectedErrMsg)); // Validate Error Message var e = Assert.Throws<InvalidQueryException>(() => table.Insert(pocoAndLinqAttributesPocos).Execute()); Assert.AreEqual(expectedErrMsg, e.Message); } private class PocoWithCounterAttribute { [Cassandra.Mapping.Attributes.Counter] public long Counter; [Cassandra.Mapping.Attributes.PartitionKey(1)] public Guid KeyPart1; [Cassandra.Mapping.Attributes.PartitionKey(2)] public Decimal KeyPart2; } }
1,000
5,737
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Cassandra.Metrics.Abstractions { /// <summary> /// Represents a metric of type Counter. /// </summary> public interface IDriverCounter : IDriverMetric { void Increment(); void Increment(long value); } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Mapping\Tests\Delete.cs
Cassandra.IntegrationTests.Mapping.Tests
Delete
['ISession _session = null;', 'private List<Movie> _movieList;', 'string _uniqueKsName = TestUtils.GetUniqueKeyspaceName();', 'private Table<Movie> _movieTable;', 'private Mapper _mapper;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.Linq.Structures', 'Cassandra.IntegrationTests.TestBase', 'Cassandra.Mapping', 'Cassandra.Tests', 'Cassandra.Tests.Mapping.Pocos', 'NUnit.Framework']
NUnit
net8
[Category(TestCategory.Short), Category(TestCategory.RealCluster)] public class Delete : SharedClusterTest { ISession _session = null; private List<Movie> _movieList; string _uniqueKsName = TestUtils.GetUniqueKeyspaceName(); private Table<Movie> _movieTable; private Mapper _mapper; public override void OneTimeSetUp() { base.OneTimeSetUp(); _session = Session; _session.CreateKeyspace(_uniqueKsName); _session.ChangeKeyspace(_uniqueKsName); // drop table if exists, re-create var config = new Map<Movie>().PartitionKey(c => c.Title).PartitionKey(c => c.MovieMaker); var mappingConfig = new MappingConfiguration().Define(config); _mapper = new Mapper(_session, mappingConfig); _movieTable = new Table<Movie>(_session, mappingConfig); _movieTable.Create(); //Insert some data _movieList = Movie.GetDefaultMovieList(); } [SetUp] public void TestSetup() { foreach (var movie in _movieList) { _movieTable.Insert(movie).Execute(); } } /// <summary> /// Successfully delete a single record using a mapped instance /// </summary> [Test] public void Delete_Success() { // Setup Movie movieToDelete = _movieList[1]; // Delete the record _mapper.Delete(movieToDelete); List<Movie> actualMovieList = _movieTable.Execute().ToList(); Assert.AreEqual(_movieList.Count - 1, actualMovieList.Count()); Assert.IsFalse(Movie.ListContains(actualMovieList, movieToDelete)); } /// <summary> /// Successfully delete a single record using a mapped instance, async /// </summary> [Test] public void Delete_Async_Success() { // Setup Movie movieToDelete = _movieList[1]; // Delete the record _mapper.DeleteAsync(movieToDelete).Wait(); List<Movie> actualMovieList = _movieTable.Execute().ToList(); Assert.AreEqual(_movieList.Count - 1, actualMovieList.Count()); Assert.IsFalse(Movie.ListContains(actualMovieList, movieToDelete)); } /// <summary> /// Successfully delete a single record using a mapped instance, async /// with /// </summary> [Test] public void Delete_ConsistencyLevel_Valids() { // Setup Movie movieToDelete = _movieList[1]; // Insert the data var consistencyLevels = new ConsistencyLevel[] { ConsistencyLevel.All, ConsistencyLevel.Any, ConsistencyLevel.EachQuorum, ConsistencyLevel.LocalOne, ConsistencyLevel.LocalQuorum, ConsistencyLevel.One, ConsistencyLevel.Quorum, }; foreach (var consistencyLevel in consistencyLevels) { // Delete the record _mapper.DeleteAsync(movieToDelete, new CqlQueryOptions().SetConsistencyLevel(consistencyLevel)).Wait(); List<Movie> actualMovieList = _movieTable.Execute().ToList(); DateTime futureDateTime = DateTime.Now.AddSeconds(2); while (actualMovieList.Count == _movieList.Count && futureDateTime > DateTime.Now) { actualMovieList = _movieTable.Execute().ToList(); } Assert.AreEqual(_movieList.Count - 1, actualMovieList.Count(), "Unexpected failure for consistency level: " + consistencyLevel); Assert.IsFalse(Movie.ListContains(actualMovieList, movieToDelete)); // re-insert the movie _mapper.Insert(movieToDelete); actualMovieList.Clear(); actualMovieList = _movieTable.Execute().ToList(); futureDateTime = DateTime.Now.AddSeconds(2); while (actualMovieList.Count < _movieList.Count && futureDateTime > DateTime.Now) { actualMovieList = _movieTable.Execute().ToList(); } Assert.AreEqual(actualMovieList.Count, _movieList.Count); } } /// <summary> /// Successfully delete a single record using a mapped instance, async /// Also set the consistency level to one more than the current number of nodes /// Expect the request to fail silently. /// </summary> [Test] public void Delete_ConsistencyLevel_Invalids() { // Setup Movie movieToDelete = _movieList[1]; // Attempt to Delete the record Assert.Throws<AggregateException>(() => _mapper.DeleteAsync(movieToDelete, new CqlQueryOptions().SetConsistencyLevel(ConsistencyLevel.Two)).Wait()); Assert.Throws<AggregateException>(() => _mapper.DeleteAsync(movieToDelete, new CqlQueryOptions().SetConsistencyLevel(ConsistencyLevel.Three)).Wait()); } [Test] public void DeleteIf_Applied_Test() { var config = new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Id).TableName("song_delete_if")); //Use linq to create the table new Table<Song>(_session, config).Create(); var mapper = new Mapper(_session, config); var song = new Song { Id = Guid.NewGuid(), Artist = "Cream", Title = "Crossroad", ReleaseDate = DateTimeOffset.Parse("1970/1/1") }; mapper.Insert(song); //It should not apply it as the condition will NOT be satisfied var appliedInfo = mapper.DeleteIf<Song>(Cql.New("WHERE id = ? IF title = ?", song.Id, "Crossroad2")); Assert.False(appliedInfo.Applied); Assert.NotNull(appliedInfo.Existing); Assert.AreEqual("Crossroad", appliedInfo.Existing.Title); //It should apply it as the condition will be satisfied appliedInfo = mapper.DeleteIf<Song>(Cql.New("WHERE id = ? IF title = ?", song.Id, song.Title)); Assert.True(appliedInfo.Applied); Assert.Null(appliedInfo.Existing); } }
1,000
7,602
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Linq.Expressions; using Cassandra.Mapping; using Cassandra.Mapping.Statements; namespace Cassandra.Data.Linq { public class CqlDelete : CqlCommand { private bool _ifExists = false; internal CqlDelete(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData) : base(expression, table, stmtFactory, pocoData) { } public CqlDelete IfExists() { _ifExists = true; return this; } protected internal override string GetCql(out object[] values) { var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); return visitor.GetDelete(Expression, out values, _timestamp, _ifExists); } public override string ToString() { object[] _; return GetCql(out _); } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Cassandra.IntegrationTests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.IntegrationTests\Mapping\Tests\Update.cs
Cassandra.IntegrationTests.Mapping.Tests
Update
['ISession _session;', 'private List<Movie> _movieList = Movie.GetDefaultMovieList();', 'string _uniqueKsName = TestUtils.GetUniqueKeyspaceName();', 'private Table<Movie> _movieTable;', 'private Mapper _mapper;', 'public int Size;', 'public string TheDirector;', 'public string TheMaker;']
['System', 'System.Collections.Generic', 'System.Linq', 'Cassandra.Data.Linq', 'Cassandra.IntegrationTests.Linq.Structures', 'Cassandra.IntegrationTests.TestBase', 'Cassandra.Mapping', 'Cassandra.Tests', 'Cassandra.Tests.Mapping.Pocos', 'NUnit.Framework']
NUnit
net8
[Category(TestCategory.Short), Category(TestCategory.RealCluster)] public class Update : SharedClusterTest { ISession _session; private List<Movie> _movieList = Movie.GetDefaultMovieList(); string _uniqueKsName = TestUtils.GetUniqueKeyspaceName(); private Table<Movie> _movieTable; private Mapper _mapper; public override void OneTimeSetUp() { base.OneTimeSetUp(); _session = Session; _session.CreateKeyspace(_uniqueKsName); _session.ChangeKeyspace(_uniqueKsName); _session.Execute(string.Format(PocoWithEnumCollections.DefaultCreateTableCql, "tbl_with_enum_collections")); // drop table if exists, re-create var config = new Map<Movie>().PartitionKey(c => c.MovieMaker); var mappingConfig = new MappingConfiguration().Define(config); _mapper = new Mapper(_session, mappingConfig); _movieTable = new Table<Movie>(_session, mappingConfig); _movieTable.Create(); //Insert some data foreach (var movie in _movieList) _movieTable.Insert(movie).Execute(); } /// <summary> /// Attempt to update a single record to the same values, validate that the record is not altered. /// /// @test_category queries:basic /// </summary> [Test] public void Update_Single_ToSameValues() { // Setup Movie movieToUpdate = _movieList[1]; // update to the same values _mapper.Update(movieToUpdate); List<Movie> actualMovieList = _movieTable.Execute().ToList(); Assert.AreEqual(_movieList.Count, actualMovieList.Count()); Movie.AssertListContains(actualMovieList, movieToUpdate); } /// <summary> /// Update a single record to different values, validate that the resultant data in Cassandra is correct. /// /// @test_category queries:basic /// </summary> [Test] public void Update_Single_ToDifferentValues() { // Setup Movie movieToUpdate = _movieList[1]; // Update to different values var expectedMovie = new Movie(movieToUpdate.Title + "_something_different", movieToUpdate.Director, movieToUpdate.MainActor + "_something_different", movieToUpdate.MovieMaker, 1212); _mapper.Update(expectedMovie); List<Movie> actualMovieList = _movieTable.Execute().ToList(); Assert.AreEqual(_movieList.Count, actualMovieList.Count()); Assert.IsFalse(Movie.ListContains(_movieList, expectedMovie)); Movie.AssertListContains(actualMovieList, expectedMovie); Assert.IsFalse(Movie.ListContains(actualMovieList, movieToUpdate)); } [Test] public void UpdateIf_Applied_Test() { var config = new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Id).TableName("song_update_if")); //Use linq to create the table new Table<Song>(_session, config).Create(); var mapper = new Mapper(_session, config); var song = new Song { Id = Guid.NewGuid(), Artist = "Cream", Title = "Crossroad", ReleaseDate = DateTimeOffset.Parse("1970/1/1")}; //It is the first song there, it should apply it mapper.Insert(song); const string query = "SET artist = ?, title = ? WHERE id = ? IF releasedate = ?"; var appliedInfo = mapper.UpdateIf<Song>(Cql.New(query, song.Artist, "Crossroad2", song.Id, song.ReleaseDate)); Assert.True(appliedInfo.Applied); Assert.Null(appliedInfo.Existing); //Following times, it should not apply the mutation as the condition is not valid appliedInfo = mapper.UpdateIf<Song>(Cql.New(query, song.Artist, "Crossroad3", song.Id, DateTimeOffset.Now)); Assert.False(appliedInfo.Applied); Assert.NotNull(appliedInfo.Existing); Assert.AreEqual(song.ReleaseDate, appliedInfo.Existing.ReleaseDate); Assert.AreEqual("Crossroad2", mapper.First<Song>("WHERE id = ?", song.Id).Title); } /// <summary> /// Attempt to update a record without defining the partition key /// /// @test_category queries:basic /// </summary> [Test] public void Update_PartitionKeyOmitted() { // Setup Movie movieToUpdate = _movieList[1]; // Update to different values var expectedMovie = new Movie(movieToUpdate.Title + "_something_different", movieToUpdate.Director, "something_different_" + Randomm.RandomAlphaNum(10), null, 1212); var err = Assert.Throws<InvalidQueryException>(() => _mapper.Update(expectedMovie)); string expectedErrMsg = "Invalid null value (for partition key part|in condition for column) moviemaker"; StringAssert.IsMatch(expectedErrMsg, err.Message); } [Test] public void Update_Poco_With_Enum_Collections_Test() { var expectedCollection = new[]{ HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary<HairColor, TimeUuid> { { HairColor.Brown, TimeUuid.NewId() }, { HairColor.Red, TimeUuid.NewId() } }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = new SortedDictionary<int, Guid>(expectedMap.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value)); var pocoToUpdate = new PocoWithEnumCollections { Id = 3000L, Dictionary1 = expectedMap.ToDictionary(x => x.Key, x=> x.Value), Dictionary2 = expectedMap.ToDictionary(x => x.Key, x=> x.Value), Dictionary3 = expectedMap, List1 = expectedCollection.ToList(), List2 = expectedCollection.ToList(), Set1 = new SortedSet<HairColor>(expectedCollection), Set2 = new SortedSet<HairColor>(expectedCollection), Set3 = new HashSet<HairColor>(expectedCollection) }; pocoToUpdate.Array1 = new[]{ HairColor.Blonde, HairColor.Red, HairColor.Black }; pocoToUpdate.Dictionary1.Add(HairColor.Black, Guid.NewGuid()); pocoToUpdate.Dictionary2.Add(HairColor.Black, Guid.NewGuid()); pocoToUpdate.List1.Add(HairColor.Black); pocoToUpdate.Set1.Add(HairColor.Black); pocoToUpdate.Set2.Add(HairColor.Black); pocoToUpdate.Set3.Add(HairColor.Black); const string insertQuery = "INSERT INTO tbl_with_enum_collections (id, list1, list2, array1, set1, set2, set3, map1, map2, map3)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; _session.Execute(new SimpleStatement(insertQuery, pocoToUpdate.Id, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, mapValues, mapValues, mapValues)); var config = new MappingConfiguration().Define( PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections")); var mapper = new Mapper(_session, config); mapper.Update(pocoToUpdate); var statement = new SimpleStatement("SELECT * FROM tbl_with_enum_collections WHERE id = ?", pocoToUpdate.Id); var row = _session.Execute(statement).First(); Assert.AreEqual(pocoToUpdate.Id, row.GetValue<long>("id")); CollectionAssert.AreEquivalent(pocoToUpdate.List1.Select(x => (int)x).ToList(), row.GetValue<IEnumerable<int>>("list1")); CollectionAssert.AreEquivalent(pocoToUpdate.List2.Select(x => (int)x).ToList(), row.GetValue<IEnumerable<int>>("list2")); CollectionAssert.AreEquivalent(pocoToUpdate.Array1.Select(x => (int)x).ToArray(), row.GetValue<IEnumerable<int>>("array1")); CollectionAssert.AreEquivalent(pocoToUpdate.Set1.Select(x => (int)x), row.GetValue<IEnumerable<int>>("set1")); CollectionAssert.AreEquivalent(pocoToUpdate.Set2.Select(x => (int)x), row.GetValue<IEnumerable<int>>("set2")); CollectionAssert.AreEquivalent(pocoToUpdate.Set3.Select(x => (int)x), row.GetValue<IEnumerable<int>>("set3")); CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary1.ToDictionary(x => (int) x.Key, x=> (Guid)x.Value), row.GetValue<IDictionary<int, Guid>>("map1")); CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary2.ToDictionary(x => (int) x.Key, x=> (Guid)x.Value), row.GetValue<IDictionary<int, Guid>>("map2")); CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary3.ToDictionary(x => (int) x.Key, x=> (Guid)x.Value), row.GetValue<IDictionary<int, Guid>>("map3")); } public class ExtMovie { public int Size; public string TheDirector; public string TheMaker; } }
1,000
10,515
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Linq.Expressions; using Cassandra.Mapping; using Cassandra.Mapping.Statements; namespace Cassandra.Data.Linq { public class CqlUpdate : CqlCommand { private readonly MapperFactory _mapperFactory; internal CqlUpdate(Expression expression, ITable table, StatementFactory stmtFactory, PocoData pocoData, MapperFactory mapperFactory) : base(expression, table, stmtFactory, pocoData) { _mapperFactory = mapperFactory; } protected internal override string GetCql(out object[] values) { var visitor = new CqlExpressionVisitor(PocoData, Table.Name, Table.KeyspaceName); return visitor.GetUpdate(Expression, out values, _ttl, _timestamp, _mapperFactory); } public override string ToString() { object[] _; return GetCql(out _); } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\Cassandra.Tests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\CqlCommandTest.cs
Cassandra.Tests
CqlCommandTest
[]
['System', 'System.Data', 'Cassandra.Data', 'NUnit.Framework']
NUnit
net8
[TestFixture] public class CqlCommandTest { [Test] public void TestCqlCommand() { var target = new CqlCommand(); // test CreateDbParameter() var parameter = target.CreateParameter(); Assert.IsNotNull(parameter); // test Parameters var parameterCollection = target.Parameters; Assert.IsNotNull(parameterCollection); Assert.AreEqual(parameterCollection, target.Parameters); // test Connection var connection = new CqlConnection("contact points=127.0.0.1;port=9042"); Assert.IsNull(target.Connection); target.Connection = connection; Assert.AreEqual(connection, target.Connection); // test IsPrepared Assert.IsTrue(target.IsPrepared); // test CommandText var cqlQuery = "test query"; Assert.IsNull(target.CommandText); target.CommandText = cqlQuery; Assert.AreEqual(cqlQuery, target.CommandText); // test CommandTimeout, it should always return -1 var timeout = 1; Assert.AreEqual(-1, target.CommandTimeout); target.CommandTimeout = timeout; Assert.AreEqual(-1, target.CommandTimeout); // test CommandType, it should always return CommandType.Text var commandType = CommandType.TableDirect; Assert.AreEqual(CommandType.Text, target.CommandType); target.CommandType = commandType; Assert.AreEqual(CommandType.Text, target.CommandType); // test DesignTimeVisible, it should always return true Assert.IsTrue(target.DesignTimeVisible); target.DesignTimeVisible = false; Assert.IsTrue(target.DesignTimeVisible); // test UpdateRowSource, it should always return UpdateRowSource.FirstReturnedRecord var updateRowSource = UpdateRowSource.Both; Assert.AreEqual(UpdateRowSource.FirstReturnedRecord, target.UpdatedRowSource); target.UpdatedRowSource = updateRowSource; Assert.AreEqual(UpdateRowSource.FirstReturnedRecord, target.UpdatedRowSource); } [Test] public void TestCqlCommand_Prepare_Without_Connection() { var target = new CqlCommand(); target.Parameters.Add("p1", "1"); Assert.Throws<InvalidOperationException>(() => target.Prepare()); } }
752
3,340
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Data.Common; using System.Text.RegularExpressions; using System.Threading; namespace Cassandra.Data { /// <summary> /// Represents an CQL statement to execute against Cassandra /// </summary> public sealed class CqlCommand : DbCommand { internal CqlConnection CqlConnection; internal CqlBatchTransaction CqlTransaction; private string _commandText; private ConsistencyLevel _consistencyLevel = ConsistencyLevel.One; private static readonly Regex RegexParseParameterName = new Regex(@"\B:[a-zA-Z][a-zA-Z0-9_]*", RegexOptions.Compiled | RegexOptions.Multiline); private PreparedStatement _preparedStatement; private readonly CqlParameterCollection _parameters = new CqlParameterCollection(); public override void Cancel() { } /// <inheritdoc /> public override string CommandText { get { return _commandText; } set { _preparedStatement = null; _commandText = value; } } /// <summary> /// Gets or sets the ConsistencyLevel when executing the current <see cref="CqlCommand"/>. /// </summary> public ConsistencyLevel ConsistencyLevel { get { return _consistencyLevel; } set { _consistencyLevel = value; } } /// <summary> /// Gets whether this command has been prepared. /// </summary> public bool IsPrepared { get { return Parameters.Count == 0 || _preparedStatement != null; } } /// <summary> /// Gets the <see cref="CqlParameter"/>s. /// </summary> public new CqlParameterCollection Parameters { get { return _parameters; } } public override int CommandTimeout { get { return Timeout.Infinite; } set { } } public override CommandType CommandType { get { return CommandType.Text; } set { } } protected override DbParameter CreateDbParameter() { return new CqlParameter(); } protected override DbConnection DbConnection { get { return CqlConnection; } set { if (!(value is CqlConnection)) throw new InvalidOperationException(); CqlConnection = (CqlConnection)value; } } protected override DbParameterCollection DbParameterCollection { get { return _parameters; } } protected override DbTransaction DbTransaction { get { return CqlTransaction; } set { CqlTransaction = (value as CqlBatchTransaction); } } public override bool DesignTimeVisible { get { return true; } set { } } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { Prepare(); RowSet rowSet; if (_preparedStatement == null) { rowSet = CqlConnection.ManagedConnection.Execute(_commandText, ConsistencyLevel); } else //if _preparedStatement != null { var query = _preparedStatement.Bind(GetParameterValues()); query.SetConsistencyLevel(ConsistencyLevel); rowSet = CqlConnection.ManagedConnection.Execute(query); } return new CqlReader(rowSet); } public override int ExecuteNonQuery() { Prepare(); var cm = _commandText.ToUpperInvariant().TrimStart(); var managedConnection = CqlConnection.ManagedConnection; if (_preparedStatement == null) { if (cm.StartsWith("CREATE ") || cm.StartsWith("DROP ") || cm.StartsWith("ALTER ")) managedConnection.Execute(_commandText, ConsistencyLevel); else managedConnection.Execute(_commandText, ConsistencyLevel); } else //if _preparedStatement != null { var query = _preparedStatement.Bind(GetParameterValues()); query.SetConsistencyLevel(ConsistencyLevel); if (cm.StartsWith("CREATE ") || cm.StartsWith("DROP ") || cm.StartsWith("ALTER ")) managedConnection.Execute(query); else managedConnection.Execute(query); } return -1; } public override object ExecuteScalar() { Prepare(); RowSet rowSet; if (_preparedStatement == null) { rowSet = CqlConnection.ManagedConnection.Execute(_commandText, ConsistencyLevel); } else //if _preparedStatement != null { var query = _preparedStatement.Bind(GetParameterValues()); query.SetConsistencyLevel(ConsistencyLevel); rowSet = CqlConnection.ManagedConnection.Execute(query); } // return the first field value of the first row if exists if (rowSet == null) { return null; } var row = rowSet.GetRows().FirstOrDefault(); if (row == null || !row.Any()) { return null; } return row[0]; } public override void Prepare() { if (CqlConnection == null) { throw new InvalidOperationException("No connection bound to this command!"); } if (!IsPrepared && Parameters.Count > 0) { // replace all named parameter names to ? before preparing the statement // when binding the parameter values got from GetParameterValues() for executing // GetParameterValues() returns the array of parameter values // order by the occurence of parameter names in cql // so that we could support cases that parameters of the same name occur multiple times in cql var cqlQuery = RegexParseParameterName.Replace(CommandText, "?"); _preparedStatement = CqlConnection.CreatePreparedStatement(cqlQuery); } } private object[] GetParameterValues() { if (Parameters.Count == 0) { return null; } // returns the parameter values as an array order by the occurence of parameter names in CommandText var matches = RegexParseParameterName.Matches(CommandText); var values = new List<object>(); foreach (Match match in matches) { object value = null; foreach (IDataParameter p in Parameters) { if (string.Compare(match.Value, p.ParameterName, StringComparison.OrdinalIgnoreCase) == 0) { value = p.Value; break; } } values.Add(value); } return values.ToArray(); } public override UpdateRowSource UpdatedRowSource { get { return UpdateRowSource.FirstReturnedRecord; } set { } } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\Cassandra.Tests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\CqlParameterCollectionTest.cs
Cassandra.Tests
CqlParameterCollectionTest
[]
['Cassandra.Data', 'NUnit.Framework']
NUnit
net8
[TestFixture] public class CqlParameterCollectionTest { [Test] public void TestCqlParameterCollection() { var target = new CqlParameterCollection(); // test Count Assert.AreEqual(0, target.Count); var p1 = target.Add("p1", 1); Assert.AreEqual(1, target.Count); // test SyncRoot Assert.IsNotNull(target.SyncRoot); Assert.AreEqual(target.SyncRoot, target.SyncRoot); // test IsFixedSize Assert.IsFalse(target.IsFixedSize); // test IsReadOnly Assert.IsFalse(target.IsReadOnly); // test IsSynchronized Assert.IsFalse(target.IsSynchronized); // test Add() var p2Index = target.Add(new CqlParameter("p2")); Assert.AreEqual(2, target.Count); Assert.AreEqual(1, p2Index); // test Contains() var p3 = new CqlParameter("p3"); Assert.IsTrue(target.Contains(p1)); Assert.IsFalse(target.Contains(p3)); // test IndexOf() Assert.AreEqual(0, target.IndexOf(p1)); // test Insert(); target.Insert(0, p3); Assert.AreEqual(0, target.IndexOf(p3)); Assert.AreEqual(1, target.IndexOf(p1)); // test Remove() var toBeRemove = new CqlParameter("toberemoved"); target.Add(toBeRemove); Assert.IsTrue(target.Contains(toBeRemove)); target.Remove(toBeRemove); Assert.IsFalse(target.Contains(toBeRemove)); // test RemoveAt() target.RemoveAt(0); Assert.AreEqual(2, target.Count); target.RemoveAt("p2"); Assert.IsFalse(target.Contains("p2")); // test CopyTo() var arr = new CqlParameter[1]; target.CopyTo(arr, 0); Assert.AreEqual(arr[0], target[0]); // test AddRange() var p4p5 = new[] { new CqlParameter("p4"), new CqlParameter("p5") }; target.AddRange(p4p5); Assert.AreEqual(3, target.Count); Assert.IsTrue(target.Contains(p4p5[0])); Assert.IsTrue(target.Contains(p4p5[1])); // test Clear() target.Clear(); Assert.AreEqual(0, target.Count); } }
717
3,183
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.Data.Common; namespace Cassandra.Data { /// <summary> /// Represents a collection of <see cref="CqlParameter"/>s. /// </summary> public class CqlParameterCollection : DbParameterCollection { private readonly List<CqlParameter> _parameters = new List<CqlParameter>(); private readonly object _syncLock = new object(); #region DbParameterCollection Members /// <summary> /// Specifies the number of items in the collection. /// </summary> /// <returns>The number of items in the collection.</returns> public override int Count { get { return _parameters.Count; } } /// <summary> /// Specifies the <see cref="T:System.Object" /> to be used to synchronize access to the collection. /// </summary> /// <returns> /// A <see cref="T:System.Object" /> to be used to synchronize access /// to the <see cref="T:System.Data.Common.DbParameterCollection" />. /// </returns> public override object SyncRoot { get { return _syncLock; } } /// <summary> /// Specifies whether the collection is a fixed size. /// </summary> /// <returns>true if the collection is a fixed size; otherwise false.</returns> public override bool IsFixedSize { get { return IsReadOnly; } } /// <summary> /// Specifies whether the collection is read-only. /// </summary> /// <returns>true if the collection is read-only; otherwise false.</returns> public override bool IsReadOnly { get { return false; } } /// <summary> /// Specifies whether the collection is synchronized. /// </summary> /// <returns>true if the collection is synchronized; otherwise false.</returns> public override bool IsSynchronized { get { return false; } } /// <summary> /// Adds the specified <see cref="T:System.Data.Common.DbParameter" /> object /// to the <see cref="T:System.Data.Common.DbParameterCollection" />. /// </summary> /// <param name="value"> /// The <see cref="P:System.Data.Common.DbParameter.Value" /> /// of the <see cref="T:System.Data.Common.DbParameter" /> to add to the collection. /// </param> /// <returns> /// The index of the <see cref="T:System.Data.Common.DbParameter" /> object in the collection. /// </returns> public override int Add(object value) { return Add((CqlParameter)value); } /// <summary> /// Adds the specified parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <returns> </returns> public int Add(CqlParameter parameter) { _parameters.Add(parameter); return _parameters.Count - 1; } /// <summary> /// Adds a new parameter with the specified name and value. The name will be /// parsed to extract table and keyspace information (if any). The parameter type /// will be guessed from the object value. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns>The created <see cref="CqlParameter"/>.</returns> public CqlParameter Add(string name, object value) { var parameter = new CqlParameter(name, value); Add(parameter); return parameter; } /// <summary> /// Indicates whether a <see cref="T:System.Data.Common.DbParameter" /> /// with the specified <see cref="P:System.Data.Common.DbParameter.Value" /> /// is contained in the collection. /// </summary> /// <param name="value"> /// The <see cref="P:System.Data.Common.DbParameter.Value" /> /// of the <see cref="T:System.Data.Common.DbParameter" /> to look for in the collection. /// </param> /// <returns> /// true if the <see cref="T:System.Data.Common.DbParameter" /> is in the collection; otherwise false. /// </returns> public override bool Contains(object value) { return _parameters.Contains((CqlParameter)value); } /// <summary> /// Removes all <see cref="T:System.Data.Common.DbParameter" /> values /// from the <see cref="T:System.Data.Common.DbParameterCollection" />. /// </summary> public override void Clear() { _parameters.Clear(); } /// <summary> /// Returns the index of the specified <see cref="T:System.Data.Common.DbParameter" /> object. /// </summary> /// <param name="value">The <see cref="T:System.Data.Common.DbParameter" /> object in the collection.</param> /// <returns>The index of the specified <see cref="T:System.Data.Common.DbParameter" /> object.</returns> public override int IndexOf(object value) { return _parameters.IndexOf((CqlParameter)value); } /// <summary> /// Inserts the specified index of the <see cref="T:System.Data.Common.DbParameter" /> object /// with the specified name into the collection at the specified index. /// </summary> /// <param name="index">The index at which to insert the <see cref="T:System.Data.Common.DbParameter" /> object.</param> /// <param name="value">The <see cref="T:System.Data.Common.DbParameter" /> object to insert into the collection.</param> public override void Insert(int index, object value) { var param = (CqlParameter)value; _parameters.Insert(index, param); } /// <summary> /// Removes the specified <see cref="T:System.Data.Common.DbParameter" /> object from the collection. /// </summary> /// <param name="value">The <see cref="T:System.Data.Common.DbParameter" /> object to remove.</param> public override void Remove(object value) { var param = (CqlParameter)value; _parameters.Remove(param); } /// <summary> /// Removes the <see cref="T:System.Data.Common.DbParameter" /> object at the specified from the collection. /// </summary> /// <param name="index"> /// The index where the <see cref="T:System.Data.Common.DbParameter" /> object is located. /// </param> public override void RemoveAt(int index) { _parameters.RemoveAt(index); } /// <summary> /// Removes the <see cref="T:System.Data.Common.DbParameter" /> object /// with the specified name from the collection. /// </summary> /// <param name="parameterName"> /// The name of the <see cref="T:System.Data.Common.DbParameter" /> object to remove. /// </param> public override void RemoveAt(string parameterName) { int index = GetIndex(parameterName); _parameters.RemoveAt(index); } /// <summary> /// Sets the <see cref="T:System.Data.Common.DbParameter" /> object /// at the specified index to a new value. /// </summary> /// <param name="index"> /// The index where the <see cref="T:System.Data.Common.DbParameter" /> objectis located. /// </param> /// <param name="value">The new <see cref="T:System.Data.Common.DbParameter" /> value.</param> protected override void SetParameter(int index, DbParameter value) { SetParameter(index, (CqlParameter)value); } /// <summary> /// Sets the <see cref="T:System.Data.Common.DbParameter" /> object /// with the specified name to a new value. /// </summary> /// <param name="parameterName"> /// The name of the <see cref="T:System.Data.Common.DbParameter" /> object in the collection. /// </param> /// <param name="value">The new <see cref="T:System.Data.Common.DbParameter" /> value.</param> protected override void SetParameter(string parameterName, DbParameter value) { SetParameter(parameterName, (CqlParameter)value); } /// <summary> /// Returns the index of the <see cref="T:System.Data.Common.DbParameter" /> object with the specified name. /// </summary> /// <returns> /// <param name="parameterName"> /// The name of the <see cref="T:System.Data.Common.DbParameter" /> object in the collection. /// </param> /// The index of the <see cref="T:System.Data.Common.DbParameter" /> object with the specified name. /// </returns> public override int IndexOf(string parameterName) { if (parameterName == null) throw new ArgumentNullException("parameterName"); var name = parameterName.StartsWith(":") ? parameterName : ":" + parameterName; return _parameters.FindIndex(p => p.ParameterName == name); } /// <summary> /// Exposes the <see cref="M:System.Collections.IEnumerable.GetEnumerator" /> method, /// which supports a simple iteration over a collection by a .NET Framework data provider. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> that can be used /// to iterate through the collection. /// </returns> public override IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); } /// <summary> /// Returns the <see cref="T:System.Data.Common.DbParameter" /> object at the specified index in the collection. /// </summary> /// <param name="index"> /// The index of the <see cref="T:System.Data.Common.DbParameter" />in the collection. /// </param> /// <returns> /// The <see cref="T:System.Data.Common.DbParameter" /> object /// at the specified index in the collection. /// </returns> protected override DbParameter GetParameter(int index) { return _parameters[index]; } /// <summary> /// Returns <see cref="T:System.Data.Common.DbParameter" /> the object with the specified name. /// </summary> /// <param name="parameterName"> /// The name of the <see cref="T:System.Data.Common.DbParameter" /> in the collection. /// </param> /// <returns>The <see cref="T:System.Data.Common.DbParameter" /> the object with the specified name. </returns> protected override DbParameter GetParameter(string parameterName) { return GetCqlParameter(parameterName); } /// <summary> /// Indicates whether a <see cref="T:System.Data.Common.DbParameter" /> /// with the specified name exists in the collection. /// </summary> /// <param name="value"> /// The name of the <see cref="T:System.Data.Common.DbParameter" /> /// to look for in the collection. /// </param> /// <returns> /// true if the <see cref="T:System.Data.Common.DbParameter" /> is /// in the collection; otherwise false. /// </returns> public override bool Contains(string value) { return IndexOf(value) > 0; } /// <summary> /// Copies an array of items to the collection starting at the specified index. /// </summary> /// <param name="array">The array of items to copy to the collection.</param> /// <param name="index">The index in the collection to copy the items.</param> public override void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); var c = (ICollection)_parameters; c.CopyTo(array, index); } /// <summary> /// Adds an array of items with the specified values /// to the <see cref="T:System.Data.Common.DbParameterCollection" />. /// </summary> /// <param name="values"> /// An array of values of type <see cref="T:System.Data.Common.DbParameter" /> /// to add to the collection. /// </param> public override void AddRange(Array values) { if (values == null) throw new ArgumentNullException("values"); foreach (object obj in values) { if (!(obj is CqlParameter)) throw new ArgumentException("All values must be CqlParameter instances"); } foreach (CqlParameter cqlParameter in values) { _parameters.Add(cqlParameter); } } #endregion #region Private Methods private void SetParameter(string parameterName, CqlParameter value) { int index = GetIndex(parameterName); _parameters[index] = value; } private void SetParameter(int index, CqlParameter value) { _parameters[index] = value; } private int GetIndex(string parameterName) { int index = IndexOf(parameterName); if (index < 0) throw new IndexOutOfRangeException("Parameter with the given name is not found"); return index; } private CqlParameter GetCqlParameter(string parameterName) { int index = GetIndex(parameterName); return _parameters[index]; } #endregion } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\Cassandra.Tests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\CqlParameterTest.cs
Cassandra.Tests
CqlParameterTest
[]
['System', 'System.Data', 'Cassandra.Data', 'NUnit.Framework']
NUnit
net8
[TestFixture] public class CqlParameterTest { [Test] public void TestCqlParameter() { var name = "p1"; var value = 1; var target = new CqlParameter(name, value); // test ParameterName var formattedName = ":p1"; var name2 = ":p2"; Assert.AreEqual(formattedName, target.ParameterName); target.ParameterName = name2; Assert.AreEqual(name2, target.ParameterName); // test IsNullable & SourceColumnNullMapping Assert.IsTrue(target.IsNullable); Assert.IsTrue(target.SourceColumnNullMapping); target.IsNullable = false; Assert.IsFalse(target.IsNullable); Assert.IsFalse(target.SourceColumnNullMapping); // test Direction, only Input is supported Assert.AreEqual(ParameterDirection.Input, target.Direction); Exception ex = null; try { target.Direction = ParameterDirection.Output; } catch (Exception e) { ex = e; } Assert.IsNotNull(ex); // test Value Assert.AreEqual(value, target.Value); var value2 = "2"; target.Value = value2; Assert.AreEqual(value2, target.Value); // test Size, it should always return 0 Assert.AreEqual(0, target.Size); target.Size = 1; Assert.AreEqual(0, target.Size); } }
752
2,380
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Data; using System.Data.Common; namespace Cassandra.Data { /// <summary> /// Represents a Cql parameter. /// </summary> public class CqlParameter : DbParameter { private string _name; private bool _isNullable; private object _value; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CqlParameter" /> class. /// </summary> public CqlParameter() { _isNullable = true; } /// <summary> /// Initializes a new instance of the <see cref="CqlParameter" /> class. /// </summary> /// <param name="name">The name.</param> public CqlParameter(string name) : this() { SetParameterName(name); } /// <summary> /// Initializes a new instance of the <see cref="CqlParameter" /> class. /// The type of the parameter will be guessed from the value. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> public CqlParameter(string name, object value) : this(name) { _value = value; } #endregion #region DbParameter Members /// <summary> /// Gets or sets the <see cref="T:System.Data.DbType" /> of the parameter. /// </summary> public override DbType DbType { get; set; } /// <summary> /// Gets or sets a value indicating whether the parameter is /// input-only, output-only, bidirectional, or a stored procedure return value parameter. /// </summary> /// <returns> /// One of the <see cref="T:System.Data.ParameterDirection" /> values. /// The default is Input. /// </returns> /// <exception cref="System.NotSupportedException">Cql only supports input parameters</exception> public override ParameterDirection Direction { get { return ParameterDirection.Input; } set { if (value != ParameterDirection.Input) throw new NotSupportedException("Cql only supports input parameters"); } } /// <summary> /// Gets a value indicating whether the parameter accepts null values. /// </summary> /// <returns>true if null values are accepted; otherwise, false. The default is false. </returns> public override bool IsNullable { get { return _isNullable; } set { _isNullable = value; } } /// <summary> /// Gets or sets the name of the <see cref="T:System.Data.IDataParameter" />. /// </summary> /// <returns> /// The name of the <see cref="T:System.Data.IDataParameter" />. /// The default is an empty string. /// </returns> public override string ParameterName { get { return _name; } set { SetParameterName(value); } } /// <summary> /// Gets or sets the name of the source column that is mapped /// to the <see cref="T:System.Data.DataSet" /> and used for loading or /// returning the <see cref="P:System.Data.IDataParameter.Value" />. /// </summary> /// <returns> /// The name of the source column that is mapped to the <see cref="T:System.Data.DataSet" />. /// The default is an empty string. /// </returns> public override string SourceColumn { get; set; } /// <summary> /// Gets or sets the <see cref="T:System.Data.DataRowVersion" /> /// to use when loading <see cref="P:System.Data.IDataParameter.Value" />. /// </summary> /// <returns> /// One of the <see cref="T:System.Data.DataRowVersion" /> values. /// The default is Current. /// </returns> public override DataRowVersion SourceVersion { get; set; } /// <summary> /// Gets or sets the value of the parameter. /// If no type information was provided earlier, the type of the parameter will be /// guessed from the value's type. /// </summary> /// <returns> /// An <see cref="T:System.Object" /> that is the value of the parameter. /// The default value is null. /// </returns> public override object Value { get { return _value; } set { _value = value; } } /// <summary> /// The size of the parameter. /// </summary> /// <returns>Always returns 0.</returns> public override int Size { get { return 0; } set { } } /// <summary> /// Sets or gets a value which indicates whether the source column is nullable. /// This allows <see cref="T:System.Data.Common.DbCommandBuilder" /> /// to correctly generate Update statements for nullable columns. /// </summary> /// <returns>true if the source column is nullable; false if it is not. </returns> public override bool SourceColumnNullMapping { get { return IsNullable; } set { IsNullable = value; } } /// <summary> /// Resets the DbType property to its original settings. /// </summary> public override void ResetDbType() { } #endregion #region Private Methods private void SetParameterName(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } _name = name.StartsWith(":") ? name : ":" + name; } #endregion } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\Cassandra.Tests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\HostTests.cs
Cassandra.Tests
HostTests
['private static readonly IPEndPoint Address = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000);']
['System', 'System.Collections.Generic', 'System.Net', 'System.Threading', 'NUnit.Framework']
NUnit
net8
[TestFixture] public class HostTests { private static readonly IPEndPoint Address = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000); [Test] public void BringUpIfDown_Should_Allow_Multiple_Concurrent_Calls() { var host = new Host(Address, contactPoint: null); var counter = 0; host.Up += _ => Interlocked.Increment(ref counter); host.SetDown(); TestHelper.ParallelInvoke(() => { host.BringUpIfDown(); }, 100); //Should fire event only once Assert.AreEqual(1, counter); } [Test] public void Should_UseHostIdEmpty_When_HostIdIsNull() { var hostAddress = new IPEndPoint(IPAddress.Parse("163.10.10.10"), 9092); var host = new Host(hostAddress, contactPoint: null); var row = BuildRow(null); host.SetInfo(row); Assert.AreEqual(Guid.Empty, host.HostId); } private IRow BuildRow(Guid? hostId) { return new TestHelper.DictionaryBasedRow(new Dictionary<string, object> { { "host_id", hostId }, { "data_center", "dc1"}, { "rack", "rack1" }, { "release_version", "3.11.1" }, { "tokens", new List<string> { "1" }} }); } }
788
2,267
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.Net; using Cassandra.Collections; using Cassandra.Connections; using Cassandra.Connections.Control; namespace Cassandra { internal class Hosts : IEnumerable<Host> { private readonly CopyOnWriteDictionary<IPEndPoint, Host> _hosts = new CopyOnWriteDictionary<IPEndPoint, Host>(); /// <summary> /// Event that gets triggered when a host is considered as DOWN (not available) /// </summary> internal event Action<Host> Down; /// <summary> /// Event that gets triggered when a host is considered back UP (available for queries) /// </summary> internal event Action<Host> Up; /// <summary> /// Event that gets triggered when a new host has been added to the pool /// </summary> internal event Action<Host> Added; /// <summary> /// Event that gets triggered when a host has been removed /// </summary> internal event Action<Host> Removed; /// <summary> /// Gets the total amount of hosts in the cluster /// </summary> internal int Count { get { return _hosts.Count; } } public bool TryGet(IPEndPoint endpoint, out Host host) { return _hosts.TryGetValue(endpoint, out host); } public ICollection<Host> ToCollection() { return _hosts.Values; } /// <summary> /// Adds the host if not exists /// </summary> public Host Add(IPEndPoint key) { return Add(key, null); } /// <summary> /// Adds the host if not exists /// </summary> public Host Add(IPEndPoint key, IContactPoint contactPoint) { var newHost = new Host(key, contactPoint); var host = _hosts.GetOrAdd(key, newHost); if (!ReferenceEquals(newHost, host)) { //The host was not added, return the existing host return host; } //The node was added host.Down += OnHostDown; host.Up += OnHostUp; Added?.Invoke(newHost); return host; } private void OnHostDown(Host sender) { Down?.Invoke(sender); } private void OnHostUp(Host sender) { Up?.Invoke(sender); } public void RemoveIfExists(IPEndPoint ep) { if (!_hosts.TryRemove(ep, out Host host)) { //The host does not exists return; } host.Down -= OnHostDown; host.Up -= OnHostUp; host.SetAsRemoved(); Removed?.Invoke(host); } public IEnumerable<IPEndPoint> AllEndPointsToCollection() { return _hosts.Keys; } public IEnumerator<Host> GetEnumerator() { return _hosts.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _hosts.Values.GetEnumerator(); } } }
datastax
csharp-driver
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.sln
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\Cassandra.Tests.csproj
F:\Projects\TestMap\Temp\csharp-driver\src\Cassandra.Tests\TokenTests.cs
Cassandra.Tests
TokenTests
[]
['System', 'System.Collections.Concurrent', 'System.Collections.Generic', 'System.Linq', 'System.Net', 'System.Threading.Tasks', 'Cassandra.Connections', 'Cassandra.Connections.Control', 'Cassandra.MetadataHelpers', 'Cassandra.ProtocolEvents', 'Cassandra.SessionManagement', 'Cassandra.Tests.Connections.TestHelpers', 'Cassandra.Tests.MetadataHelpers.TestHelpers', 'Moq', 'NUnit.Framework']
NUnit
net8
[TestFixture] public class TokenTests { [Test] public void Murmur_Hash_Test() { //inputs and result values from Cassandra var values = new Dictionary<byte[], M3PToken>() { {new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, new M3PToken(-5563837382979743776L)}, {new byte[] {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, new M3PToken(-1513403162740402161L)}, {new byte[] {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}, new M3PToken(-495360443712684655L)}, {new byte[] {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, new M3PToken(1734091135765407943L)}, {new byte[] {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}, new M3PToken(-3199412112042527988L)}, {new byte[] {6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}, new M3PToken(-6316563938475080831L)}, {new byte[] {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}, new M3PToken(8228893370679682632L)}, {new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new M3PToken(5457549051747178710L)}, {new byte[] {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, new M3PToken(-2824192546314762522L)}, {new byte[] {254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254}, new M3PToken(-833317529301936754)}, {new byte[] {000, 001, 002, 003, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, new M3PToken(6463632673159404390L)}, {new byte[] {254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254}, new M3PToken(-1672437813826982685L)}, {new byte[] {254, 254, 254, 254}, new M3PToken(4566408979886474012L)}, {new byte[] {0, 0, 0, 0}, new M3PToken(-3485513579396041028L)}, {new byte[] {0, 1, 127, 127}, new M3PToken(6573459401642635627)}, {new byte[] {0, 255, 255, 255}, new M3PToken(123573637386978882)}, {new byte[] {255, 1, 2, 3}, new M3PToken(-2839127690952877842)}, {new byte[] {000, 001, 002, 003, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}, new M3PToken(6463632673159404390L)}, {new byte[] {226, 231}, new M3PToken(-8582699461035929883L)}, {new byte[] {226, 231, 226, 231, 226, 231, 1}, new M3PToken(2222373981930033306)}, }; var factory = new M3PToken.M3PTokenFactory(); foreach (var kv in values) { Assert.AreEqual(kv.Value, factory.Hash(kv.Key)); } } [Test] public void RandomPartitioner_Hash_Test() { //inputs and result values from Cassandra Func<string, IToken> getToken = RPToken.Factory.Parse; var values = new Dictionary<byte[], IToken>() { {new byte[] {0}, getToken("143927757573010354572009627285182898319")}, {new byte[] {1}, getToken("113842407384990359002707962975597223745")}, {new byte[] {2}, getToken("129721498153058668219395762571499089729")}, {new byte[] {3}, getToken("161634087634434392855851743730996420760")}, {new byte[] {1, 1, 1, 1, 1}, getToken("62826831507722661030027787191787718361")}, {new byte[] {1, 1, 1, 1, 3}, getToken("3280052967642184217852195524766331890")}, {new byte[] {1, 1, 1, 1, 3}, getToken("3280052967642184217852195524766331890")}, {TestHelper.HexToByteArray("00112233445566778899aabbccddeeff"), getToken("146895617013011042239963905141456044092")}, {TestHelper.HexToByteArray("00112233445566778899aabbccddeef0"), getToken("152768415488763703226794584233555130431")} }; foreach (var kv in values) { Assert.AreEqual(kv.Value, RPToken.Factory.Hash(kv.Key)); Assert.AreEqual(kv.Value.ToString(), RPToken.Factory.Hash(kv.Key).ToString()); } } [Test] public void TokenMap_SimpleStrategy_With_Keyspace_Test() { var hosts = new List<Host> { { TestHelper.CreateHost("192.168.0.0", "dc1", "rack", new HashSet<string>{"0"})}, { TestHelper.CreateHost("192.168.0.1", "dc1", "rack", new HashSet<string>{"10"})}, { TestHelper.CreateHost("192.168.0.2", "dc1", "rack", new HashSet<string>{"20"})} }; var keyspaces = new List<KeyspaceMetadata> { FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 2), FakeSchemaParserFactory.CreateSimpleKeyspace("ks2", 10) }; var tokenMap = TokenMap.Build("Murmur3Partitioner", hosts, keyspaces); //the primary replica and the next var replicas = tokenMap.GetReplicas("ks1", new M3PToken(0)); Assert.AreEqual("0,1", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); replicas = tokenMap.GetReplicas("ks1", new M3PToken(-100)); Assert.AreEqual("0,1", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //Greater than the greatest token replicas = tokenMap.GetReplicas("ks1", new M3PToken(500000)); Assert.AreEqual("0,1", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //The next replica should be the first replicas = tokenMap.GetReplicas("ks1", new M3PToken(20)); Assert.AreEqual("2,0", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //The closest replica and the next replicas = tokenMap.GetReplicas("ks1", new M3PToken(19)); Assert.AreEqual("2,0", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //Even if the replication factor is greater than the ring, it should return only ring size replicas = tokenMap.GetReplicas("ks2", new M3PToken(5)); Assert.AreEqual("1,2,0", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //The primary replica only as the keyspace was not found replicas = tokenMap.GetReplicas(null, new M3PToken(0)); Assert.AreEqual("0", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); replicas = tokenMap.GetReplicas(null, new M3PToken(10)); Assert.AreEqual("1", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); replicas = tokenMap.GetReplicas("ks_does_not_exist", new M3PToken(20)); Assert.AreEqual("2", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); replicas = tokenMap.GetReplicas(null, new M3PToken(19)); Assert.AreEqual("2", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); } [Test] public void TokenMap_SimpleStrategy_With_Hosts_Without_Tokens() { var hosts = new List<Host> { { TestHelper.CreateHost("192.168.0.0", "dc1", "rack", new HashSet<string>{"0"})}, { TestHelper.CreateHost("192.168.0.1", "dc1", "rack", new string[0])}, { TestHelper.CreateHost("192.168.0.2", "dc1", "rack", new HashSet<string>{"20"})} }; var keyspaces = new List<KeyspaceMetadata> { FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 10), FakeSchemaParserFactory.CreateSimpleKeyspace("ks2", 2) }; var tokenMap = TokenMap.Build("Murmur3Partitioner", hosts, keyspaces); //the primary replica and the next var replicas = tokenMap.GetReplicas("ks1", new M3PToken(0)); //The node without tokens should not be considered CollectionAssert.AreEqual(new byte[] { 0, 2 }, replicas.Select(TestHelper.GetLastAddressByte)); replicas = tokenMap.GetReplicas("ks1", new M3PToken(-100)); CollectionAssert.AreEqual(new byte[] { 0, 2 }, replicas.Select(TestHelper.GetLastAddressByte)); //Greater than the greatest token replicas = tokenMap.GetReplicas("ks1", new M3PToken(500000)); CollectionAssert.AreEqual(new byte[] { 0, 2 }, replicas.Select(TestHelper.GetLastAddressByte)); //The next replica should be the first replicas = tokenMap.GetReplicas("ks1", new M3PToken(20)); CollectionAssert.AreEqual(new byte[] { 2, 0 }, replicas.Select(TestHelper.GetLastAddressByte)); } [Test] public void TokenMap_NetworkTopologyStrategy_With_Keyspace_Test() { var hosts = new List<Host> { { TestHelper.CreateHost("192.168.0.0", "dc1", "rack1", new HashSet<string>{"0"})}, { TestHelper.CreateHost("192.168.0.1", "dc1", "rack1", new HashSet<string>{"100"})}, { TestHelper.CreateHost("192.168.0.2", "dc1", "rack1", new HashSet<string>{"200"})}, { TestHelper.CreateHost("192.168.0.100", "dc2", "rack1", new HashSet<string>{"1"})}, { TestHelper.CreateHost("192.168.0.101", "dc2", "rack1", new HashSet<string>{"101"})}, { TestHelper.CreateHost("192.168.0.102", "dc2", "rack1", new HashSet<string>{"201"})} }; const string strategy = ReplicationStrategies.NetworkTopologyStrategy; var keyspaces = new List<KeyspaceMetadata> { //network strategy with rf 2 per dc CreateKeyspaceMetadata(null, "ks1", true, strategy, new Dictionary<string, string> {{"dc1", "2"}, {"dc2", "2"}}), //Testing simple (even it is not supposed to be) CreateKeyspaceMetadata(null, "ks2", true, ReplicationStrategies.SimpleStrategy, new Dictionary<string, string> {{"replication_factor", "3"}}), //network strategy with rf 3 dc1 and 1 dc2 CreateKeyspaceMetadata(null, "ks3", true, strategy, new Dictionary<string, string> {{"dc1", "3"}, {"dc2", "1"}, {"dc3", "5"}}), //network strategy with rf 4 dc1 CreateKeyspaceMetadata(null, "ks4", true, strategy, new Dictionary<string, string> {{"dc1", "5"}}) }; var tokenMap = TokenMap.Build("Murmur3Partitioner", hosts, keyspaces); //KS1 //the primary replica and the next var replicas = tokenMap.GetReplicas("ks1", new M3PToken(0)); Assert.AreEqual("0,100,1,101", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //The next replica should be the first replicas = tokenMap.GetReplicas("ks1", new M3PToken(200)); Assert.AreEqual("2,102,0,100", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //The closest replica and the next replicas = tokenMap.GetReplicas("ks1", new M3PToken(190)); Assert.AreEqual("2,102,0,100", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //KS2 //Simple strategy: 3 tokens no matter which dc replicas = tokenMap.GetReplicas("ks2", new M3PToken(5000)); Assert.AreEqual("0,100,1", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //KS3 replicas = tokenMap.GetReplicas("ks3", new M3PToken(0)); Assert.AreEqual("0,100,1,2", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); replicas = tokenMap.GetReplicas("ks3", new M3PToken(201)); Assert.AreEqual("102,0,1,2", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); //KS4 replicas = tokenMap.GetReplicas("ks4", new M3PToken(0)); Assert.AreEqual("0,1,2", String.Join(",", replicas.Select(TestHelper.GetLastAddressByte))); } [Test] public void TokenMap_Build_NetworkTopology_Adjacent_Ranges_Test() { const string strategy = ReplicationStrategies.NetworkTopologyStrategy; var hosts = new[] { //0 and 100 are adjacent TestHelper.CreateHost("192.168.0.1", "dc1", "rack1", new HashSet<string> {"0", "100", "1000"}), TestHelper.CreateHost("192.168.0.2", "dc1", "rack1", new HashSet<string> {"200", "2000", "20000"}), TestHelper.CreateHost("192.168.0.3", "dc1", "rack1", new HashSet<string> {"300", "3000", "30000"}) }; var ks = CreateKeyspaceMetadata(null, "ks1", true, strategy, new Dictionary<string, string> { { "dc1", "2" } }); var map = TokenMap.Build("Murmur3Partitioner", hosts, new[] { ks }); var replicas = map.GetReplicas("ks1", new M3PToken(0)); Assert.AreEqual(2, replicas.Count); //It should contain the first host and the second, even though the first host contains adjacent CollectionAssert.AreEqual(new byte[] { 1, 2 }, replicas.Select(TestHelper.GetLastAddressByte)); } [Test] public void TokenMap_Build_Should_Memorize_Tokens_Per_Replication_Test() { const string strategy = ReplicationStrategies.NetworkTopologyStrategy; var hosts = new[] { //0 and 100 are adjacent TestHelper.CreateHost("192.168.0.1", "dc1", "dc1_rack1", new HashSet<string> {"0", "100", "1000"}), TestHelper.CreateHost("192.168.0.2", "dc1", "dc1_rack2", new HashSet<string> {"200", "2000", "20000"}), TestHelper.CreateHost("192.168.0.3", "dc1", "dc1_rack1", new HashSet<string> {"300", "3000", "30000"}), TestHelper.CreateHost("192.168.0.4", "dc2", "dc2_rack1", new HashSet<string> {"400", "4000", "40000"}), TestHelper.CreateHost("192.168.0.5", "dc2", "dc2_rack2", new HashSet<string> {"500", "5000", "50000"}) }; var ks1 = CreateKeyspaceMetadata(null, "ks1", true, strategy, new Dictionary<string, string> { { "dc1", "2" }, { "dc2", "1" } }); var ks2 = CreateKeyspaceMetadata(null, "ks2", true, strategy, new Dictionary<string, string> { { "dc1", "2" }, { "dc2", "1" } }); var ks3 = CreateKeyspaceMetadata(null, "ks3", true, strategy, new Dictionary<string, string> { { "dc1", "2" } }); var map = TokenMap.Build("Murmur3Partitioner", hosts, new[] { ks1, ks2, ks3 }); var tokens1 = map.GetByKeyspace("ks1"); var tokens2 = map.GetByKeyspace("ks2"); var tokens3 = map.GetByKeyspace("ks3"); Assert.AreSame(tokens1, tokens2); Assert.AreNotSame(tokens1, tokens3); } [Test] public void TokenMap_Build_NetworkTopology_Multiple_Racks_Test() { const string strategy = ReplicationStrategies.NetworkTopologyStrategy; var hosts = new[] { // DC1 racks has contiguous tokens // DC2 racks are properly organized TestHelper.CreateHost("192.168.0.0", "dc1", "dc1_rack1", new HashSet<string> {"0"}), TestHelper.CreateHost("192.168.0.1", "dc2", "dc2_rack1", new HashSet<string> {"1"}), TestHelper.CreateHost("192.168.0.2", "dc1", "dc1_rack2", new HashSet<string> {"2"}), TestHelper.CreateHost("192.168.0.3", "dc2", "dc2_rack2", new HashSet<string> {"3"}), TestHelper.CreateHost("192.168.0.4", "dc1", "dc1_rack1", new HashSet<string> {"4"}), TestHelper.CreateHost("192.168.0.5", "dc2", "dc2_rack1", new HashSet<string> {"5"}), TestHelper.CreateHost("192.168.0.6", "dc1", "dc1_rack2", new HashSet<string> {"6"}), TestHelper.CreateHost("192.168.0.7", "dc2", "dc2_rack2", new HashSet<string> {"7"}) }; var ks = CreateKeyspaceMetadata(null, "ks1", true, strategy, new Dictionary<string, string> { { "dc1", "3" }, { "dc2", "2" } }); var map = TokenMap.Build("Murmur3Partitioner", hosts, new[] { ks }); var replicas = map.GetReplicas("ks1", new M3PToken(0)); CollectionAssert.AreEqual(new byte[] { 0, 1, 2, 3, 4 }, replicas.Select(TestHelper.GetLastAddressByte)); } [Test] public void TokenMap_Build_NetworkTopology_Multiple_Racks_Skipping_Hosts_Test() { const string strategy = ReplicationStrategies.NetworkTopologyStrategy; var hosts = new[] { // DC1 racks has contiguous tokens // DC2 racks are properly organized TestHelper.CreateHost("192.168.0.0", "dc1", "dc1_rack1", new HashSet<string> {"0"}), TestHelper.CreateHost("192.168.0.1", "dc2", "dc2_rack1", new HashSet<string> {"1"}), TestHelper.CreateHost("192.168.0.2", "dc1", "dc1_rack1", new HashSet<string> {"2"}), TestHelper.CreateHost("192.168.0.3", "dc2", "dc2_rack2", new HashSet<string> {"3"}), TestHelper.CreateHost("192.168.0.4", "dc1", "dc1_rack2", new HashSet<string> {"4"}), TestHelper.CreateHost("192.168.0.5", "dc2", "dc2_rack1", new HashSet<string> {"5"}), TestHelper.CreateHost("192.168.0.6", "dc1", "dc1_rack2", new HashSet<string> {"6"}), TestHelper.CreateHost("192.168.0.7", "dc2", "dc2_rack2", new HashSet<string> {"7"}) }; var ks = CreateKeyspaceMetadata(null, "ks1", true, strategy, new Dictionary<string, string> { { "dc1", "3" }, { "dc2", "2" } }); var map = TokenMap.Build("Murmur3Partitioner", hosts, new[] { ks }); var values = new[] { Tuple.Create(0, new byte[] { 0, 1, 3, 4, 2 }), Tuple.Create(1, new byte[] { 1, 2, 3, 4, 6 }), Tuple.Create(4, new byte[] { 4, 5, 7, 0, 6 }) }; foreach (var v in values) { var replicas = map.GetReplicas("ks1", new M3PToken(v.Item1)); CollectionAssert.AreEqual(v.Item2, replicas.Select(TestHelper.GetLastAddressByte)); } } [Test, TestTimeout(2000)] public void TokenMap_Build_NetworkTopology_Quickly_Leave_When_Dc_Not_Found() { const string strategy = ReplicationStrategies.NetworkTopologyStrategy; var hosts = new Host[100]; for (var i = 0; i < hosts.Length; i++) { hosts[i] = TestHelper.CreateHost("192.168.0." + i, "dc" + (i % 2), "rack1", new HashSet<string>()); } for (var i = 0; i < 256 * hosts.Length; i++) { var tokens = (HashSet<string>)hosts[i % hosts.Length].Tokens; tokens.Add(i.ToString()); } var ks = CreateKeyspaceMetadata(null, "ks1", true, strategy, new Dictionary<string, string> { { "dc1", "3" }, { "dc2", "2" }, { "dc3", "1" } }); TokenMap.Build("Murmur3Partitioner", hosts, new[] { ks }); } [Test] public void TokenMap_Build_SimpleStrategy_Adjacent_Ranges_Test() { var hosts = new[] { //0 and 100 are adjacent TestHelper.CreateHost("192.168.0.1", "dc1", "rack1", new HashSet<string> {"0", "100", "1000"}), TestHelper.CreateHost("192.168.0.2", "dc1", "rack1", new HashSet<string> {"200", "2000", "20000"}), TestHelper.CreateHost("192.168.0.3", "dc1", "rack1", new HashSet<string> {"300", "3000", "30000"}) }; var ks = FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 2); var map = TokenMap.Build("Murmur3Partitioner", hosts, new[] { ks }); var replicas = map.GetReplicas("ks1", new M3PToken(0)); Assert.AreEqual(2, replicas.Count); //It should contain the first host and the second, even though the first host contains adjacent CollectionAssert.AreEqual(new byte[] { 1, 2 }, replicas.Select(TestHelper.GetLastAddressByte)); } [Test] public void Build_Should_OnlyCallOncePerReplicationConfiguration_When_MultipleKeyspacesWithSameReplicationOptions() { var hosts = new List<Host> { { TestHelper.CreateHost("192.168.0.0", "dc1", "rack", new HashSet<string>{"0"})}, { TestHelper.CreateHost("192.168.0.1", "dc1", "rack", new HashSet<string>{"10"})}, { TestHelper.CreateHost("192.168.0.2", "dc1", "rack", new HashSet<string>{"20"})}, { TestHelper.CreateHost("192.168.0.3", "dc2", "rack", new HashSet<string>{"30"})}, { TestHelper.CreateHost("192.168.0.4", "dc2", "rack", new HashSet<string>{"40"})} }; var factory = new ProxyReplicationStrategyFactory(); var keyspaces = new List<KeyspaceMetadata> { // unique configurations FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 2, factory), FakeSchemaParserFactory.CreateSimpleKeyspace("ks2", 10, factory), FakeSchemaParserFactory.CreateSimpleKeyspace("ks3", 5, factory), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks4", new Dictionary<string, string> {{"dc1", "2"}, {"dc2", "2"}}, factory), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks5", new Dictionary<string, string> {{"dc1", "1"}, {"dc2", "2"}}, factory), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks6", new Dictionary<string, string> {{"dc1", "1"}}, factory), // duplicate configurations FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks7", new Dictionary<string, string> {{"dc1", "2"}, {"dc2", "2"}}, factory), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks8", new Dictionary<string, string> {{"dc1", "1"}}, factory), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks9", new Dictionary<string, string> {{"dc1", "1"}, {"dc2", "2"}}, factory), FakeSchemaParserFactory.CreateSimpleKeyspace("ks10", 10, factory), FakeSchemaParserFactory.CreateSimpleKeyspace("ks11", 2, factory) }; var tokenMap = TokenMap.Build("Murmur3Partitioner", hosts, keyspaces); var proxyStrategies = keyspaces.Select(k => (ProxyReplicationStrategy)k.Strategy).ToList(); Assert.AreEqual(6, proxyStrategies.Count(strategy => strategy.Calls > 0)); AssertOnlyOneStrategyIsCalled(proxyStrategies, 0, 10); AssertOnlyOneStrategyIsCalled(proxyStrategies, 1, 9); AssertOnlyOneStrategyIsCalled(proxyStrategies, 2); AssertOnlyOneStrategyIsCalled(proxyStrategies, 3, 6); AssertOnlyOneStrategyIsCalled(proxyStrategies, 4, 8); AssertOnlyOneStrategyIsCalled(proxyStrategies, 5, 7); } /// <summary> /// If the replication strategy returns Equals true for different hashcodes then /// it is possible for Dictionary to accept a "duplicate" but the TokenMap constructor /// will blow up when copying the elements of that Dictionary to a ConcurrentDictionary. /// See https://datastax-oss.atlassian.net/browse/CSHARP-943 /// </summary> [Test] public void Build_Should_CopyReplicationStrategiesFromDictionaryToConcurrentDictionary_When_DifferentStrategiesAreUsed() { foreach (var rf1 in Enumerable.Range(1, 32).Select(r => r.ToString())) foreach (var rf2 in Enumerable.Range(1, 32).Select(r => r.ToString())) { if (rf1 == rf2) { continue; } var keyspaces = new List<KeyspaceMetadata> { // unique configurations FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 2), FakeSchemaParserFactory.CreateSimpleKeyspace("ks2", 10), FakeSchemaParserFactory.CreateSimpleKeyspace("ks3", 5), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks4", new Dictionary<string, string> {{"dc1", rf1}, {"dc2", rf1}}), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks5", new Dictionary<string, string> {{"dc1", rf2}, {"dc2", rf2}}), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks6", new Dictionary<string, string> {{"dc1", "1"}}), // duplicate configurations FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks7", new Dictionary<string, string> {{"dc1", rf1}, {"dc2", rf1}}), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks8", new Dictionary<string, string> {{"dc1", "1"}}), FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks9", new Dictionary<string, string> {{"dc1", rf2}, {"dc2", rf2}}), FakeSchemaParserFactory.CreateSimpleKeyspace("ks10", 10), FakeSchemaParserFactory.CreateSimpleKeyspace("ks11", 2) }; var strategies = keyspaces.Select(k => k.Strategy).ToList(); var dictionary = new Dictionary<IReplicationStrategy, object>(); foreach (var strategy in strategies) { if (!dictionary.ContainsKey(strategy)) { dictionary.Add(strategy, ""); } } // private const in ConcurrentDictionary const int defaultCapacity = 31; // would love to test every possible value but it would take too much time foreach (var concurrencyLevel in Enumerable.Range(1, 512)) { var concurrentDictionary = new ConcurrentDictionary<IReplicationStrategy, object>(concurrencyLevel, defaultCapacity); foreach (var strategy in dictionary) { if (!concurrentDictionary.TryAdd(strategy.Key, strategy.Value)) { Assert.Fail($"This would throw ArgumentException, duplicate values with processor count: {concurrencyLevel}, rf1: {rf1}, rf2: {rf2}"); return; } } } } } [Test] [Repeat(1)] public void Should_UpdateKeyspacesAndTokenMapCorrectly_When_MultipleThreadsCallingRefreshKeyspace() { var keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(); // unique configurations keyspaces.AddOrUpdate("ks1", FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 2), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks2", FakeSchemaParserFactory.CreateSimpleKeyspace("ks2", 10), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks3", FakeSchemaParserFactory.CreateSimpleKeyspace("ks3", 5), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks4", FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks4", new Dictionary<string, string> { { "dc1", "2" }, { "dc2", "2" } }), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks5", FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks5", new Dictionary<string, string> { { "dc1", "1" }, { "dc2", "2" } }), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks6", FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks6", new Dictionary<string, string> { { "dc1", "1" } }), (s, keyspaceMetadata) => keyspaceMetadata); // duplicate configurations keyspaces.AddOrUpdate("ks7", FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks7", new Dictionary<string, string> { { "dc1", "2" }, { "dc2", "2" } }), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks8", FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks8", new Dictionary<string, string> { { "dc1", "1" } }), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks9", FakeSchemaParserFactory.CreateNetworkTopologyKeyspace("ks9", new Dictionary<string, string> { { "dc1", "1" }, { "dc2", "2" } }), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks10", FakeSchemaParserFactory.CreateSimpleKeyspace("ks10", 10), (s, keyspaceMetadata) => keyspaceMetadata); keyspaces.AddOrUpdate("ks11", FakeSchemaParserFactory.CreateSimpleKeyspace("ks11", 2), (s, keyspaceMetadata) => keyspaceMetadata); var schemaParser = new FakeSchemaParser(keyspaces); var config = new TestConfigurationBuilder { ConnectionFactory = new FakeConnectionFactory() }.Build(); var metadata = new Metadata(config, schemaParser) {Partitioner = "Murmur3Partitioner"}; metadata.ControlConnection = new ControlConnection( Mock.Of<IInternalCluster>(), new ProtocolEventDebouncer(new TaskBasedTimerFactory(), TimeSpan.FromMilliseconds(20), TimeSpan.FromSeconds(100)), ProtocolVersion.V3, config, metadata, new List<IContactPoint> { new IpLiteralContactPoint(IPAddress.Parse("127.0.0.1"), config.ProtocolOptions, config.ServerNameResolver) }); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.2"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.3"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.4"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.5"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.6"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.7"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.8"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.9"), 9042)); metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.10"), 9042)); var initialToken = 1; foreach (var h in metadata.Hosts) { h.SetInfo(new TestHelper.DictionaryBasedRow(new Dictionary<string, object> { { "data_center", initialToken % 2 == 0 ? "dc1" : "dc2"}, { "rack", "rack1" }, { "tokens", GenerateTokens(initialToken, 256) }, { "release_version", "3.11.1" } })); initialToken++; } metadata.RebuildTokenMapAsync(false, true).GetAwaiter().GetResult(); var expectedTokenMap = metadata.TokenToReplicasMap; Assert.NotNull(expectedTokenMap); var bag = new ConcurrentBag<string>(); var tasks = new List<Task>(); for (var i = 0; i < 100; i++) { var index = i; tasks.Add(Task.Factory.StartNew( () => { for (var j = 0; j < 35; j++) { if (j % 10 == 0 && index % 2 == 0) { metadata.RefreshSchemaAsync().GetAwaiter().GetResult(); } else if (j % 16 == 0) { if (bag.TryTake(out var ksName)) { if (keyspaces.TryRemove(ksName, out var ks)) { metadata.RefreshSchemaAsync(ksName).GetAwaiter().GetResult(); ks = metadata.GetKeyspace(ksName); if (ks != null) { throw new Exception($"refresh for {ks.Name} returned non null after refresh single."); } } } } else if (j % 2 == 0) { if (bag.TryTake(out var ksName)) { if (keyspaces.TryRemove(ksName, out var ks)) { metadata.ControlConnection.HandleKeyspaceRefreshLaterAsync(ks.Name).GetAwaiter().GetResult(); ks = metadata.GetKeyspace(ksName); if (ks != null) { throw new Exception($"refresh for {ks.Name} returned non null after remove."); } } } } else { var keyspaceName = $"ks_____{index}_____{j}"; var ks = FakeSchemaParserFactory.CreateSimpleKeyspace(keyspaceName, (index * j) % 10); keyspaces.AddOrUpdate( keyspaceName, ks, (s, keyspaceMetadata) => ks); metadata.ControlConnection.HandleKeyspaceRefreshLaterAsync(ks.Name).GetAwaiter().GetResult(); ks = metadata.GetKeyspace(ks.Name); if (ks == null) { throw new Exception($"refresh for {keyspaceName} returned null after add."); } bag.Add(keyspaceName); } } }, TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach)); } Task.WaitAll(tasks.ToArray()); AssertSameReplicas(keyspaces.Values, expectedTokenMap, metadata.TokenToReplicasMap); } [Test] public void RefreshSingleKeyspace_Should_BuildTokenMap_When_TokenMapIsNull() { var keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(); keyspaces.GetOrAdd("ks1", FakeSchemaParserFactory.CreateSimpleKeyspace("ks1", 1)); var schemaParser = new FakeSchemaParser(keyspaces); var metadata = new Metadata(new Configuration(), schemaParser) { Partitioner = "Murmur3Partitioner" }; metadata.Hosts.Add(new IPEndPoint(IPAddress.Parse("192.168.0.1"), 9042)); ; metadata.Hosts.First().SetInfo(new TestHelper.DictionaryBasedRow(new Dictionary<string, object> { { "data_center", "dc1"}, { "rack", "rack1" }, { "tokens", GenerateTokens(1, 256) }, { "release_version", "3.11.1" } })); Assert.IsNull(metadata.TokenToReplicasMap); metadata.RefreshSingleKeyspace("ks1").GetAwaiter().GetResult(); Assert.NotNull(metadata.TokenToReplicasMap); } private KeyspaceMetadata CreateKeyspaceMetadata( Metadata parent, string name, bool durableWrites, string strategyClass, IDictionary<string, string> replicationOptions, bool isVirtual = false) { return new KeyspaceMetadata( parent, name, durableWrites, strategyClass, replicationOptions, new ReplicationStrategyFactory(), null, isVirtual); } private void AssertSameReplicas(IEnumerable<KeyspaceMetadata> keyspaces, IReadOnlyTokenMap expectedTokenMap, IReadOnlyTokenMap actualTokenMap) { foreach (var k in keyspaces) { var actual = actualTokenMap.GetByKeyspace(k.Name); var expected = expectedTokenMap.GetByKeyspace(k.Name); if (expected != null) { CollectionAssert.AreEqual(expected.Keys, actual.Keys); foreach (var kvp in expected) { Assert.IsTrue( expected[kvp.Key].SetEquals(actual[kvp.Key]), $"mismatch in keyspace '{k}' and token '{kvp.Key}': " + $"'{string.Join(",", expected[kvp.Key].Select(h => h.Address.ToString()))}' vs " + $"'{string.Join(",", actual[kvp.Key].Select(h => h.Address.ToString()))}'"); } } else { // keyspace is one of the keyspaces that were inserted by the tasks and wasn't removed var rf = k.Replication["replication_factor"]; Assert.AreEqual(10 * 256, actual.Count); foreach (var kvp in actual) { Assert.AreEqual(rf, kvp.Value.Count); } } } } private void AssertOnlyOneStrategyIsCalled(IList<ProxyReplicationStrategy> strategies, params int[] equalStrategiesIndexes) { var sameStrategies = equalStrategiesIndexes.Select(t => strategies[t]).ToList(); Assert.AreEqual(1, sameStrategies.Count(strategy => strategy.Calls == 1)); Assert.AreEqual(sameStrategies.Count - 1, sameStrategies.Count(strategy => strategy.Calls == 0)); } private IEnumerable<string> GenerateTokens(int initialToken, int numTokens) { var output = new List<string>(); for (var i = 0; i < numTokens; i++) { output.Add(initialToken.ToString()); initialToken += 1000; } return output; } }
1,135
42,182
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion namespace Cassandra.Serialization.Graph.Tinkerpop.Structure.IO.GraphSON { internal class GraphSONTokens { public static string TypeKey = "@type"; public static string ValueKey = "@value"; public static string GremlinTypeNamespace = "g"; } }
nbuilder
nbuilder
F:\Projects\TestMap\Temp\nbuilder\NBuilder.sln
F:\Projects\TestMap\Temp\nbuilder\tests\FizzWare.NBuilder.Tests\FizzWare.NBuilder.Tests.csproj
F:\Projects\TestMap\Temp\nbuilder\tests\FizzWare.NBuilder.Tests\Unit\OperableExtensionTests.cs
FizzWare.NBuilder.Tests.Unit
OperableExtensionTests
['public int Length { get; }', 'public int NumberOfAffectedItems { get; }', 'public IList<int> MasterListAffectedIndexes { get; }', 'public int Start { get; }', 'public int End { get; }', 'public IListBuilderImpl<MyClass> ListBuilderImpl { get; }', 'public IObjectBuilder<MyClass> ObjectBuilder { get; }', 'public BuilderSettings BuilderSettings { get; set; }', 'private IObjectBuilder<MyClass> objectBuilder;', 'private Func<MyClass, float> func;', 'private Expression<Func<MyClass, int>> propertyExpression;', 'private IDeclaration<MyClass> operable;']
['System', 'System.Collections.Generic', 'FizzWare.NBuilder.Implementation', 'FizzWare.NBuilder.Tests.TestClasses', 'NSubstitute', 'System.Linq.Expressions', 'Shouldly', 'Xunit']
xUnit
net47;netcoreapp2.1
// ReSharper disable InvokeAsExtensionMethod public class OperableExtensionTests { private IObjectBuilder<MyClass> objectBuilder; private Func<MyClass, float> func; private Expression<Func<MyClass, int>> propertyExpression; private IDeclaration<MyClass> operable; private class MyDeclaration : IDeclaration<MyClass>, IOperable<MyClass> { public void Construct() { } public int Length { get; } public void CallFunctions(IList<MyClass> masterList) { throw new NotImplementedException(); } public void AddToMaster(MyClass[] masterList) { throw new NotImplementedException(); } public int NumberOfAffectedItems { get; } public IList<int> MasterListAffectedIndexes { get; } public int Start { get; } public int End { get; } public IListBuilderImpl<MyClass> ListBuilderImpl { get; } public IObjectBuilder<MyClass> ObjectBuilder { get; } public BuilderSettings BuilderSettings { get; set; } public IList<MyClass> Build() { throw new NotImplementedException(); } public IOperable<MyClass> All() { throw new NotImplementedException(); } } public OperableExtensionTests() { objectBuilder = Substitute.For<IObjectBuilder<MyClass>>(); operable = Substitute.For<IDeclaration<MyClass> , IOperable<MyClass>>(); // typeof(IOperable<MyClass>) func = x => x.Float = 1f; propertyExpression = x => x.IntGetterOnly; } [Fact] public void ShouldBeAbleToUseWith() { var builderSetup = new BuilderSettings(); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(func); } OperableExtensions.With((IOperable<MyClass>)operable, func); } [Fact] public void ShouldBeAbleToUseWith_WithAnIndex() { var builderSetup = new BuilderSettings(); Action<MyClass, int> funcWithIndex = (x, idx) => x.StringOne = "String" + (idx + 5); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(funcWithIndex); } OperableExtensions.With((IOperable<MyClass>)operable, funcWithIndex); } [Fact] public void ShouldBeAbleToUseHas() { var builderSetup = new BuilderSettings(); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(func); } OperableExtensions.With((IOperable<MyClass>)operable, func); } [Fact] public void ShouldBeAbleToUseAnd() { var builderSetup = new BuilderSettings(); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(func); } OperableExtensions.And((IOperable<MyClass>)operable, func); } [Fact] public void ShouldBeAbleToUseAndWithAnIndex() { var builderSetup = new BuilderSettings(); Action<MyClass, int> funcWithIndex = (x, idx) => x.StringOne = "String" + (idx + 5); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(funcWithIndex); } OperableExtensions.And((IOperable<MyClass>)operable, funcWithIndex); } [Fact] public void ShouldBeAbleToUseWithToSetPrivateProperties() { var builderSetup = new BuilderSettings(); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(propertyExpression, 100); } OperableExtensions.With((IOperable<MyClass>)operable, propertyExpression, 100); } [Fact] public void ShouldBeAbleToUseHasToSetPrivateProperties() { var builderSetup = new BuilderSettings(); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(propertyExpression, 100); } OperableExtensions.With((IOperable<MyClass>)operable, propertyExpression, 100); } [Fact] public void ShouldBeAbleToUseAndToSetPrivateProperties() { var builderSetup = new BuilderSettings(); { operable.ObjectBuilder.Returns(new ObjectBuilder<MyClass>(null, builderSetup)); objectBuilder.With(propertyExpression, 100); } OperableExtensions.And((IOperable<MyClass>)operable, propertyExpression, 100); } [Fact] public void ShouldBeAbleToUseDoForEach() { var simpleClasses = new List<SimpleClass>(); Action<MyClass, SimpleClass> action = (x, y) => x.Add(y); { operable.ObjectBuilder.Returns(objectBuilder); objectBuilder.DoMultiple(action, simpleClasses).Returns(objectBuilder); } OperableExtensions.DoForEach((IOperable<MyClass>)operable, action, simpleClasses); } [Fact] public void ShouldBeAbleToUseHasDoneToItForAll() { var simpleClasses = new List<SimpleClass>(); Action<MyClass, SimpleClass> action = (x, y) => x.Add(y); { operable.ObjectBuilder.Returns(objectBuilder); objectBuilder.DoMultiple(action, simpleClasses).Returns(objectBuilder); } OperableExtensions.DoForEach((IOperable<MyClass>)operable, action, simpleClasses); } [Fact] public void ShouldBeAbleToUseDo() { Action<MyClass> action = x => x.DoSomething(); { operable.ObjectBuilder.Returns(objectBuilder); objectBuilder.Do(action).Returns(objectBuilder); } OperableExtensions.Do((IOperable<MyClass>)operable, action); } [Fact] public void ShouldBeAbleToUseHasDoneToIt() { Action<MyClass, int> action = (x, y) => x.DoSomething(); { operable.ObjectBuilder.Returns(objectBuilder); objectBuilder.Do(action).Returns(objectBuilder); } OperableExtensions.With((IOperable<MyClass>)operable, action); } [Fact] public void ShouldBeAbleToUseAndToAddAnAction() { Action<MyClass> action = x => x.DoSomething(); { operable.ObjectBuilder.Returns(objectBuilder); objectBuilder.Do(action).Returns(objectBuilder); } OperableExtensions.And((IOperable<MyClass>)operable, action); } [Fact] public void ShouldComplainIfOperableIsNotAlsoOfTypeIDeclaration() { var operableOnly = Substitute.For<IOperable<MyClass>>(); Should.Throw<ArgumentException>(() => { OperableExtensions.With(operableOnly, x => x.StringOne = "test"); }); } }
327
8,200
using System; using System.Collections.Generic; using System.Linq.Expressions; using FizzWare.NBuilder.Implementation; namespace FizzWare.NBuilder { public static class OperableExtensions { /// <summary> /// Sets the value of one of the type's public properties /// </summary> public static IOperable<T> With<T, TFunc>(this IOperable<T> operable, Func<T, TFunc> func) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.With(func); return (IOperable<T>)declaration; } /// <summary> /// Sets the value of one of the type's public properties and provides the index of the object being set /// </summary> public static IOperable<T> With<T>(this IOperable<T> operable, Action<T, int> func) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.With(func); return (IOperable<T>)declaration; } /// <summary> /// Sets the value of one of the type's private properties or readonly fields /// </summary> public static IOperable<T> With<T, TProperty>(this IOperable<T> operable, Expression<Func<T, TProperty>> property, TProperty value) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.With(property, value); return (IOperable<T>)declaration; } /// <summary> /// Sets the value of one of the type's public properties /// </summary> public static IOperable<T> And<T, TFunc>(this IOperable<T> operable, Func<T, TFunc> func) { return With(operable, func); } /// <summary> /// Sets the value of one of the type's public properties and provides the index of the object being set /// </summary> public static IOperable<T> And<T>(this IOperable<T> operable, Action<T, int> func) { return With(operable, func); } /// <summary> /// Sets the value of one of the type's private properties or readonly fields /// </summary> public static IOperable<T> And<T, TProperty>(this IOperable<T> operable, Expression<Func<T, TProperty>> property, TProperty value) { return With(operable, property, value); } /// <summary> /// Performs an action on the type. /// </summary> public static IOperable<T> And<T>(this IOperable<T> operable, Action<T> action) { return Do(operable, action); } /// <summary> /// Specify the constructor for the type like this: /// /// WithConstructor( () => new MyType(arg1, arg2) ) /// </summary> [Obsolete("Use WithFactory instead.")] public static IOperable<T> WithConstructor<T>(this IOperable<T> operable, Func<T> constructor) { return operable.WithFactory(constructor); //var declaration = GetDeclaration(operable); //declaration.ObjectBuilder.WithConstructor(constructor); //return (IOperable<T>)declaration; } /// <summary> /// Specify the constructor for the type like this: /// /// WithFactory( () => new MyType(arg1, arg2) ) /// </summary> public static IOperable<T> WithFactory<T>(this IOperable<T> operable, Func<T> factory) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.WithFactory(factory); return (IOperable<T>)declaration; } /// <summary> /// Specify the constructor for the type like this: /// /// WithConstructor( () => new MyType(arg1, arg2) ) /// </summary> [Obsolete("Use WithFactory instead.")] public static IOperable<T> WithConstructor<T>(this IOperable<T> operable, Func<int, T> constructor) { return operable.WithFactory(constructor); } /// <summary> /// Specify the constructor for the type like this: /// /// WithFactory( () => new MyType(arg1, arg2) ) /// </summary> public static IOperable<T> WithFactory<T>(this IOperable<T> operable, Func<int, T> factory) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.WithFactory(factory); return (IOperable<T>)declaration; } /// <summary> /// Performs an action on the object. /// </summary> public static IOperable<T> Do<T>(this IOperable<T> operable, Action<T> action) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.Do(action); return (IOperable<T>)declaration; } /// <summary> /// Performs an action on the object. /// </summary> public static IOperable<T> Do<T>(this IOperable<T> operable, Action<T, int> action) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.Do(action); return (IOperable<T>)declaration; } /// <summary> /// Performs an action for each item in a list. /// </summary> public static IOperable<T> DoForEach<T, U>(this IOperable<T> operable, Action<T, U> action, IList<U> list) { var declaration = GetDeclaration(operable); declaration.ObjectBuilder.DoMultiple(action, list); return (IOperable<T>)declaration; } private static IDeclaration<T> GetDeclaration<T>(IOperable<T> operable) { var declaration = operable as IDeclaration<T>; if (declaration == null) throw new ArgumentException("Must be of type IDeclaration<T>"); return declaration; } } }
nbuilder
nbuilder
F:\Projects\TestMap\Temp\nbuilder\NBuilder.sln
F:\Projects\TestMap\Temp\nbuilder\tests\FizzWare.NBuilder.Tests\FizzWare.NBuilder.Tests.csproj
F:\Projects\TestMap\Temp\nbuilder\tests\FizzWare.NBuilder.Tests\Unit\PersistenceExtensionTests.cs
FizzWare.NBuilder.Tests.Unit
PersistenceExtensionTests
['private IPersistenceService persistenceService;', 'private IOperable<MyClass> operable;', 'private IListBuilderImpl<MyClass> listBuilderImpl;', 'private ISingleObjectBuilder<MyClass> singleObjectBuilder;', 'private IList<MyClass> theList;']
['System', 'System.Collections.Generic', 'FizzWare.NBuilder.Implementation', 'FizzWare.NBuilder.Tests.TestClasses', 'NSubstitute', 'Shouldly', 'Xunit']
xUnit
net47;netcoreapp2.1
// ReSharper disable InvokeAsExtensionMethod public class PersistenceExtensionTests { private IPersistenceService persistenceService; private IOperable<MyClass> operable; private IListBuilderImpl<MyClass> listBuilderImpl; private ISingleObjectBuilder<MyClass> singleObjectBuilder; private IList<MyClass> theList; public PersistenceExtensionTests() { persistenceService = Substitute.For<IPersistenceService>(); listBuilderImpl = Substitute.For<IListBuilderImpl<MyClass>>(); operable = Substitute.For<IOperable<MyClass>, IDeclaration<MyClass>>(); singleObjectBuilder = Substitute.For<ISingleObjectBuilder<MyClass>>(); theList = new List<MyClass>(); } [Fact] public void ShouldBeAbleToPersistUsingSingleObjectBuilder() { var builderSetup = new BuilderSettings(); var obj = new MyClass(); { singleObjectBuilder.BuilderSettings.Returns(builderSetup); singleObjectBuilder.Build().Returns(obj); persistenceService.Create(obj); } { builderSetup.SetPersistenceService(persistenceService); PersistenceExtensions.Persist(singleObjectBuilder); } } [Fact] public void ShouldBeAbleToPersistUsingListBuilder() { var builderSetup = new BuilderSettings(); { listBuilderImpl.BuilderSettings.Returns(builderSetup); listBuilderImpl.Build().Returns(theList); persistenceService.Create(theList); } { builderSetup.SetPersistenceService(persistenceService); PersistenceExtensions.Persist(listBuilderImpl); } } [Fact] public void ShouldBeAbleToPersistFromADeclaration() { var builderSetup = new BuilderSettings(); { listBuilderImpl.BuilderSettings.Returns(builderSetup); listBuilderImpl.Build().Returns(theList); listBuilderImpl.BuilderSettings.Returns(builderSetup); persistenceService.Create(theList); ((IDeclaration<MyClass>) operable).ListBuilderImpl.Returns(listBuilderImpl); } { builderSetup.SetPersistenceService(persistenceService); PersistenceExtensions.Persist(operable); } } [Fact] public void Persist_TypeOfIOperableOnlyNotIDeclaration_ThrowsException() { var operableOnly = Substitute.For<IOperable<MyClass>>(); { Should.Throw<ArgumentException>(() => PersistenceExtensions.Persist(operableOnly)); } } }
295
3,217
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FizzWare.NBuilder.Implementation; namespace FizzWare.NBuilder { public static class PersistenceExtensions { private static IDeclaration<T> GetDeclaration<T>(IOperable<T> operable) { var declaration = operable as IDeclaration<T>; if (declaration == null) throw new ArgumentException("Must be of type IDeclaration<T>"); return declaration; } public static T Persist<T>(this ISingleObjectBuilder<T> singleObjectBuilder) { var obj = singleObjectBuilder.Build(); IPersistenceService persistenceService = singleObjectBuilder.BuilderSettings.GetPersistenceService(); persistenceService.Create(obj); return obj; } public static IList<T> Persist<T>(this IOperable<T> operable) { var declaration = GetDeclaration(operable); return Persist(declaration.ListBuilderImpl); } public static IList<T> Persist<T>(this IListBuilder<T> listBuilder) { var list = listBuilder.Build(); var persistenceService = listBuilder.BuilderSettings.GetPersistenceService(); persistenceService.Create(list); return list; } } }
mongodb
mongo-csharp-driver
F:\Projects\TestMap\Temp\mongo-csharp-driver\CSharpDriver.sln
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\MongoDB.Driver.Tests.csproj
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\CreateOneIndexOptionsTest.cs
MongoDB.Driver.Tests
CreateOneIndexOptionsTest
[]
['System', 'FluentAssertions', 'MongoDB.TestHelpers.XunitExtensions', 'Xunit']
xUnit
null
public class CreateOneIndexOptionsTest { [Theory] [ParameterAttributeData] public void CommitQuorum_get_should_return_expected_result( [Values(null, 1, 2)] int? w) { var commitQuorum = w.HasValue ? CreateIndexCommitQuorum.Create(w.Value) : null; var subject = new CreateOneIndexOptions() { CommitQuorum = commitQuorum }; var result = subject.CommitQuorum; result.Should().BeSameAs(commitQuorum); } [Theory] [ParameterAttributeData] public void CommitQuorum_set_should_have_expected_result( [Values(null, 1, 2)] int? w) { var commitQuorum = w.HasValue ? CreateIndexCommitQuorum.Create(w.Value) : null; var subject = new CreateOneIndexOptions() { CommitQuorum = commitQuorum }; subject.CommitQuorum = commitQuorum; subject.CommitQuorum.Should().Be(commitQuorum); } [Fact] public void MaxTime_get_should_return_expected_result() { var subject = new CreateOneIndexOptions { MaxTime = TimeSpan.FromSeconds(123) }; var result = subject.MaxTime; result.Should().Be(TimeSpan.FromSeconds(123)); } [Theory] [ParameterAttributeData] public void MaxTime_set_should_have_expected_result( [Values(null, -10000, 0, 1, 9999, 10000, 10001)] int? maxTimeTicks) { var subject = new CreateOneIndexOptions(); var maxTime = maxTimeTicks == null ? (TimeSpan?)null : TimeSpan.FromTicks(maxTimeTicks.Value); subject.MaxTime = maxTime; subject.MaxTime.Should().Be(maxTime); } [Theory] [ParameterAttributeData] public void MaxTime_set_should_throw_when_value_is_invalid( [Values(-10001, -9999, -1)] long maxTimeTicks) { var subject = new CreateOneIndexOptions(); var value = TimeSpan.FromTicks(maxTimeTicks); var exception = Record.Exception(() => subject.MaxTime = value); var e = exception.Should().BeOfType<ArgumentOutOfRangeException>().Subject; e.ParamName.Should().Be("value"); } }
739
3,067
/* Copyright 2018-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver { /// <summary> /// Options for creating a single index. /// </summary> public class CreateOneIndexOptions { // private fields private CreateIndexCommitQuorum _commitQuorum; private TimeSpan? _maxTime; // public properties /// <summary> /// Gets or sets the commit quorum. /// </summary> /// <value>The commit quorum.</value> public CreateIndexCommitQuorum CommitQuorum { get { return _commitQuorum; } set { _commitQuorum = value; } } /// <summary> /// Gets or sets the maximum time. /// </summary> /// <value>The maximum time.</value> public TimeSpan? MaxTime { get { return _maxTime; } set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } } }
mongodb
mongo-csharp-driver
F:\Projects\TestMap\Temp\mongo-csharp-driver\CSharpDriver.sln
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\MongoDB.Driver.Tests.csproj
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\DropIndexOptionsTest.cs
MongoDB.Driver.Tests
DropIndexOptionsTest
[]
['System', 'FluentAssertions', 'MongoDB.TestHelpers.XunitExtensions', 'Xunit']
xUnit
null
public class DropIndexOptionsTest { [Fact] public void MaxTime_get_should_return_expected_result() { var subject = new DropIndexOptions { MaxTime = TimeSpan.FromSeconds(123) }; var result = subject.MaxTime; result.Should().Be(TimeSpan.FromSeconds(123)); } [Theory] [ParameterAttributeData] public void MaxTime_set_should_have_expected_result( [Values(null, -10000, 0, 1, 9999, 10000, 10001)] int? maxTimeTicks) { var subject = new DropIndexOptions(); var maxTime = maxTimeTicks == null ? (TimeSpan?)null : TimeSpan.FromTicks(maxTimeTicks.Value); subject.MaxTime = maxTime; subject.MaxTime.Should().Be(maxTime); } [Theory] [ParameterAttributeData] public void MaxTime_set_should_throw_when_value_is_invalid( [Values(-10001, -9999, -1)] long maxTimeTicks) { var subject = new DropIndexOptions(); var value = TimeSpan.FromTicks(maxTimeTicks); var exception = Record.Exception(() => subject.MaxTime = value); var e = exception.Should().BeOfType<ArgumentOutOfRangeException>().Subject; e.ParamName.Should().Be("value"); } }
739
2,089
/* Copyright 2018-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using MongoDB.Bson; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver { /// <summary> /// Options for dropping an index. /// </summary> public class DropIndexOptions { private BsonValue _comment; private TimeSpan? _maxTime; /// <summary> /// Gets or sets the comment. /// </summary> /// <value> /// The comment. /// </value> public BsonValue Comment { get { return _comment; } set { _comment = value; } } /// <summary> /// Gets or sets the maximum time. /// </summary> /// <value>The maximum time.</value> public TimeSpan? MaxTime { get { return _maxTime; } set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } } }
mongodb
mongo-csharp-driver
F:\Projects\TestMap\Temp\mongo-csharp-driver\CSharpDriver.sln
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\MongoDB.Driver.Tests.csproj
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\FieldDefinitionTests.cs
MongoDB.Driver.Tests
FieldDefinitionTests
['[BsonElement("name")]\n public Name Name { get; set; }', '[BsonElement("pets")]\n public IEnumerable<Pet> Pets { get; set; }', '[BsonElement("g")]\n public Gender Gender { get; set; }', '[BsonElement("gs")]\n public IEnumerable<Gender> Genders { get; set; }', '[BsonElement("fn")]\n public string First { get; set; }', '[BsonElement("ln")]\n public string Last { get; set; }', '[BsonElement("type")]\n public string Type { get; set; }', '[BsonElement("name")]\n public Name Name { get; set; }']
['System', 'System.Collections.Generic', 'System.Linq', 'System.Linq.Expressions', 'FluentAssertions', 'MongoDB.Bson', 'MongoDB.Bson.Serialization', 'MongoDB.Bson.Serialization.Attributes', 'MongoDB.Bson.Serialization.Serializers', 'Xunit']
xUnit
null
public class FieldDefinitionTests { [Fact] public void Should_resolve_from_a_non_IBsonDocumentSerializer() { var subject = new StringFieldDefinition<string, string>("test"); var renderedField = subject.Render(new(new StringSerializer(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("test"); renderedField.UnderlyingSerializer.Should().BeNull(); renderedField.FieldSerializer.Should().BeNull(); renderedField.ValueSerializer.Should().BeOfType<StringSerializer>(); } [Fact] public void Should_resolve_from_a_BsonDocumentSerializer() { var subject = new StringFieldDefinition<BsonDocument, BsonValue>("test"); var renderedField = subject.Render(new(BsonDocumentSerializer.Instance, BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("test"); renderedField.UnderlyingSerializer.Should().BeNull(); renderedField.FieldSerializer.Should().BeNull(); renderedField.ValueSerializer.Should().BeOfType<BsonValueSerializer>(); } [Fact] public void Should_resolve_from_a_BsonDocumentSerializer_with_dots() { var subject = new StringFieldDefinition<BsonDocument, BsonValue>("test.one.two.three"); var renderedField = subject.Render(new(BsonDocumentSerializer.Instance, BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("test.one.two.three"); renderedField.UnderlyingSerializer.Should().BeNull(); renderedField.FieldSerializer.Should().BeNull(); renderedField.ValueSerializer.Should().BeOfType<BsonValueSerializer>(); } [Fact] public void Should_resolve_top_level_field() { var subject = new StringFieldDefinition<Person, Name>("Name"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("name"); renderedField.UnderlyingSerializer.Should().BeOfType<BsonClassMapSerializer<Name>>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_a_nested_field() { var subject = new StringFieldDefinition<Person, string>("Name.First"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("name.fn"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_a_nested_field_that_does_not_exist() { var subject = new StringFieldDefinition<Person, string>("Name.NoExisty"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("name.NoExisty"); renderedField.UnderlyingSerializer.Should().BeNull(); renderedField.FieldSerializer.Should().BeNull(); renderedField.ValueSerializer.Should().BeOfType<StringSerializer>(); } [Fact] public void Should_resolve_array_name() { var subject = new StringFieldDefinition<Person, string>("Pets.Type"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.type"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_array_name_with_multiple_dots() { var subject = new StringFieldDefinition<Person, string>("Pets.Name.First"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.name.fn"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_array_name_with_single_digit_indexer() { var subject = new StringFieldDefinition<Person, string>("Pets.3.Type"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.3.type"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_array_name_with_a_multi_digit_indexer() { var subject = new StringFieldDefinition<Person, string>("Pets.42.Type"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.42.type"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_array_name_with_positional_operator() { var subject = new StringFieldDefinition<Person, string>("Pets.$.Type"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.$.type"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_array_name_with_positional_operator_with_multiple_dots() { var subject = new StringFieldDefinition<Person, string>("Pets.$.Name.Last"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.$.name.ln"); renderedField.UnderlyingSerializer.Should().BeOfType<StringSerializer>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_an_enum_with_field_type() { var subject = new ExpressionFieldDefinition<Person, Gender>(x => x.Gender); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("g"); renderedField.UnderlyingSerializer.Should().BeOfType<EnumSerializer<Gender>>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_an_enum_without_field_type() { Expression<Func<Person, object>> exp = x => x.Gender; var subject = new ExpressionFieldDefinition<Person>(exp); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("g"); renderedField.FieldSerializer.Should().BeOfType<EnumSerializer<Gender>>(); } [Fact] public void Should_assign_a_non_typed_field_definition_from_a_typed_field_definition() { FieldDefinition<Person, Gender> subject = new ExpressionFieldDefinition<Person, Gender>(x => x.Gender); FieldDefinition<Person> subject2 = subject; var renderedField = subject2.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("g"); renderedField.FieldSerializer.Should().BeOfType<EnumSerializer<Gender>>(); } [Fact] public void Should_resolve_an_array_field_with_field_lambda() { FieldDefinition<Person, IEnumerable<Gender>> subject = new ExpressionFieldDefinition<Person, IEnumerable<Gender>>(x => x.Genders); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("gs"); renderedField.UnderlyingSerializer.Should().BeOfType<IEnumerableDeserializingAsCollectionSerializer<IEnumerable<Gender>, Gender, List<Gender>>>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_an_array_fields_field_with_lambda() { var subject = new ExpressionFieldDefinition<Person, IEnumerable<Name>>(x => x.Pets.Select(p => p.Name)); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("pets.name"); renderedField.UnderlyingSerializer.Should().BeAssignableTo<SerializerBase<IEnumerable<Name>>>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_an_array_field_with_field_name() { FieldDefinition<Person, IEnumerable<Gender>> subject = new StringFieldDefinition<Person, IEnumerable<Gender>>("Genders"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry)); renderedField.FieldName.Should().Be("gs"); renderedField.UnderlyingSerializer.Should().BeOfType<IEnumerableDeserializingAsCollectionSerializer<IEnumerable<Gender>, Gender, List<Gender>>>(); renderedField.FieldSerializer.Should().BeSameAs(renderedField.UnderlyingSerializer); renderedField.ValueSerializer.Should().BeSameAs(renderedField.FieldSerializer); } [Fact] public void Should_resolve_an_array_field_with_field_name_and_scalar_value_and_scalar_value_is_allowed() { FieldDefinition<Person, Gender> subject = new StringFieldDefinition<Person, Gender>("Genders"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry, pathRenderArgs: new PathRenderArgs(AllowScalarValueForArray: true))); renderedField.FieldName.Should().Be("gs"); renderedField.UnderlyingSerializer.Should().BeOfType<IEnumerableDeserializingAsCollectionSerializer<IEnumerable<Gender>, Gender, List<Gender>>>(); renderedField.FieldSerializer.Should().BeNull(); renderedField.ValueSerializer.Should().BeOfType<EnumSerializer<Gender>>(); } [Fact] public void Should_resolve_an_array_field_with_field_name_and_scalar_value_and_scalar_value_is_not_allowed() { FieldDefinition<Person, Gender> subject = new StringFieldDefinition<Person, Gender>("Genders"); var renderedField = subject.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<Person>(), BsonSerializer.SerializerRegistry, pathRenderArgs: new PathRenderArgs(AllowScalarValueForArray: false))); renderedField.FieldName.Should().Be("gs"); renderedField.UnderlyingSerializer.Should().BeOfType<IEnumerableDeserializingAsCollectionSerializer<IEnumerable<Gender>, Gender, List<Gender>>>(); renderedField.FieldSerializer.Should().BeNull(); renderedField.ValueSerializer.ValueType.Should().Be(typeof(Gender)); renderedField.ValueSerializer.GetType().Name.Should().Be("ConvertIfPossibleSerializer`2"); } private class Person { [BsonElement("name")] public Name Name { get; set; } [BsonElement("pets")] public IEnumerable<Pet> Pets { get; set; } [BsonElement("g")] public Gender Gender { get; set; } [BsonElement("gs")] public IEnumerable<Gender> Genders { get; set; } } private class Name { [BsonElement("fn")] public string First { get; set; } [BsonElement("ln")] public string Last { get; set; } } private class Pet { [BsonElement("type")] public string Type { get; set; } [BsonElement("name")] public Name Name { get; set; } } private enum Gender { Male, Female } }
931
15,830
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using MongoDB.Bson; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Linq; namespace MongoDB.Driver { /// <summary> /// Defines the fields to be set by a $set stage. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> public abstract class SetFieldDefinitions<TDocument> { /// <summary> /// Renders the set field definitions. /// </summary> /// <param name="args">The render arguments.</param> /// <returns>The rendered set field definitions.</returns> public abstract BsonDocument Render(RenderArgs<TDocument> args); } /// <summary> /// A subclass of SetFieldDefinitions containing a list of SetFieldDefinition instances to define the fields to be set. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> public sealed class ListSetFieldDefinitions<TDocument> : SetFieldDefinitions<TDocument> { private readonly IReadOnlyList<SetFieldDefinition<TDocument>> _list; /// <summary> /// Initializes an instances ListSetFieldDefinitions. /// </summary> /// <param name="setFieldDefinitions">The set field definitions.</param> public ListSetFieldDefinitions(IEnumerable<SetFieldDefinition<TDocument>> setFieldDefinitions) { _list = Ensure.IsNotNull(setFieldDefinitions, nameof(setFieldDefinitions)).ToList(); } /// <summary> /// Gets the list of SetFieldDefinition instances. /// </summary> public IReadOnlyList<SetFieldDefinition<TDocument>> List => _list; /// <inheritdoc/> public override BsonDocument Render(RenderArgs<TDocument> args) { var document = new BsonDocument(); foreach (var setFieldDefinition in _list) { var renderedSetFieldDefinition = setFieldDefinition.Render(args); document[renderedSetFieldDefinition.Name] = renderedSetFieldDefinition.Value; // if same element name is set more than once last one wins } return document; } } /// <summary> /// A subclass of SetFieldDefinition that uses an Expression to define the fields to be set. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <typeparam name="TFields">The type of object specifying the fields to set.</typeparam> public sealed class ExpressionSetFieldDefinitions<TDocument, TFields> : SetFieldDefinitions<TDocument> { private Expression<Func<TDocument, TFields>> _expression; /// <summary> /// Initializes an instance of ExpressionSetFieldDefinitions. /// </summary> /// <param name="expression">The expression.</param> public ExpressionSetFieldDefinitions(Expression<Func<TDocument, TFields>> expression) { _expression = Ensure.IsNotNull(expression, nameof(expression)); } /// <inheritdoc/> public override BsonDocument Render(RenderArgs<TDocument> args) { var stage = LinqProviderAdapter.TranslateExpressionToSetStage(_expression, args.DocumentSerializer, args.SerializerRegistry, args.TranslationOptions); return stage["$set"].AsBsonDocument; } } }
mongodb
mongo-csharp-driver
F:\Projects\TestMap\Temp\mongo-csharp-driver\CSharpDriver.sln
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\MongoDB.Driver.Tests.csproj
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\Search\SearchDefinitionTests.cs
MongoDB.Driver.Tests.Search
SearchDefinitionTests
[]
['FluentAssertions', 'MongoDB.Bson', 'MongoDB.Bson.Serialization', 'MongoDB.Driver.Search', 'Xunit']
xUnit
null
public class SearchDefinitionTests { [Theory] [InlineData(null)] [InlineData("{ operator: 'parameter' }")] public void BsonDocument_implicit_cast_should_create_BsonSearchDefinition(string searchDefinitionJson) { var searchDefinitionDocument = searchDefinitionJson != null ? BsonDocument.Parse(searchDefinitionJson) : null; var searchDefinition = (SearchDefinition<BsonDocument>)searchDefinitionDocument; if (searchDefinitionJson == null) { searchDefinition.Should().BeNull(); } else { var subject = searchDefinition.Should().BeOfType<BsonDocumentSearchDefinition<BsonDocument>>().Subject; subject.Document.Should().Be(searchDefinitionDocument); } } [Fact] public void Pipeline_with_BsonDocumentSearchDefinition_should_render_correctly_multiple_times() { var searchOptions = new SearchOptions<BsonDocument>() { IndexName = "test", ScoreDetails = true, }; var document = new BsonDocument("operator", "parameter"); var searchDefinition = (BsonDocumentSearchDefinition<BsonDocument>)document; var pipeline = (new EmptyPipelineDefinition<BsonDocument>()).Search(searchDefinition, searchOptions); var renderedPipeline = pipeline.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<BsonDocument>(), BsonSerializer.SerializerRegistry)); AssertStages(); renderedPipeline = pipeline.Render(new(BsonSerializer.SerializerRegistry.GetSerializer<BsonDocument>(), BsonSerializer.SerializerRegistry)); AssertStages(); void AssertStages() { var stages = renderedPipeline.Documents; stages.Count.Should().Be(1); stages[0].Should().Be("{ $search: { operator: 'parameter', index: 'test', scoreDetails: true} }"); } } [Theory] [InlineData(null)] [InlineData("{ operator: 'parameter' }")] public void String_implicit_cast_should_create_JsonSearchDefinition(string searchDefinitionJson) { var searchDefinition = (SearchDefinition<BsonDocument>)searchDefinitionJson; if (searchDefinitionJson == null) { searchDefinition.Should().BeNull(); } else { var subject = searchDefinition.Should().BeOfType<JsonSearchDefinition<BsonDocument>>().Subject; subject.Json.Should().Be(searchDefinitionJson); } } }
773
3,576
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.GeoJsonObjectModel; namespace MongoDB.Driver.Search { internal sealed class AutocompleteSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly SearchFuzzyOptions _fuzzy; private readonly SearchQueryDefinition _query; private readonly SearchAutocompleteTokenOrder _tokenOrder; public AutocompleteSearchDefinition( SearchPathDefinition<TDocument> path, SearchQueryDefinition query, SearchAutocompleteTokenOrder tokenOrder, SearchFuzzyOptions fuzzy, SearchScoreDefinition<TDocument> score) : base(OperatorType.Autocomplete, path, score) { _query = Ensure.IsNotNull(query, nameof(query)); _tokenOrder = tokenOrder; _fuzzy = fuzzy; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "query", _query.Render() }, { "tokenOrder", _tokenOrder.ToCamelCase(), _tokenOrder != SearchAutocompleteTokenOrder.Any }, { "fuzzy", () => _fuzzy.Render(), _fuzzy != null }, }; } internal sealed class CompoundSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly List<SearchDefinition<TDocument>> _filter; private readonly int _minimumShouldMatch; private readonly List<SearchDefinition<TDocument>> _must; private readonly List<SearchDefinition<TDocument>> _mustNot; private readonly List<SearchDefinition<TDocument>> _should; public CompoundSearchDefinition( List<SearchDefinition<TDocument>> must, List<SearchDefinition<TDocument>> mustNot, List<SearchDefinition<TDocument>> should, List<SearchDefinition<TDocument>> filter, int minimumShouldMatch, SearchScoreDefinition<TDocument> score) : base(OperatorType.Compound, score) { // This constructor should always be called from the compound search definition builder that ensures the arguments are valid. _must = must; _mustNot = mustNot; _should = should; _filter = filter; _minimumShouldMatch = minimumShouldMatch; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) { return new() { { "must", Render(_must), _must != null }, { "mustNot", Render(_mustNot), _mustNot != null }, { "should", Render(_should), _should != null }, { "filter", Render(_filter), _filter != null }, { "minimumShouldMatch", _minimumShouldMatch, _minimumShouldMatch > 0 }, }; Func<BsonArray> Render(List<SearchDefinition<TDocument>> searchDefinitions) => () => new BsonArray(searchDefinitions.Select(clause => clause.Render(args))); } } internal sealed class EmbeddedDocumentSearchDefinition<TDocument, TField> : OperatorSearchDefinition<TDocument> { private readonly SearchDefinition<TField> _operator; public EmbeddedDocumentSearchDefinition(FieldDefinition<TDocument, IEnumerable<TField>> path, SearchDefinition<TField> @operator, SearchScoreDefinition<TDocument> score) : base(OperatorType.EmbeddedDocument, new SingleSearchPathDefinition<TDocument>(path), score) { _operator = Ensure.IsNotNull(@operator, nameof(@operator)); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) { // Add base path to all nested operator paths var pathPrefix = _path.Render(args).AsString; var newArgs = args .WithNewDocumentType(args.SerializerRegistry.GetSerializer<TField>()) with { PathRenderArgs = new(pathPrefix) }; return new("operator", _operator.Render(newArgs)); } } internal sealed class EqualsSearchDefinition<TDocument, TField> : OperatorSearchDefinition<TDocument> { private readonly BsonValue _value; public EqualsSearchDefinition(FieldDefinition<TDocument> path, TField value, SearchScoreDefinition<TDocument> score) : base(OperatorType.Equals, path, score) { _value = ToBsonValue(value); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new("value", _value); private static BsonValue ToBsonValue(TField value) => value switch { bool v => (BsonBoolean)v, sbyte v => (BsonInt32)v, byte v => (BsonInt32)v, short v => (BsonInt32)v, ushort v => (BsonInt32)v, int v => (BsonInt32)v, uint v => (BsonInt64)v, long v => (BsonInt64)v, float v => (BsonDouble)v, double v => (BsonDouble)v, DateTime v => (BsonDateTime)v, DateTimeOffset v => (BsonDateTime)v.UtcDateTime, ObjectId v => (BsonObjectId)v, _ => throw new InvalidCastException() }; } internal sealed class ExistsSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { public ExistsSearchDefinition(FieldDefinition<TDocument> path) : base(OperatorType.Exists, path, null) { } } internal sealed class FacetSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly SearchFacet<TDocument>[] _facets; private readonly SearchDefinition<TDocument> _operator; public FacetSearchDefinition(SearchDefinition<TDocument> @operator, IEnumerable<SearchFacet<TDocument>> facets) : base(OperatorType.Facet) { _operator = Ensure.IsNotNull(@operator, nameof(@operator)); _facets = Ensure.IsNotNull(facets, nameof(facets)).ToArray(); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "operator", _operator.Render(args) }, { "facets", new BsonDocument(_facets.Select(f => new BsonElement(f.Name, f.Render(args)))) } }; } internal sealed class GeoShapeSearchDefinition<TDocument, TCoordinates> : OperatorSearchDefinition<TDocument> where TCoordinates : GeoJsonCoordinates { private readonly GeoJsonGeometry<TCoordinates> _geometry; private readonly GeoShapeRelation _relation; public GeoShapeSearchDefinition( SearchPathDefinition<TDocument> path, GeoShapeRelation relation, GeoJsonGeometry<TCoordinates> geometry, SearchScoreDefinition<TDocument> score) : base(OperatorType.GeoShape, path, score) { _geometry = Ensure.IsNotNull(geometry, nameof(geometry)); _relation = relation; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "geometry", _geometry.ToBsonDocument() }, { "relation", _relation.ToCamelCase() } }; } internal sealed class GeoWithinSearchDefinition<TDocument, TCoordinates> : OperatorSearchDefinition<TDocument> where TCoordinates : GeoJsonCoordinates { private readonly GeoWithinArea<TCoordinates> _area; public GeoWithinSearchDefinition( SearchPathDefinition<TDocument> path, GeoWithinArea<TCoordinates> area, SearchScoreDefinition<TDocument> score) : base(OperatorType.GeoWithin, path, score) { _area = Ensure.IsNotNull(area, nameof(area)); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new(_area.Render()); } internal sealed class InSearchDefinition<TDocument, TField> : OperatorSearchDefinition<TDocument> { private readonly BsonArray _values; public InSearchDefinition( SearchPathDefinition<TDocument> path, IEnumerable<TField> values, SearchScoreDefinition<TDocument> score) : base(OperatorType.In, path, score) { Ensure.IsNotNullOrEmpty(values, nameof(values)); var array = new BsonArray(values.Select(ToBsonValue)); var bsonType = array[0].GetType(); _values = Ensure.That(array, arr => arr.All(v => v.GetType() == bsonType), nameof(values), "All values must be of the same type."); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new("value", _values); private static BsonValue ToBsonValue(TField value) => value switch { bool v => (BsonBoolean)v, sbyte v => (BsonInt32)v, byte v => (BsonInt32)v, short v => (BsonInt32)v, ushort v => (BsonInt32)v, int v => (BsonInt32)v, uint v => (BsonInt64)v, long v => (BsonInt64)v, float v => (BsonDouble)v, double v => (BsonDouble)v, decimal v => (BsonDecimal128)v, DateTime v => (BsonDateTime)v, DateTimeOffset v => (BsonDateTime)v.UtcDateTime, string v => (BsonString)v, ObjectId v => (BsonObjectId)v, _ => throw new InvalidCastException() }; } internal sealed class MoreLikeThisSearchDefinition<TDocument, TLike> : OperatorSearchDefinition<TDocument> { private readonly TLike[] _like; public MoreLikeThisSearchDefinition(IEnumerable<TLike> like) : base(OperatorType.MoreLikeThis) { _like = Ensure.IsNotNull(like, nameof(like)).ToArray(); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) { var likeSerializer = typeof(TLike) switch { var t when t == typeof(BsonDocument) => null, var t when t == typeof(TDocument) => (IBsonSerializer<TLike>)args.DocumentSerializer, _ => args.SerializerRegistry.GetSerializer<TLike>() }; return new("like", new BsonArray(_like.Select(document => document.ToBsonDocument(likeSerializer)))); } } internal sealed class NearSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly BsonValue _origin; private readonly BsonValue _pivot; public NearSearchDefinition( SearchPathDefinition<TDocument> path, BsonValue origin, BsonValue pivot, SearchScoreDefinition<TDocument> score = null) : base(OperatorType.Near, path, score) { _origin = origin; _pivot = pivot; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "origin", _origin }, { "pivot", _pivot } }; } internal sealed class PhraseSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly SearchQueryDefinition _query; private readonly int? _slop; public PhraseSearchDefinition( SearchPathDefinition<TDocument> path, SearchQueryDefinition query, int? slop, SearchScoreDefinition<TDocument> score) : base(OperatorType.Phrase, path, score) { _query = Ensure.IsNotNull(query, nameof(query)); _slop = slop; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "query", _query.Render() }, { "slop", _slop, _slop != null } }; } internal sealed class QueryStringSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly SingleSearchPathDefinition<TDocument> _defaultPath; private readonly string _query; public QueryStringSearchDefinition(FieldDefinition<TDocument> defaultPath, string query, SearchScoreDefinition<TDocument> score) : base(OperatorType.QueryString, score) { _defaultPath = new SingleSearchPathDefinition<TDocument>(defaultPath); _query = Ensure.IsNotNull(query, nameof(query)); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "defaultPath", _defaultPath.Render(args) }, { "query", _query } }; } internal sealed class RangeSearchDefinition<TDocument, TField> : OperatorSearchDefinition<TDocument> where TField : struct, IComparable<TField> { private readonly SearchRange<TField> _range; private readonly BsonValue _min; private readonly BsonValue _max; public RangeSearchDefinition( SearchPathDefinition<TDocument> path, SearchRange<TField> range, SearchScoreDefinition<TDocument> score) : base(OperatorType.Range, path, score) { _range = range; _min = ToBsonValue(_range.Min); _max = ToBsonValue(_range.Max); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { _range.IsMinInclusive ? "gte" : "gt", _min, _min != null }, { _range.IsMaxInclusive ? "lte" : "lt", _max, _max != null }, }; private static BsonValue ToBsonValue(TField? value) => value switch { sbyte v => (BsonInt32)v, byte v => (BsonInt32)v, short v => (BsonInt32)v, ushort v => (BsonInt32)v, int v => (BsonInt32)v, uint v => (BsonInt64)v, long v => (BsonInt64)v, float v => (BsonDouble)v, double v => (BsonDouble)v, DateTime v => (BsonDateTime)v, DateTimeOffset v => (BsonDateTime)v.UtcDateTime, null => null, _ => throw new InvalidCastException() }; } internal sealed class RegexSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly bool _allowAnalyzedField; private readonly SearchQueryDefinition _query; public RegexSearchDefinition( SearchPathDefinition<TDocument> path, SearchQueryDefinition query, bool allowAnalyzedField, SearchScoreDefinition<TDocument> score) : base(OperatorType.Regex, path, score) { _query = Ensure.IsNotNull(query, nameof(query)); _allowAnalyzedField = allowAnalyzedField; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "query", _query.Render() }, { "allowAnalyzedField", _allowAnalyzedField, _allowAnalyzedField }, }; } internal sealed class SpanSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly SearchSpanDefinition<TDocument> _clause; public SpanSearchDefinition(SearchSpanDefinition<TDocument> clause) : base(OperatorType.Span) { _clause = Ensure.IsNotNull(clause, nameof(clause)); } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => _clause.Render(args); } internal sealed class TextSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly SearchFuzzyOptions _fuzzy; private readonly SearchQueryDefinition _query; private readonly string _synonyms; public TextSearchDefinition( SearchPathDefinition<TDocument> path, SearchQueryDefinition query, SearchFuzzyOptions fuzzy, SearchScoreDefinition<TDocument> score, string synonyms) : base(OperatorType.Text, path, score) { _query = Ensure.IsNotNull(query, nameof(query)); _fuzzy = fuzzy; _synonyms = synonyms; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "query", _query.Render() }, { "fuzzy", () => _fuzzy.Render(), _fuzzy != null }, { "synonyms", _synonyms, _synonyms != null } }; } internal sealed class WildcardSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument> { private readonly bool _allowAnalyzedField; private readonly SearchQueryDefinition _query; public WildcardSearchDefinition( SearchPathDefinition<TDocument> path, SearchQueryDefinition query, bool allowAnalyzedField, SearchScoreDefinition<TDocument> score) : base(OperatorType.Wildcard, path, score) { _query = Ensure.IsNotNull(query, nameof(query)); _allowAnalyzedField = allowAnalyzedField; } private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args) => new() { { "query", _query.Render() }, { "allowAnalyzedField", _allowAnalyzedField, _allowAnalyzedField }, }; } }
mongodb
mongo-csharp-driver
F:\Projects\TestMap\Temp\mongo-csharp-driver\CSharpDriver.sln
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\MongoDB.Driver.Tests.csproj
F:\Projects\TestMap\Temp\mongo-csharp-driver\tests\MongoDB.Driver.Tests\Specifications\bson-decimal128\TestRunner.cs
MongoDB.Driver.Tests.Specifications.bson_decimal128
TestRunner
[]
['System.Collections', 'System.Collections.Generic', 'System.IO', 'System.Linq', 'System.Reflection', 'FluentAssertions', 'MongoDB.Bson', 'MongoDB.Bson.IO', 'MongoDB.Bson.Serialization', 'MongoDB.Bson.Serialization.Serializers', 'Xunit']
xUnit
null
public class TestRunner { [Theory] [ClassData(typeof(TestCaseFactory))] public void RunTestDefinition(TestType testType, BsonDocument definition) { switch (testType) { case TestType.Valid: RunValid(definition); break; case TestType.ParseError: RunParseError(definition); break; } } private void RunValid(BsonDocument definition) { // see the pseudo code in the specification var B = BsonUtils.ParseHexString(((string)definition["bson"]).ToLowerInvariant()); var E = ((string)definition["extjson"]).Replace(" ", ""); byte[] cB; if (definition.Contains("canonical_bson")) { cB = BsonUtils.ParseHexString(((string)definition["canonical_bson"]).ToLowerInvariant()); } else { cB = B; } string cE; if (definition.Contains("canonical_extjson")) { cE = ((string)definition["canonical_extjson"]).Replace(" ", ""); } else { cE = E; } EncodeBson(DecodeBson(B)).Should().Equal(cB, "B -> cB"); if (B != cB) { EncodeBson(DecodeBson(cB)).Should().Equal(cB, "cB -> cB"); } if (definition.Contains("extjson")) { EncodeExtjson(DecodeBson(B)).Should().Be(cE, "B -> cE"); EncodeExtjson(DecodeExtjson(E)).Should().Be(cE, "E -> cE"); if (B != cB) { EncodeExtjson(DecodeBson(cB)).Should().Be(cE, "cB -> cE"); } if (E != cE) { EncodeExtjson(DecodeExtjson(cE)).Should().Be(cE, "cE -> cE"); } if (!definition.GetValue("lossy", false).ToBoolean()) { EncodeBson(DecodeExtjson(E)).Should().Equal(cB, "E -> cB"); if (E != cE) { EncodeBson(DecodeExtjson(cE)).Should().Equal(cB, "cE -> cB"); } } } } private BsonDocument DecodeBson(byte[] bytes) { using (var stream = new MemoryStream(bytes)) using (var reader = new BsonBinaryReader(stream)) { var context = BsonDeserializationContext.CreateRoot(reader); return BsonDocumentSerializer.Instance.Deserialize(context); } } private BsonDocument DecodeExtjson(string extjson) { return BsonDocument.Parse(extjson); } private byte[] EncodeBson(BsonDocument document) { using (var stream = new MemoryStream()) using (var writer = new BsonBinaryWriter(stream)) { var context = BsonSerializationContext.CreateRoot(writer); BsonDocumentSerializer.Instance.Serialize(context, document); return stream.ToArray(); } } private string EncodeExtjson(BsonDocument document) { #pragma warning disable 618 var json = document.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }); #pragma warning restore 618 return json.Replace(" ", ""); } private void RunParseError(BsonDocument definition) { var subject = (string)definition["string"]; Decimal128 result; if (Decimal128.TryParse(subject, out result)) { Assert.True(false, $"{subject} should have resulted in a parse failure."); } } public enum TestType { Valid, ParseError } private class TestCaseFactory : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { const string prefix = "MongoDB.Driver.Tests.Specifications.bson_decimal128.tests."; var executingAssembly = typeof(TestCaseFactory).GetTypeInfo().Assembly; var enumerable = executingAssembly .GetManifestResourceNames() .Where(path => path.StartsWith(prefix) && path.EndsWith(".json")) .SelectMany(path => { var definition = ReadDefinition(path); var fullName = path.Remove(0, prefix.Length); var tests = Enumerable.Empty<object[]>(); if (definition.Contains("valid")) { tests = tests.Concat(GetTestCasesHelper( TestType.Valid, (string)definition["description"], definition["valid"].AsBsonArray.Cast<BsonDocument>())); } if (definition.Contains("parseErrors")) { tests = tests.Concat(GetTestCasesHelper( TestType.ParseError, (string)definition["description"], definition["parseErrors"].AsBsonArray.Cast<BsonDocument>())); } return tests; }); return enumerable.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static IEnumerable<object[]> GetTestCasesHelper(TestType type, string description, IEnumerable<BsonDocument> documents) { var nameList = new Dictionary<string, int>(); foreach (BsonDocument document in documents) { var data = new object[] { type, document }; //data.SetCategory("Specifications"); //data.SetCategory("bson"); //var name = GetTestName(description, document); //int i = 0; //if (nameList.TryGetValue(name, out i)) //{ // nameList[name] = i + 1; // name += " #" + i; //} //else //{ // nameList[name] = 1; //} //data.SetName(name); yield return data; } } private static string GetTestName(string description, BsonDocument definition) { var name = description; if (definition.Contains("description")) { name += " - " + (string)definition["description"]; } return name; } private static BsonDocument ReadDefinition(string path) { var executingAssembly = typeof(TestCaseFactory).GetTypeInfo().Assembly; using (var definitionStream = executingAssembly.GetManifestResourceStream(path)) using (var definitionStringReader = new StreamReader(definitionStream)) { var definitionString = definitionStringReader.ReadToEnd(); return BsonDocument.Parse(definitionString); } } } }
964
8,926
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; namespace MongoDB.Bson.Serialization.Conventions { /// <summary> /// Runs the conventions against a BsonClassMap and its BsonMemberMaps. /// </summary> public class ConventionRunner { // private fields private readonly IEnumerable<IConvention> _conventions; // constructors /// <summary> /// Initializes a new instance of the <see cref="ConventionRunner" /> class. /// </summary> /// <param name="conventions">The conventions.</param> public ConventionRunner(IConventionPack conventions) { if (conventions == null) { throw new ArgumentNullException("conventions"); } _conventions = conventions.Conventions.ToList(); } // public methods /// <summary> /// Applies a modification to the class map. /// </summary> /// <param name="classMap">The class map.</param> public void Apply(BsonClassMap classMap) { foreach (var convention in _conventions.OfType<IClassMapConvention>()) { convention.Apply(classMap); } foreach (var convention in _conventions.OfType<IMemberMapConvention>()) { foreach (var memberMap in classMap.DeclaredMemberMaps) { convention.Apply(memberMap); } } foreach (var convention in _conventions.OfType<ICreatorMapConvention>()) { foreach (var creatorMap in classMap.CreatorMaps) { convention.Apply(creatorMap); } } foreach (var convention in _conventions.OfType<IPostProcessingConvention>()) { convention.PostProcess(classMap); } } } }