CSLA.NET 6.0.0
CSLA .NET is a software development framework that helps you build a reusable, maintainable object-oriented business layer for your app.
IsBusinessObjectSerializableMakeSerializableCodeFix.cs
Go to the documentation of this file.
1using System.Collections.Immutable;
2using System.Composition;
3using System.Linq;
4using System.Threading.Tasks;
5using Microsoft.CodeAnalysis;
6using Microsoft.CodeAnalysis.CodeFixes;
7using Microsoft.CodeAnalysis.CSharp.Syntax;
8using Microsoft.CodeAnalysis.CSharp;
9using Microsoft.CodeAnalysis.CodeActions;
11using static Csla.Analyzers.Constants;
12
13namespace Csla.Analyzers
14{
15 [ExportCodeFixProvider(LanguageNames.CSharp)]
16 [Shared]
18 : CodeFixProvider
19 {
20 public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(Constants.AnalyzerIdentifiers.IsBusinessObjectSerializable);
21
22 public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
23
24 public override async Task RegisterCodeFixesAsync(CodeFixContext context)
25 {
26 var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
27
28 context.CancellationToken.ThrowIfCancellationRequested();
29
30 var diagnostic = context.Diagnostics.First();
31 var classNode = root.FindNode(diagnostic.Location.SourceSpan) as ClassDeclarationSyntax;
32
33 context.CancellationToken.ThrowIfCancellationRequested();
34
35 AddCodeFix(context, root, diagnostic, classNode);
36 }
37
38 private static SyntaxNode AddAttribute(SyntaxNode root, ClassDeclarationSyntax classNode, string name)
39 {
40 var attribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(name));
41 var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList<AttributeSyntax>().Add(attribute));
42 var newClassNode = classNode.AddAttributeLists(attributeList);
43 return root.ReplaceNode(classNode, newClassNode);
44 }
45
46 private static void AddCodeFix(CodeFixContext context, SyntaxNode root,
47 Diagnostic diagnostic, ClassDeclarationSyntax classNode)
48 {
49 var newRoot = AddAttribute(
50 root, classNode, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SerializableName);
51
52 var description = IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableDescription;
53
54 if (!root.HasUsing(Namespaces.System))
55 {
56 newRoot = (newRoot as CompilationUnitSyntax).AddUsings(
57 SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(Namespaces.System)));
58 description = IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription;
59 }
60
61 context.RegisterCodeFix(
62 CodeAction.Create(
63 description,
64 _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),
65 description), diagnostic);
66 }
67 }
68}