Beispiel #1
0
        private static void AnalyzeCall(SyntaxNodeAnalysisContext context, ISymbol migratableAttributeType, ISymbol dataContractAttributeType, ISymbol dataMemberAttributeType)
        {
            var typeDecl      = (TypeDeclarationSyntax)context.Node;
            var semanticModel = context.SemanticModel;
            var ct            = context.CancellationToken;

            var isMigratable = MigrationHashHelper.HasAttribute(typeDecl, migratableAttributeType, semanticModel, ct);

            if (!isMigratable)
            {
                return;
            }

            if (dataContractAttributeType != null && dataMemberAttributeType != null)
            {
                var isDataContract = MigrationHashHelper.HasAttribute(typeDecl, dataContractAttributeType, semanticModel, ct);
                var hasDataMember  = MigrationHashHelper.GetDataMembers(typeDecl, ct, semanticModel, dataMemberAttributeType).Any();

                if (isDataContract && hasDataMember)
                {
                    return;
                }
            }

            var diagnostic = Diagnostic.Create(Rule, typeDecl.GetLocation(), typeDecl.Identifier.ToString());

            context.ReportDiagnostic(diagnostic);
        }
        public void ShouldGetAllDataMembers()
        {
            var tree = SyntaxFactory.ParseSyntaxTree(@"using System.Runtime.Serialization;

public class A
{
    public string PropertyA { get; }
    [DataMember] public string PropertyB { get; }
    public int FieldA { get; }
    [DataMember] public int FieldB { get; }
}");

            var compilation = CSharpCompilation.Create(
                "MyCompilation",
                syntaxTrees: new[] { tree },
                references: new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(DataMemberAttribute).Assembly.Location)
            });
            var model = compilation.GetSemanticModel(tree);

            var typeDecl = tree
                           .GetRoot()
                           .ChildNodes()
                           .OfType <TypeDeclarationSyntax>()
                           .Single();

            var dataMemberAttributeType = compilation.GetTypeByMetadataName(Constants.DataMemberAttributeMetadataName);

            var dataMembers = MigrationHashHelper.GetDataMembers(typeDecl, CancellationToken.None, model, dataMemberAttributeType);

            dataMembers.Count.Should().Be(2);
            dataMembers[0].Identifier.Should().Be("FieldB");
            dataMembers[0].Type.Should().Be("int");
            dataMembers[1].Identifier.Should().Be("PropertyB");
            dataMembers[1].Type.Should().Be("string");
        }