diff --git a/.editorconfig b/.editorconfig index 583fba1594..05642ceb8b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -77,6 +77,49 @@ csharp_using_directive_placement = outside_namespace # xUnit1004: Test methods should not be skipped dotnet_diagnostic.xUnit1004.severity = refactoring +# Non-private static fields are PascalCase +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Non-private readonly fields are PascalCase +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style + +dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly + +dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case + +# Constants are PascalCase +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = pascal_case + +# Static fields are camelCase and start with s_ +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = camel_case +dotnet_naming_style.static_field_style.required_prefix = s_ + # Instance fields are camelCase and start with _ dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields @@ -86,3 +129,30 @@ dotnet_naming_symbols.instance_fields.applicable_kinds = field dotnet_naming_style.instance_field_style.capitalization = camel_case dotnet_naming_style.instance_field_style.required_prefix = _ + +# Locals and parameters are camelCase +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# By default, name items with PascalCase +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members +dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.all_members.applicable_kinds = * + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case \ No newline at end of file diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/ProjectSystem/FullProjectSnapshotHandleSerializationBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/ProjectSystem/FullProjectSnapshotHandleSerializationBenchmark.cs index 3ff0157d72..c37bb07900 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/ProjectSystem/FullProjectSnapshotHandleSerializationBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/ProjectSystem/FullProjectSnapshotHandleSerializationBenchmark.cs @@ -13,8 +13,8 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks public class FullProjectSnapshotHandleSerializationBenchmark { // Hardcoded expectations from `ProjectSystem\project.razor.json` - private static readonly string ExpectedFilePath = "C:\\Users\\admin\\location\\blazorserver\\blazorserver.csproj"; - private static readonly int ExpectedTagHelperCount = 228; + private const string ExpectedFilePath = "C:\\Users\\admin\\location\\blazorserver\\blazorserver.csproj"; + private const int ExpectedTagHelperCount = 228; private JsonSerializer Serializer { get; set; } private JsonReader Reader { get; set; } diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperBenchmarkBase.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperBenchmarkBase.cs index cd7781ff06..9022d60b7c 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperBenchmarkBase.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperBenchmarkBase.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks { public abstract class TagHelperBenchmarkBase { - protected readonly byte[] _tagHelperBuffer; + protected readonly byte[] TagHelperBuffer; public TagHelperBenchmarkBase() { @@ -23,14 +23,14 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks } var tagHelperFilePath = Path.Combine(current.FullName, "taghelpers.json"); - _tagHelperBuffer = File.ReadAllBytes(tagHelperFilePath); + TagHelperBuffer = File.ReadAllBytes(tagHelperFilePath); // Deserialize from json file. TagHelperDescriptorJsonConverter.DisableCachingForTesting = true; DefaultSerializer = new JsonSerializer(); DefaultSerializer.Converters.Add(TagHelperDescriptorJsonConverter.Instance); - using var stream = new MemoryStream(_tagHelperBuffer); + using var stream = new MemoryStream(TagHelperBuffer); using var reader = new JsonTextReader(new StreamReader(stream)); DefaultTagHelpers = DefaultSerializer.Deserialize>(reader); TagHelperDescriptorJsonConverter.DisableCachingForTesting = false; diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperSerializationBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperSerializationBenchmark.cs index eb6bb2db0f..db98775810 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperSerializationBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/TagHelperSerializationBenchmark.cs @@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Razor.Microbenchmarks { // Deserialize from json file. IReadOnlyList tagHelpers; - using var stream = new MemoryStream(_tagHelperBuffer); + using var stream = new MemoryStream(TagHelperBuffer); using var reader = new JsonTextReader(new StreamReader(stream)); tagHelpers = DefaultSerializer.Deserialize>(reader); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer.Common/RazorCodeDocumentExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer.Common/RazorCodeDocumentExtensions.cs index 714d54c50a..e88b730573 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer.Common/RazorCodeDocumentExtensions.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer.Common/RazorCodeDocumentExtensions.cs @@ -8,10 +8,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Common { internal static class RazorCodeDocumentExtensions { - private static readonly object UnsupportedKey = new object(); - private static readonly object SourceTextKey = new object(); - private static readonly object CSharpSourceTextKey = new object(); - private static readonly object HtmlSourceTextKey = new object(); + private static readonly object s_unsupportedKey = new object(); + private static readonly object s_sourceTextKey = new object(); + private static readonly object s_csharpSourceTextKey = new object(); + private static readonly object s_htmlSourceTextKey = new object(); public static bool IsUnsupported(this RazorCodeDocument document) { @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Common throw new ArgumentNullException(nameof(document)); } - var unsupportedObj = document.Items[UnsupportedKey]; + var unsupportedObj = document.Items[s_unsupportedKey]; if (unsupportedObj == null) { return false; @@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Common throw new ArgumentNullException(nameof(document)); } - document.Items[UnsupportedKey] = true; + document.Items[s_unsupportedKey] = true; } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/AutoInsert/AutoClosingTagOnAutoInsertProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/AutoInsert/AutoClosingTagOnAutoInsertProvider.cs index b428104007..806f2a187e 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/AutoInsert/AutoClosingTagOnAutoInsertProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/AutoInsert/AutoClosingTagOnAutoInsertProvider.cs @@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.AutoInsert internal class AutoClosingTagOnAutoInsertProvider : RazorOnAutoInsertProvider { // From http://dev.w3.org/html5/spec/Overview.html#elements-0 - public static readonly HashSet s_VoidElements = new HashSet(StringComparer.OrdinalIgnoreCase) + public static readonly HashSet VoidElements = new HashSet(StringComparer.OrdinalIgnoreCase) { "area", "base", @@ -239,7 +239,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.AutoInsert private static AutoClosingBehavior InferAutoClosingBehavior(string name) { - if (s_VoidElements.Contains(name)) + if (VoidElements.Contains(name)) { return AutoClosingBehavior.SelfClosing; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/CSharpCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/CSharpCodeActionResolver.cs index 7639890766..ee57e2e3aa 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/CSharpCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/CSharpCodeActionResolver.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { internal abstract class CSharpCodeActionResolver : BaseCodeActionResolver { - protected readonly ClientNotifierServiceBase _languageServer; + protected readonly ClientNotifierServiceBase LanguageServer; public CSharpCodeActionResolver(ClientNotifierServiceBase languageServer) { @@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions throw new ArgumentNullException(nameof(languageServer)); } - _languageServer = languageServer; + LanguageServer = languageServer; } public abstract Task ResolveAsync( @@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions protected async Task ResolveCodeActionWithServerAsync(CodeAction codeAction, CancellationToken cancellationToken) { - var response = await _languageServer.SendRequestAsync(LanguageServerConstants.RazorResolveCodeActionsEndpoint, codeAction).ConfigureAwait(false); + var response = await LanguageServer.SendRequestAsync(LanguageServerConstants.RazorResolveCodeActionsEndpoint, codeAction).ConfigureAwait(false); var resolvedCodeAction = await response.Returning(cancellationToken).ConfigureAwait(false); return resolvedCodeAction; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs index 6710a40734..b87efb66e9 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionResolver.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions // Usually when we need to format code, we utilize the formatting options provided // by the platform. However, we aren't provided such options in the case of code actions // so we use a default (and commonly used) configuration. - private static readonly FormattingOptions DefaultFormattingOptions = new FormattingOptions() + private static readonly FormattingOptions s_defaultFormattingOptions = new FormattingOptions() { TabSize = 4, InsertSpaces = true, @@ -128,7 +128,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions documentSnapshot, RazorLanguageKind.CSharp, csharpTextEdits, - DefaultFormattingOptions, + s_defaultFormattingOptions, cancellationToken, bypassValidationPasses: true); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/TypeAccessibilityCodeActionProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/TypeAccessibilityCodeActionProvider.cs index e9a183825f..2fa1f5d6b8 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/TypeAccessibilityCodeActionProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/TypeAccessibilityCodeActionProvider.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { internal class TypeAccessibilityCodeActionProvider : CSharpCodeActionProvider { - private static readonly IEnumerable SupportedDiagnostics = new[] + private static readonly IEnumerable s_supportedDiagnostics = new[] { // `The type or namespace name 'type/namespace' could not be found // (are you missing a using directive or an assembly reference?)` @@ -74,7 +74,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var diagnostics = context.Request.Context.Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error && diagnostic.Code?.IsString == true && - SupportedDiagnostics.Any(d => diagnostic.Code.Value.String.Equals(d, StringComparison.OrdinalIgnoreCase))); + s_supportedDiagnostics.Any(d => diagnostic.Code.Value.String.Equals(d, StringComparison.OrdinalIgnoreCase))); if (diagnostics is null || !diagnostics.Any()) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolutionEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolutionEndpoint.cs index 816a8b342c..e490e1c735 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolutionEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolutionEndpoint.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { internal class CodeActionResolutionEndpoint : IRazorCodeActionResolveHandler { - private static readonly string CodeActionsResolveProviderCapability = "codeActionsResolveProvider"; + private const string CodeActionsResolveProviderCapability = "codeActionsResolveProvider"; private readonly IReadOnlyDictionary _razorCodeActionResolvers; private readonly IReadOnlyDictionary _csharpCodeActionResolvers; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ComponentAccessibilityCodeActionProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ComponentAccessibilityCodeActionProvider.cs index 42d391d363..e8eb7e2b4a 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ComponentAccessibilityCodeActionProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ComponentAccessibilityCodeActionProvider.cs @@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { internal class ComponentAccessibilityCodeActionProvider : RazorCodeActionProvider { - private static readonly Task> EmptyResult = Task.FromResult>(null); + private static readonly Task> s_emptyResult = Task.FromResult>(null); private readonly TagHelperFactsService _tagHelperFactsService; private readonly FilePathNormalizer _filePathNormalizer; @@ -43,25 +43,25 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var node = context.CodeDocument.GetSyntaxTree().Root.LocateOwner(change); if (node is null) { - return EmptyResult; + return s_emptyResult; } // Find start tag var startTag = (MarkupStartTagSyntax)node.Ancestors().FirstOrDefault(n => n is MarkupStartTagSyntax); if (startTag is null) { - return EmptyResult; + return s_emptyResult; } // Ignore if start tag has dots, as we only handle short tags if (startTag.Name.Content.Contains(".")) { - return EmptyResult; + return s_emptyResult; } if (!IsApplicableTag(startTag)) { - return EmptyResult; + return s_emptyResult; } if (IsTagUnknown(startTag, context)) @@ -131,12 +131,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions // For all the matches, add options for add @using and fully qualify foreach (var tagHelperPair in matching.Values) { - if (tagHelperPair.FullyQualified is null) + if (tagHelperPair._fullyQualified is null) { continue; } - var fullyQualifiedName = tagHelperPair.Short.Name; + var fullyQualifiedName = tagHelperPair._short.Name; // Insert @using var addUsingCodeAction = AddUsingsCodeActionProviderFactory.CreateAddUsingCodeAction( @@ -178,7 +178,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { if (tagHelper.TagMatchingRules.All(rule => TagHelperMatchingConventions.SatisfiesRule(tagName, parentTagName, attributes, rule))) { - matching.Add(tagHelper.Name, new TagHelperPair { Short = tagHelper }); + matching.Add(tagHelper.Name, new TagHelperPair { _short = tagHelper }); } } @@ -187,9 +187,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { if (matching.TryGetValue(tagHelper.Name, out var tagHelperPair)) { - if (tagHelperPair != null && tagHelper != tagHelperPair.Short) + if (tagHelperPair != null && tagHelper != tagHelperPair._short) { - tagHelperPair.FullyQualified = tagHelper; + tagHelperPair._fullyQualified = tagHelper; } } } @@ -257,8 +257,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions private class TagHelperPair { - public TagHelperDescriptor Short = null; - public TagHelperDescriptor FullyQualified = null; + public TagHelperDescriptor _short = null; + public TagHelperDescriptor _fullyQualified = null; } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionProvider.cs index b1a777a557..b44e1fdbdd 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionProvider.cs @@ -20,73 +20,73 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { internal class ExtractToCodeBehindCodeActionProvider : RazorCodeActionProvider { - private static readonly Task> EmptyResult = Task.FromResult>(null); + private static readonly Task> s_emptyResult = Task.FromResult>(null); public override Task> ProvideAsync(RazorCodeActionContext context, CancellationToken cancellationToken) { if (context is null) { - return EmptyResult; + return s_emptyResult; } if (!context.SupportsFileCreation) { - return EmptyResult; + return s_emptyResult; } if (!FileKinds.IsComponent(context.CodeDocument.GetFileKind())) { - return EmptyResult; + return s_emptyResult; } var change = new SourceChange(context.Location.AbsoluteIndex, length: 0, newText: string.Empty); var syntaxTree = context.CodeDocument.GetSyntaxTree(); if (syntaxTree?.Root is null) { - return EmptyResult; + return s_emptyResult; } var owner = syntaxTree.Root.LocateOwner(change); if (owner == null) { Debug.Fail("Owner should never be null."); - return EmptyResult; + return s_emptyResult; } var node = owner.Ancestors().FirstOrDefault(n => n.Kind == SyntaxKind.RazorDirective); if (node == null || !(node is RazorDirectiveSyntax directiveNode)) { - return EmptyResult; + return s_emptyResult; } // Make sure we've found a @code or @functions if (directiveNode.DirectiveDescriptor != ComponentCodeDirective.Directive && directiveNode.DirectiveDescriptor != FunctionsDirective.Directive) { - return EmptyResult; + return s_emptyResult; } // No code action if malformed if (directiveNode.GetDiagnostics().Any(d => d.Severity == RazorDiagnosticSeverity.Error)) { - return EmptyResult; + return s_emptyResult; } var csharpCodeBlockNode = directiveNode.Body.DescendantNodes().FirstOrDefault(n => n is CSharpCodeBlockSyntax); if (csharpCodeBlockNode is null) { - return EmptyResult; + return s_emptyResult; } if (HasUnsupportedChildren(csharpCodeBlockNode)) { - return EmptyResult; + return s_emptyResult; } // Do not provide code action if the cursor is inside the code block if (context.Location.AbsoluteIndex > csharpCodeBlockNode.SpanStart) { - return EmptyResult; + return s_emptyResult; } var actionParams = new ExtractToCodeBehindCodeActionParams() diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs index 5b14eaa134..6a5981360c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs @@ -30,7 +30,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions private readonly DocumentResolver _documentResolver; private readonly FilePathNormalizer _filePathNormalizer; - private static readonly Range StartOfDocumentRange = new Range(new Position(0, 0), new Position(0, 0)); + private static readonly Range s_startOfDocumentRange = new Range(new Position(0, 0), new Position(0, 0)); public ExtractToCodeBehindCodeActionResolver( ForegroundDispatcher foregroundDispatcher, @@ -130,7 +130,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions new TextEdit { NewText = codeBehindContent, - Range = StartOfDocumentRange, + Range = s_startOfDocumentRange, } }, }) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/DirectiveAttributeTransitionCompletionItemProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/DirectiveAttributeTransitionCompletionItemProvider.cs index 087149d8e7..2db6feb45d 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/DirectiveAttributeTransitionCompletionItemProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/DirectiveAttributeTransitionCompletionItemProvider.cs @@ -12,15 +12,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { internal class DirectiveAttributeTransitionCompletionItemProvider : DirectiveAttributeCompletionItemProviderBase { - private static RazorCompletionItem _transitionCompletionItem; + private static RazorCompletionItem s_transitionCompletionItem; public static RazorCompletionItem TransitionCompletionItem { get { - if (_transitionCompletionItem == null) + if (s_transitionCompletionItem == null) { - _transitionCompletionItem = new RazorCompletionItem( + s_transitionCompletionItem = new RazorCompletionItem( displayText: "@...", insertText: "@", kind: RazorCompletionItemKind.Directive, @@ -32,14 +32,14 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion // where this directive attribute transition character ("@...") gets provided and then typing // `@` should re-trigger OR typing `/` should re-trigger. commitCharacters: new[] { "@", "/", ">" }); - _transitionCompletionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(RazorLS.Resources.Blazor_directive_attributes)); + s_transitionCompletionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(RazorLS.Resources.Blazor_directive_attributes)); } - return _transitionCompletionItem; + return s_transitionCompletionItem; } } - private static readonly IReadOnlyList Completions = new[] { TransitionCompletionItem }; + private static readonly IReadOnlyList s_completions = new[] { TransitionCompletionItem }; public override IReadOnlyList GetCompletionItems(RazorSyntaxTree syntaxTree, TagHelperDocumentContext tagHelperDocumentContext, SourceSpan location) { @@ -61,7 +61,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion if (attribute is MarkupMiscAttributeContentSyntax && attribute.ContainsOnlyWhitespace()) { // This represents a tag when there's no attribute content . - return Completions; + return s_completions; } if (!TryGetAttributeInfo(owner, out var prefixLocation, out var attributeName, out var attributeNameLocation, out _, out _)) @@ -82,7 +82,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion } // This represents a tag when there's no attribute content . - return Completions; + return s_completions; } // Internal for testing diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/OptimizedCompletionList.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/OptimizedCompletionList.cs index 754e150e58..81e4545b26 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/OptimizedCompletionList.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/OptimizedCompletionList.cs @@ -19,13 +19,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion public class OptimizedCompletionListJsonConverter : JsonConverter { public static readonly OptimizedCompletionListJsonConverter Instance = new OptimizedCompletionListJsonConverter(); - private static readonly ConcurrentDictionary CommitCharactersRawJson; - private static readonly JsonSerializer DefaultSerializer; + private static readonly ConcurrentDictionary s_commitCharactersRawJson; + private static readonly JsonSerializer s_defaultSerializer; static OptimizedCompletionListJsonConverter() { - DefaultSerializer = JsonSerializer.CreateDefault(); - CommitCharactersRawJson = new ConcurrentDictionary(); + s_defaultSerializer = JsonSerializer.CreateDefault(); + s_commitCharactersRawJson = new ConcurrentDictionary(); } public override bool CanConvert(Type objectType) @@ -35,7 +35,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - var result = DefaultSerializer.Deserialize(reader, objectType); + var result = s_defaultSerializer.Deserialize(reader, objectType); return result; } @@ -150,10 +150,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { writer.WritePropertyName("commitCharacters"); - if (!CommitCharactersRawJson.TryGetValue(completionItem.CommitCharacters, out var jsonString)) + if (!s_commitCharactersRawJson.TryGetValue(completionItem.CommitCharacters, out var jsonString)) { jsonString = JsonConvert.SerializeObject(completionItem.CommitCharacters); - CommitCharactersRawJson.TryAdd(completionItem.CommitCharacters, jsonString); + s_commitCharactersRawJson.TryAdd(completionItem.CommitCharacters, jsonString); } writer.WriteRawValue(jsonString); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionEndpoint.cs index 74c5964f0b..ed3bf4cd07 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionEndpoint.cs @@ -32,7 +32,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion private readonly VSLSPTagHelperTooltipFactory _vsLspTagHelperTooltipFactory; private readonly ClientNotifierServiceBase _languageServer; private readonly CompletionListCache _completionListCache; - private static readonly Command RetriggerCompletionCommand = new() + private static readonly Command s_retriggerCompletionCommand = new() { Name = "editor.action.triggerSuggest", Title = RazorLS.Resources.ReTrigger_Completions_Title, @@ -348,7 +348,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion if (razorCompletionItem == DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem) { - directiveCompletionItem.Command = RetriggerCompletionCommand; + directiveCompletionItem.Command = s_retriggerCompletionCommand; directiveCompletionItem.Kind = tagHelperCompletionItemKind; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionItemExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionItemExtensions.cs index 8e4258e5e8..62d895aff6 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionItemExtensions.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/RazorCompletionItemExtensions.cs @@ -11,11 +11,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { internal static class RazorCompletionItemExtensions { - private readonly static string TagHelperElementCompletionDescriptionKey = "Razor.TagHelperElementDescription"; + private readonly static string s_tagHelperElementCompletionDescriptionKey = "Razor.TagHelperElementDescription"; public static void SetTagHelperElementDescriptionInfo(this RazorCompletionItem completionItem, AggregateBoundElementDescription elementDescriptionInfo) { - completionItem.Items[TagHelperElementCompletionDescriptionKey] = elementDescriptionInfo; + completionItem.Items[s_tagHelperElementCompletionDescriptionKey] = elementDescriptionInfo; } public static AggregateBoundElementDescription? GetTagHelperElementDescriptionInfo(this RazorCompletionItem completionItem) @@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion throw new ArgumentNullException(nameof(completionItem)); } - var description = completionItem.Items[TagHelperElementCompletionDescriptionKey] as AggregateBoundElementDescription; + var description = completionItem.Items[s_tagHelperElementCompletionDescriptionKey] as AggregateBoundElementDescription; return description; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/TagHelperCompletionProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/TagHelperCompletionProvider.cs index e048e9738d..efff7be4e7 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/TagHelperCompletionProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/TagHelperCompletionProvider.cs @@ -22,8 +22,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion internal static readonly IReadOnlyCollection MinimizedAttributeCommitCharacters = new List { "=", " " }; internal static readonly IReadOnlyCollection AttributeCommitCharacters = new List { "=" }; - private static readonly IReadOnlyCollection ElementCommitCharacters = new List { " ", ">" }; - private static readonly IReadOnlyCollection NoCommitCharacters = new List(); + private static readonly IReadOnlyCollection s_elementCommitCharacters = new List { " ", ">" }; + private static readonly IReadOnlyCollection s_noCommitCharacters = new List(); private readonly HtmlFactsService _htmlFactsService; private readonly TagHelperCompletionService _tagHelperCompletionService; private readonly TagHelperFactsService _tagHelperFactsService; @@ -217,7 +217,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion displayText: completion.Key, insertText: completion.Key, RazorCompletionItemKind.TagHelperElement, - ElementCommitCharacters); + s_elementCommitCharacters); var tagHelperDescriptions = completion.Value.Select(tagHelper => BoundElementDescriptionInfo.From(tagHelper)); var elementDescription = new AggregateBoundElementDescription(tagHelperDescriptions.ToList()); @@ -233,7 +233,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { if (indexerCompletion) { - return NoCommitCharacters; + return s_noCommitCharacters; } else if (boundAttributes.Any(b => b.TypeName == "System.Boolean")) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultDocumentVersionCache.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultDocumentVersionCache.cs index e6991a4523..0adc0e1c25 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultDocumentVersionCache.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultDocumentVersionCache.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer internal const int MaxDocumentTrackingCount = 20; // Internal for testing - internal readonly Dictionary> _documentLookup; + internal readonly Dictionary> DocumentLookup; private readonly ForegroundDispatcher _foregroundDispatcher; private ProjectSnapshotManagerBase _projectSnapshotManager; @@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer } _foregroundDispatcher = foregroundDispatcher; - _documentLookup = new Dictionary>(FilePathComparer.Instance); + DocumentLookup = new Dictionary>(FilePathComparer.Instance); } public override void TrackDocumentVersion(DocumentSnapshot documentSnapshot, int version) @@ -37,10 +37,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer _foregroundDispatcher.AssertForegroundThread(); - if (!_documentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries)) + if (!DocumentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries)) { documentEntries = new List(); - _documentLookup[documentSnapshot.FilePath] = documentEntries; + DocumentLookup[documentSnapshot.FilePath] = documentEntries; } if (documentEntries.Count == MaxDocumentTrackingCount) @@ -65,7 +65,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer _foregroundDispatcher.AssertForegroundThread(); - if (!_documentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries)) + if (!DocumentLookup.TryGetValue(documentSnapshot.FilePath, out var documentEntries)) { version = null; return false; @@ -106,11 +106,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer switch (args.Kind) { case ProjectChangeKind.DocumentChanged: - if (_documentLookup.ContainsKey(args.DocumentFilePath) && + if (DocumentLookup.ContainsKey(args.DocumentFilePath) && !_projectSnapshotManager.IsDocumentOpen(args.DocumentFilePath)) { // Document closed, evict entry. - _documentLookup.Remove(args.DocumentFilePath); + DocumentLookup.Remove(args.DocumentFilePath); } break; } @@ -147,7 +147,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // Internal for testing internal bool TryGetLatestVersionFromPath(string filePath, out int? version) { - if (!_documentLookup.TryGetValue(filePath, out var documentEntries)) + if (!DocumentLookup.TryGetValue(filePath, out var documentEntries)) { version = null; return false; @@ -163,7 +163,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { foreach (var documentPath in projectSnapshot.DocumentFilePaths) { - if (_documentLookup.ContainsKey(documentPath)) + if (DocumentLookup.ContainsKey(documentPath)) { var document = projectSnapshot.GetDocument(documentPath); MarkAsLatestVersion(document); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultHostServicesProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultHostServicesProvider.cs index 8f61a5bd6d..1c69cb62a5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultHostServicesProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultHostServicesProvider.cs @@ -11,8 +11,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { // We mark this as Lazy because construction of an AdhocWorkspace without services will utilize MEF under the covers // which can be expensive and we don't want to do that until absolutely necessary. - private static readonly Lazy DefaultWorkspace = new Lazy(() => new AdhocWorkspace()); + private static readonly Lazy s_defaultWorkspace = new Lazy(() => new AdhocWorkspace()); - public override HostServices GetServices() => DefaultWorkspace.Value.Services.HostServices; + public override HostServices GetServices() => s_defaultWorkspace.Value.Services.HostServices; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs index 849a12d11c..e2064f32f8 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs @@ -381,16 +381,16 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer } } - private static bool _haveAsserted = false; + private static bool s_haveAsserted = false; private static bool IsRangeWithinDocument(Range range, SourceText sourceText) { // This might happen when the document that ranges were created against was not the same as the document we're consulting. var result = IsPositionWithinDocument(range.Start, sourceText) && IsPositionWithinDocument(range.End, sourceText); - if(!_haveAsserted && !result) + if(!s_haveAsserted && !result) { - _haveAsserted = true; + s_haveAsserted = true; Debug.Fail($"Attempted to map a range {range} outside of the Source (line count {sourceText.Lines.Count}.) This could happen if the Roslyn and Razor LSP servers are not in sync."); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Definition/RazorDefinitionEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Definition/RazorDefinitionEndpoint.cs index 05e7ae39f1..14f9a7f4d5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Definition/RazorDefinitionEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Definition/RazorDefinitionEndpoint.cs @@ -25,8 +25,6 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Definition private readonly DocumentResolver _documentResolver; private readonly RazorComponentSearchEngine _componentSearchEngine; - private DefinitionCapability _capability { get; set; } - public RazorDefinitionEndpoint( ForegroundDispatcher foregroundDispatcher, DocumentResolver documentResolver, @@ -112,7 +110,6 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Definition public void SetCapability(DefinitionCapability capability) { - _capability = capability; } internal static async Task GetOriginTagHelperBindingAsync( diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectConfigurationStateSynchronizer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectConfigurationStateSynchronizer.cs index 08aca652c1..cd6ab0a547 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectConfigurationStateSynchronizer.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectConfigurationStateSynchronizer.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer private readonly RazorProjectService _projectService; private readonly FilePathNormalizer _filePathNormalizer; private readonly Dictionary _configurationToProjectMap; - internal readonly Dictionary _projectInfoMap; + internal readonly Dictionary ProjectInfoMap; public ProjectConfigurationStateSynchronizer( ForegroundDispatcher foregroundDispatcher, @@ -44,7 +44,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer _projectService = projectService; _filePathNormalizer = filePathNormalizer; _configurationToProjectMap = new Dictionary(FilePathComparer.Instance); - _projectInfoMap = new Dictionary(FilePathComparer.Instance); + ProjectInfoMap = new Dictionary(FilePathComparer.Instance); } internal int EnqueueDelay { get; set; } = 250; @@ -141,18 +141,18 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { await Task.Delay(EnqueueDelay).ConfigureAwait(true); - var delayedProjectInfo = _projectInfoMap[projectFilePath]; + var delayedProjectInfo = ProjectInfoMap[projectFilePath]; UpdateProject(projectFilePath, delayedProjectInfo.FullProjectSnapshotHandle); } void EnqueueUpdateProject(string projectFilePath, FullProjectSnapshotHandle snapshotHandle) { - if (!_projectInfoMap.ContainsKey(projectFilePath)) + if (!ProjectInfoMap.ContainsKey(projectFilePath)) { - _projectInfoMap[projectFilePath] = new DelayedProjectInfo(); + ProjectInfoMap[projectFilePath] = new DelayedProjectInfo(); } - var delayedProjectInfo = _projectInfoMap[projectFilePath]; + var delayedProjectInfo = ProjectInfoMap[projectFilePath]; delayedProjectInfo.FullProjectSnapshotHandle = snapshotHandle; if (delayedProjectInfo.ProjectUpdateTask is null || delayedProjectInfo.ProjectUpdateTask.IsCompleted) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/DefaultProjectResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/DefaultProjectResolver.cs index 9d278d047b..9e9f77bf82 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/DefaultProjectResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/ProjectSystem/DefaultProjectResolver.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem internal class DefaultProjectResolver : ProjectResolver { // Internal for testing - protected internal readonly HostProject _miscellaneousHostProject; + protected internal readonly HostProject MiscellaneousHostProject; private readonly ForegroundDispatcher _foregroundDispatcher; private readonly FilePathNormalizer _filePathNormalizer; @@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem _projectSnapshotManagerAccessor = projectSnapshotManagerAccessor; var miscellaneousProjectPath = Path.Combine(TempDirectory.Instance.DirectoryPath, "__MISC_RAZOR_PROJECT__"); - _miscellaneousHostProject = new HostProject(miscellaneousProjectPath, RazorDefaults.Configuration, RazorDefaults.RootNamespace); + MiscellaneousHostProject = new HostProject(miscellaneousProjectPath, RazorDefaults.Configuration, RazorDefaults.RootNamespace); } public override bool TryResolveProject(string documentFilePath, out ProjectSnapshot projectSnapshot, bool enforceDocumentInProject = true) @@ -61,7 +61,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem { projectSnapshot = projects[i]; - if (projectSnapshot.FilePath == _miscellaneousHostProject.FilePath) + if (projectSnapshot.FilePath == MiscellaneousHostProject.FilePath) { if (enforceDocumentInProject && IsDocumentInProject(projectSnapshot, documentFilePath)) @@ -93,11 +93,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem { _foregroundDispatcher.AssertForegroundThread(); - var miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(_miscellaneousHostProject.FilePath); + var miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(MiscellaneousHostProject.FilePath); if (miscellaneousProject == null) { - _projectSnapshotManagerAccessor.Instance.ProjectAdded(_miscellaneousHostProject); - miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(_miscellaneousHostProject.FilePath); + _projectSnapshotManagerAccessor.Instance.ProjectAdded(MiscellaneousHostProject); + miscellaneousProject = _projectSnapshotManagerAccessor.Instance.GetLoadedProject(MiscellaneousHostProject.FilePath); } return miscellaneousProject; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorDiagnosticsPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorDiagnosticsPublisher.cs index cdb0567dc8..d00e13321b 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorDiagnosticsPublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorDiagnosticsPublisher.cs @@ -21,11 +21,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { // Internal for testing internal TimeSpan _publishDelay = TimeSpan.FromSeconds(2); - internal readonly Dictionary> _publishedDiagnostics; + internal readonly Dictionary> PublishedDiagnostics; internal Timer _workTimer; internal Timer _documentClosedTimer; - private static readonly TimeSpan CheckForDocumentClosedDelay = TimeSpan.FromSeconds(5); + private static readonly TimeSpan s_checkForDocumentClosedDelay = TimeSpan.FromSeconds(5); private readonly ForegroundDispatcher _foregroundDispatcher; private readonly ITextDocumentLanguageServer _languageServer; private readonly Dictionary _work; @@ -54,7 +54,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer _foregroundDispatcher = foregroundDispatcher; _languageServer = languageServer; - _publishedDiagnostics = new Dictionary>(FilePathComparer.Instance); + PublishedDiagnostics = new Dictionary>(FilePathComparer.Instance); _work = new Dictionary(FilePathComparer.Instance); _logger = loggerFactory.CreateLogger(); } @@ -106,7 +106,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { if (_documentClosedTimer == null) { - _documentClosedTimer = new Timer(DocumentClosedTimer_Tick, null, CheckForDocumentClosedDelay, Timeout.InfiniteTimeSpan); + _documentClosedTimer = new Timer(DocumentClosedTimer_Tick, null, s_checkForDocumentClosedDelay, Timeout.InfiniteTimeSpan); } } @@ -124,15 +124,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // Internal for testing internal void ClearClosedDocuments() { - lock (_publishedDiagnostics) + lock (PublishedDiagnostics) { - var publishedDiagnostics = new Dictionary>(_publishedDiagnostics); + var publishedDiagnostics = new Dictionary>(PublishedDiagnostics); foreach (var entry in publishedDiagnostics) { if (!_projectManager.IsDocumentOpen(entry.Key)) { // Document is now closed, we shouldn't track its diagnostics anymore. - _publishedDiagnostics.Remove(entry.Key); + PublishedDiagnostics.Remove(entry.Key); // If the last published diagnostics for the document were > 0 then we need to clear them out so the user // doesn't have a ton of closed document errors that they can't get rid of. @@ -146,7 +146,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer _documentClosedTimer?.Dispose(); _documentClosedTimer = null; - if (_publishedDiagnostics.Count > 0) + if (PublishedDiagnostics.Count > 0) { lock (_work) { @@ -165,16 +165,16 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer var diagnostics = result.GetCSharpDocument().Diagnostics; - lock (_publishedDiagnostics) + lock (PublishedDiagnostics) { - if (_publishedDiagnostics.TryGetValue(document.FilePath, out var previousDiagnostics) && + if (PublishedDiagnostics.TryGetValue(document.FilePath, out var previousDiagnostics) && diagnostics.SequenceEqual(previousDiagnostics)) { // Diagnostics are the same as last publish return; } - _publishedDiagnostics[document.FilePath] = diagnostics; + PublishedDiagnostics[document.FilePath] = diagnostics; } if (!document.TryGetText(out var sourceText)) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorFileChangeDetector.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorFileChangeDetector.cs index 3568cdaa78..5f963bacc7 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorFileChangeDetector.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorFileChangeDetector.cs @@ -15,10 +15,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { internal class RazorFileChangeDetector : IFileChangeDetector { - private static readonly IReadOnlyList RazorFileExtensions = new[] { ".razor", ".cshtml" }; + private static readonly IReadOnlyList s_razorFileExtensions = new[] { ".razor", ".cshtml" }; // Internal for testing - internal readonly Dictionary _pendingNotifications; + internal readonly Dictionary PendingNotifications; private readonly ForegroundDispatcher _foregroundDispatcher; private readonly FilePathNormalizer _filePathNormalizer; @@ -49,8 +49,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer _foregroundDispatcher = foregroundDispatcher; _filePathNormalizer = filePathNormalizer; _listeners = listeners; - _watchers = new List(RazorFileExtensions.Count); - _pendingNotifications = new Dictionary(FilePathComparer.Instance); + _watchers = new List(s_razorFileExtensions.Count); + PendingNotifications = new Dictionary(FilePathComparer.Instance); } // Internal for testing @@ -94,9 +94,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // Start listening for project file changes (added/removed/renamed). - for (var i = 0; i < RazorFileExtensions.Count; i++) + for (var i = 0; i < s_razorFileExtensions.Count; i++) { - var extension = RazorFileExtensions[i]; + var extension = s_razorFileExtensions[i]; var watcher = new RazorFileSystemWatcher(workspaceDirectory, "*" + extension) { NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime, @@ -149,9 +149,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer protected virtual IReadOnlyList GetExistingRazorFiles(string workspaceDirectory) { var existingRazorFiles = Enumerable.Empty(); - for (var i = 0; i < RazorFileExtensions.Count; i++) + for (var i = 0; i < s_razorFileExtensions.Count; i++) { - var extension = RazorFileExtensions[i]; + var extension = s_razorFileExtensions[i]; var existingFiles = Directory.GetFiles(workspaceDirectory, "*" + extension, SearchOption.AllDirectories); existingRazorFiles = existingRazorFiles.Concat(existingFiles); } @@ -164,10 +164,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { lock (_pendingNotificationsLock) { - if (!_pendingNotifications.TryGetValue(physicalFilePath, out var currentNotification)) + if (!PendingNotifications.TryGetValue(physicalFilePath, out var currentNotification)) { currentNotification = new DelayedFileChangeNotification(); - _pendingNotifications[physicalFilePath] = currentNotification; + PendingNotifications[physicalFilePath] = currentNotification; } if (currentNotification.ChangeKind != null) @@ -215,10 +215,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { lock (_pendingNotificationsLock) { - var result = _pendingNotifications.TryGetValue(physicalFilePath, out var notification); + var result = PendingNotifications.TryGetValue(physicalFilePath, out var notification); Debug.Assert(result, "We should always have an associated notification after delaying an update."); - _pendingNotifications.Remove(physicalFilePath); + PendingNotifications.Remove(physicalFilePath); if (notification.ChangeKind == null) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLSPOptionsMonitor.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLSPOptionsMonitor.cs index 7c8858951e..7b2d3fc9a0 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLSPOptionsMonitor.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLSPOptionsMonitor.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { private readonly RazorConfigurationService _configurationService; private readonly IOptionsMonitorCache _cache; - internal event Action _onChange; + private event Action OnChangeEvent; private RazorLSPOptions _currentValue; public RazorLSPOptionsMonitor(RazorConfigurationService configurationService, IOptionsMonitorCache cache) @@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer public IDisposable OnChange(Action listener) { var disposable = new ChangeTrackerDisposable(this, listener); - _onChange += disposable.OnChange; + OnChangeEvent += disposable.OnChange; return disposable; } @@ -62,7 +62,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer var name = Options.DefaultName; _cache.TryRemove(name); var options = Get(name); - _onChange?.Invoke(options, name); + OnChangeEvent?.Invoke(options, name); } internal class ChangeTrackerDisposable : IDisposable @@ -78,7 +78,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer public void OnChange(RazorLSPOptions options, string name) => _listener.Invoke(options, name); - public void Dispose() => _monitor._onChange -= OnChange; + public void Dispose() => _monitor.OnChangeEvent -= OnChange; } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServerCapability.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServerCapability.cs index 9ba83b56f9..4ed9afaf35 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServerCapability.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServerCapability.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer internal record RazorLanguageServerCapability(bool LanguageQuery, bool RangeMapping, bool EditMapping, bool MonitorProjectConfigurationFilePath) { private const string RazorCapabilityKey = "razor"; - private static readonly RazorLanguageServerCapability Default = new RazorLanguageServerCapability(LanguageQuery: true, RangeMapping: true, EditMapping: true, MonitorProjectConfigurationFilePath: true); + private static readonly RazorLanguageServerCapability s_default = new RazorLanguageServerCapability(LanguageQuery: true, RangeMapping: true, EditMapping: true, MonitorProjectConfigurationFilePath: true); public static void AddTo(ServerCapabilities capabilities) { @@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // server capabilities to our client side code having lost the information of the custom capabilities. To avoid this we use the // experimental bag since it's part of the official LSP spec. This approach enables us to work with any client. capabilities.Experimental ??= new Dictionary(); - capabilities.Experimental[RazorCapabilityKey] = JToken.FromObject(Default); + capabilities.Experimental[RazorCapabilityKey] = JToken.FromObject(s_default); } public static bool TryGet(JToken token, out RazorLanguageServerCapability razorCapability) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Models/RazorSemanticTokensLegend.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Models/RazorSemanticTokensLegend.cs index 784e561cc8..bcc19fb214 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Models/RazorSemanticTokensLegend.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Models/RazorSemanticTokensLegend.cs @@ -148,7 +148,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic.Models MarkupAttributeValueString, }; - private static readonly string[] _tokenModifiers = new string[] { + private static readonly string[] s_tokenModifiers = new string[] { // Razor "None", // C# Modifiers @@ -159,7 +159,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic.Models public static readonly SemanticTokensLegend Instance = new SemanticTokensLegend { - TokenModifiers = new Container(_tokenModifiers), + TokenModifiers = new Container(s_tokenModifiers), TokenTypes = new Container(TokenTypes), }; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/TextDiffer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/TextDiffer.cs index 2382e614bf..5ff7906984 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/TextDiffer.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/TextDiffer.cs @@ -26,16 +26,16 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer var edits = new List(); // Initialize the vectors to use for forward and reverse searches. - var MAX = NewTextLength + OldTextLength; - var Vf = new int[(2 * MAX) + 1]; - var Vr = new int[(2 * MAX) + 1]; + var max = NewTextLength + OldTextLength; + var vf = new int[(2 * max) + 1]; + var vr = new int[(2 * max) + 1]; - ComputeDiffRecursive(edits, 0, OldTextLength, 0, NewTextLength, Vf, Vr); + ComputeDiffRecursive(edits, 0, OldTextLength, 0, NewTextLength, vf, vr); return edits; } - private void ComputeDiffRecursive(List edits, int lowA, int highA, int lowB, int highB, int[] Vf, int[] Vr) + private void ComputeDiffRecursive(List edits, int lowA, int highA, int lowB, int highB, int[] vf, int[] vr) { while (lowA < highA && lowB < highB && ContentEquals(lowA, lowB)) { @@ -72,55 +72,55 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer else { // Find the midpoint of the optimal path. - var (middleX, middleY) = FindMiddleSnake(lowA, highA, lowB, highB, Vf, Vr); + var (middleX, middleY) = FindMiddleSnake(lowA, highA, lowB, highB, vf, vr); // Recursively find the midpoint of the left half. - ComputeDiffRecursive(edits, lowA, middleX, lowB, middleY, Vf, Vr); + ComputeDiffRecursive(edits, lowA, middleX, lowB, middleY, vf, vr); // Recursively find the midpoint of the right half. - ComputeDiffRecursive(edits, middleX, highA, middleY, highB, Vf, Vr); + ComputeDiffRecursive(edits, middleX, highA, middleY, highB, vf, vr); } } - private (int, int) FindMiddleSnake(int lowA, int highA, int lowB, int highB, int[] Vf, int[] Vr) + private (int, int) FindMiddleSnake(int lowA, int highA, int lowB, int highB, int[] vf, int[] vr) { - var N = highA - lowA; - var M = highB - lowB; - var delta = N - M; + var n = highA - lowA; + var m = highB - lowB; + var delta = n - m; var deltaIsEven = delta % 2 == 0; - var MAX = N + M; + var max = n + m; // Compute the k-line to start the forward and reverse searches. var forwardK = lowA - lowB; var reverseK = highA - highB; // The paper uses negative indexes but we can't do that here. So we'll add an offset. - var forwardOffset = MAX - forwardK; - var reverseOffset = MAX - reverseK; + var forwardOffset = max - forwardK; + var reverseOffset = max - reverseK; // Initialize the vector - Vf[forwardOffset + forwardK + 1] = lowA; - Vr[reverseOffset + reverseK - 1] = highA; + vf[forwardOffset + forwardK + 1] = lowA; + vr[reverseOffset + reverseK - 1] = highA; - var maxD = Math.Ceiling((double)(M + N) / 2); - for (var D = 0; D <= maxD; D++) // For D ← 0 to ceil((M + N)/2) Do + var maxD = Math.Ceiling((double)(m + n) / 2); + for (var d = 0; d <= maxD; d++) // For D ← 0 to ceil((M + N)/2) Do { // Run the algorithm in forward direction. - for (var k = forwardK - D; k <= forwardK + D; k += 2) // For k ← −D to D in steps of 2 Do + for (var k = forwardK - d; k <= forwardK + d; k += 2) // For k ← −D to D in steps of 2 Do { // Find the end of the furthest reaching forward D-path in diagonal k. int x; - if (k == forwardK - D || - (k != forwardK + D && Vf[forwardOffset + k - 1] < Vf[forwardOffset + k + 1])) + if (k == forwardK - d || + (k != forwardK + d && vf[forwardOffset + k - 1] < vf[forwardOffset + k + 1])) { // Down - x = Vf[forwardOffset + k + 1]; + x = vf[forwardOffset + k + 1]; } else { // Right - x = Vf[forwardOffset + k - 1] + 1; + x = vf[forwardOffset + k - 1] + 1; } var y = x - k; @@ -132,17 +132,17 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer y++; } - Vf[forwardOffset + k] = x; + vf[forwardOffset + k] = x; if (deltaIsEven) { // Can't have overlap here. } - else if (k > reverseK - D && k < reverseK + D) // If ∆ is odd and k ∈ [∆ − (D − 1) , ∆ + (D − 1)] Then + else if (k > reverseK - d && k < reverseK + d) // If ∆ is odd and k ∈ [∆ − (D − 1) , ∆ + (D − 1)] Then { - if (Vr[reverseOffset + k] <= Vf[forwardOffset + k]) // If the path overlaps the furthest reaching reverse (D − 1)-path in diagonal k Then + if (vr[reverseOffset + k] <= vf[forwardOffset + k]) // If the path overlaps the furthest reaching reverse (D − 1)-path in diagonal k Then { // The last snake of the forward path is the middle snake. - x = Vf[forwardOffset + k]; + x = vf[forwardOffset + k]; y = x - k; return (x, y); } @@ -150,20 +150,20 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer } // Run the algorithm in reverse direction. - for (var k = reverseK - D; k <= reverseK + D; k += 2) // For k ← −D to D in steps of 2 Do + for (var k = reverseK - d; k <= reverseK + d; k += 2) // For k ← −D to D in steps of 2 Do { // Find the end of the furthest reaching reverse D-path in diagonal k+∆. int x; - if (k == reverseK + D || - (k != reverseK - D && Vr[reverseOffset + k - 1] < Vr[reverseOffset + k + 1] - 1)) + if (k == reverseK + d || + (k != reverseK - d && vr[reverseOffset + k - 1] < vr[reverseOffset + k + 1] - 1)) { // Up - x = Vr[reverseOffset + k - 1]; + x = vr[reverseOffset + k - 1]; } else { // Left - x = Vr[reverseOffset + k + 1] - 1; + x = vr[reverseOffset + k + 1] - 1; } var y = x - k; @@ -175,17 +175,17 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer y--; } - Vr[reverseOffset + k] = x; + vr[reverseOffset + k] = x; if (!deltaIsEven) { // Can't have overlap here. } - else if (k >= forwardK - D && k <= forwardK + D) // If ∆ is even and k + ∆ ∈ [−D, D] Then + else if (k >= forwardK - d && k <= forwardK + d) // If ∆ is even and k + ∆ ∈ [−D, D] Then { - if (Vr[reverseOffset + k] <= Vf[forwardOffset + k]) // If the path overlaps the furthest reaching forward D-path in diagonal k+∆ Then + if (vr[reverseOffset + k] <= vf[forwardOffset + k]) // If the path overlaps the furthest reaching forward D-path in diagonal k+∆ Then { // The last snake of the reverse path is the middle snake. - x = Vf[forwardOffset + k]; + x = vf[forwardOffset + k]; y = x - k; return (x, y); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultLSPTagHelperTooltipFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultLSPTagHelperTooltipFactory.cs index 03d0ad01b3..7e1beac26f 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultLSPTagHelperTooltipFactory.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultLSPTagHelperTooltipFactory.cs @@ -20,10 +20,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip throw new ArgumentNullException(nameof(languageServer)); } - LanguageServer = languageServer; + _languageServer = languageServer; } - public ClientNotifierServiceBase LanguageServer; + private readonly ClientNotifierServiceBase _languageServer; public override bool TryCreateTooltip(AggregateBoundElementDescription elementDescriptionInfo, out MarkupContent tooltipContent) { @@ -192,8 +192,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip private MarkupKind GetMarkupKind() { - var completionSupportedKinds = LanguageServer.ClientSettings?.Capabilities?.TextDocument?.Completion.Value?.CompletionItem?.DocumentationFormat; - var hoverSupportedKinds = LanguageServer.ClientSettings?.Capabilities?.TextDocument?.Hover.Value?.ContentFormat; + var completionSupportedKinds = _languageServer.ClientSettings?.Capabilities?.TextDocument?.Completion.Value?.CompletionItem?.DocumentationFormat; + var hoverSupportedKinds = _languageServer.ClientSettings?.Capabilities?.TextDocument?.Hover.Value?.ContentFormat; // For now we're assuming that if you support Markdown for either completions or hovers you support it for both. // If this assumption is ever untrue we'll have to start informing this class about if a request is for Hover or Completions. diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultVSLSPTagHelperTooltipFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultVSLSPTagHelperTooltipFactory.cs index b2a12e5160..5d4db70bb7 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultVSLSPTagHelperTooltipFactory.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/DefaultVSLSPTagHelperTooltipFactory.cs @@ -11,23 +11,23 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip { internal class DefaultVSLSPTagHelperTooltipFactory : VSLSPTagHelperTooltipFactory { - private static readonly Guid ImageCatalogGuid = new("{ae27a6b0-e345-4288-96df-5eaf394ee369}"); + private static readonly Guid s_imageCatalogGuid = new("{ae27a6b0-e345-4288-96df-5eaf394ee369}"); // Internal for testing internal static readonly VSImageElement ClassGlyph = new( - new VSImageId(ImageCatalogGuid, 463), // KnownImageIds.Type = 463 + new VSImageId(s_imageCatalogGuid, 463), // KnownImageIds.Type = 463 RazorLS.Resources.TagHelper_Element_Glyph); // Internal for testing internal static readonly VSImageElement PropertyGlyph = new( - new VSImageId(ImageCatalogGuid, 2429), // KnownImageIds.Type = 2429 + new VSImageId(s_imageCatalogGuid, 2429), // KnownImageIds.Type = 2429 RazorLS.Resources.TagHelper_Attribute_Glyph); - private static readonly IReadOnlyList CSharpPrimitiveTypes = + private static readonly IReadOnlyList s_cSharpPrimitiveTypes = new string[] { "bool", "byte", "sbyte", "char", "decimal", "double", "float", "int", "uint", "nint", "nuint", "long", "ulong", "short", "ushort", "object", "string", "dynamic" }; - private static readonly IReadOnlyDictionary TypeNameToAlias = new Dictionary(StringComparer.Ordinal) + private static readonly IReadOnlyDictionary s_typeNameToAlias = new Dictionary(StringComparer.Ordinal) { { "Int32", "int" }, { "Int64", "long" }, @@ -40,10 +40,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip { "Char", "char" } }; - private static readonly VSClassifiedTextRun Space = new(VSPredefinedClassificationTypeNames.WhiteSpace, " "); - private static readonly VSClassifiedTextRun Dot = new(VSPredefinedClassificationTypeNames.Punctuation, "."); - private static readonly VSClassifiedTextRun NewLine = new(VSPredefinedClassificationTypeNames.WhiteSpace, Environment.NewLine); - private static readonly VSClassifiedTextRun NullableType = new(VSPredefinedClassificationTypeNames.Punctuation, "?"); + private static readonly VSClassifiedTextRun s_space = new(VSPredefinedClassificationTypeNames.WhiteSpace, " "); + private static readonly VSClassifiedTextRun s_dot = new(VSPredefinedClassificationTypeNames.Punctuation, "."); + private static readonly VSClassifiedTextRun s_newLine = new(VSPredefinedClassificationTypeNames.WhiteSpace, Environment.NewLine); + private static readonly VSClassifiedTextRun s_nullableType = new(VSPredefinedClassificationTypeNames.Punctuation, "?"); public override bool TryCreateTooltip(AggregateBoundElementDescription elementDescriptionInfo, out VSContainerElement tooltipContent) { @@ -184,9 +184,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip var reducedReturnTypeName = ReduceTypeName(returnTypeName); ClassifyReducedTypeName(typeRuns, reducedReturnTypeName); - typeRuns.Add(Space); + typeRuns.Add(s_space); ClassifyTypeName(typeRuns, descriptionInfo.TypeName); - typeRuns.Add(Dot); + typeRuns.Add(s_dot); typeRuns.Add(new VSClassifiedTextRun(VSPredefinedClassificationTypeNames.Identifier, descriptionInfo.PropertyName)); // 2. Classify summary @@ -219,7 +219,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip { if (partIndex != 0) { - runs.Add(Dot); + runs.Add(s_dot); } var typeNamePart = typeNameParts[partIndex]; @@ -293,12 +293,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip } // Case 1: Type can be aliased as a C# built-in type (e.g. Boolean -> bool, Int32 -> int, etc.). - if (TypeNameToAlias.TryGetValue(typeName, out var aliasedTypeName)) + if (s_typeNameToAlias.TryGetValue(typeName, out var aliasedTypeName)) { runs.Add(new VSClassifiedTextRun(VSPredefinedClassificationTypeNames.Keyword, aliasedTypeName)); } // Case 2: Type is a C# built-in type (e.g. bool, int, etc.). - else if (CSharpPrimitiveTypes.Contains(typeName)) + else if (s_cSharpPrimitiveTypes.Contains(typeName)) { runs.Add(new VSClassifiedTextRun(VSPredefinedClassificationTypeNames.Keyword, typeName)); } @@ -310,7 +310,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip if (nullableType) { - runs.Add(NullableType); + runs.Add(s_nullableType); } } @@ -433,14 +433,14 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip { if (runs.Count > 0) { - runs.Add(NewLine); - runs.Add(NewLine); + runs.Add(s_newLine); + runs.Add(s_newLine); } runs.AddRange(classification.Type); if (classification.Documentation.Count > 0) { - runs.Add(NewLine); + runs.Add(s_newLine); runs.AddRange(classification.Documentation); } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/TagHelperTooltipFactoryBase.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/TagHelperTooltipFactoryBase.cs index f2cdfc9357..ec17afcd63 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/TagHelperTooltipFactoryBase.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Tooltip/TagHelperTooltipFactoryBase.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip { internal abstract class TagHelperTooltipFactoryBase { - private static readonly IReadOnlyList NewLineChars = new char[] { '\n', '\r' }; + private static readonly IReadOnlyList s_newLineChars = new char[] { '\n', '\r' }; // Internal for testing internal static string ReduceCrefValue(string value) @@ -52,8 +52,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip // Internal for testing internal static bool TryExtractSummary(string documentation, out string summary) { - const string summaryStartTag = ""; - const string summaryEndTag = ""; + const string SummaryStartTag = ""; + const string SummaryEndTag = ""; if (string.IsNullOrEmpty(documentation)) { @@ -61,10 +61,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip return false; } - documentation = documentation.Trim(NewLineChars.ToArray()); + documentation = documentation.Trim(s_newLineChars.ToArray()); - var summaryTagStart = documentation.IndexOf(summaryStartTag, StringComparison.OrdinalIgnoreCase); - var summaryTagEndStart = documentation.IndexOf(summaryEndTag, StringComparison.OrdinalIgnoreCase); + var summaryTagStart = documentation.IndexOf(SummaryStartTag, StringComparison.OrdinalIgnoreCase); + var summaryTagEndStart = documentation.IndexOf(SummaryEndTag, StringComparison.OrdinalIgnoreCase); if (summaryTagStart == -1 || summaryTagEndStart == -1) { // A really wrong but cheap way to check if this is XML @@ -79,7 +79,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Tooltip return false; } - var summaryContentStart = summaryTagStart + summaryStartTag.Length; + var summaryContentStart = summaryTagStart + SummaryStartTag.Length; var summaryContentLength = summaryTagEndStart - summaryContentStart; summary = documentation.Substring(summaryContentStart, summaryContentLength); diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs index e6ba9bf4a2..eb7905057d 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectChangePublisher.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin private const string TempFileExt = ".temp"; // Internal for testing - internal readonly Dictionary _deferredPublishTasks; + internal readonly Dictionary DeferredPublishTasks; private readonly ILogger _logger; private readonly JsonSerializer _serializer; private readonly Dictionary _publishFilePathMappings; @@ -44,7 +44,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin }; _serializer.Converters.RegisterOmniSharpRazorConverters(); _publishFilePathMappings = new Dictionary(FilePathComparer.Instance); - _deferredPublishTasks = new Dictionary(FilePathComparer.Instance); + DeferredPublishTasks = new Dictionary(FilePathComparer.Instance); _pendingProjectPublishes = new Dictionary(FilePathComparer.Instance); _publishLock = new object(); } @@ -137,9 +137,9 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin { _pendingProjectPublishes[projectSnapshot.FilePath] = projectSnapshot; - if (!_deferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted) + if (!DeferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted) { - _deferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath); + DeferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath); } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs index bc0b47e3d2..07f841baea 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/DefaultProjectInstanceEvaluator.cs @@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin private const string CoreCompileTargetName = "CoreCompile"; private const string RazorGenerateDesignTimeTargetName = "RazorGenerateDesignTime"; private const string RazorGenerateComponentDesignTimeTargetName = "RazorGenerateComponentDesignTime"; - private static readonly IEnumerable EmptyMSBuildLoggers = Enumerable.Empty(); + private static readonly IEnumerable s_emptyMSBuildLoggers = Enumerable.Empty(); private readonly OmniSharpForegroundDispatcher _foregroundDispatcher; private readonly object _evaluationLock = new object(); @@ -79,14 +79,14 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin if (refreshTargets.Count > 2) { - var _projectCollection = new ProjectCollection(projectInstance.GlobalProperties); - var project = _projectCollection.LoadProject(projectInstance.ProjectFileLocation.File, projectInstance.ToolsVersion); + var projectCollection = new ProjectCollection(projectInstance.GlobalProperties); + var project = projectCollection.LoadProject(projectInstance.ProjectFileLocation.File, projectInstance.ToolsVersion); SetTargetFrameworkIfNeeded(project); var refreshedProjectInstance = project.CreateProjectInstance(); // Force a Razor information refresh - refreshedProjectInstance.Build(refreshTargets.ToArray(), EmptyMSBuildLoggers); + refreshedProjectInstance.Build(refreshTargets.ToArray(), s_emptyMSBuildLoggers); return refreshedProjectInstance; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs index 78ab96ae46..bcbffcfd09 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparer.cs @@ -8,22 +8,22 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin { internal static class FilePathComparer { - private static StringComparer _instance; + private static StringComparer s_instance; public static StringComparer Instance { get { - if (_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + if (s_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - _instance = StringComparer.Ordinal; + s_instance = StringComparer.Ordinal; } - else if (_instance == null) + else if (s_instance == null) { - _instance = StringComparer.OrdinalIgnoreCase; + s_instance = StringComparer.OrdinalIgnoreCase; } - return _instance; + return s_instance; } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs index f94921b41c..e888b40763 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/FilePathComparison.cs @@ -8,22 +8,22 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin { internal static class FilePathComparison { - private static StringComparison? _instance; + private static StringComparison? s_instance; public static StringComparison Instance { get { - if (_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + if (s_instance == null && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - _instance = StringComparison.Ordinal; + s_instance = StringComparison.Ordinal; } - else if (_instance == null) + else if (s_instance == null) { - _instance = StringComparison.OrdinalIgnoreCase; + s_instance = StringComparison.OrdinalIgnoreCase; } - return _instance.Value; + return s_instance.Value; } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs index f831b5a5d2..03bedb3230 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.OmniSharpPlugin/MSBuildProjectDocumentChangeDetector.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin { private const string MSBuildProjectFullPathPropertyName = "MSBuildProjectFullPath"; private const string MSBuildProjectDirectoryPropertyName = "MSBuildProjectDirectory"; - private static readonly IReadOnlyList RazorFileExtensions = new[] { ".razor", ".cshtml" }; + private static readonly IReadOnlyList s_razorFileExtensions = new[] { ".razor", ".cshtml" }; private readonly Dictionary> _watcherMap; private readonly IReadOnlyList _documentChangeListeners; @@ -74,10 +74,10 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin } } - var watchers = new List(RazorFileExtensions.Count); - for (var i = 0; i < RazorFileExtensions.Count; i++) + var watchers = new List(s_razorFileExtensions.Count); + for (var i = 0; i < s_razorFileExtensions.Count; i++) { - var documentWatcher = new FileSystemWatcher(projectDirectory, "*" + RazorFileExtensions[i]) + var documentWatcher = new FileSystemWatcher(projectDirectory, "*" + s_razorFileExtensions[i]) { NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime, IncludeSubdirectories = true, @@ -90,13 +90,13 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin { // Translate file renames into remove / add - if (RazorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension, StringComparison.Ordinal))) + if (s_razorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension, StringComparison.Ordinal))) { // Renaming from Razor file to something else. FileSystemWatcher_RazorDocumentEvent(args.OldFullPath, projectInstance, RazorFileChangeKind.Removed); } - if (RazorFileExtensions.Any(extension => args.FullPath.EndsWith(extension, StringComparison.Ordinal))) + if (s_razorFileExtensions.Any(extension => args.FullPath.EndsWith(extension, StringComparison.Ordinal))) { // Renaming into a Razor file. This typically occurs when users go from .cshtml => .razor FileSystemWatcher_RazorDocumentEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added); @@ -104,7 +104,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin }; watchers.Add(documentWatcher); - var documentOutputWatcher = new FileSystemWatcher(projectDirectory, "*" + RazorFileExtensions[i] + ".g.cs") + var documentOutputWatcher = new FileSystemWatcher(projectDirectory, "*" + s_razorFileExtensions[i] + ".g.cs") { NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, IncludeSubdirectories = true, @@ -117,13 +117,13 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin { // Translate file renames into remove / add - if (RazorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal))) + if (s_razorFileExtensions.Any(extension => args.OldFullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal))) { // Renaming from Razor background file to something else. FileSystemWatcher_RazorDocumentOutputEvent(args.OldFullPath, projectInstance, RazorFileChangeKind.Removed); } - if (RazorFileExtensions.Any(extension => args.FullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal))) + if (s_razorFileExtensions.Any(extension => args.FullPath.EndsWith(extension + ".g.cs", StringComparison.Ordinal))) { // Renaming into a Razor generated file. FileSystemWatcher_RazorDocumentOutputEvent(args.FullPath, projectInstance, RazorFileChangeKind.Added); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveAttributeCompletionItemProvider.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveAttributeCompletionItemProvider.cs index 955cbb2f40..53e3025583 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveAttributeCompletionItemProvider.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveAttributeCompletionItemProvider.cs @@ -16,7 +16,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion [Export(typeof(RazorCompletionItemProvider))] internal class DirectiveAttributeCompletionItemProvider : DirectiveAttributeCompletionItemProviderBase { - private static readonly RazorCompletionItem[] NoDirectiveAttributeCompletionItems = Array.Empty(); + private static readonly RazorCompletionItem[] s_noDirectiveAttributeCompletionItems = Array.Empty(); private readonly TagHelperFactsService _tagHelperFactsService; @@ -46,7 +46,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion if (!FileKinds.IsComponent(syntaxTree.Options.FileKind)) { // Directive attributes are only supported in components - return NoDirectiveAttributeCompletionItems; + return s_noDirectiveAttributeCompletionItems; } var change = new SourceChange(location, string.Empty); @@ -54,25 +54,25 @@ namespace Microsoft.CodeAnalysis.Razor.Completion if (owner == null) { - return NoDirectiveAttributeCompletionItems; + return s_noDirectiveAttributeCompletionItems; } if (!TryGetAttributeInfo(owner, out _, out var attributeName, out var attributeNameLocation, out _, out _)) { // Either we're not in an attribute or the attribute is so malformed that we can't provide proper completions. - return NoDirectiveAttributeCompletionItems; + return s_noDirectiveAttributeCompletionItems; } if (!attributeNameLocation.IntersectsWith(location.AbsoluteIndex)) { // We're trying to retrieve completions on a portion of the name that is not supported (such as a parameter). - return NoDirectiveAttributeCompletionItems; + return s_noDirectiveAttributeCompletionItems; } if (!TryGetElementInfo(owner.Parent.Parent, out var containingTagName, out var attributes)) { // This should never be the case, it means that we're operating on an attribute that doesn't have a tag. - return NoDirectiveAttributeCompletionItems; + return s_noDirectiveAttributeCompletionItems; } // At this point we've determined that completions have been requested for the name portion of the selected attribute. @@ -87,7 +87,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion return completionItems; } - return NoDirectiveAttributeCompletionItems; + return s_noDirectiveAttributeCompletionItems; } // Internal for testing diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveCompletionItemProvider.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveCompletionItemProvider.cs index e0aef33588..776bcb9550 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveCompletionItemProvider.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/DirectiveCompletionItemProvider.cs @@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion internal static readonly IReadOnlyCollection SingleLineDirectiveCommitCharacters = new string[] { " " }; internal static readonly IReadOnlyCollection BlockDirectiveCommitCharacters = new string[] { " ", "{" }; - private static readonly IEnumerable DefaultDirectives = new[] + private static readonly IEnumerable s_defaultDirectives = new[] { CSharpCodeParser.AddTagHelperDirectiveDescriptor, CSharpCodeParser.RemoveTagHelperDirectiveDescriptor, @@ -109,7 +109,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion // Internal for testing internal static List GetDirectiveCompletionItems(RazorSyntaxTree syntaxTree) { - var defaultDirectives = FileKinds.IsComponent(syntaxTree.Options.FileKind) ? Array.Empty() : DefaultDirectives; + var defaultDirectives = FileKinds.IsComponent(syntaxTree.Options.FileKind) ? Array.Empty() : s_defaultDirectives; var directives = syntaxTree.Options.Directives.Concat(defaultDirectives); var completionItems = new List(); foreach (var directive in directives) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/MarkupTransitionCompletionItemProvider.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/MarkupTransitionCompletionItemProvider.cs index 6781686d27..36441cc012 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/MarkupTransitionCompletionItemProvider.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/MarkupTransitionCompletionItemProvider.cs @@ -14,28 +14,28 @@ namespace Microsoft.CodeAnalysis.Razor.Completion { internal class MarkupTransitionCompletionItemProvider : RazorCompletionItemProvider { - private static readonly IReadOnlyCollection ElementCommitCharacters = new HashSet{ ">" }; + private static readonly IReadOnlyCollection s_elementCommitCharacters = new HashSet{ ">" }; private readonly HtmlFactsService _htmlFactsService; - private static RazorCompletionItem _markupTransitionCompletionItem; + private static RazorCompletionItem s_markupTransitionCompletionItem; public static RazorCompletionItem MarkupTransitionCompletionItem { get { - if (_markupTransitionCompletionItem == null) + if (s_markupTransitionCompletionItem == null) { var completionDisplayText = SyntaxConstants.TextTagName; - _markupTransitionCompletionItem = new RazorCompletionItem( + s_markupTransitionCompletionItem = new RazorCompletionItem( completionDisplayText, completionDisplayText, RazorCompletionItemKind.MarkupTransition, - ElementCommitCharacters); + s_elementCommitCharacters); var completionDescription = new MarkupTransitionCompletionDescription(Resources.MarkupTransition_Description); - _markupTransitionCompletionItem.SetMarkupTransitionCompletionDescription(completionDescription); + s_markupTransitionCompletionItem.SetMarkupTransitionCompletionDescription(completionDescription); } - return _markupTransitionCompletionItem; + return s_markupTransitionCompletionItem; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/RazorCompletionItemExtensions.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/RazorCompletionItemExtensions.cs index 0eb0df0c57..5e6fd838f8 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/RazorCompletionItemExtensions.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Completion/RazorCompletionItemExtensions.cs @@ -8,9 +8,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion { internal static class RazorCompletionItemExtensions { - private readonly static string AttributeCompletionDescriptionKey = "Razor.AttributeDescription"; - private readonly static string DirectiveCompletionDescriptionKey = "Razor.DirectiveDescription"; - private readonly static string MarkupTransitionDescriptionKey = "Razor.MarkupTransitionDescription"; + private readonly static string s_attributeCompletionDescriptionKey = "Razor.AttributeDescription"; + private readonly static string s_directiveCompletionDescriptionKey = "Razor.DirectiveDescription"; + private readonly static string s_markupTransitionDescriptionKey = "Razor.MarkupTransitionDescription"; public static void SetAttributeCompletionDescription(this RazorCompletionItem completionItem, AggregateBoundAttributeDescription attributeCompletionDescription) { @@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion throw new ArgumentNullException(nameof(completionItem)); } - completionItem.Items[AttributeCompletionDescriptionKey] = attributeCompletionDescription; + completionItem.Items[s_attributeCompletionDescriptionKey] = attributeCompletionDescription; } public static AggregateBoundAttributeDescription GetAttributeCompletionDescription(this RazorCompletionItem completionItem) @@ -29,7 +29,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion throw new ArgumentNullException(nameof(completionItem)); } - var attributeCompletionDescription = completionItem.Items[AttributeCompletionDescriptionKey] as AggregateBoundAttributeDescription; + var attributeCompletionDescription = completionItem.Items[s_attributeCompletionDescriptionKey] as AggregateBoundAttributeDescription; return attributeCompletionDescription; } @@ -40,7 +40,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion throw new ArgumentNullException(nameof(completionItem)); } - completionItem.Items[DirectiveCompletionDescriptionKey] = attributeCompletionDescription; + completionItem.Items[s_directiveCompletionDescriptionKey] = attributeCompletionDescription; } public static DirectiveCompletionDescription GetDirectiveCompletionDescription(this RazorCompletionItem completionItem) @@ -50,7 +50,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion throw new ArgumentNullException(nameof(completionItem)); } - var attributeCompletionDescription = completionItem.Items[DirectiveCompletionDescriptionKey] as DirectiveCompletionDescription; + var attributeCompletionDescription = completionItem.Items[s_directiveCompletionDescriptionKey] as DirectiveCompletionDescription; return attributeCompletionDescription; } @@ -61,7 +61,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion throw new ArgumentNullException(nameof(completionItem)); } - completionItem.Items[MarkupTransitionDescriptionKey] = markupTransitionCompletionDescription; + completionItem.Items[s_markupTransitionDescriptionKey] = markupTransitionCompletionDescription; } public static MarkupTransitionCompletionDescription GetMarkupTransitionCompletionDescription(this RazorCompletionItem completionItem) @@ -71,7 +71,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion throw new ArgumentNullException(nameof(completionItem)); } - var markupTransitionCompletionDescription = completionItem.Items[MarkupTransitionDescriptionKey] as MarkupTransitionCompletionDescription; + var markupTransitionCompletionDescription = completionItem.Items[s_markupTransitionDescriptionKey] as MarkupTransitionCompletionDescription; return markupTransitionCompletionDescription; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectSnapshotProjectEngineFactory.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectSnapshotProjectEngineFactory.cs index a693b52a24..e6b8e4748c 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectSnapshotProjectEngineFactory.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectSnapshotProjectEngineFactory.cs @@ -9,7 +9,7 @@ namespace Microsoft.CodeAnalysis.Razor { internal class DefaultProjectSnapshotProjectEngineFactory : ProjectSnapshotProjectEngineFactory { - private readonly static RazorConfiguration DefaultConfiguration = FallbackRazorConfiguration.Latest; + private readonly static RazorConfiguration s_defaultConfiguration = FallbackRazorConfiguration.Latest; private readonly IFallbackProjectEngineFactory _fallback; private readonly Lazy[] _factories; @@ -50,7 +50,7 @@ namespace Microsoft.CodeAnalysis.Razor // // We typically want this because the language adds features over time - we don't want to a bunch of errors // to show up when a document is first opened, and then go away when the configuration loads, we'd prefer the opposite. - configuration ??= DefaultConfiguration; + configuration ??= s_defaultConfiguration; // If there's no factory to handle the configuration then fall back to a very basic configuration. // @@ -67,7 +67,7 @@ namespace Microsoft.CodeAnalysis.Razor throw new ArgumentNullException(nameof(project)); } - return SelectFactory(project.Configuration ?? DefaultConfiguration, requireSerializable: false); + return SelectFactory(project.Configuration ?? s_defaultConfiguration, requireSerializable: false); } public override IProjectEngineFactory FindSerializableFactory(ProjectSnapshot project) @@ -77,7 +77,7 @@ namespace Microsoft.CodeAnalysis.Razor throw new ArgumentNullException(nameof(project)); } - return SelectFactory(project.Configuration ?? DefaultConfiguration, requireSerializable: true); + return SelectFactory(project.Configuration ?? s_defaultConfiguration, requireSerializable: true); } private IProjectEngineFactory SelectFactory(RazorConfiguration configuration, bool requireSerializable = false) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectWorkspaceStateGenerator.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectWorkspaceStateGenerator.cs index c845d9c45a..af94209ccc 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectWorkspaceStateGenerator.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultProjectWorkspaceStateGenerator.cs @@ -18,7 +18,7 @@ namespace Microsoft.CodeAnalysis.Razor internal class DefaultProjectWorkspaceStateGenerator : ProjectWorkspaceStateGenerator, IDisposable { // Internal for testing - internal readonly Dictionary _updates; + internal readonly Dictionary Updates; private readonly ForegroundDispatcher _foregroundDispatcher; private readonly SemaphoreSlim _semaphore; @@ -37,7 +37,7 @@ namespace Microsoft.CodeAnalysis.Razor _foregroundDispatcher = foregroundDispatcher; _semaphore = new SemaphoreSlim(initialCount: 1); - _updates = new Dictionary(FilePathComparer.Instance); + Updates = new Dictionary(FilePathComparer.Instance); } // Used in unit tests to ensure we can control when background work starts. @@ -72,7 +72,7 @@ namespace Microsoft.CodeAnalysis.Razor return; } - if (_updates.TryGetValue(projectSnapshot.FilePath, out var updateItem) && + if (Updates.TryGetValue(projectSnapshot.FilePath, out var updateItem) && !updateItem.Task.IsCompleted && !updateItem.Cts.IsCancellationRequested) { @@ -92,7 +92,7 @@ namespace Microsoft.CodeAnalysis.Razor _foregroundDispatcher.BackgroundScheduler).Unwrap(); updateTask.ConfigureAwait(false); updateItem = new UpdateItem(updateTask, lcts); - _updates[projectSnapshot.FilePath] = updateItem; + Updates[projectSnapshot.FilePath] = updateItem; } public void Dispose() @@ -101,7 +101,7 @@ namespace Microsoft.CodeAnalysis.Razor _disposed = true; - foreach (var update in _updates) + foreach (var update in Updates) { if (!update.Value.Task.IsCompleted && !update.Value.Cts.IsCancellationRequested) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultTagHelperCompletionService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultTagHelperCompletionService.cs index 2c8dd74e08..ea86aae053 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultTagHelperCompletionService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/DefaultTagHelperCompletionService.cs @@ -16,7 +16,7 @@ namespace Microsoft.VisualStudio.Editor.Razor internal class DefaultTagHelperCompletionService : TagHelperCompletionService { private readonly TagHelperFactsService _tagHelperFactsService; - private static readonly HashSet _emptyHashSet = new HashSet(); + private static readonly HashSet s_emptyHashSet = new HashSet(); [ImportingConstructor] public DefaultTagHelperCompletionService(TagHelperFactsService tagHelperFactsService) @@ -302,7 +302,7 @@ namespace Microsoft.VisualStudio.Editor.Razor { if (!elementCompletions.ContainsKey(prefixedName)) { - elementCompletions[prefixedName] = _emptyHashSet; + elementCompletions[prefixedName] = s_emptyHashSet; } continue; diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/HtmlFactsService.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/HtmlFactsService.cs index 18edfc7a98..e8ed2a787a 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/HtmlFactsService.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/HtmlFactsService.cs @@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.Editor.Razor { internal abstract class HtmlFactsService { - private static readonly HashSet _htmlSchemaTagNames = new HashSet(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet s_htmlSchemaTagNames = new HashSet(StringComparer.OrdinalIgnoreCase) { "DOCTYPE", "a", @@ -150,7 +150,7 @@ namespace Microsoft.VisualStudio.Editor.Razor public static bool IsHtmlTagName(string name) { - return _htmlSchemaTagNames.Contains(name); + return s_htmlSchemaTagNames.Contains(name); } } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DefaultProjectSnapshotManager.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DefaultProjectSnapshotManager.cs index 75ec715bb1..d2b3b2e959 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DefaultProjectSnapshotManager.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DefaultProjectSnapshotManager.cs @@ -541,7 +541,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem private class Entry { - public ProjectSnapshot SnapshotUnsafe; + private ProjectSnapshot _snapshotUnsafe; public readonly ProjectState State; public Entry(ProjectState state) @@ -551,7 +551,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem public ProjectSnapshot GetSnapshot() { - return SnapshotUnsafe ??= new DefaultProjectSnapshot(State); + return _snapshotUnsafe ??= new DefaultProjectSnapshot(State); } } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs index 1c7fdb965e..eede1f4a43 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/DocumentState.cs @@ -14,11 +14,11 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem { internal class DocumentState { - private static readonly TextAndVersion EmptyText = TextAndVersion.Create( + private static readonly TextAndVersion s_emptyText = TextAndVersion.Create( SourceText.From(string.Empty), VersionStamp.Default); - public static readonly Func> EmptyLoader = () => Task.FromResult(EmptyText); + public static readonly Func> EmptyLoader = () => Task.FromResult(s_emptyText); private readonly object _lock; @@ -287,7 +287,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem // We utilize a WeakReference here to avoid bloating committed memory. If pieces request document output inbetween GC collections // then we will provide the weak referenced task; otherwise we require any state requests to be re-computed. - public WeakReference> TaskUnsafeReference; + private WeakReference> _taskUnsafeReference; public ComputedStateTracker(DocumentState state, ComputedStateTracker older = null) { @@ -299,12 +299,12 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem { get { - if (TaskUnsafeReference == null) + if (_taskUnsafeReference == null) { return false; } - if (TaskUnsafeReference.TryGetTarget(out var taskUnsafe)) + if (_taskUnsafeReference.TryGetTarget(out var taskUnsafe)) { return taskUnsafe.IsCompleted; } @@ -325,15 +325,15 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem throw new ArgumentNullException(nameof(document)); } - if (TaskUnsafeReference == null || - !TaskUnsafeReference.TryGetTarget(out var taskUnsafe)) + if (_taskUnsafeReference == null || + !_taskUnsafeReference.TryGetTarget(out var taskUnsafe)) { TaskCompletionSource<(RazorCodeDocument, VersionStamp, VersionStamp, VersionStamp)> tcs = null; lock (_lock) { - if (TaskUnsafeReference == null || - !TaskUnsafeReference.TryGetTarget(out taskUnsafe)) + if (_taskUnsafeReference == null || + !_taskUnsafeReference.TryGetTarget(out taskUnsafe)) { // So this is a bit confusing. Instead of directly calling the Razor parser inside of this lock we create an indirect TaskCompletionSource // to represent when it completes. The reason behind this is that there are several scenarios in which the Razor parser will run synchronously @@ -342,7 +342,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); taskUnsafe = tcs.Task; - TaskUnsafeReference = new WeakReference>(taskUnsafe); + _taskUnsafeReference = new WeakReference>(taskUnsafe); } } @@ -449,8 +449,8 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem RazorCodeDocument olderOutput = null; var olderCSharpOutputVersion = default(VersionStamp); var olderHtmlOutputVersion = default(VersionStamp); - if (_older?.TaskUnsafeReference != null && - _older.TaskUnsafeReference.TryGetTarget(out var taskUnsafe)) + if (_older?._taskUnsafeReference != null && + _older._taskUnsafeReference.TryGetTarget(out var taskUnsafe)) { VersionStamp olderInputVersion; (olderOutput, olderInputVersion, olderCSharpOutputVersion, olderHtmlOutputVersion) = await taskUnsafe.ConfigureAwait(false); @@ -459,7 +459,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem // Nothing has changed, we can use the cached result. lock (_lock) { - TaskUnsafeReference = _older.TaskUnsafeReference; + _taskUnsafeReference = _older._taskUnsafeReference; _older = null; return (olderOutput, olderInputVersion, olderCSharpOutputVersion, olderHtmlOutputVersion); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs index 2b08980b8c..9dead57d79 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectState.cs @@ -28,9 +28,9 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem ProjectDifference.DocumentAdded | ProjectDifference.DocumentRemoved; - private static readonly ImmutableDictionary EmptyDocuments = ImmutableDictionary.Create(FilePathComparer.Instance); - private static readonly ImmutableDictionary> EmptyImportsToRelatedDocuments = ImmutableDictionary.Create>(FilePathComparer.Instance); - private static readonly IReadOnlyList EmptyTagHelpers = Array.Empty(); + private static readonly ImmutableDictionary s_emptyDocuments = ImmutableDictionary.Create(FilePathComparer.Instance); + private static readonly ImmutableDictionary> s_emptyImportsToRelatedDocuments = ImmutableDictionary.Create>(FilePathComparer.Instance); + private static readonly IReadOnlyList s_emptyTagHelpers = Array.Empty(); private readonly object _lock; private RazorProjectEngine _projectEngine; @@ -61,8 +61,8 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem Services = services; HostProject = hostProject; ProjectWorkspaceState = projectWorkspaceState; - Documents = EmptyDocuments; - ImportsToRelatedDocuments = EmptyImportsToRelatedDocuments; + Documents = s_emptyDocuments; + ImportsToRelatedDocuments = s_emptyImportsToRelatedDocuments; Version = VersionStamp.Create(); DocumentCollectionVersion = Version; @@ -160,7 +160,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem public HostWorkspaceServices Services { get; } - public IReadOnlyList TagHelpers => ProjectWorkspaceState?.TagHelpers ?? EmptyTagHelpers; + public IReadOnlyList TagHelpers => ProjectWorkspaceState?.TagHelpers ?? s_emptyTagHelpers; public LanguageVersion CSharpLanguageVersion => ProjectWorkspaceState?.CSharpLanguageVersion ?? LanguageVersion.Default; @@ -342,7 +342,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem var documents = Documents.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.WithConfigurationChange(), FilePathComparer.Instance); // If the host project has changed then we need to recompute the imports map - var importsToRelatedDocuments = EmptyImportsToRelatedDocuments; + var importsToRelatedDocuments = s_emptyImportsToRelatedDocuments; foreach (var document in documents) { diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/RazorCodeDocumentExtensions.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/RazorCodeDocumentExtensions.cs index c833c6e96d..9c0c6ca9b9 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/RazorCodeDocumentExtensions.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/RazorCodeDocumentExtensions.cs @@ -9,9 +9,9 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces { internal static class RazorCodeDocumentExtensions { - private static readonly object SourceTextKey = new object(); - private static readonly object CSharpSourceTextKey = new object(); - private static readonly object HtmlSourceTextKey = new object(); + private static readonly object s_sourceTextKey = new object(); + private static readonly object s_cSharpSourceTextKey = new object(); + private static readonly object s_htmlSourceTextKey = new object(); public static SourceText GetSourceText(this RazorCodeDocument document) { @@ -20,14 +20,14 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces throw new ArgumentNullException(nameof(document)); } - var sourceTextObj = document.Items[SourceTextKey]; + var sourceTextObj = document.Items[s_sourceTextKey]; if (sourceTextObj == null) { var source = document.Source; var charBuffer = new char[source.Length]; source.CopyTo(0, charBuffer, 0, source.Length); var sourceText = SourceText.From(new string(charBuffer)); - document.Items[SourceTextKey] = sourceText; + document.Items[s_sourceTextKey] = sourceText; return sourceText; } @@ -42,12 +42,12 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces throw new ArgumentNullException(nameof(document)); } - var sourceTextObj = document.Items[CSharpSourceTextKey]; + var sourceTextObj = document.Items[s_cSharpSourceTextKey]; if (sourceTextObj == null) { var csharpDocument = document.GetCSharpDocument(); var sourceText = SourceText.From(csharpDocument.GeneratedCode); - document.Items[CSharpSourceTextKey] = sourceText; + document.Items[s_cSharpSourceTextKey] = sourceText; return sourceText; } @@ -62,12 +62,12 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces throw new ArgumentNullException(nameof(document)); } - var sourceTextObj = document.Items[HtmlSourceTextKey]; + var sourceTextObj = document.Items[s_htmlSourceTextKey]; if (sourceTextObj == null) { var htmlDocument = document.GetHtmlDocument(); var sourceText = SourceText.From(htmlDocument.GeneratedHtml); - document.Items[HtmlSourceTextKey] = sourceText; + document.Items[s_htmlSourceTextKey] = sourceText; return sourceText; } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/TagHelperDescriptorJsonConverter.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/TagHelperDescriptorJsonConverter.cs index e5849eb31a..7b2597bd2d 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/TagHelperDescriptorJsonConverter.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/TagHelperDescriptorJsonConverter.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Razor.Serialization { public static readonly TagHelperDescriptorJsonConverter Instance = new TagHelperDescriptorJsonConverter(); - private static readonly StringCache _stringCache = new StringCache(); + private static readonly StringCache s_stringCache = new StringCache(); public static bool DisableCachingForTesting { private get; set; } = false; @@ -968,7 +968,7 @@ namespace Microsoft.CodeAnalysis.Razor.Serialization } // We cache all our stings here to prevent them from balooning memory in our Descriptors. - return _stringCache.GetOrAddValue(str); + return s_stringCache.GetOrAddValue(str); } } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/TagHelperDescriptorCache.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/TagHelperDescriptorCache.cs index e86b6329ad..f98f06ca50 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/TagHelperDescriptorCache.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/TagHelperDescriptorCache.cs @@ -7,13 +7,13 @@ namespace Microsoft.CodeAnalysis.Razor { internal static class TagHelperDescriptorCache { - private static readonly MemoryCache CachedTagHelperDescriptors = + private static readonly MemoryCache s_cachedTagHelperDescriptors = new MemoryCache(4500); internal static bool TryGetDescriptor(int hashCode, out TagHelperDescriptor descriptor) => - CachedTagHelperDescriptors.TryGetValue(hashCode, out descriptor); + s_cachedTagHelperDescriptors.TryGetValue(hashCode, out descriptor); internal static void Set(int hashCode, TagHelperDescriptor descriptor) => - CachedTagHelperDescriptors.Set(hashCode, descriptor); + s_cachedTagHelperDescriptors.Set(hashCode, descriptor); } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Tooltip/TypeNameStringResolver.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Tooltip/TypeNameStringResolver.cs index 24e75087c3..116bb46918 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Tooltip/TypeNameStringResolver.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Tooltip/TypeNameStringResolver.cs @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Razor.Tooltip { internal static class TypeNameStringResolver { - private static readonly IReadOnlyDictionary PrimitiveDisplayTypeNameLookups = new Dictionary(StringComparer.Ordinal) + private static readonly IReadOnlyDictionary s_primitiveDisplayTypeNameLookups = new Dictionary(StringComparer.Ordinal) { [typeof(byte).FullName] = "byte", [typeof(sbyte).FullName] = "sbyte", @@ -34,7 +34,7 @@ namespace Microsoft.CodeAnalysis.Razor.Tooltip throw new ArgumentNullException(nameof(typeName)); } - if (PrimitiveDisplayTypeNameLookups.TryGetValue(typeName, out var simpleName)) + if (s_primitiveDisplayTypeNameLookups.TryGetValue(typeName, out var simpleName)) { resolvedName = simpleName; return true; diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RazorServiceDescriptors.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RazorServiceDescriptors.cs index 94bf72487e..bae8e12956 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RazorServiceDescriptors.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RazorServiceDescriptors.cs @@ -15,10 +15,10 @@ namespace Microsoft.CodeAnalysis.Remote.Razor { private const string ComponentName = "Razor"; - private static readonly ImmutableArray JsonConverters = new JsonConverterCollection() + private static readonly ImmutableArray s_jsonConverters = new JsonConverterCollection() .RegisterRazorConverters() .ToImmutableArray(); - public static readonly RazorServiceDescriptorsWrapper TagHelperProviderServiceDescriptors = new RazorServiceDescriptorsWrapper(ComponentName, _ => "Razor TagHelper Provider", JsonConverters, new (Type, Type?)[] { (typeof(IRemoteTagHelperProviderService), null) }); + public static readonly RazorServiceDescriptorsWrapper TagHelperProviderServiceDescriptors = new RazorServiceDescriptorsWrapper(ComponentName, _ => "Razor TagHelper Provider", s_jsonConverters, new (Type, Type?)[] { (typeof(IRemoteTagHelperProviderService), null) }); } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RemoteTagHelperResolver.cs b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RemoteTagHelperResolver.cs index 8ec6c372a8..6b89fc93fb 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RemoteTagHelperResolver.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/RemoteTagHelperResolver.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Razor { internal class RemoteTagHelperResolver : TagHelperResolver { - private readonly static RazorConfiguration DefaultConfiguration = FallbackRazorConfiguration.MVC_2_0; + private readonly static RazorConfiguration s_defaultConfiguration = FallbackRazorConfiguration.MVC_2_0; private readonly IFallbackProjectEngineFactory _fallbackFactory; @@ -63,7 +63,7 @@ namespace Microsoft.CodeAnalysis.Razor // The default configuration currently matches MVC-2.0. Beyond MVC-2.0 we added SDK support for // properly detecting project versions, so that's a good version to assume when we can't find a // configuration. - configuration ??= DefaultConfiguration; + configuration ??= s_defaultConfiguration; // If there's no factory to handle the configuration then fall back to a very basic configuration. // diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/BackgroundDocumentGenerator.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/BackgroundDocumentGenerator.cs index ef97d6c381..1a9936120b 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/BackgroundDocumentGenerator.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/BackgroundDocumentGenerator.cs @@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Razor internal class BackgroundDocumentGenerator : ProjectSnapshotChangeTrigger { // Internal for testing - internal readonly Dictionary _work; + internal readonly Dictionary Work; private readonly ForegroundDispatcher _foregroundDispatcher; private readonly RazorDynamicFileInfoProvider _infoProvider; @@ -44,16 +44,16 @@ namespace Microsoft.CodeAnalysis.Razor _infoProvider = infoProvider; _suppressedDocuments = new HashSet(FilePathComparer.Instance); - _work = new Dictionary(); + Work = new Dictionary(); } public bool HasPendingNotifications { get { - lock (_work) + lock (Work) { - return _work.Count > 0; + return Work.Count > 0; } } } @@ -160,7 +160,7 @@ namespace Microsoft.CodeAnalysis.Razor _foregroundDispatcher.AssertForegroundThread(); - lock (_work) + lock (Work) { if (Suppressed(project, document)) { @@ -169,7 +169,7 @@ namespace Microsoft.CodeAnalysis.Razor // We only want to store the last 'seen' version of any given document. That way when we pick one to process // it's always the best version to use. - _work[new DocumentKey(project.FilePath, document.FilePath)] = (project, document); + Work[new DocumentKey(project.FilePath, document.FilePath)] = (project, document); StartWorker(); } @@ -202,10 +202,10 @@ namespace Microsoft.CodeAnalysis.Razor OnStartingBackgroundWork(); KeyValuePair[] work; - lock (_work) + lock (Work) { - work = _work.ToArray(); - _work.Clear(); + work = Work.ToArray(); + Work.Clear(); } OnBackgroundCapturedWorkload(); @@ -234,14 +234,14 @@ namespace Microsoft.CodeAnalysis.Razor OnCompletingBackgroundWork(); - lock (_work) + lock (Work) { // Resetting the timer allows another batch of work to start. _timer.Dispose(); _timer = null; // If more work came in while we were running start the worker again. - if (_work.Count > 0) + if (Work.Count > 0) { StartWorker(); } diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/DefaultVisualStudioDescriptionFactory.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/DefaultVisualStudioDescriptionFactory.cs index 41f50b8ff4..b40e51015d 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/DefaultVisualStudioDescriptionFactory.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/DefaultVisualStudioDescriptionFactory.cs @@ -20,7 +20,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion new ClassifiedTextElement( new ClassifiedTextRun(PredefinedClassificationNames.Comment, "------------"))); - private static readonly IReadOnlyDictionary KeywordTypeNameLookups = new Dictionary(StringComparer.Ordinal) + private static readonly IReadOnlyDictionary s_keywordTypeNameLookups = new Dictionary(StringComparer.Ordinal) { [typeof(byte).FullName] = "byte", [typeof(sbyte).FullName] = "sbyte", @@ -41,12 +41,12 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion // Hardcoding the Guid here to avoid a reference to Microsoft.VisualStudio.ImageCatalog.dll // that is not present in Visual Studio for Mac - private static readonly Guid ImageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}"); - private static readonly ImageElement PropertyGlyph = new ImageElement( - new ImageId(ImageCatalogGuid, 2429), // KnownImageIds.Type = 2429 + private static readonly Guid s_imageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}"); + private static readonly ImageElement s_propertyGlyph = new ImageElement( + new ImageId(s_imageCatalogGuid, 2429), // KnownImageIds.Type = 2429 "Razor Attribute Glyph"); - private static readonly ClassifiedTextRun SpaceLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, " "); - private static readonly ClassifiedTextRun DotLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, "."); + private static readonly ClassifiedTextRun s_spaceLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, " "); + private static readonly ClassifiedTextRun s_dotLiteral = new ClassifiedTextRun(PredefinedClassificationNames.Literal, "."); public override ContainerElement CreateClassifiedDescription(AggregateBoundAttributeDescription completionDescription) { @@ -94,13 +94,13 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion descriptionElements.Add( new ContainerElement( ContainerElementStyle.Wrapped, - PropertyGlyph, + s_propertyGlyph, new ClassifiedTextElement( new ClassifiedTextRun(returnTypeClassification, returnTypeName), - SpaceLiteral, + s_spaceLiteral, new ClassifiedTextRun(PredefinedClassificationNames.Literal, tagHelperTypeNamePrefix), new ClassifiedTextRun(PredefinedClassificationNames.Type, tagHelperTypeNameProper), - DotLiteral, + s_dotLiteral, new ClassifiedTextRun(PredefinedClassificationNames.Identifier, descriptionInfo.PropertyName)))); if (descriptionInfo.Documentation != null) diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveAttributeCompletionSource.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveAttributeCompletionSource.cs index c382f40ed4..da9fef893c 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveAttributeCompletionSource.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveAttributeCompletionSource.cs @@ -27,12 +27,12 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion // Hardcoding the Guid here to avoid a reference to Microsoft.VisualStudio.ImageCatalog.dll // that is not present in Visual Studio for Mac - private static readonly Guid ImageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}"); - private static readonly ImageElement DirectiveAttributeImageGlyph = new ImageElement( - new ImageId(ImageCatalogGuid, 3564), // KnownImageIds.Type = 3564 + private static readonly Guid s_imageCatalogGuid = new Guid("{ae27a6b0-e345-4288-96df-5eaf394ee369}"); + private static readonly ImageElement s_directiveAttributeImageGlyph = new ImageElement( + new ImageId(s_imageCatalogGuid, 3564), // KnownImageIds.Type = 3564 "Razor Directive Attribute."); - private static readonly ImmutableArray DirectiveAttributeCompletionFilters = new[] { - new CompletionFilter("Razor Directive Attrsibute", "r", DirectiveAttributeImageGlyph) + private static readonly ImmutableArray s_directiveAttributeCompletionFilters = new[] { + new CompletionFilter("Razor Directive Attrsibute", "r", s_directiveAttributeImageGlyph) }.ToImmutableArray(); private readonly VisualStudioRazorParser _parser; @@ -133,8 +133,8 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion filterText: razorCompletionItem.DisplayText, insertText: razorCompletionItem.InsertText, source: this, - icon: DirectiveAttributeImageGlyph, - filters: DirectiveAttributeCompletionFilters, + icon: s_directiveAttributeImageGlyph, + filters: s_directiveAttributeCompletionFilters, suffix: string.Empty, sortText: razorCompletionItem.DisplayText, attributeIcons: ImmutableArray.Empty); diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveCompletionSource.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveCompletionSource.cs index f3c2b4bfd6..dd35c211e8 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveCompletionSource.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Completion/RazorDirectiveCompletionSource.cs @@ -32,7 +32,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion }.ToImmutableArray(); // Internal for testing - internal readonly VisualStudioRazorParser _parser; + internal readonly VisualStudioRazorParser Parser; private readonly RazorCompletionFactsService _completionFactsService; private readonly ForegroundDispatcher _foregroundDispatcher; @@ -57,7 +57,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion } _foregroundDispatcher = foregroundDispatcher; - _parser = parser; + Parser = parser; _completionFactsService = completionFactsService; } @@ -72,7 +72,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion try { - var codeDocument = await _parser.GetLatestCodeDocumentAsync(triggerLocation.Snapshot, token); + var codeDocument = await Parser.GetLatestCodeDocumentAsync(triggerLocation.Snapshot, token); if (codeDocument == null) { return CompletionContext.Empty; diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultEditorSettingsManager.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultEditorSettingsManager.cs index 2ae1709dec..66d9f411dc 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultEditorSettingsManager.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultEditorSettingsManager.cs @@ -14,7 +14,7 @@ namespace Microsoft.VisualStudio.Editor.Razor { public override event EventHandler Changed; - private readonly object SettingsAccessorLock = new object(); + private readonly object _settingsAccessorLock = new object(); private readonly ForegroundDispatcher _foregroundDispatcher; private EditorSettings _settings; @@ -29,7 +29,7 @@ namespace Microsoft.VisualStudio.Editor.Razor { get { - lock (SettingsAccessorLock) + lock (_settingsAccessorLock) { return _settings; } @@ -45,7 +45,7 @@ namespace Microsoft.VisualStudio.Editor.Razor _foregroundDispatcher.AssertForegroundThread(); - lock (SettingsAccessorLock) + lock (_settingsAccessorLock) { if (!_settings.Equals(updatedSettings)) { diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultRazorEditorFactoryService.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultRazorEditorFactoryService.cs index 66f624d02d..030bb955a9 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultRazorEditorFactoryService.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultRazorEditorFactoryService.cs @@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.Editor.Razor [Export(typeof(RazorEditorFactoryService))] internal class DefaultRazorEditorFactoryService : RazorEditorFactoryService { - private static readonly object RazorTextBufferInitializationKey = new object(); + private static readonly object s_razorTextBufferInitializationKey = new object(); private readonly VisualStudioWorkspaceAccessor _workspaceAccessor; [ImportingConstructor] @@ -117,7 +117,7 @@ namespace Microsoft.VisualStudio.Editor.Razor // Internal for testing internal bool TryInitializeTextBuffer(ITextBuffer textBuffer) { - if (textBuffer.Properties.ContainsProperty(RazorTextBufferInitializationKey)) + if (textBuffer.Properties.ContainsProperty(s_razorTextBufferInitializationKey)) { // Buffer already initialized. return true; @@ -143,7 +143,7 @@ namespace Microsoft.VisualStudio.Editor.Razor var braceSmartIndenter = braceSmartIndenterFactory.Create(tracker); textBuffer.Properties[typeof(BraceSmartIndenter)] = braceSmartIndenter; - textBuffer.Properties.AddProperty(RazorTextBufferInitializationKey, RazorTextBufferInitializationKey); + textBuffer.Properties.AddProperty(s_razorTextBufferInitializationKey, s_razorTextBufferInitializationKey); return true; } diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultVisualStudioRazorParser.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultVisualStudioRazorParser.cs index ed7e1420c8..f0f2fc3250 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultVisualStudioRazorParser.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/DefaultVisualStudioRazorParser.cs @@ -24,14 +24,14 @@ namespace Microsoft.VisualStudio.Editor.Razor public override event EventHandler DocumentStructureChanged; // Internal for testing. - internal TimeSpan IdleDelay = TimeSpan.FromSeconds(3); + internal TimeSpan _idleDelay = TimeSpan.FromSeconds(3); internal Timer _idleTimer; internal BackgroundParser _parser; internal ChangeReference _latestChangeReference; internal RazorSyntaxTreePartialParser _partialParser; - private readonly object IdleLock = new object(); - private readonly object UpdateStateLock = new object(); + private readonly object _idleLock = new object(); + private readonly object _updateStateLock = new object(); private readonly VisualStudioCompletionBroker _completionBroker; private readonly VisualStudioDocumentTracker _documentTracker; private readonly ForegroundDispatcher _dispatcher; @@ -115,7 +115,7 @@ namespace Microsoft.VisualStudio.Editor.Razor throw new ArgumentNullException(nameof(atOrNewerSnapshot)); } - lock (UpdateStateLock) + lock (_updateStateLock) { if (_disposed || (_latestParsedSnapshot != null && atOrNewerSnapshot.Version.VersionNumber <= _latestParsedSnapshot.Version.VersionNumber)) @@ -167,7 +167,7 @@ namespace Microsoft.VisualStudio.Editor.Razor StopIdleTimer(); - lock (UpdateStateLock) + lock (_updateStateLock) { _disposed = true; foreach (var request in _codeDocumentRequests) @@ -260,12 +260,12 @@ namespace Microsoft.VisualStudio.Editor.Razor { _dispatcher.AssertForegroundThread(); - lock (IdleLock) + lock (_idleLock) { if (_idleTimer == null) { // Timer will fire after a fixed delay, but only once. - _idleTimer = NonCapturingTimer.Create(state => ((DefaultVisualStudioRazorParser)state).Timer_Tick(), this, IdleDelay, Timeout.InfiniteTimeSpan); + _idleTimer = NonCapturingTimer.Create(state => ((DefaultVisualStudioRazorParser)state).Timer_Tick(), this, _idleDelay, Timeout.InfiniteTimeSpan); } } } @@ -275,7 +275,7 @@ namespace Microsoft.VisualStudio.Editor.Razor { // Can be called from any thread. - lock (IdleLock) + lock (_idleLock) { if (_idleTimer != null) { @@ -485,7 +485,7 @@ namespace Microsoft.VisualStudio.Editor.Razor private void UpdateParserState(RazorCodeDocument codeDocument, ITextSnapshot snapshot) { - lock (UpdateStateLock) + lock (_updateStateLock) { if (_snapshot != null && snapshot.Version.VersionNumber < _snapshot.Version.VersionNumber) { @@ -508,7 +508,7 @@ namespace Microsoft.VisualStudio.Editor.Razor throw new ArgumentNullException(nameof(snapshot)); } - lock (UpdateStateLock) + lock (_updateStateLock) { if (_latestParsedSnapshot == null || _latestParsedSnapshot.Version.VersionNumber < snapshot.Version.VersionNumber) @@ -522,7 +522,7 @@ namespace Microsoft.VisualStudio.Editor.Razor private void CompleteCodeDocumentRequestsForSnapshot(RazorCodeDocument codeDocument, ITextSnapshot snapshot) { - lock (UpdateStateLock) + lock (_updateStateLock) { if (_codeDocumentRequests.Count == 0) { @@ -588,7 +588,7 @@ namespace Microsoft.VisualStudio.Editor.Razor // Internal for testing internal class CodeDocumentRequest { - private readonly object CompletionLock = new object(); + private readonly object _completionLock = new object(); private readonly TaskCompletionSource _taskCompletionSource; private readonly CancellationTokenRegistration _cancellationTokenRegistration; private bool _done; @@ -623,7 +623,7 @@ namespace Microsoft.VisualStudio.Editor.Razor throw new ArgumentNullException(nameof(codeDocument)); } - lock (CompletionLock) + lock (_completionLock) { if (_done) { @@ -640,7 +640,7 @@ namespace Microsoft.VisualStudio.Editor.Razor public void Cancel() { - lock (CompletionLock) + lock (_completionLock) { if (_done) { diff --git a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Documents/EditorDocumentManagerBase.cs b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Documents/EditorDocumentManagerBase.cs index a19e8e741a..1fe2a783fd 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Documents/EditorDocumentManagerBase.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Editor.Razor/Documents/EditorDocumentManagerBase.cs @@ -17,7 +17,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents private readonly FileChangeTrackerFactory _fileChangeTrackerFactory; private readonly Dictionary _documents; private readonly Dictionary> _documentsByFilePath; - protected readonly object _lock; + protected readonly object Lock; public EditorDocumentManagerBase( ForegroundDispatcher foregroundDispatcher, @@ -38,7 +38,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents _documents = new Dictionary(); _documentsByFilePath = new Dictionary>(FilePathComparer.Instance); - _lock = new object(); + Lock = new object(); } protected ForegroundDispatcher ForegroundDispatcher { get; } @@ -53,7 +53,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { return _documents.TryGetValue(key, out document); } @@ -63,7 +63,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { if (!_documentsByFilePath.TryGetValue(filePath, out var keys)) { @@ -92,7 +92,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents EditorDocument document; - lock (_lock) + lock (Lock) { if (TryGetDocument(key, out document)) { @@ -149,7 +149,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { if (TryGetMatchingDocuments(filePath, out var documents)) { @@ -173,7 +173,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { if (TryGetMatchingDocuments(filePath, out var documents)) { diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFileUriProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFileUriProvider.cs index 30989e013f..4cd96f7b23 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFileUriProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFileUriProvider.cs @@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage internal class DefaultFileUriProvider : FileUriProvider { private readonly ITextDocumentFactoryService _textDocumentFactory; - private readonly string TextBufferUri = "__MsLspTextBufferUri"; + private const string TextBufferUri = "__MsLspTextBufferUri"; [ImportingConstructor] public DefaultFileUriProvider(ITextDocumentFactoryService textDocumentFactory) diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPDocumentSynchronizer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPDocumentSynchronizer.cs index 17bb3a65fd..402049c54d 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPDocumentSynchronizer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPDocumentSynchronizer.cs @@ -19,7 +19,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage // Internal for testing internal TimeSpan _synchronizationTimeout = TimeSpan.FromSeconds(2); private readonly Dictionary _virtualDocumentContexts; - private readonly object DocumentContextLock = new object(); + private readonly object _documentContextLock = new object(); private readonly FileUriProvider _fileUriProvider; [ImportingConstructor] @@ -51,7 +51,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage throw new ArgumentNullException(nameof(virtualDocument)); } - lock (DocumentContextLock) + lock (_documentContextLock) { if (!_virtualDocumentContexts.TryGetValue(virtualDocument.Uri, out var documentContext)) { @@ -84,7 +84,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage return; } - lock (DocumentContextLock) + lock (_documentContextLock) { if (!_virtualDocumentContexts.TryGetValue(virtualDocumentUri, out var documentContext)) { @@ -108,7 +108,7 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage throw new ArgumentNullException(nameof(args)); } - lock (DocumentContextLock) + lock (_documentContextLock) { if (args.Kind == LSPDocumentChangeKind.Added) { diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/TextBufferExtensions.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/TextBufferExtensions.cs index 1b1146e47f..2d97450242 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/TextBufferExtensions.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/TextBufferExtensions.cs @@ -7,7 +7,7 @@ namespace Microsoft.VisualStudio.Text { internal static class TextBufferExtensions { - private static readonly string HostDocumentVersionMarked = "__MsLsp_HostDocumentVersionMarker__"; + private const string HostDocumentVersionMarked = "__MsLsp_HostDocumentVersionMarker__"; public static void SetHostDocumentSyncVersion(this ITextBuffer textBuffer, long hostDocumentVersion) { diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/CSharpVirtualDocumentFactory.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/CSharpVirtualDocumentFactory.cs index c31036eff3..9f0e852faa 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/CSharpVirtualDocumentFactory.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/CSharpVirtualDocumentFactory.cs @@ -17,12 +17,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor internal class CSharpVirtualDocumentFactory : VirtualDocumentFactoryBase { public static readonly string CSharpClientName = "RazorCSharp"; - private static readonly IReadOnlyDictionary _languageBufferProperties = new Dictionary + private static readonly IReadOnlyDictionary s_languageBufferProperties = new Dictionary { { LanguageClientConstants.ClientNamePropertyKey, CSharpClientName } }; - private static IContentType _csharpContentType; + private static IContentType s_csharpContentType; [ImportingConstructor] public CSharpVirtualDocumentFactory( @@ -38,24 +38,24 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { get { - if (_csharpContentType == null) + if (s_csharpContentType == null) { var contentType = ContentTypeRegistry.GetContentType(RazorLSPConstants.CSharpContentTypeName); - _csharpContentType = new RemoteContentDefinitionType(contentType); + s_csharpContentType = new RemoteContentDefinitionType(contentType); } - return _csharpContentType; + return s_csharpContentType; } } protected override string HostDocumentContentTypeName => RazorLSPConstants.RazorLSPContentTypeName; protected override string LanguageFileNameSuffix => RazorLSPConstants.VirtualCSharpFileNameSuffix; - protected override IReadOnlyDictionary LanguageBufferProperties => _languageBufferProperties; + protected override IReadOnlyDictionary LanguageBufferProperties => s_languageBufferProperties; protected override VirtualDocument CreateVirtualDocument(Uri uri, ITextBuffer textBuffer) => new CSharpVirtualDocument(uri, textBuffer); private class RemoteContentDefinitionType : IContentType { - private static readonly IReadOnlyList ExtendedBaseContentTypes = new[] + private static readonly IReadOnlyList s_extendedBaseContentTypes = new[] { "code-languageserver-base", CodeRemoteContentDefinition.CodeRemoteContentTypeName @@ -83,7 +83,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor public bool IsOfType(string type) { - return ExtendedBaseContentTypes.Contains(type) || _innerContentType.IsOfType(type); + return s_extendedBaseContentTypes.Contains(type) || _innerContentType.IsOfType(type); } } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Debugging/VsEnumBSTR.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Debugging/VsEnumBSTR.cs index 0edeeb22b4..ac1d52bc05 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Debugging/VsEnumBSTR.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Debugging/VsEnumBSTR.cs @@ -9,34 +9,34 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor internal class VsEnumBSTR : IVsEnumBSTR { // Internal for testing - internal readonly IReadOnlyList _values; + internal readonly IReadOnlyList Values; private int _currentIndex; public VsEnumBSTR(IReadOnlyList values) { - _values = values; + Values = values; _currentIndex = 0; } public int Clone(out IVsEnumBSTR ppEnum) { - ppEnum = new VsEnumBSTR(_values); + ppEnum = new VsEnumBSTR(Values); return VSConstants.S_OK; } public int GetCount(out uint pceltCount) { - pceltCount = (uint)_values.Count; + pceltCount = (uint)Values.Count; return VSConstants.S_OK; } public int Next(uint celt, string[] rgelt, out uint pceltFetched) { var i = 0; - for (; i < celt && _currentIndex < _values.Count; i++, _currentIndex++) + for (; i < celt && _currentIndex < Values.Count; i++, _currentIndex++) { - rgelt[i] = _values[_currentIndex]; + rgelt[i] = Values[_currentIndex]; } pceltFetched = (uint)i; @@ -54,7 +54,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor public int Skip(uint celt) { _currentIndex += (int)celt; - return _currentIndex < _values.Count + return _currentIndex < Values.Count ? VSConstants.S_OK : VSConstants.S_FALSE; } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultLSPEditorFeatureDetector.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultLSPEditorFeatureDetector.cs index 8c87e9175b..ef35cf2088 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultLSPEditorFeatureDetector.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultLSPEditorFeatureDetector.cs @@ -19,8 +19,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor private const string UseLegacyASPNETCoreEditorSettingTemp = "TextEditor.HTMLX.Specific.UseLegacyASPNETCoreRazorEditor"; private const string UseLegacyASPNETCoreEditorSetting = "TextEditor.HTML.Specific.UseLegacyASPNETCoreRazorEditor"; - private static readonly Guid LiveShareHostUIContextGuid = Guid.Parse("62de1aa5-70b0-4934-9324-680896466fe1"); - private static readonly Guid LiveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e"); + private static readonly Guid s_liveShareHostUIContextGuid = Guid.Parse("62de1aa5-70b0-4934-9324-680896466fe1"); + private static readonly Guid s_liveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e"); private readonly ProjectHierarchyInspector _projectHierarchyInspector; private readonly Lazy _vsUIShellOpenDocument; @@ -91,7 +91,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor public override bool IsLiveShareHost() { - var context = UIContext.FromUIContextGuid(LiveShareHostUIContextGuid); + var context = UIContext.FromUIContextGuid(s_liveShareHostUIContextGuid); return context.IsActive; } @@ -128,7 +128,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Private protected virtual for testing private protected virtual bool IsLiveShareGuest() { - var context = UIContext.FromUIContextGuid(LiveShareGuestUIContextGuid); + var context = UIContext.FromUIContextGuid(s_liveShareGuestUIContextGuid); return context.IsActive; } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultRazorProjectChangePublisher.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultRazorProjectChangePublisher.cs index 302395c490..c0582268e5 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultRazorProjectChangePublisher.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/DefaultRazorProjectChangePublisher.cs @@ -26,7 +26,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor [Export(typeof(ProjectSnapshotChangeTrigger))] internal class DefaultRazorProjectChangePublisher : ProjectSnapshotChangeTrigger { - internal readonly Dictionary _deferredPublishTasks; + internal readonly Dictionary DeferredPublishTasks; // Internal for testing internal bool _active; @@ -70,7 +70,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor throw new ArgumentNullException(nameof(serviceProvider)); } - _deferredPublishTasks = new Dictionary(FilePathComparer.Instance); + DeferredPublishTasks = new Dictionary(FilePathComparer.Instance); _pendingProjectPublishes = new Dictionary(FilePathComparer.Instance); _publishLock = new object(); @@ -105,9 +105,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // by capturing the sync context. _pendingProjectPublishes[projectSnapshot.FilePath] = projectSnapshot; - if (!_deferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted) + if (!DeferredPublishTasks.TryGetValue(projectSnapshot.FilePath, out var update) || update.IsCompleted) { - _deferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath); + DeferredPublishTasks[projectSnapshot.FilePath] = PublishAfterDelayAsync(projectSnapshot.FilePath); } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Feedback/LegacyHTMLCSharpLanguageServerFeedbackFileLoggerProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Feedback/LegacyHTMLCSharpLanguageServerFeedbackFileLoggerProvider.cs index 34c79e6816..c3ce4271e0 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Feedback/LegacyHTMLCSharpLanguageServerFeedbackFileLoggerProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Feedback/LegacyHTMLCSharpLanguageServerFeedbackFileLoggerProvider.cs @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Feedback [Obsolete("Use the LogHub logging infrastructure instead.")] internal class LegacyHTMLCSharpLanguageServerFeedbackFileLoggerProvider : ILoggerProvider { - private static readonly string LogFileIdentifier = "HTMLCSharpLanguageServer"; + private const string LogFileIdentifier = "HTMLCSharpLanguageServer"; private readonly FeedbackFileLoggerProvider _loggerProvider; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/CompletionHandler.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/CompletionHandler.cs index 6f16e85cd2..9a8c63be6f 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/CompletionHandler.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/CompletionHandler.cs @@ -20,22 +20,22 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp [ExportLspMethod(Methods.TextDocumentCompletionName)] internal class CompletionHandler : IRequestHandler?> { - private static readonly IReadOnlyList RazorTriggerCharacters = new[] { "@" }; - private static readonly IReadOnlyList CSharpTriggerCharacters = new[] { " ", "(", "=", "#", ".", "<", "[", "{", "\"", "/", ":", "~" }; - private static readonly IReadOnlyList HtmlTriggerCharacters = new[] { ":", "@", "#", ".", "!", "*", ",", "(", "[", "-", "<", "&", "\\", "/", "'", "\"", "=", ":", " ", "`" }; + private static readonly IReadOnlyList s_razorTriggerCharacters = new[] { "@" }; + private static readonly IReadOnlyList s_cSharpTriggerCharacters = new[] { " ", "(", "=", "#", ".", "<", "[", "{", "\"", "/", ":", "~" }; + private static readonly IReadOnlyList s_htmlTriggerCharacters = new[] { ":", "@", "#", ".", "!", "*", ",", "(", "[", "-", "<", "&", "\\", "/", "'", "\"", "=", ":", " ", "`" }; public static readonly IReadOnlyList AllTriggerCharacters = new HashSet( - CSharpTriggerCharacters - .Concat(HtmlTriggerCharacters) - .Concat(RazorTriggerCharacters)) + s_cSharpTriggerCharacters + .Concat(s_htmlTriggerCharacters) + .Concat(s_razorTriggerCharacters)) .ToArray(); - private static readonly IReadOnlyCollection Keywords = new string[] { + private static readonly IReadOnlyCollection s_keywords = new string[] { "for", "foreach", "while", "switch", "lock", "case", "if", "try", "do", "using" }; - private static readonly IReadOnlyCollection DesignTimeHelpers = new string[] + private static readonly IReadOnlyCollection s_designTimeHelpers = new string[] { "__builder", "__o", @@ -47,8 +47,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp "BuildRenderTree" }; - private static readonly IReadOnlyCollection KeywordCompletionItems = GenerateCompletionItems(Keywords); - private static readonly IReadOnlyCollection DesignTimeHelpersCompletionItems = GenerateCompletionItems(DesignTimeHelpers); + private static readonly IReadOnlyCollection s_keywordCompletionItems = GenerateCompletionItems(s_keywords); + private static readonly IReadOnlyCollection s_designTimeHelpersCompletionItems = GenerateCompletionItems(s_designTimeHelpers); private readonly JoinableTaskFactory _joinableTaskFactory; private readonly LSPRequestInvoker _requestInvoker; @@ -321,7 +321,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp TextExtent? wordExtent, CompletionList completionList) { - var filteredItems = completionList.Items.Except(DesignTimeHelpersCompletionItems, CompletionItemComparer.Instance).ToArray(); + var filteredItems = completionList.Items.Except(s_designTimeHelpersCompletionItems, CompletionItemComparer.Instance).ToArray(); // If the current identifier starts with "__", only trim out common design time helpers from the list. // In all other cases, trim out both common design time helpers and all completion items starting with "__". @@ -368,13 +368,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp return context; } - if (languageKind == RazorLanguageKind.CSharp && CSharpTriggerCharacters.Contains(context.TriggerCharacter)) + if (languageKind == RazorLanguageKind.CSharp && s_cSharpTriggerCharacters.Contains(context.TriggerCharacter)) { // C# trigger character for C# content return context; } - if (languageKind == RazorLanguageKind.Html && HtmlTriggerCharacters.Contains(context.TriggerCharacter)) + if (languageKind == RazorLanguageKind.Html && s_htmlTriggerCharacters.Contains(context.TriggerCharacter)) { // HTML trigger character for HTML content return context; @@ -392,7 +392,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp rewrittenContext.InvokeKind = invokeKind.Value; } - if (languageKind == RazorLanguageKind.CSharp && RazorTriggerCharacters.Contains(context.TriggerCharacter)) + if (languageKind == RazorLanguageKind.CSharp && s_razorTriggerCharacters.Contains(context.TriggerCharacter)) { // The C# language server will not return any completions for the '@' character unless we // send the completion request explicitly. @@ -505,7 +505,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // but once C# starts providing them their completion will be offered instead, at which point we should be able to remove this step. private static CompletionList IncludeCSharpKeywords(CompletionList completionList) { - var newList = completionList.Items.Union(KeywordCompletionItems, CompletionItemComparer.Instance); + var newList = completionList.Items.Union(s_keywordCompletionItems, CompletionItemComparer.Instance); completionList.Items = newList.ToArray(); return completionList; @@ -647,18 +647,18 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp private static bool IsApplicableTriggerCharacter(string triggerCharacter, RazorLanguageKind languageKind) { - if (RazorTriggerCharacters.Contains(triggerCharacter)) + if (s_razorTriggerCharacters.Contains(triggerCharacter)) { // Razor trigger characters always transition into either C# or HTML, always note as "applicable". return true; } else if (languageKind == RazorLanguageKind.CSharp) { - return CSharpTriggerCharacters.Contains(triggerCharacter); + return s_cSharpTriggerCharacters.Contains(triggerCharacter); } else if (languageKind == RazorLanguageKind.Html) { - return HtmlTriggerCharacters.Contains(triggerCharacter); + return s_htmlTriggerCharacters.Contains(triggerCharacter); } // Unknown trigger character. diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/DefaultLSPDocumentMappingProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/DefaultLSPDocumentMappingProvider.cs index 410b726637..4610b874a5 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/DefaultLSPDocumentMappingProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/DefaultLSPDocumentMappingProvider.cs @@ -19,7 +19,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp [Export(typeof(LSPDocumentMappingProvider))] internal class DefaultLSPDocumentMappingProvider : LSPDocumentMappingProvider { - private static readonly TextEdit[] EmptyEdits = Array.Empty(); + private static readonly TextEdit[] s_emptyEdits = Array.Empty(); private readonly LSPRequestInvoker _requestInvoker; @@ -358,7 +358,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp mappingResult.HostDocumentVersion != documentSnapshot.Version)) { // Couldn't remap the location or the document changed in the meantime. Discard these ranges. - return (null, EmptyEdits); + return (null, s_emptyEdits); } return (documentSnapshot, mappingResult.TextEdits); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/FindAllReferencesHandler.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/FindAllReferencesHandler.cs index 4c5564b9df..2cbd32cfb1 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/FindAllReferencesHandler.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/FindAllReferencesHandler.cs @@ -261,18 +261,18 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp private static object FilterReferenceDisplayText(object referenceText) { - const string codeBehindObjectPrefix = "__o = "; - const string codeBehindBackingFieldSuffix = "k__BackingField"; + const string CodeBehindObjectPrefix = "__o = "; + const string CodeBehindBackingFieldSuffix = "k__BackingField"; if (referenceText is string text) { - if (text.StartsWith(codeBehindObjectPrefix, StringComparison.Ordinal)) + if (text.StartsWith(CodeBehindObjectPrefix, StringComparison.Ordinal)) { return text - .Substring(codeBehindObjectPrefix.Length, text.Length - codeBehindObjectPrefix.Length - 1); // -1 for trailing `;` + .Substring(CodeBehindObjectPrefix.Length, text.Length - CodeBehindObjectPrefix.Length - 1); // -1 for trailing `;` } - return text.Replace(codeBehindBackingFieldSuffix, string.Empty); + return text.Replace(CodeBehindBackingFieldSuffix, string.Empty); } if (referenceText is ClassifiedTextElement textElement && diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/InitializeHandler.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/InitializeHandler.cs index f5812e4c1e..de3c4fed1e 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/InitializeHandler.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/InitializeHandler.cs @@ -21,7 +21,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp [ExportLspMethod(Methods.InitializeName)] internal class InitializeHandler : IRequestHandler { - private static readonly InitializeResult InitializeResult = new() + private static readonly InitializeResult s_initializeResult = new() { Capabilities = new VSServerCapabilities { @@ -108,7 +108,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp _logger.LogInformation("Providing initialization configuration."); - return Task.FromResult(InitializeResult); + return Task.FromResult(s_initializeResult); } [Conditional("DEBUG")] @@ -339,7 +339,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp private async Task VerifyMergedHoverAsync(VSServerCapabilities mergedCapabilities) { - if (mergedCapabilities.HoverProvider != InitializeResult.Capabilities.HoverProvider) + if (mergedCapabilities.HoverProvider != s_initializeResult.Capabilities.HoverProvider) { await _joinableTaskFactory.SwitchToMainThreadAsync(); @@ -363,8 +363,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp mergedTriggerCharEnumeration = mergedTriggerCharEnumeration.Except(purposefullyRemovedTriggerCharacters); var mergedTriggerChars = new HashSet(mergedTriggerCharEnumeration); - if (!mergedCommitChars.SetEquals(InitializeResult.Capabilities.CompletionProvider?.AllCommitCharacters!) || - !mergedTriggerChars.SetEquals(InitializeResult.Capabilities.CompletionProvider?.TriggerCharacters!)) + if (!mergedCommitChars.SetEquals(s_initializeResult.Capabilities.CompletionProvider?.AllCommitCharacters!) || + !mergedTriggerChars.SetEquals(s_initializeResult.Capabilities.CompletionProvider?.TriggerCharacters!)) { await _joinableTaskFactory.SwitchToMainThreadAsync(); @@ -380,9 +380,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var mergedRetriggerChars = new HashSet(mergedRetriggerCharEnumeration); var mergedWorkDoneProgress = mergedCapabilities.SignatureHelpProvider?.WorkDoneProgress; - if (!mergedTriggerChars.SetEquals(InitializeResult.Capabilities.SignatureHelpProvider?.TriggerCharacters!) || - !mergedRetriggerChars.SetEquals(InitializeResult.Capabilities.SignatureHelpProvider?.RetriggerCharacters!) || - mergedWorkDoneProgress != InitializeResult.Capabilities.SignatureHelpProvider?.WorkDoneProgress) + if (!mergedTriggerChars.SetEquals(s_initializeResult.Capabilities.SignatureHelpProvider?.TriggerCharacters!) || + !mergedRetriggerChars.SetEquals(s_initializeResult.Capabilities.SignatureHelpProvider?.RetriggerCharacters!) || + mergedWorkDoneProgress != s_initializeResult.Capabilities.SignatureHelpProvider?.WorkDoneProgress) { await _joinableTaskFactory.SwitchToMainThreadAsync(); @@ -392,7 +392,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp private async Task VerifyMergedDefinitionProviderAsync(VSServerCapabilities mergedCapabilities) { - if (mergedCapabilities.DefinitionProvider != InitializeResult.Capabilities.DefinitionProvider) + if (mergedCapabilities.DefinitionProvider != s_initializeResult.Capabilities.DefinitionProvider) { await _joinableTaskFactory.SwitchToMainThreadAsync(); @@ -402,7 +402,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp private async Task VerifyMergedReferencesProviderAsync(VSServerCapabilities mergedCapabilities) { - if (mergedCapabilities.ReferencesProvider != InitializeResult.Capabilities.ReferencesProvider) + if (mergedCapabilities.ReferencesProvider != s_initializeResult.Capabilities.ReferencesProvider) { await _joinableTaskFactory.SwitchToMainThreadAsync(); @@ -412,7 +412,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp private async Task VerifyMergedRenameProviderAsync(VSServerCapabilities mergedCapabilities) { - if (mergedCapabilities.RenameProvider != InitializeResult.Capabilities.RenameProvider) + if (mergedCapabilities.RenameProvider != s_initializeResult.Capabilities.RenameProvider) { await _joinableTaskFactory.SwitchToMainThreadAsync(); @@ -430,7 +430,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var filteredMergedTriggerCharacters = mergedTriggerCharacters.Except(purposefullyRemovedTriggerCharacters); var mergedTriggerChars = new HashSet(filteredMergedTriggerCharacters); - var razorOnTypeFormattingOptions = InitializeResult.Capabilities.DocumentOnTypeFormattingProvider; + var razorOnTypeFormattingOptions = s_initializeResult.Capabilities.DocumentOnTypeFormattingProvider; var razorTriggerCharacters = new HashSet { razorOnTypeFormattingOptions.FirstTriggerCharacter diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnAutoInsertHandler.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnAutoInsertHandler.cs index 2eb2da36b6..bf7045283a 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnAutoInsertHandler.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnAutoInsertHandler.cs @@ -18,10 +18,10 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp [ExportLspMethod(MSLSPMethods.OnAutoInsertName)] internal class OnAutoInsertHandler : IRequestHandler { - private static readonly HashSet HTMLAllowedTriggerCharacters = new HashSet(); - private static readonly HashSet CSharpAllowedTriggerCharacters = new() { "'", "/", "\n" }; - private static readonly HashSet AllAllowedTriggerCharacters = HTMLAllowedTriggerCharacters - .Concat(CSharpAllowedTriggerCharacters) + private static readonly HashSet s_htmlAllowedTriggerCharacters = new HashSet(); + private static readonly HashSet s_cSharpAllowedTriggerCharacters = new() { "'", "/", "\n" }; + private static readonly HashSet s_allAllowedTriggerCharacters = s_htmlAllowedTriggerCharacters + .Concat(s_cSharpAllowedTriggerCharacters) .ToHashSet(); private readonly LSPDocumentManager _documentManager; @@ -78,7 +78,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp throw new ArgumentNullException(nameof(request)); } - if (!AllAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) + if (!s_allAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) { // We haven't built support for this character yet. return null; @@ -103,13 +103,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp return null; } else if (projectionResult.LanguageKind == RazorLanguageKind.Html && - !HTMLAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) + !s_htmlAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) { _logger.LogInformation("Inapplicable HTML trigger char."); return null; } else if (projectionResult.LanguageKind == RazorLanguageKind.CSharp && - !CSharpAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) + !s_cSharpAllowedTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) { _logger.LogInformation("Inapplicable C# trigger char."); return null; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnTypeFormattingHandler.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnTypeFormattingHandler.cs index 2691cc80a0..dbdd5cfff6 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnTypeFormattingHandler.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlCSharp/OnTypeFormattingHandler.cs @@ -19,9 +19,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp [ExportLspMethod(Methods.TextDocumentOnTypeFormattingName)] internal class OnTypeFormattingHandler : IRequestHandler { - private static readonly IReadOnlyList CSharpTriggerCharacters = new[] { "}", ";" }; - private static readonly IReadOnlyList HtmlTriggerCharacters = Array.Empty(); - private static readonly IReadOnlyList AllTriggerCharacters = CSharpTriggerCharacters.Concat(HtmlTriggerCharacters).ToArray(); + private static readonly IReadOnlyList s_cSharpTriggerCharacters = new[] { "}", ";" }; + private static readonly IReadOnlyList s_htmlTriggerCharacters = Array.Empty(); + private static readonly IReadOnlyList s_allTriggerCharacters = s_cSharpTriggerCharacters.Concat(s_htmlTriggerCharacters).ToArray(); private readonly LSPDocumentManager _documentManager; private readonly LSPRequestInvoker _requestInvoker; @@ -72,7 +72,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp public async Task HandleRequestAsync(DocumentOnTypeFormattingParams request, ClientCapabilities clientCapabilities, CancellationToken cancellationToken) { - if (!AllTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) + if (!s_allTriggerCharacters.Contains(request.Character, StringComparer.Ordinal)) { // Unexpected trigger character. return null; @@ -175,11 +175,11 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp { if (languageKind == RazorLanguageKind.CSharp) { - return CSharpTriggerCharacters.Contains(triggerCharacter); + return s_cSharpTriggerCharacters.Contains(triggerCharacter); } else if (languageKind == RazorLanguageKind.Html) { - return HtmlTriggerCharacters.Contains(triggerCharacter); + return s_htmlTriggerCharacters.Contains(triggerCharacter); } // Unknown trigger character. diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlVirtualDocumentFactory.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlVirtualDocumentFactory.cs index eed4df362f..b15378d31b 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlVirtualDocumentFactory.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/HtmlVirtualDocumentFactory.cs @@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor [Export(typeof(VirtualDocumentFactory))] internal class HtmlVirtualDocumentFactory : VirtualDocumentFactoryBase { - private static IContentType _htmlLSPContentType; + private static IContentType s_htmlLSPContentType; [ImportingConstructor] public HtmlVirtualDocumentFactory( @@ -29,12 +29,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { get { - if (_htmlLSPContentType == null) + if (s_htmlLSPContentType == null) { - _htmlLSPContentType = ContentTypeRegistry.GetContentType(RazorLSPConstants.HtmlLSPContentTypeName); + s_htmlLSPContentType = ContentTypeRegistry.GetContentType(RazorLSPConstants.HtmlLSPContentTypeName); } - return _htmlLSPContentType; + return s_htmlLSPContentType; } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/HTMLCSharpLanguageServerLogHubLoggerProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/HTMLCSharpLanguageServerLogHubLoggerProvider.cs index da116a110c..e0d61c3624 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/HTMLCSharpLanguageServerLogHubLoggerProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/HTMLCSharpLanguageServerLogHubLoggerProvider.cs @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging [Export(typeof(HTMLCSharpLanguageServerLogHubLoggerProvider))] internal class HTMLCSharpLanguageServerLogHubLoggerProvider : ILoggerProvider { - private static readonly string LogFileIdentifier = "Razor.HTMLCSharpLanguageServerClient"; + private const string LogFileIdentifier = "Razor.HTMLCSharpLanguageServerClient"; private LogHubLoggerProvider _loggerProvider; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/LogHubLoggerProviderFactoryBase.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/LogHubLoggerProviderFactoryBase.cs index e7513832ce..38300ea5cb 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/LogHubLoggerProviderFactoryBase.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/LogHubLoggerProviderFactoryBase.cs @@ -11,7 +11,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging { // Unique, monotomically increasing ID to identify loghub session to persist // across server restarts. - private static int _logHubSessionId; + private static int s_logHubSessionId; private readonly RazorLogHubTraceProvider _traceProvider; private readonly SemaphoreSlim _initializationSemaphore; @@ -40,7 +40,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging _currentLogWriter.Dispose(); } - var logInstanceNumber = Interlocked.Increment(ref _logHubSessionId); + var logInstanceNumber = Interlocked.Increment(ref s_logHubSessionId); var traceSource = await _traceProvider.InitializeTraceAsync(logIdentifier, logInstanceNumber, cancellationToken).ConfigureAwait(false); _currentLogWriter = new DefaultLogHubLogWriter(traceSource); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/RazorLogHubTraceProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/RazorLogHubTraceProvider.cs index 1d68017202..6f0189948a 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/RazorLogHubTraceProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/Logging/RazorLogHubTraceProvider.cs @@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging [Export(typeof(RazorLogHubTraceProvider))] internal class RazorLogHubTraceProvider { - private static readonly LoggerOptions _logOptions = new( + private static readonly LoggerOptions s_logOptions = new( requestedLoggingLevel: new LoggingLevelSettings(SourceLevels.Information | SourceLevels.ActivityTracing), privacySetting: PrivacyFlags.MayContainPersonallyIdentifibleInformation | PrivacyFlags.MayContainPrivateInformation); @@ -34,12 +34,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Logging return null; } - var _logId = new LogId( + var logId = new LogId( logName: $"{logIdentifier}.{logHubSessionId}", serviceId: new ServiceMoniker($"Razor.{logIdentifier}")); using var traceConfig = await LogHub.TraceConfiguration.CreateTraceConfigurationInstanceAsync(_serviceBroker, cancellationToken).ConfigureAwait(false); - var traceSource = await traceConfig.RegisterLogSourceAsync(_logId, _logOptions, cancellationToken).ConfigureAwait(false); + var traceSource = await traceConfig.RegisterLogSourceAsync(logId, s_logOptions, cancellationToken).ConfigureAwait(false); return traceSource; } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/RazorLanguageServerClient.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/RazorLanguageServerClient.cs index 9a70c7abf0..0e9710290c 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/RazorLanguageServerClient.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/RazorLanguageServerClient.cs @@ -30,7 +30,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor [ContentType(RazorLSPConstants.RazorLSPContentTypeName)] internal class RazorLanguageServerClient : ILanguageClient, ILanguageClientCustomMessage2, ILanguageClientPriority { - private static readonly string LogFileIdentifier = "Razor.RazorLanguageServerClient"; + private const string LogFileIdentifier = "Razor.RazorLanguageServerClient"; private readonly RazorLanguageServerCustomMessageTarget _customMessageTarget; private readonly ILanguageClientMiddleLayer _middleLayer; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Documents/VisualStudioEditorDocumentManager.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Documents/VisualStudioEditorDocumentManager.cs index 63bf476f42..a396d7f098 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Documents/VisualStudioEditorDocumentManager.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Documents/VisualStudioEditorDocumentManager.cs @@ -105,7 +105,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { // Casts avoid dynamic if ((object)_runningDocumentTable.GetDocumentData(cookie) is IVsTextBuffer vsTextBuffer) @@ -157,7 +157,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { for (var i = 0; i < documents.Length; i++) { @@ -170,7 +170,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { if (!_documentsByCookie.TryGetValue(cookie, out var documents)) { @@ -200,7 +200,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Documents return; } - lock (_lock) + lock (Lock) { // Treat a rename as a close + reopen. // diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/DefaultRazorProjectHost.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/DefaultRazorProjectHost.cs index 70e323f1fe..e69932ddf3 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/DefaultRazorProjectHost.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/DefaultRazorProjectHost.cs @@ -114,7 +114,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem if (TryGetIntermediateOutputPath(update.Value.CurrentState, out var intermediatePath)) { var projectRazorJson = Path.Combine(intermediatePath, "project.razor.json"); - _projectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson); + ProjectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson); } UpdateProjectUnsafe(hostProject); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/FallbackRazorProjectHost.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/FallbackRazorProjectHost.cs index 6c48b2343f..809ea7ac89 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/FallbackRazorProjectHost.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/FallbackRazorProjectHost.cs @@ -141,7 +141,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem if (TryGetIntermediateOutputPath(update.Value.CurrentState, out var intermediatePath)) { var projectRazorJson = Path.Combine(intermediatePath, "project.razor.json"); - _projectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson); + ProjectConfigurationFilePathStore.Set(hostProject.FilePath, projectRazorJson); } UpdateProjectUnsafe(hostProject); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/RazorProjectHostBase.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/RazorProjectHostBase.cs index d57d1b21ac..2421c11ba3 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/RazorProjectHostBase.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/ProjectSystem/RazorProjectHostBase.cs @@ -27,7 +27,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem private ProjectSnapshotManagerBase _projectManager; private readonly Dictionary _currentDocuments; - protected readonly ProjectConfigurationFilePathStore _projectConfigurationFilePathStore; + protected readonly ProjectConfigurationFilePathStore ProjectConfigurationFilePathStore; internal const string BaseIntermediateOutputPathPropertyName = "BaseIntermediateOutputPath"; internal const string IntermediateOutputPathPropertyName = "IntermediateOutputPath"; @@ -60,7 +60,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem _lock = new AsyncSemaphore(initialCount: 1); _currentDocuments = new Dictionary(FilePathComparer.Instance); - _projectConfigurationFilePathStore = projectConfigurationFilePathStore; + ProjectConfigurationFilePathStore = projectConfigurationFilePathStore; } // Internal for testing @@ -184,7 +184,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem { Debug.Assert(_currentDocuments.Count == 0); projectManager.ProjectRemoved(Current); - _projectConfigurationFilePathStore.Remove(Current.FilePath); + ProjectConfigurationFilePathStore.Remove(Current.FilePath); } else { diff --git a/src/Razor/src/Microsoft.VisualStudio.Mac.LanguageServices.Razor/VisualStudioMacEditorDocumentManager.cs b/src/Razor/src/Microsoft.VisualStudio.Mac.LanguageServices.Razor/VisualStudioMacEditorDocumentManager.cs index 6252c5647f..88cf915d2c 100644 --- a/src/Razor/src/Microsoft.VisualStudio.Mac.LanguageServices.Razor/VisualStudioMacEditorDocumentManager.cs +++ b/src/Razor/src/Microsoft.VisualStudio.Mac.LanguageServices.Razor/VisualStudioMacEditorDocumentManager.cs @@ -43,7 +43,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { if (!TryGetMatchingDocuments(filePath, out var documents)) { @@ -59,7 +59,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { if (!TryGetMatchingDocuments(filePath, out var documents)) { @@ -88,7 +88,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor return; } - lock (_lock) + lock (Lock) { // Treat a rename as a close + reopen. // @@ -104,7 +104,7 @@ namespace Microsoft.VisualStudio.Mac.LanguageServices.Razor { ForegroundDispatcher.AssertForegroundThread(); - lock (_lock) + lock (Lock) { for (var i = 0; i < documents.Length; i++) { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs index 6c674950bc..7719b813ef 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs @@ -20,13 +20,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class AddUsingsCodeActionResolverTest : LanguageServerTestBase { - private readonly DocumentResolver EmptyDocumentResolver = Mock.Of(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); + private readonly DocumentResolver _emptyDocumentResolver = Mock.Of(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); [Fact] public async Task Handle_MissingFile() { // Arrange - var resolver = new AddUsingsCodeActionResolver(new DefaultForegroundDispatcher(), EmptyDocumentResolver); + var resolver = new AddUsingsCodeActionResolver(new DefaultForegroundDispatcher(), _emptyDocumentResolver); var data = JObject.FromObject(new AddUsingsCodeActionParams() { Uri = new Uri("c:/Test.razor"), diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/AddUsingsCSharpCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/AddUsingsCSharpCodeActionResolverTest.cs index eec8a87ff3..35d39f10aa 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/AddUsingsCSharpCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/AddUsingsCSharpCodeActionResolverTest.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class AddUsingsCSharpCodeActionResolverTest : LanguageServerTestBase { - private static readonly CodeAction DefaultResolvedCodeAction = new CodeAction() + private static readonly CodeAction s_defaultResolvedCodeAction = new CodeAction() { Title = "@using System.Net", Data = JToken.FromObject(new object()), @@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions } }; - private static readonly CodeAction DefaultUnresolvedCodeAction = new CodeAction() + private static readonly CodeAction s_defaultUnresolvedCodeAction = new CodeAction() { Title = "@using System.Net" }; @@ -55,11 +55,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultResolvedCodeAction.Title, returnedCodeAction.Title); - Assert.Equal(DefaultResolvedCodeAction.Data, returnedCodeAction.Data); + Assert.Equal(s_defaultResolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultResolvedCodeAction.Data, returnedCodeAction.Data); var returnedEdits = Assert.Single(returnedCodeAction.Edit.DocumentChanges); Assert.True(returnedEdits.IsTextDocumentEdit); var returnedTextDocumentEdit = Assert.Single(returnedEdits.TextDocumentEdit.Edits); @@ -85,10 +85,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title); } [Fact] @@ -132,10 +132,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title); } [Fact] @@ -163,10 +163,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title); } private void CreateCodeActionResolver( @@ -208,7 +208,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var responseRouterReturns = new Mock(MockBehavior.Strict); responseRouterReturns .Setup(l => l.Returning(It.IsAny())) - .Returns(Task.FromResult(resolvedCodeAction ?? DefaultResolvedCodeAction)); + .Returns(Task.FromResult(resolvedCodeAction ?? s_defaultResolvedCodeAction)); var languageServer = new Mock(MockBehavior.Strict); languageServer diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionProviderTest.cs index 3a7c1272ed..f76be84d62 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionProviderTest.cs @@ -19,11 +19,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class DefaultCSharpCodeActionProviderTest : LanguageServerTestBase { - private readonly RazorCodeAction[] SupportedCodeActions; + private readonly RazorCodeAction[] _supportedCodeActions; public DefaultCSharpCodeActionProviderTest() { - SupportedCodeActions = DefaultCSharpCodeActionProvider + _supportedCodeActions = DefaultCSharpCodeActionProvider .SupportedDefaultCodeActionNames .Select(name => new RazorCodeAction() { Name = name }) .ToArray(); @@ -49,12 +49,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var provider = new DefaultCSharpCodeActionProvider(); // Act - var providedCodeActions = await provider.ProvideAsync(context, SupportedCodeActions, default); + var providedCodeActions = await provider.ProvideAsync(context, _supportedCodeActions, default); // Assert - Assert.Equal(SupportedCodeActions.Length, providedCodeActions.Count); + Assert.Equal(_supportedCodeActions.Length, providedCodeActions.Count); var providedNames = providedCodeActions.Select(action => action.Name); - var expectedNames = SupportedCodeActions.Select(action => action.Name); + var expectedNames = _supportedCodeActions.Select(action => action.Name); Assert.Equal(expectedNames, providedNames); } @@ -78,7 +78,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var provider = new DefaultCSharpCodeActionProvider(); // Act - var providedCodeActions = await provider.ProvideAsync(context, SupportedCodeActions, default); + var providedCodeActions = await provider.ProvideAsync(context, _supportedCodeActions, default); // Assert Assert.Empty(providedCodeActions); @@ -104,7 +104,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var provider = new DefaultCSharpCodeActionProvider(); // Act - var providedCodeActions = await provider.ProvideAsync(context, SupportedCodeActions, default); + var providedCodeActions = await provider.ProvideAsync(context, _supportedCodeActions, default); // Assert Assert.Empty(providedCodeActions); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs index b93bb34a13..059e6daa86 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs @@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class DefaultCSharpCodeActionResolverTest : LanguageServerTestBase { - private static readonly CodeAction DefaultResolvedCodeAction = new CodeAction() + private static readonly CodeAction s_defaultResolvedCodeAction = new CodeAction() { Title = "ResolvedCodeAction", Data = JToken.FromObject(new object()), @@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions } }; - private static readonly TextEdit[] DefaultFormattedEdits = new TextEdit[] + private static readonly TextEdit[] s_defaultFormattedEdits = new TextEdit[] { new TextEdit() { @@ -53,7 +53,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions } }; - private static readonly CodeAction DefaultUnresolvedCodeAction = new CodeAction() + private static readonly CodeAction s_defaultUnresolvedCodeAction = new CodeAction() { Title = "Unresolved Code Action" }; @@ -65,15 +65,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultResolvedCodeAction.Title, returnedCodeAction.Title); - Assert.Equal(DefaultResolvedCodeAction.Data, returnedCodeAction.Data); + Assert.Equal(s_defaultResolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultResolvedCodeAction.Data, returnedCodeAction.Data); var returnedEdits = Assert.Single(returnedCodeAction.Edit.DocumentChanges); Assert.True(returnedEdits.IsTextDocumentEdit); var returnedTextDocumentEdit = Assert.Single(returnedEdits.TextDocumentEdit.Edits); - Assert.Equal(DefaultFormattedEdits.First(), returnedTextDocumentEdit); + Assert.Equal(s_defaultFormattedEdits.First(), returnedTextDocumentEdit); } [Fact] @@ -95,10 +95,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title); } [Fact] @@ -142,10 +142,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title); } [Fact] @@ -173,10 +173,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions CreateCodeActionResolver(out var codeActionParams, out var csharpCodeActionResolver, languageServer: languageServer); // Act - var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, DefaultUnresolvedCodeAction, default); + var returnedCodeAction = await csharpCodeActionResolver.ResolveAsync(codeActionParams, s_defaultUnresolvedCodeAction, default); // Assert - Assert.Equal(DefaultUnresolvedCodeAction.Title, returnedCodeAction.Title); + Assert.Equal(s_defaultUnresolvedCodeAction.Title, returnedCodeAction.Title); } private void CreateCodeActionResolver( @@ -220,7 +220,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions It.IsAny(), It.IsAny(), /*bypassValidationPasses:*/ true, - It.IsAny()) == Task.FromResult(DefaultFormattedEdits), MockBehavior.Strict); + It.IsAny()) == Task.FromResult(s_defaultFormattedEdits), MockBehavior.Strict); return razorFormattingService; } @@ -236,7 +236,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var responseRouterReturns = new Mock(MockBehavior.Strict); responseRouterReturns .Setup(l => l.Returning(It.IsAny())) - .Returns(Task.FromResult(resolvedCodeAction ?? DefaultResolvedCodeAction)); + .Returns(Task.FromResult(resolvedCodeAction ?? s_defaultResolvedCodeAction)); var languageServer = new Mock(MockBehavior.Strict); languageServer diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs index 748a1d35dd..18682e6eae 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs @@ -25,10 +25,10 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class CodeActionEndpointTest : LanguageServerTestBase { - private readonly RazorDocumentMappingService DocumentMappingService = Mock.Of(s => s.TryMapToProjectedDocumentRange(It.IsAny(), It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); - private readonly DocumentResolver EmptyDocumentResolver = Mock.Of(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); - private readonly LanguageServerFeatureOptions LanguageServerFeatureOptions = Mock.Of(l => l.SupportsFileManipulation == true, MockBehavior.Strict); - private readonly ClientNotifierServiceBase LanguageServer = Mock.Of(MockBehavior.Strict); + private readonly RazorDocumentMappingService _documentMappingService = Mock.Of(s => s.TryMapToProjectedDocumentRange(It.IsAny(), It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); + private readonly DocumentResolver _emptyDocumentResolver = Mock.Of(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); + private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = Mock.Of(l => l.SupportsFileManipulation == true, MockBehavior.Strict); + private readonly ClientNotifierServiceBase _languageServer = Mock.Of(MockBehavior.Strict); [Fact] public async Task Handle_NoDocument() @@ -36,13 +36,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions // Arrange var documentPath = "C:/path/to/Page.razor"; var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, Array.Empty(), Array.Empty(), Dispatcher, - EmptyDocumentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _emptyDocumentResolver, + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -69,13 +69,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var documentResolver = CreateDocumentResolver(documentPath, codeDocument); codeDocument.SetUnsupported(); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, Array.Empty(), Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -101,13 +101,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, Array.Empty(), Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -133,15 +133,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockRazorCodeActionProvider() }, Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -178,7 +178,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Dispatcher, documentResolver, languageServer, - LanguageServerFeatureOptions) + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -205,15 +205,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockMultipleRazorCodeActionProvider(), }, Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -255,7 +255,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Dispatcher, documentResolver, languageServer, - LanguageServerFeatureOptions) + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -297,7 +297,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Dispatcher, documentResolver, languageServer, - LanguageServerFeatureOptions) + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -324,15 +324,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockNullRazorCodeActionProvider() }, Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -375,7 +375,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Dispatcher, documentResolver, languageServer, - LanguageServerFeatureOptions) + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -402,7 +402,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockRazorCodeActionProvider(), new MockRazorCommandProvider(), @@ -411,8 +411,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = true }; @@ -449,7 +449,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockRazorCodeActionProvider(), new MockRazorCommandProvider(), @@ -458,8 +458,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -494,15 +494,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockRazorCodeActionProvider() }, Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -535,15 +535,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions var codeDocument = CreateCodeDocument("@code {}"); var documentResolver = CreateDocumentResolver(documentPath, codeDocument); var codeActionEndpoint = new CodeActionEndpoint( - DocumentMappingService, + _documentMappingService, new RazorCodeActionProvider[] { new MockRazorCodeActionProvider() }, Array.Empty(), Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -586,8 +586,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions }, Dispatcher, documentResolver, - LanguageServer, - LanguageServerFeatureOptions) + _languageServer, + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; @@ -629,7 +629,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions Dispatcher, documentResolver, languageServer, - LanguageServerFeatureOptions) + _languageServerFeatureOptions) { _supportsCodeActionResolve = false }; diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs index 005b50cd49..8a884f9da3 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs @@ -20,13 +20,13 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class CreateComponentCodeActionResolverTest : LanguageServerTestBase { - private readonly DocumentResolver EmptyDocumentResolver = Mock.Of(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); + private readonly DocumentResolver _emptyDocumentResolver = Mock.Of(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny) == false, MockBehavior.Strict); [Fact] public async Task Handle_MissingFile() { // Arrange - var resolver = new CreateComponentCodeActionResolver(new DefaultForegroundDispatcher(), EmptyDocumentResolver); + var resolver = new CreateComponentCodeActionResolver(new DefaultForegroundDispatcher(), _emptyDocumentResolver); var data = JObject.FromObject(new CreateComponentCodeActionParams() { Uri = new Uri("c:/Test.razor"), diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs index f55d4858c1..03e2ae31d8 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs @@ -21,19 +21,19 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions { public class ExtractToCodeBehindCodeActionResolverTest : LanguageServerTestBase { - private readonly DocumentResolver EmptyDocumentResolver; + private readonly DocumentResolver _emptyDocumentResolver; public ExtractToCodeBehindCodeActionResolverTest() { - EmptyDocumentResolver = new Mock(MockBehavior.Strict).Object; - Mock.Get(EmptyDocumentResolver).Setup(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny)).Returns(false); + _emptyDocumentResolver = new Mock(MockBehavior.Strict).Object; + Mock.Get(_emptyDocumentResolver).Setup(r => r.TryResolveDocument(It.IsAny(), out It.Ref.IsAny)).Returns(false); } [Fact] public async Task Handle_MissingFile() { // Arrange - var resolver = new ExtractToCodeBehindCodeActionResolver(new DefaultForegroundDispatcher(), EmptyDocumentResolver, FilePathNormalizer); + var resolver = new ExtractToCodeBehindCodeActionResolver(new DefaultForegroundDispatcher(), _emptyDocumentResolver, FilePathNormalizer); var data = JObject.FromObject(new ExtractToCodeBehindCodeActionParams() { Uri = new Uri("c:/Test.razor"), diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionEndpointTest.cs index cedb5cd48e..c9259efb57 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionEndpointTest.cs @@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { public class RazorCompletionEndpointTest : LanguageServerTestBase { - private readonly IReadOnlyList SupportedCompletionItemKinds = new[] + private readonly IReadOnlyList _supportedCompletionItemKinds = new[] { ExtendedCompletionItemKinds.Struct, ExtendedCompletionItemKinds.Keyword, @@ -115,7 +115,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion completionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(description)); // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); @@ -134,7 +134,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = new RazorCompletionItem("testDisplay", "testInsert", RazorCompletionItemKind.Directive); var description = "Something"; completionItem.SetDirectiveCompletionDescription(new DirectiveCompletionDescription(description)); - RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Act & Assert JsonConvert.SerializeObject(converted); @@ -145,7 +145,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { // Arrange var completionItem = DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem; - RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Act & Assert JsonConvert.SerializeObject(converted); @@ -158,7 +158,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem; // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); @@ -179,7 +179,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = MarkupTransitionCompletionItemProvider.MarkupTransitionCompletionItem; // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); @@ -197,7 +197,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { // Arrange var completionItem = MarkupTransitionCompletionItemProvider.MarkupTransitionCompletionItem; - RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Act & Assert JsonConvert.SerializeObject(converted); @@ -210,7 +210,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = new RazorCompletionItem("@testDisplay", "testInsert", RazorCompletionItemKind.DirectiveAttribute, new[] { "=", ":" }); // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); @@ -231,7 +231,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = new RazorCompletionItem("format", "format", RazorCompletionItemKind.DirectiveAttributeParameter); // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); @@ -251,7 +251,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = new RazorCompletionItem("format", "format", RazorCompletionItemKind.TagHelperElement); // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); @@ -271,7 +271,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion var completionItem = new RazorCompletionItem("format", "format", RazorCompletionItemKind.TagHelperAttribute); // Act - var result = RazorCompletionEndpoint.TryConvert(completionItem, SupportedCompletionItemKinds, out var converted); + var result = RazorCompletionEndpoint.TryConvert(completionItem, _supportedCompletionItemKinds, out var converted); // Assert Assert.True(result); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultDocumentVersionCacheTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultDocumentVersionCacheTest.cs index 9d70244fca..239b86a501 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultDocumentVersionCacheTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultDocumentVersionCacheTest.cs @@ -182,7 +182,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer documentVersionCache.TrackDocumentVersion(document, 1337); // Assert - var kvp = Assert.Single(documentVersionCache._documentLookup); + var kvp = Assert.Single(documentVersionCache.DocumentLookup); Assert.Equal(document.FilePath, kvp.Key); var entry = Assert.Single(kvp.Value); Assert.True(entry.Document.TryGetTarget(out var actualDocument)); @@ -206,7 +206,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer documentVersionCache.TrackDocumentVersion(document, 1337); // Assert - var kvp = Assert.Single(documentVersionCache._documentLookup); + var kvp = Assert.Single(documentVersionCache.DocumentLookup); Assert.Equal(DefaultDocumentVersionCache.MaxDocumentTrackingCount, kvp.Value.Count); Assert.Equal(1337, kvp.Value.Last().Version); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultProjectResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultProjectResolverTest.cs index 6cc8ab9a99..ff50c503a6 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultProjectResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultProjectResolverTest.cs @@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer DefaultProjectResolver projectResolver = null; var miscProject = new Mock(MockBehavior.Strict); miscProject.Setup(p => p.FilePath) - .Returns(() => projectResolver._miscellaneousHostProject.FilePath); + .Returns(() => projectResolver.MiscellaneousHostProject.FilePath); miscProject.Setup(p => p.GetDocument(documentFilePath)) .Returns((DocumentSnapshot)null); projectResolver = CreateProjectResolver(() => new[] { miscProject.Object }); @@ -60,7 +60,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer DefaultProjectResolver projectResolver = null; var miscProject = new Mock(MockBehavior.Strict); miscProject.Setup(p => p.FilePath) - .Returns(() => projectResolver._miscellaneousHostProject.FilePath); + .Returns(() => projectResolver.MiscellaneousHostProject.FilePath); miscProject.Setup(p => p.GetDocument(documentFilePath)).Returns(Mock.Of(MockBehavior.Strict)); projectResolver = CreateProjectResolver(() => new[] { miscProject.Object }); @@ -116,7 +116,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer DefaultProjectResolver projectResolver = null; var miscProject = new Mock(MockBehavior.Strict); miscProject.Setup(p => p.FilePath) - .Returns(() => projectResolver._miscellaneousHostProject.FilePath); + .Returns(() => projectResolver.MiscellaneousHostProject.FilePath); miscProject.Setup(p => p.GetDocument(documentFilePath)).Returns(Mock.Of(MockBehavior.Strict)); var ownerProject = Mock.Of( p => p.FilePath == "C:/path/to/project.csproj" && @@ -140,7 +140,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer DefaultProjectResolver projectResolver = null; var miscProject = new Mock(MockBehavior.Strict); miscProject.Setup(p => p.FilePath) - .Returns(() => projectResolver._miscellaneousHostProject.FilePath); + .Returns(() => projectResolver.MiscellaneousHostProject.FilePath); miscProject.Setup(p => p.GetDocument(documentFilePath)).Returns(Mock.Of(MockBehavior.Strict)); var ownerProject = Mock.Of( p => p.FilePath == "C:/path/to/project.csproj" && @@ -182,7 +182,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer DefaultProjectResolver projectResolver = null; var miscProject = new Mock(MockBehavior.Strict); miscProject.Setup(p => p.FilePath) - .Returns(() => projectResolver._miscellaneousHostProject.FilePath); + .Returns(() => projectResolver.MiscellaneousHostProject.FilePath); var expectedProject = miscProject.Object; projectResolver = CreateProjectResolver(() => new[] { expectedProject }); @@ -215,7 +215,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // Assert Assert.Single(projects); - Assert.Equal(projectResolver._miscellaneousHostProject.FilePath, project.FilePath); + Assert.Equal(projectResolver.MiscellaneousHostProject.FilePath, project.FilePath); } private DefaultProjectResolver CreateProjectResolver(Func projectFactory) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorComponentSearchEngineTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorComponentSearchEngineTest.cs index ede87b6a73..236f7e1d19 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorComponentSearchEngineTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorComponentSearchEngineTest.cs @@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test { public class DefaultRazorComponentSearchEngineTest : LanguageServerTestBase { - private static readonly ProjectSnapshotManagerAccessor _projectSnapshotManager = CreateProjectSnapshotManagerAccessor(); + private static readonly ProjectSnapshotManagerAccessor s_projectSnapshotManager = CreateProjectSnapshotManagerAccessor(); [Fact] public async Task Handle_SearchFound_GenericComponent() @@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test // Arrange var tagHelperDescriptor1 = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component1", typeName: "Component1"); var tagHelperDescriptor2 = CreateRazorComponentTagHelperDescriptor("Second", "Second.Components", "Component3", typeName: "Component3"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot1 = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor1).ConfigureAwait(false); @@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test // Arrange var tagHelperDescriptor1 = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component1"); var tagHelperDescriptor2 = CreateRazorComponentTagHelperDescriptor("Second", "Second.Components", "Component3"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot1 = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor1).ConfigureAwait(false); @@ -58,7 +58,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test { // Arrange var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("First", "Test", "Component2"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false); @@ -72,7 +72,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test { // Arrange var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("Third", "First.Components", "Component3"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false); @@ -86,7 +86,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test { // Arrange var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component2"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false); @@ -100,7 +100,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test { // Arrange var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("First", "First.Components", "Component3"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false); @@ -114,7 +114,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test { // Arrange var tagHelperDescriptor = CreateRazorComponentTagHelperDescriptor("AssemblyName", "Test", "Component2"); - var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, _projectSnapshotManager); + var searchEngine = new DefaultRazorComponentSearchEngine(Dispatcher, s_projectSnapshotManager); // Act var documentSnapshot = await searchEngine.TryLocateComponentAsync(tagHelperDescriptor).ConfigureAwait(false); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingLanguageServerClient.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingLanguageServerClient.cs index 4c2f646d28..6b739efacb 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingLanguageServerClient.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingLanguageServerClient.cs @@ -155,9 +155,11 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting private struct HtmlFormatterTextEdit { #pragma warning disable CS0649 // Field 'name' is never assigned to, and will always have its default value +#pragma warning disable IDE1006 // Naming Styles - This type is deserialized above so these need to be cased like this public int Position; public int Length; public string NewText; +#pragma warning restore IDE1006 // Naming Styles #pragma warning restore CS0649 // Field 'name' is never assigned to, and will always have its default value public TextEdit AsTextEdit(SourceText sourceText) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingTestBase.cs index a1da7e5ea6..c71dd4b033 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Formatting/FormattingTestBase.cs @@ -35,8 +35,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting [Collection("FormattingTestSerialRuns")] public class FormattingTestBase : RazorIntegrationTestBase { - private static readonly AsyncLocal _fileName = new AsyncLocal(); - private static readonly IReadOnlyList _defaultComponents = GetDefaultRuntimeComponents(); + private static readonly AsyncLocal s_fileName = new AsyncLocal(); + private static readonly IReadOnlyList s_defaultComponents = GetDefaultRuntimeComponents(); public FormattingTestBase() { @@ -54,8 +54,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting // Used by the test framework to set the 'base' name for test files. public static string FileName { - get { return _fileName.Value; } - set { _fileName.Value = value; } + get { return s_fileName.Value; } + set { s_fileName.Value = value; } } protected async Task RunFormattingTestAsync( @@ -189,12 +189,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting tagHelpers ??= Array.Empty(); if (fileKind == FileKinds.Component) { - tagHelpers = tagHelpers.Concat(_defaultComponents).ToArray(); + tagHelpers = tagHelpers.Concat(s_defaultComponents).ToArray(); } var sourceDocument = text.GetRazorSourceDocument(path, path); // Yes I know "BlazorServer_31 is weird, but thats what is in the taghelpers.json file - const string defaultImports = @" + const string DefaultImports = @" @using BlazorServer_31 @using BlazorServer_31.Pages @using BlazorServer_31.Shared @@ -205,7 +205,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Formatting "; var importsPath = new Uri("file:///path/to/_Imports.razor").AbsolutePath; - var importsSourceText = SourceText.From(defaultImports); + var importsSourceText = SourceText.From(DefaultImports); var importsDocument = importsSourceText.GetRazorSourceDocument(importsPath, importsPath); var importsSnapshot = new Mock(MockBehavior.Strict); importsSnapshot.Setup(d => d.GetTextAsync()).Returns(Task.FromResult(importsSourceText)); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectConfigurationStateSynchronizerTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectConfigurationStateSynchronizerTest.cs index 25b0e0d198..74cf71b79a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectConfigurationStateSynchronizerTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProjectConfigurationStateSynchronizerTest.cs @@ -329,12 +329,12 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer { if (hasTask) { - var kvp = Assert.Single(synchronizer._projectInfoMap); + var kvp = Assert.Single(synchronizer.ProjectInfoMap); await Task.Factory.StartNew(() => kvp.Value.ProjectUpdateTask.Wait(), CancellationToken.None, TaskCreationOptions.None, Dispatcher.ForegroundScheduler); } else { - Assert.Empty(synchronizer._projectInfoMap); + Assert.Empty(synchronizer.ProjectInfoMap); } } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorDiagnosticsPublisherTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorDiagnosticsPublisherTest.cs index 8c158d509f..a20fd4120a 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorDiagnosticsPublisherTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorDiagnosticsPublisherTest.cs @@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer using (var publisher = new TestRazorDiagnosticsPublisher(Dispatcher, languageServer.Object, LoggerFactory)) { - publisher._publishedDiagnostics[processedOpenDocument.FilePath] = EmptyDiagnostics; + publisher.PublishedDiagnostics[processedOpenDocument.FilePath] = EmptyDiagnostics; publisher.Initialize(ProjectManager); // Act @@ -160,7 +160,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer processedOpenDocument.With(codeDocument); using (var publisher = new TestRazorDiagnosticsPublisher(Dispatcher, languageServer.Object, LoggerFactory)) { - publisher._publishedDiagnostics[processedOpenDocument.FilePath] = SingleDiagnosticCollection; + publisher.PublishedDiagnostics[processedOpenDocument.FilePath] = SingleDiagnosticCollection; publisher.Initialize(ProjectManager); // Act & Assert @@ -181,7 +181,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer }); using (var publisher = new TestRazorDiagnosticsPublisher(Dispatcher, languageServer.Object, LoggerFactory)) { - publisher._publishedDiagnostics[ClosedDocument.FilePath] = SingleDiagnosticCollection; + publisher.PublishedDiagnostics[ClosedDocument.FilePath] = SingleDiagnosticCollection; publisher.Initialize(ProjectManager); // Act @@ -199,7 +199,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer var languageServer = new Mock(MockBehavior.Strict); using (var publisher = new TestRazorDiagnosticsPublisher(Dispatcher, languageServer.Object, LoggerFactory)) { - publisher._publishedDiagnostics[OpenedDocument.FilePath] = SingleDiagnosticCollection; + publisher.PublishedDiagnostics[OpenedDocument.FilePath] = SingleDiagnosticCollection; publisher.Initialize(ProjectManager); // Act & Assert @@ -214,7 +214,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer var languageServer = new Mock(MockBehavior.Strict); using (var publisher = new TestRazorDiagnosticsPublisher(Dispatcher, languageServer.Object, LoggerFactory)) { - publisher._publishedDiagnostics[ClosedDocument.FilePath] = EmptyDiagnostics; + publisher.PublishedDiagnostics[ClosedDocument.FilePath] = EmptyDiagnostics; publisher.Initialize(ProjectManager); // Act & Assert @@ -229,8 +229,8 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer var languageServer = new Mock(MockBehavior.Strict); using (var publisher = new TestRazorDiagnosticsPublisher(Dispatcher, languageServer.Object, LoggerFactory)) { - publisher._publishedDiagnostics[ClosedDocument.FilePath] = EmptyDiagnostics; - publisher._publishedDiagnostics[OpenedDocument.FilePath] = EmptyDiagnostics; + publisher.PublishedDiagnostics[ClosedDocument.FilePath] = EmptyDiagnostics; + publisher.PublishedDiagnostics[OpenedDocument.FilePath] = EmptyDiagnostics; publisher.Initialize(ProjectManager); // Act diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorFileChangeDetectorTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorFileChangeDetectorTest.cs index dc1c33253d..ed3bbca049 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorFileChangeDetectorTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorFileChangeDetectorTest.cs @@ -83,7 +83,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // Assert // We acquire the notification prior to unblocking notification work because once we allow that work to proceed the notification will be removed. - var notification = Assert.Single(fileChangeDetector._pendingNotifications); + var notification = Assert.Single(fileChangeDetector.PendingNotifications); fileChangeDetector.BlockNotificationWorkStart.Set(); @@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer // Assert // We acquire the notification prior to unblocking notification work because once we allow that work to proceed the notification will be removed. - var notification = Assert.Single(fileChangeDetector._pendingNotifications); + var notification = Assert.Single(fileChangeDetector.PendingNotifications); fileChangeDetector.BlockNotificationWorkStart.Set(); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorServerReadyPublisherTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorServerReadyPublisherTest.cs index 9b062dfecd..6fee77ed55 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorServerReadyPublisherTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/RazorServerReadyPublisherTest.cs @@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test clientNotifierService.Verify(); } - private const string _razorServerReadyEndpoint = "razor/serverReady"; + private const string RazorServerReadyEndpoint = "razor/serverReady"; [Fact] public void ProjectSnapshotManager_WorkspacePopulated_SetsUIContext() @@ -54,7 +54,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test .Returns(() => Task.CompletedTask); var clientNotifierService = new Mock(MockBehavior.Strict); - clientNotifierService.Setup(l => l.SendRequestAsync(_razorServerReadyEndpoint)) + clientNotifierService.Setup(l => l.SendRequestAsync(RazorServerReadyEndpoint)) .Returns(Task.FromResult(responseRouterReturns.Object)); var razorServerReadyPublisher = new RazorServerReadyPublisher(Dispatcher, clientNotifierService.Object); @@ -87,7 +87,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Test .Returns(() => Task.CompletedTask); var clientNotifierService = new Mock(MockBehavior.Strict); - clientNotifierService.Setup(l => l.SendRequestAsync(_razorServerReadyEndpoint)) + clientNotifierService.Setup(l => l.SendRequestAsync(RazorServerReadyEndpoint)) .Returns(Task.FromResult(responseRouterReturns.Object)); var razorServerReadyPublisher = new RazorServerReadyPublisher(Dispatcher, clientNotifierService.Object); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokenTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokenTestBase.cs index 36cf4b3f7a..7113cc54a2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokenTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Semantic/SemanticTokenTestBase.cs @@ -21,15 +21,15 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic { public abstract class SemanticTokenTestBase : TagHelperServiceTestBase { - private static readonly AsyncLocal _fileName = new AsyncLocal(); + private static readonly AsyncLocal s_fileName = new AsyncLocal(); - private static readonly string _projectPath = TestProject.GetProjectDirectory(typeof(TagHelperServiceTestBase)); + private static readonly string s_projectPath = TestProject.GetProjectDirectory(typeof(TagHelperServiceTestBase)); // Used by the test framework to set the 'base' name for test files. public static string? FileName { - get { return _fileName.Value; } - set { _fileName.Value = value; } + get { return s_fileName.Value; } + set { s_fileName.Value = value; } } #if GENERATE_BASELINES @@ -193,7 +193,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic } } - var semanticBaselineEditPath = Path.Combine(_projectPath, baselineFileName); + var semanticBaselineEditPath = Path.Combine(s_projectPath, baselineFileName); File.WriteAllText(semanticBaselineEditPath, builder.ToString()); } @@ -217,7 +217,7 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.Semantic } } - var semanticBaselinePath = Path.Combine(_projectPath, baselineFileName); + var semanticBaselinePath = Path.Combine(s_projectPath, baselineFileName); File.WriteAllText(semanticBaselinePath, builder.ToString()); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/DefaultProjectChangePublisherTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/DefaultProjectChangePublisherTest.cs index 0231dd0b96..fe2d0a5b21 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/DefaultProjectChangePublisherTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/DefaultProjectChangePublisherTest.cs @@ -40,7 +40,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin publisher.ProjectManager_Changed(null, args); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value; Assert.True(serializationSuccessful); } @@ -97,7 +97,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin publisher.EnqueuePublish(secondSnapshot); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value; Assert.True(serializationSuccessful); } @@ -160,7 +160,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin Action onSerializeToFile = null ) : base(loggerFactory) { - _onSerializeToFile = onSerializeToFile ?? ((_, __) => throw new XunitException("SerializeToFile should not have been called.")); + _onSerializeToFile = onSerializeToFile ?? ((_1, _2) => throw new XunitException("SerializeToFile should not have been called.")); } protected override void SerializeToFile(OmniSharpProjectSnapshot projectSnapshot, string publishFilePath) => _onSerializeToFile?.Invoke(projectSnapshot, publishFilePath); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TagHelperRefreshTriggerTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TagHelperRefreshTriggerTest.cs index 94f8584a01..ebb9f70c15 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TagHelperRefreshTriggerTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TagHelperRefreshTriggerTest.cs @@ -148,7 +148,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin using var mre = new ManualResetEventSlim(initialState: false); var workspaceStateGenerator = new Mock(MockBehavior.Strict); workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny(), It.IsAny())) - .Callback((_, __) => mre.Set()); + .Callback((_1, _2) => mre.Set()); var refreshTrigger = CreateRefreshTrigger(workspaceStateGenerator.Object); var args = new ProjectLoadedEventArgs( id: null, @@ -177,7 +177,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin using var mre = new ManualResetEventSlim(initialState: false); var workspaceStateGenerator = new Mock(MockBehavior.Strict); workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny(), It.IsAny())) - .Callback((_, __) => + .Callback((_1, _2) => { if (mre.IsSet) { @@ -217,7 +217,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin using var mre = new ManualResetEventSlim(initialState: false); var workspaceStateGenerator = new Mock(MockBehavior.Strict); workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny(), It.IsAny())) - .Callback((_, __) => mre.Set()); + .Callback((_1, _2) => mre.Set()); var refreshTrigger = CreateRefreshTrigger(workspaceStateGenerator.Object); var args = new RazorFileChangeEventArgs("/path/to/obj/file.cshtml.g.cs", (ProjectInstance)Project1Instance, RazorFileChangeKind.Added); @@ -237,7 +237,7 @@ namespace Microsoft.AspNetCore.Razor.OmniSharpPlugin using var mre = new ManualResetEventSlim(initialState: false); var workspaceStateGenerator = new Mock(MockBehavior.Strict); workspaceStateGenerator.Setup(generator => generator.Update(It.IsAny(), It.IsAny())) - .Callback((_, __) => + .Callback((_1, _2) => { if (mre.IsSet) { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TestOmniSharpWorkspace.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TestOmniSharpWorkspace.cs index 39995f6536..932371e30e 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TestOmniSharpWorkspace.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.OmniSharpPlugin.Test/TestOmniSharpWorkspace.cs @@ -10,11 +10,11 @@ namespace OmniSharp { public static class TestOmniSharpWorkspace { - private static readonly object WorkspaceLock = new object(); + private static readonly object s_workspaceLock = new object(); public static OmniSharpWorkspace Create() { - lock (WorkspaceLock) + lock (s_workspaceLock) { var factory = LoggerFactory.Create((b) => { }); var hostServicesAggregator = new HostServicesAggregator(Enumerable.Empty(), factory); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/ExportProviderCache.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/ExportProviderCache.cs index c7839adec0..b41e3694a0 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/ExportProviderCache.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/ExportProviderCache.cs @@ -23,8 +23,8 @@ namespace Microsoft.AspNetCore.Razor.Test.Common private static readonly TestComposition s_defaultHostExportProviderComposition = TestComposition.Empty .AddAssemblies(MefHostServices.DefaultAssemblies); - private static readonly ConcurrentDictionary _scopes = new ConcurrentDictionary(); - private static readonly string DefaultScope = "default"; + private static readonly ConcurrentDictionary s_scopes = new ConcurrentDictionary(); + private const string DefaultScope = "default"; internal static bool Enabled { get; private set; } @@ -32,14 +32,14 @@ namespace Microsoft.AspNetCore.Razor.Test.Common { get { - var scopes = _scopes.Values.ToArray(); + var scopes = s_scopes.Values.ToArray(); var defaultScope = scopes.Where(scope => scope.Name == DefaultScope); var allButDefault = scopes.Where(scope => scope.Name != DefaultScope); // Make sure to return the default scope as the last element return allButDefault.Concat(defaultScope) - .Where(scope => scope.CurrentExportProvider is { }) - .Select(scope => scope.CurrentExportProvider!) + .Where(scope => scope._currentExportProvider is { }) + .Select(scope => scope._currentExportProvider!) .ToArray(); } } @@ -49,7 +49,7 @@ namespace Microsoft.AspNetCore.Razor.Test.Common Enabled = value; if (!Enabled) { - foreach (var scope in _scopes.Values.ToArray()) + foreach (var scope in s_scopes.Values.ToArray()) { scope.Clear(); } @@ -125,7 +125,7 @@ namespace Microsoft.AspNetCore.Razor.Test.Common public static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog, string? scopeName = null) { - var scope = _scopes.GetOrAdd(scopeName ?? DefaultScope, scopeName => new Scope(scopeName)); + var scope = s_scopes.GetOrAdd(scopeName ?? DefaultScope, scopeName => new Scope(scopeName)); var configuration = CompositionConfiguration.Create(catalog.WithCompositionService()); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); var exportProviderFactory = runtimeComposition.CreateExportProviderFactory(); @@ -157,10 +157,10 @@ namespace Microsoft.AspNetCore.Razor.Test.Common throw new InvalidOperationException($"{nameof(ExportProviderCache)} may only be used from tests marked with {nameof(UseExportProviderAttribute)}"); } - var expectedCatalog = Interlocked.CompareExchange(ref _scope.ExpectedCatalog, _catalog, null) ?? _catalog; + var expectedCatalog = Interlocked.CompareExchange(ref _scope._expectedCatalog, _catalog, null) ?? _catalog; RequireForSingleExportProvider(expectedCatalog == _catalog); - var expected = _scope.ExpectedProviderForCatalog; + var expected = _scope._expectedProviderForCatalog; if (expected == null) { foreach (var errorCollection in _configuration.CompositionErrors) @@ -194,11 +194,11 @@ namespace Microsoft.AspNetCore.Razor.Test.Common } expected = _exportProviderFactory.CreateExportProvider(); - expected = Interlocked.CompareExchange(ref _scope.ExpectedProviderForCatalog, expected, null) ?? expected; - Interlocked.CompareExchange(ref _scope.CurrentExportProvider, expected, null); + expected = Interlocked.CompareExchange(ref _scope._expectedProviderForCatalog, expected, null) ?? expected; + Interlocked.CompareExchange(ref _scope._currentExportProvider, expected, null); } - var exportProvider = _scope.CurrentExportProvider; + var exportProvider = _scope._currentExportProvider; RequireForSingleExportProvider(exportProvider == expected); return exportProvider!; @@ -250,9 +250,9 @@ namespace Microsoft.AspNetCore.Razor.Test.Common private sealed class Scope { public readonly string Name; - public ExportProvider? CurrentExportProvider; - public ComposableCatalog? ExpectedCatalog; - public ExportProvider? ExpectedProviderForCatalog; + public ExportProvider? _currentExportProvider; + public ComposableCatalog? _expectedCatalog; + public ExportProvider? _expectedProviderForCatalog; public Scope(string name) { @@ -261,9 +261,9 @@ namespace Microsoft.AspNetCore.Razor.Test.Common public void Clear() { - CurrentExportProvider = null; - ExpectedCatalog = null; - ExpectedProviderForCatalog = null; + _currentExportProvider = null; + _expectedCatalog = null; + _expectedProviderForCatalog = null; } } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/IntegrationTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/IntegrationTestBase.cs index ea6453dcea..fab6316dff 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/IntegrationTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/IntegrationTestBase.cs @@ -29,9 +29,9 @@ namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests [Collection("IntegrationTestSerialRuns")] public abstract class IntegrationTestBase { - private static readonly AsyncLocal _fileName = new AsyncLocal(); + private static readonly AsyncLocal s_fileName = new AsyncLocal(); - private static readonly CSharpCompilation DefaultBaseCompilation; + private static readonly CSharpCompilation s_defaultBaseCompilation; static IntegrationTestBase() { @@ -46,7 +46,7 @@ namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests .Select(Assembly.Load) .Select(assembly => MetadataReference.CreateFromFile(assembly.Location)) .ToList(); - DefaultBaseCompilation = CSharpCompilation.Create( + s_defaultBaseCompilation = CSharpCompilation.Create( "TestAssembly", Array.Empty(), referenceAssemblies, @@ -66,7 +66,7 @@ namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests /// /// Gets the that will be used as the 'app' compilation. /// - protected virtual CSharpCompilation BaseCompilation => DefaultBaseCompilation; + protected virtual CSharpCompilation BaseCompilation => s_defaultBaseCompilation; /// /// Gets the parse options applied when using . @@ -113,8 +113,8 @@ namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests // Used by the test framework to set the 'base' name for test files. public static string FileName { - get { return _fileName.Value; } - set { _fileName.Value = value; } + get { return s_fileName.Value; } + set { s_fileName.Value = value; } } public string FileExtension { get; set; } = ".cshtml"; diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorBaselineIntegrationTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorBaselineIntegrationTestBase.cs index 8160a6fe9f..38d4bf4c8e 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorBaselineIntegrationTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorBaselineIntegrationTestBase.cs @@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests [Collection("RazorBaselineIntegrationTestSerialRuns")] public abstract class RazorBaselineIntegrationTestBase : RazorIntegrationTestBase { - private static readonly AsyncLocal _directoryPath = new AsyncLocal(); + private static readonly AsyncLocal s_directoryPath = new AsyncLocal(); protected RazorBaselineIntegrationTestBase(bool? generateBaselines = null) { @@ -35,8 +35,8 @@ namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests // Used by the test framework to set the directory for test files. public static string DirectoryPath { - get { return _directoryPath.Value; } - set { _directoryPath.Value = value; } + get { return s_directoryPath.Value; } + set { s_directoryPath.Value = value; } } #if GENERATE_BASELINES diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/Legacy/ParserTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/Legacy/ParserTestBase.cs index 73fb08fbc4..03cac9bc32 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/Legacy/ParserTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/Legacy/ParserTestBase.cs @@ -22,8 +22,8 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy [Collection("ParserTestSerialRuns")] public abstract class ParserTestBase { - private static readonly AsyncLocal _fileName = new AsyncLocal(); - private static readonly AsyncLocal _isTheory = new AsyncLocal(); + private static readonly AsyncLocal s_fileName = new AsyncLocal(); + private static readonly AsyncLocal s_isTheory = new AsyncLocal(); internal ParserTestBase() { @@ -47,14 +47,14 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy // Used by the test framework to set the 'base' name for test files. public static string FileName { - get { return _fileName.Value; } - set { _fileName.Value = value; } + get { return s_fileName.Value; } + set { s_fileName.Value = value; } } public static bool IsTheory { - get { return _isTheory.Value; } - set { _isTheory.Value = value; } + get { return s_isTheory.Value; } + set { s_isTheory.Value = value; } } protected int BaselineTestCount { get; set; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/TestCompilation.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/TestCompilation.cs index 5752f97227..4f886d40f2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/TestCompilation.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/TestCompilation.cs @@ -15,7 +15,7 @@ namespace Microsoft.CodeAnalysis { public static class TestCompilation { - private static readonly ConcurrentDictionary> _referenceCache = + private static readonly ConcurrentDictionary> s_referenceCache = new ConcurrentDictionary>(); public static IEnumerable GetMetadataReferences(Assembly assembly) @@ -65,10 +65,10 @@ namespace Microsoft.CodeAnalysis syntaxTrees = new[] { syntaxTree }; } - if (!_referenceCache.TryGetValue(assembly, out var metadataReferences)) + if (!s_referenceCache.TryGetValue(assembly, out var metadataReferences)) { metadataReferences = GetMetadataReferences(assembly); - _referenceCache.TryAdd(assembly, metadataReferences); + s_referenceCache.TryAdd(assembly, metadataReferences); } var compilation = CSharpCompilation.Create(AssemblyName, syntaxTrees, metadataReferences, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/UseExportProviderAttribute.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/UseExportProviderAttribute.cs index 249d9ef72a..83de2eaea0 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/UseExportProviderAttribute.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/UseExportProviderAttribute.cs @@ -40,7 +40,7 @@ namespace Microsoft.AspNetCore.Razor.Test.Common /// to completion. If this timeout is exceeded by the asynchronous operations running after a test completes, /// the test is failed. /// - private static readonly TimeSpan CleanupTimeout = TimeSpan.FromMinutes(1); + private static readonly TimeSpan s_cleanupTimeout = TimeSpan.FromMinutes(1); #if false private MefHostServices? _hostServices; @@ -124,7 +124,7 @@ namespace Microsoft.AspNetCore.Razor.Test.Common var denyExecutionSynchronizationContext = testExportJoinableTaskContext?.SynchronizationContext as TestExportJoinableTaskContext.DenyExecutionSynchronizationContext; // Join remaining operations with a timeout - using (var timeoutTokenSource = new CancellationTokenSource(CleanupTimeout)) + using (var timeoutTokenSource = new CancellationTokenSource(s_cleanupTimeout)) { if (denyExecutionSynchronizationContext is object) { diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version1_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version1_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs index 56893ee9ad..0114be85e2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version1_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version1_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers /// public abstract class ReadOnlyTagHelperAttributeList : ReadOnlyCollection { - private static readonly IReadOnlyList EmptyList = Array.Empty(); + private static readonly IReadOnlyList s_emptyList = Array.Empty(); /// /// Instantiates a new instance of with an empty @@ -138,7 +138,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers matchedAttributes.Add(Items[i]); } } - attributes = matchedAttributes ?? EmptyList; + attributes = matchedAttributes ?? s_emptyList; return matchedAttributes != null; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs index 56893ee9ad..0114be85e2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim.Version2_X/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers /// public abstract class ReadOnlyTagHelperAttributeList : ReadOnlyCollection { - private static readonly IReadOnlyList EmptyList = Array.Empty(); + private static readonly IReadOnlyList s_emptyList = Array.Empty(); /// /// Instantiates a new instance of with an empty @@ -138,7 +138,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers matchedAttributes.Add(Items[i]); } } - attributes = matchedAttributes ?? EmptyList; + attributes = matchedAttributes ?? s_emptyList; return matchedAttributes != null; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs index 56893ee9ad..0114be85e2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.MvcShim/Microsoft.AspNetCore.Razor.TagHelpers/ReadOnlyTagHelperAttributeList.cs @@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers /// public abstract class ReadOnlyTagHelperAttributeList : ReadOnlyCollection { - private static readonly IReadOnlyList EmptyList = Array.Empty(); + private static readonly IReadOnlyList s_emptyList = Array.Empty(); /// /// Instantiates a new instance of with an empty @@ -138,7 +138,7 @@ namespace Microsoft.AspNetCore.Razor.TagHelpers matchedAttributes.Add(Items[i]); } } - attributes = matchedAttributes ?? EmptyList; + attributes = matchedAttributes ?? s_emptyList; return matchedAttributes != null; } diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspace.cs b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspace.cs index 40367ae70a..9ac4ff2748 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspace.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspace.cs @@ -8,13 +8,13 @@ namespace Microsoft.CodeAnalysis { public static class TestWorkspace { - private static readonly object WorkspaceLock = new object(); + private static readonly object s_workspaceLock = new object(); public static Workspace Create(Action configure = null) => Create(services: null, configure: configure); public static AdhocWorkspace Create(HostServices services, Action configure = null) { - lock (WorkspaceLock) + lock (s_workspaceLock) { var workspace = services == null ? new AdhocWorkspace() : new AdhocWorkspace(services); configure?.Invoke(workspace); diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspaceServices.cs b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspaceServices.cs index 52b779915b..e019a02bb6 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspaceServices.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test.Common/TestWorkspaceServices.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.Host { internal class TestWorkspaceServices : HostWorkspaceServices { - private static readonly Workspace DefaultWorkspace = TestWorkspace.Create(); + private static readonly Workspace s_defaultWorkspace = TestWorkspace.Create(); private readonly HostServices _hostServices; private readonly HostLanguageServices _razorLanguageServices; @@ -61,7 +61,7 @@ namespace Microsoft.CodeAnalysis.Host if (service == null) { // Fallback to default host services to resolve roslyn specific features. - service = DefaultWorkspace.Services.GetService(); + service = s_defaultWorkspace.Services.GetService(); } return service; @@ -75,7 +75,7 @@ namespace Microsoft.CodeAnalysis.Host } // Fallback to default host services to resolve roslyn specific features. - return DefaultWorkspace.Services.GetLanguageServices(languageName); + return s_defaultWorkspace.Services.GetLanguageServices(languageName); } public override IEnumerable SupportedLanguages => new[] { RazorLanguage.Name }; diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/Completion/DirectiveCompletionItemProviderTest.cs b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/Completion/DirectiveCompletionItemProviderTest.cs index 6e24ba5e9d..865d96e323 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/Completion/DirectiveCompletionItemProviderTest.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/Completion/DirectiveCompletionItemProviderTest.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.Razor.Completion { public class DirectiveCompletionItemProviderTest { - private static readonly IReadOnlyList DefaultDirectives = new[] + private static readonly IReadOnlyList s_defaultDirectives = new[] { CSharpCodeParser.AddTagHelperDirectiveDescriptor, CSharpCodeParser.RemoveTagHelperDirectiveDescriptor, @@ -31,9 +31,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion // Assert Assert.Collection( completionItems, - item => AssertRazorCompletionItem(DefaultDirectives[0], item), - item => AssertRazorCompletionItem(DefaultDirectives[1], item), - item => AssertRazorCompletionItem(DefaultDirectives[2], item)); + item => AssertRazorCompletionItem(s_defaultDirectives[0], item), + item => AssertRazorCompletionItem(s_defaultDirectives[1], item), + item => AssertRazorCompletionItem(s_defaultDirectives[2], item)); } [Fact] @@ -50,9 +50,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion Assert.Collection( completionItems, item => AssertRazorCompletionItem(customDirective, item), - item => AssertRazorCompletionItem(DefaultDirectives[0], item), - item => AssertRazorCompletionItem(DefaultDirectives[1], item), - item => AssertRazorCompletionItem(DefaultDirectives[2], item)); + item => AssertRazorCompletionItem(s_defaultDirectives[0], item), + item => AssertRazorCompletionItem(s_defaultDirectives[1], item), + item => AssertRazorCompletionItem(s_defaultDirectives[2], item)); } [Fact] @@ -73,9 +73,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion Assert.Collection( completionItems, item => AssertRazorCompletionItem("different", customDirective, item), - item => AssertRazorCompletionItem(DefaultDirectives[0], item), - item => AssertRazorCompletionItem(DefaultDirectives[1], item), - item => AssertRazorCompletionItem(DefaultDirectives[2], item)); + item => AssertRazorCompletionItem(s_defaultDirectives[0], item), + item => AssertRazorCompletionItem(s_defaultDirectives[1], item), + item => AssertRazorCompletionItem(s_defaultDirectives[2], item)); } [Fact] @@ -96,9 +96,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion Assert.Collection( completionItems, item => AssertRazorCompletionItem("code", customDirective, item, DirectiveCompletionItemProvider.BlockDirectiveCommitCharacters), - item => AssertRazorCompletionItem(DefaultDirectives[0], item), - item => AssertRazorCompletionItem(DefaultDirectives[1], item), - item => AssertRazorCompletionItem(DefaultDirectives[2], item)); + item => AssertRazorCompletionItem(s_defaultDirectives[0], item), + item => AssertRazorCompletionItem(s_defaultDirectives[1], item), + item => AssertRazorCompletionItem(s_defaultDirectives[2], item)); } [Fact] @@ -119,9 +119,9 @@ namespace Microsoft.CodeAnalysis.Razor.Completion Assert.Collection( completionItems, item => AssertRazorCompletionItem("section", customDirective, item, DirectiveCompletionItemProvider.BlockDirectiveCommitCharacters), - item => AssertRazorCompletionItem(DefaultDirectives[0], item), - item => AssertRazorCompletionItem(DefaultDirectives[1], item), - item => AssertRazorCompletionItem(DefaultDirectives[2], item)); + item => AssertRazorCompletionItem(s_defaultDirectives[0], item), + item => AssertRazorCompletionItem(s_defaultDirectives[1], item), + item => AssertRazorCompletionItem(s_defaultDirectives[2], item)); } [Fact] diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/MemoryCacheTest.cs b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/MemoryCacheTest.cs index 1fcacef08f..3ee98e0bc9 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/MemoryCacheTest.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/MemoryCacheTest.cs @@ -77,11 +77,11 @@ namespace Microsoft.CodeAnalysis.Razor.Test var key = GetKey(); var value = new List { (uint)i }; cache.Set(key, value); - Assert.False(cache.WasCompacted, "It got compacted early."); + Assert.False(cache._wasCompacted, "It got compacted early."); } cache.Set(GetKey(), new List { (uint)sizeLimit + 1 }); - Assert.True(cache.WasCompacted, "Compaction is not happening"); + Assert.True(cache._wasCompacted, "Compaction is not happening"); } [Fact] @@ -111,7 +111,7 @@ namespace Microsoft.CodeAnalysis.Razor.Test private class TestMemoryCache : MemoryCache> { public static int SizeLimit = 10; - public bool WasCompacted = false; + public bool _wasCompacted = false; public TestMemoryCache() : base(SizeLimit) { @@ -124,7 +124,7 @@ namespace Microsoft.CodeAnalysis.Razor.Test protected override void Compact() { - WasCompacted = true; + _wasCompacted = true; base.Compact(); } } diff --git a/src/Razor/test/Microsoft.CodeAnalysis.Remote.Razor.Test/Serialization/TagHelperResolutionResultSerializationTest.cs b/src/Razor/test/Microsoft.CodeAnalysis.Remote.Razor.Test/Serialization/TagHelperResolutionResultSerializationTest.cs index 93a88b73c7..01a80088ee 100644 --- a/src/Razor/test/Microsoft.CodeAnalysis.Remote.Razor.Test/Serialization/TagHelperResolutionResultSerializationTest.cs +++ b/src/Razor/test/Microsoft.CodeAnalysis.Remote.Razor.Test/Serialization/TagHelperResolutionResultSerializationTest.cs @@ -17,7 +17,7 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.Test { public class TagHelperResolutionResultSerializationTest { - private static readonly JsonConverter[] Converters = new JsonConverter[] + private static readonly JsonConverter[] s_converters = new JsonConverter[] { TagHelperDescriptorJsonConverter.Instance, RazorDiagnosticJsonConverter.Instance, @@ -110,13 +110,13 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.Test var serializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), - Converters = Converters, + Converters = s_converters, }; var expectedResult = new TagHelperResolutionResult(new[] { descriptor }, Array.Empty()); // Act var serialized = JsonConvert.SerializeObject(expectedResult, serializerSettings); - var result = JsonConvert.DeserializeObject(serialized, Converters); + var result = JsonConvert.DeserializeObject(serialized, s_converters); // Assert Assert.Equal(expectedResult, result, TagHelperResolutionResultComparer.Default); @@ -161,8 +161,8 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.Test var expectedResult = new TagHelperResolutionResult(new[] { descriptor }, Array.Empty()); // Act - var serialized = JsonConvert.SerializeObject(expectedResult, Converters); - var deserializedResult = JsonConvert.DeserializeObject(serialized, Converters); + var serialized = JsonConvert.SerializeObject(expectedResult, s_converters); + var deserializedResult = JsonConvert.DeserializeObject(serialized, s_converters); // Assert Assert.Equal(expectedResult, deserializedResult, TagHelperResolutionResultComparer.Default); @@ -207,8 +207,8 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.Test var expectedResult = new TagHelperResolutionResult(new[] { descriptor }, Array.Empty()); // Act - var serialized = JsonConvert.SerializeObject(expectedResult, Converters); - var deserializedResult = JsonConvert.DeserializeObject(serialized, Converters); + var serialized = JsonConvert.SerializeObject(expectedResult, s_converters); + var deserializedResult = JsonConvert.DeserializeObject(serialized, s_converters); // Assert Assert.Equal(expectedResult, deserializedResult, TagHelperResolutionResultComparer.Default); @@ -251,8 +251,8 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.Test var expectedResult = new TagHelperResolutionResult(new[] { descriptor }, Array.Empty()); // Act - var serialized = JsonConvert.SerializeObject(expectedResult, Converters); - var deserializedResult = JsonConvert.DeserializeObject(serialized, Converters); + var serialized = JsonConvert.SerializeObject(expectedResult, s_converters); + var deserializedResult = JsonConvert.DeserializeObject(serialized, s_converters); // Assert Assert.Equal(expectedResult, deserializedResult, TagHelperResolutionResultComparer.Default); @@ -296,8 +296,8 @@ namespace Microsoft.CodeAnalysis.Remote.Razor.Test var expectedResult = new TagHelperResolutionResult(new[] { descriptor }, Array.Empty()); // Act - var serialized = JsonConvert.SerializeObject(expectedResult, Converters); - var deserializedResult = JsonConvert.DeserializeObject(serialized, Converters); + var serialized = JsonConvert.SerializeObject(expectedResult, s_converters); + var deserializedResult = JsonConvert.DeserializeObject(serialized, s_converters); // Assert Assert.Equal(expectedResult, deserializedResult, TagHelperResolutionResultComparer.Default); diff --git a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceProviderTest.cs b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceProviderTest.cs index ef438b117d..764a78fd74 100644 --- a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceProviderTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceProviderTest.cs @@ -37,7 +37,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion // Assert var completionSourceImpl = Assert.IsType(completionSource); - Assert.Same(expectedParser, completionSourceImpl._parser); + Assert.Same(expectedParser, completionSourceImpl.Parser); } [Fact] diff --git a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceTest.cs b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceTest.cs index 4e3d70d753..c3e891fc79 100644 --- a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Completion/RazorDirectiveCompletionSourceTest.cs @@ -20,7 +20,7 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion { public class RazorDirectiveCompletionSourceTest : ForegroundDispatcherTestBase { - private static readonly IReadOnlyList DefaultDirectives = new[] + private static readonly IReadOnlyList s_defaultDirectives = new[] { CSharpCodeParser.AddTagHelperDirectiveDescriptor, CSharpCodeParser.RemoveTagHelperDirectiveDescriptor, @@ -89,9 +89,9 @@ namespace Microsoft.VisualStudio.Editor.Razor.Completion Assert.Collection( completionContext.Items, item => AssertRazorCompletionItem(SectionDirective.Directive, item, completionSource), - item => AssertRazorCompletionItem(DefaultDirectives[0], item, completionSource), - item => AssertRazorCompletionItem(DefaultDirectives[1], item, completionSource), - item => AssertRazorCompletionItem(DefaultDirectives[2], item, completionSource)); + item => AssertRazorCompletionItem(s_defaultDirectives[0], item, completionSource), + item => AssertRazorCompletionItem(s_defaultDirectives[1], item, completionSource), + item => AssertRazorCompletionItem(s_defaultDirectives[2], item, completionSource)); } [Fact] diff --git a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultProjectWorkspaceStateGeneratorTest.cs b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultProjectWorkspaceStateGeneratorTest.cs index 988f01be34..ccff8999e3 100644 --- a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultProjectWorkspaceStateGeneratorTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultProjectWorkspaceStateGeneratorTest.cs @@ -62,7 +62,7 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces stateGenerator.Update(WorkspaceProject, ProjectSnapshot, CancellationToken.None); // Assert - Assert.Empty(stateGenerator._updates); + Assert.Empty(stateGenerator.Updates); } } @@ -78,7 +78,7 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces stateGenerator.Update(WorkspaceProject, ProjectSnapshot, CancellationToken.None); // Assert - var update = Assert.Single(stateGenerator._updates); + var update = Assert.Single(stateGenerator.Updates); Assert.False(update.Value.Task.IsCompleted); } } @@ -91,7 +91,7 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces { stateGenerator.BlockBackgroundWorkStart = new ManualResetEventSlim(initialState: false); stateGenerator.Update(WorkspaceProject, ProjectSnapshot, CancellationToken.None); - var initialUpdate = stateGenerator._updates.Single().Value; + var initialUpdate = stateGenerator.Updates.Single().Value; // Act stateGenerator.Update(WorkspaceProject, ProjectSnapshot, CancellationToken.None); diff --git a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserIntegrationTest.cs b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserIntegrationTest.cs index 27883a1284..e41a9eb29b 100644 --- a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserIntegrationTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserIntegrationTest.cs @@ -48,7 +48,7 @@ namespace Microsoft.VisualStudio.Editor.Razor await manager.InitializeWithDocumentAsync(snapshot); // Assert - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); var codeDocument = await manager.InnerParser.GetLatestCodeDocumentAsync(snapshot); Assert.Equal(FileKinds.Component, codeDocument.GetFileKind()); @@ -75,13 +75,13 @@ namespace Microsoft.VisualStudio.Editor.Razor await manager.ApplyEditAndWaitForParseAsync(edit); // Assert - 1 - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); // Act - 2 await manager.ApplyEditAndWaitForParseAsync(edit); // Assert - 2 - Assert.Equal(3, manager.ParseCount); + Assert.Equal(3, manager._parseCount); } } @@ -100,7 +100,7 @@ namespace Microsoft.VisualStudio.Editor.Razor await manager.ApplyEditAndWaitForReparseAsync(edit); // Assert - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } @@ -122,7 +122,7 @@ namespace Microsoft.VisualStudio.Editor.Razor void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, changed.GetText(), expectedCode); }; @@ -167,7 +167,7 @@ namespace Microsoft.VisualStudio.Editor.Razor void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, changed.GetText(), expectedCode); }; @@ -198,7 +198,7 @@ namespace Microsoft.VisualStudio.Editor.Razor void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, testEdit.NewSnapshot.GetText(), expectedCode); }; @@ -217,7 +217,7 @@ namespace Microsoft.VisualStudio.Editor.Razor // Verify the reparse finally comes await manager.WaitForReparseAsync(); - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } @@ -233,7 +233,7 @@ namespace Microsoft.VisualStudio.Editor.Razor void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, testEdit.NewSnapshot.GetText(), expectedCode); }; @@ -262,7 +262,7 @@ namespace Microsoft.VisualStudio.Editor.Razor void ApplyAndVerifyPartialChange(TestEdit testEdit, string expectedCode) { manager.ApplyEdit(testEdit); - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, testEdit.NewSnapshot.GetText(), expectedCode); }; @@ -287,7 +287,7 @@ namespace Microsoft.VisualStudio.Editor.Razor // Verify the reparse eventually happens await manager.WaitForReparseAsync(); - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } @@ -304,7 +304,7 @@ namespace Microsoft.VisualStudio.Editor.Razor void ApplyAndVerifyPartialChange(Action applyEdit, string expectedCode) { applyEdit(); - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, changed.GetText(), expectedCode); }; @@ -340,7 +340,7 @@ namespace Microsoft.VisualStudio.Editor.Razor // Verify the reparse eventually happens await manager.WaitForReparseAsync(); - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); VerifyCurrentSyntaxTree(manager); } } @@ -363,7 +363,7 @@ namespace Microsoft.VisualStudio.Editor.Razor await manager.ApplyEditAndWaitForParseAsync(charTyped); // Assert - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); VerifyPartialParseTree(manager, charTyped.NewSnapshot.GetText()); } } @@ -386,7 +386,7 @@ namespace Microsoft.VisualStudio.Editor.Razor manager.ApplyEdit(charTyped); // Assert - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, charTyped.NewSnapshot.GetText()); } } @@ -405,7 +405,7 @@ namespace Microsoft.VisualStudio.Editor.Razor manager.ApplyEdit(edit); // Assert - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, edit.NewSnapshot.GetText()); } } @@ -427,7 +427,7 @@ namespace Microsoft.VisualStudio.Editor.Razor manager.ApplyEdit(edit2); // Assert - Assert.Equal(1, manager.ParseCount); + Assert.Equal(1, manager._parseCount); VerifyPartialParseTree(manager, edit2.NewSnapshot.GetText()); } } @@ -546,7 +546,7 @@ namespace Microsoft.VisualStudio.Editor.Razor new TestCompletionBroker()) { // We block idle work with the below reset events. Therefore, make tests fast and have the idle timer fire as soon as possible. - IdleDelay = TimeSpan.FromMilliseconds(1), + _idleDelay = TimeSpan.FromMilliseconds(1), NotifyForegroundIdleStart = new ManualResetEventSlim(), BlockBackgroundIdleWork = new ManualResetEventSlim(), }; @@ -602,7 +602,7 @@ namespace Microsoft.VisualStudio.Editor.Razor await manager.ApplyEditAndWaitForParseAsync(edit); // Assert - Assert.Equal(2, manager.ParseCount); + Assert.Equal(2, manager._parseCount); } } @@ -639,7 +639,7 @@ namespace Microsoft.VisualStudio.Editor.Razor private class TestParserManager : IDisposable { - public int ParseCount; + public int _parseCount; private readonly ManualResetEventSlim _parserComplete; private readonly ManualResetEventSlim _reparseComplete; @@ -652,14 +652,14 @@ namespace Microsoft.VisualStudio.Editor.Razor _reparseComplete = new ManualResetEventSlim(); _testBuffer = (TestTextBuffer)parser.TextBuffer; - ParseCount = 0; + _parseCount = 0; _parser = parser; parser.DocumentStructureChanged += (sender, args) => { CurrentSyntaxTree = args.CodeDocument.GetSyntaxTree(); - Interlocked.Increment(ref ParseCount); + Interlocked.Increment(ref _parseCount); if (args.SourceChange == null) { diff --git a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserTest.cs b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserTest.cs index f4905f3fda..391576449b 100644 --- a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultVisualStudioRazorParserTest.cs @@ -525,7 +525,7 @@ namespace Microsoft.VisualStudio.Editor.Razor Mock.Of(MockBehavior.Strict)) { BlockBackgroundIdleWork = new ManualResetEventSlim(), - IdleDelay = TimeSpan.FromSeconds(5) + _idleDelay = TimeSpan.FromSeconds(5) }) { parser.StartIdleTimer(); @@ -555,7 +555,7 @@ namespace Microsoft.VisualStudio.Editor.Razor Mock.Of(MockBehavior.Strict)) { BlockBackgroundIdleWork = new ManualResetEventSlim(), - IdleDelay = TimeSpan.FromSeconds(5) + _idleDelay = TimeSpan.FromSeconds(5) }) { parser.StartIdleTimer(); diff --git a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultWorkspaceEditorSettingsTest.cs b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultWorkspaceEditorSettingsTest.cs index 55a5750afb..d18128d857 100644 --- a/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultWorkspaceEditorSettingsTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultWorkspaceEditorSettingsTest.cs @@ -60,14 +60,14 @@ namespace Microsoft.VisualStudio.Editor.Razor { // Arrange var manager = new TestEditorSettingsManagerInternal(Dispatcher); - static void listener1(object caller, EditorSettingsChangedEventArgs args) { } - static void listener2(object caller, EditorSettingsChangedEventArgs args) { } - manager.Changed += listener1; - manager.Changed += listener2; + static void Listener1(object caller, EditorSettingsChangedEventArgs args) { } + static void Listener2(object caller, EditorSettingsChangedEventArgs args) { } + manager.Changed += Listener1; + manager.Changed += Listener2; // Act - manager.Changed -= listener1; - manager.Changed -= listener2; + manager.Changed -= Listener1; + manager.Changed -= Listener2; // Assert Assert.Equal(1, manager.DetachCount); diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/DefaultRazorProjectChangePublisherTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/DefaultRazorProjectChangePublisherTest.cs index 6ad87f44e2..05e69bbdd1 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/DefaultRazorProjectChangePublisherTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/DefaultRazorProjectChangePublisherTest.cs @@ -63,7 +63,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test public class DefaultRazorProjectChangePublisherTest : LanguageServerTestBase { - private readonly RazorLogger RazorLogger = Mock.Of(MockBehavior.Strict); + private readonly RazorLogger _razorLogger = Mock.Of(MockBehavior.Strict); public DefaultRazorProjectChangePublisherTest() { @@ -84,7 +84,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test ProjectSnapshotManager.ProjectAdded(hostProject); var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => attemptedToSerialize = true) { EnqueueDelay = 10, @@ -95,7 +95,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test ProjectSnapshotManager.DocumentAdded(hostProject, hostDocument, new EmptyTextLoader(hostDocument.FilePath)); // Assert - Assert.Empty(publisher._deferredPublishTasks); + Assert.Empty(publisher.DeferredPublishTasks); Assert.False(attemptedToSerialize); } @@ -110,7 +110,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test ProjectSnapshotManager.DocumentAdded(hostProject, hostDocument, new EmptyTextLoader(hostDocument.FilePath)); var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => attemptedToSerialize = true) { EnqueueDelay = 10, @@ -121,7 +121,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test ProjectSnapshotManager.DocumentOpened(hostProject.FilePath, hostDocument.FilePath, SourceText.From(string.Empty)); // Assert - Assert.Empty(publisher._deferredPublishTasks); + Assert.Empty(publisher.DeferredPublishTasks); Assert.False(attemptedToSerialize); } @@ -140,7 +140,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test ProjectConfigurationFilePathStore.Set(projectSnapshot.FilePath, expectedConfigurationFilePath); var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Equal(expectedConfigurationFilePath, configurationFilePath); @@ -155,7 +155,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test ProjectSnapshotManager.DocumentOpened(hostProject.FilePath, hostDocument.FilePath, SourceText.From(string.Empty)); // Assert - Assert.Empty(publisher._deferredPublishTasks); + Assert.Empty(publisher.DeferredPublishTasks); Assert.True(serializationSuccessful); } @@ -171,7 +171,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var expectedConfigurationFilePath = "/path/to/obj/bin/Debug/project.razor.json"; var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Same(projectSnapshot, snapshot); @@ -190,7 +190,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test publisher.ProjectSnapshotManager_Changed(null, args); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.True(serializationSuccessful); } @@ -204,7 +204,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var expectedConfigurationFilePath = "/path/to/obj/bin/Debug/project.razor.json"; var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => attemptedToSerialize = true) { EnqueueDelay = 10, @@ -219,7 +219,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test publisher.ProjectSnapshotManager_Changed(null, args); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.False(attemptedToSerialize); @@ -235,7 +235,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var expectedConfigurationFilePath = "/path/to/obj/bin/Debug/project.razor.json"; var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Same(secondSnapshot, snapshot); @@ -254,7 +254,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test publisher.EnqueuePublish(secondSnapshot); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.True(serializationSuccessful); } @@ -269,7 +269,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var expectedConfigurationFilePath = "/path/to/obj/bin/Debug/project.razor.json"; var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Same(secondSnapshot, snapshot); @@ -288,7 +288,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test publisher.EnqueuePublish(secondSnapshot); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.True(serializationSuccessful); } @@ -309,7 +309,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var expectedConfigurationFilePath = "/path/to/obj/bin/Debug/project.razor.json"; var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Same(secondSnapshot, snapshot); @@ -328,7 +328,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test publisher.EnqueuePublish(secondSnapshot); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.False(serializationSuccessful); } @@ -339,7 +339,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test // Arrange var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger) + _razorLogger) { _active = true, }; @@ -359,7 +359,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var expectedConfigurationFilePath = "/path/to/obj/bin/Debug/project.razor.json"; var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Same(omniSharpProjectSnapshot, snapshot); @@ -388,7 +388,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Equal(expectedConfigurationFilePath, configurationFilePath); @@ -411,7 +411,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test }).ConfigureAwait(false); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.True(serializationSuccessful); } @@ -425,7 +425,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.True(false, "Serialization should not have been atempted because there is no ProjectWorkspaceState."); @@ -441,7 +441,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test // Act await RunOnForegroundAsync(() => ProjectSnapshotManager.ProjectAdded(hostProject)).ConfigureAwait(false); - Assert.Empty(publisher._deferredPublishTasks); + Assert.Empty(publisher.DeferredPublishTasks); // Assert Assert.False(serializationSuccessful); @@ -453,7 +453,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test // Arrange var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger) + _razorLogger) { _active = true, }; @@ -464,7 +464,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test // Act & Assert await RunOnForegroundAsync(() => ProjectSnapshotManager.ProjectRemoved(hostProject)).ConfigureAwait(false); - Assert.Empty(publisher._deferredPublishTasks); + Assert.Empty(publisher.DeferredPublishTasks); } [ForegroundFact] @@ -476,7 +476,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test var publisher = new TestDefaultRazorProjectChangePublisher( ProjectConfigurationFilePathStore, - RazorLogger, + _razorLogger, onSerializeToFile: (snapshot, configurationFilePath) => { Assert.Equal(expectedConfigurationFilePath, configurationFilePath); @@ -500,7 +500,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test }).ConfigureAwait(false); // Assert - var kvp = Assert.Single(publisher._deferredPublishTasks); + var kvp = Assert.Single(publisher.DeferredPublishTasks); await kvp.Value.ConfigureAwait(false); Assert.False(serializationSuccessful); } @@ -561,7 +561,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test private class TestDefaultRazorProjectChangePublisher : DefaultRazorProjectChangePublisher { - private static readonly Mock _lspEditorFeatureDetector = new Mock(MockBehavior.Strict); + private static readonly Mock s_lspEditorFeatureDetector = new Mock(MockBehavior.Strict); private readonly Action _onSerializeToFile; @@ -570,7 +570,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test static TestDefaultRazorProjectChangePublisher() { - _lspEditorFeatureDetector + s_lspEditorFeatureDetector .Setup(t => t.IsLSPEditorAvailable()) .Returns(true); } @@ -581,9 +581,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.Test Action onSerializeToFile = null, bool shouldSerialize = true, bool useRealShouldSerialize = false) - : base(_lspEditorFeatureDetector.Object, projectStatePublishFilePathStore, new TestServiceProvider(), logger) + : base(s_lspEditorFeatureDetector.Object, projectStatePublishFilePathStore, new TestServiceProvider(), logger) { - _onSerializeToFile = onSerializeToFile ?? ((_, __) => throw new XunitException("SerializeToFile should not have been called.")); + _onSerializeToFile = onSerializeToFile ?? ((_1, _2) => throw new XunitException("SerializeToFile should not have been called.")); _shouldSerialize = shouldSerialize; _useRealShouldSerialize = useRealShouldSerialize; } diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DefaultLSPProgressListenerTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DefaultLSPProgressListenerTest.cs index cb124a5461..2f561d31b9 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DefaultLSPProgressListenerTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DefaultLSPProgressListenerTest.cs @@ -19,7 +19,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp public class DefaultLSPProgressListenerTest { // Long timeout after last notification to avoid triggering even in slow CI environments - private static readonly TimeSpan NotificationTimeout = TimeSpan.FromSeconds(20); + private static readonly TimeSpan s_notificationTimeout = TimeSpan.FromSeconds(20); [Fact] public void TryListenForProgress_ReturnsTrue() @@ -36,7 +36,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var listenerAdded = lspProgressListener.TryListenForProgress( token, onProgressNotifyAsync: async (value, ct) => await Task.Delay(1).ConfigureAwait(false), - delayAfterLastNotifyAsync: cancellationToken => Task.Delay(NotificationTimeout, cancellationToken), + delayAfterLastNotifyAsync: cancellationToken => Task.Delay(s_notificationTimeout, cancellationToken), cts.Token, out var onCompleted); @@ -61,13 +61,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp _ = lspProgressListener.TryListenForProgress( token, onProgressNotifyAsync: async (value, ct) => await Task.Delay(1).ConfigureAwait(false), - delayAfterLastNotifyAsync: cancellationToken => Task.Delay(NotificationTimeout, cancellationToken), + delayAfterLastNotifyAsync: cancellationToken => Task.Delay(s_notificationTimeout, cancellationToken), cts.Token, out _); var listenerAdded = lspProgressListener.TryListenForProgress( token, onProgressNotifyAsync: async (value, ct) => await Task.Delay(1).ConfigureAwait(false), - delayAfterLastNotifyAsync: cancellationToken => Task.Delay(NotificationTimeout, cancellationToken), + delayAfterLastNotifyAsync: cancellationToken => Task.Delay(s_notificationTimeout, cancellationToken), cts.Token, out var onCompleted); @@ -162,7 +162,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp using var completedTokenSource = new CancellationTokenSource(); var onProgressNotifyAsyncCalled = false; - Task onProgressNotifyAsync(JToken value, CancellationToken ct) + Task OnProgressNotifyAsync(JToken value, CancellationToken ct) { var result = value.ToObject(); var firstValue = Assert.Single(result); @@ -177,8 +177,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // Act var listenerAdded = lspProgressListener.TryListenForProgress( token, - onProgressNotifyAsync: onProgressNotifyAsync, - delayAfterLastNotifyAsync: cancellationToken => DelayAfterLastNotifyAsync(NotificationTimeout, completedTokenSource.Token, cancellationToken), + onProgressNotifyAsync: OnProgressNotifyAsync, + delayAfterLastNotifyAsync: cancellationToken => DelayAfterLastNotifyAsync(s_notificationTimeout, completedTokenSource.Token, cancellationToken), cts.Token, out var onCompleted); @@ -213,7 +213,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp using var completedTokenSource = new CancellationTokenSource(); var receivedResults = new ConcurrentBag(); - Task onProgressNotifyAsync(JToken value, CancellationToken ct) + Task OnProgressNotifyAsync(JToken value, CancellationToken ct) { receivedResults.Add(value.ToObject()); if (receivedResults.Count == NUM_NOTIFICATIONS) @@ -228,8 +228,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // Act var listenerAdded = lspProgressListener.TryListenForProgress( token, - onProgressNotifyAsync: onProgressNotifyAsync, - delayAfterLastNotifyAsync: cancellationToken => DelayAfterLastNotifyAsync(NotificationTimeout, completedTokenSource.Token, cancellationToken), + onProgressNotifyAsync: OnProgressNotifyAsync, + delayAfterLastNotifyAsync: cancellationToken => DelayAfterLastNotifyAsync(s_notificationTimeout, completedTokenSource.Token, cancellationToken), cts.Token, out var onCompleted); diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DocumentPullDiagnosticsHandlerTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DocumentPullDiagnosticsHandlerTest.cs index 44b124c8f2..320d66af80 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DocumentPullDiagnosticsHandlerTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/DocumentPullDiagnosticsHandlerTest.cs @@ -19,7 +19,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp { public class DocumentPullDiagnosticsHandlerTest { - private static readonly Diagnostic ValidDiagnostic_UnknownName = new Diagnostic() + private static readonly Diagnostic s_validDiagnostic_UnknownName = new Diagnostic() { Range = new Range() { @@ -31,13 +31,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp Message = "The name 'saflkjklj' does not exist in the current context" }; - private static readonly Range ValidDiagnostic_UnknownName_MappedRange = new Range() + private static readonly Range s_validDiagnostic_UnknownName_MappedRange = new Range() { Start = new Position(49, 19), End = new Position(49, 23) }; - private static readonly Diagnostic ValidDiagnostic_InvalidExpression = new Diagnostic() + private static readonly Diagnostic s_validDiagnostic_InvalidExpression = new Diagnostic() { Range = new Range() { @@ -49,13 +49,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp Message = "Invalid expression term 'bool'" }; - private static readonly Range ValidDiagnostic_InvalidExpression_MappedRange = new Range() + private static readonly Range s_validDiagnostic_InvalidExpression_MappedRange = new Range() { Start = new Position(50, 19), End = new Position(50, 23) }; - private static readonly Diagnostic UnusedUsingsDiagnostic = new Diagnostic() + private static readonly Diagnostic s_unusedUsingsDiagnostic = new Diagnostic() { Range = new Range() { @@ -67,7 +67,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp Message = "Using directive is unnecessary." }; - private static readonly Diagnostic RemoveUnnecessaryImportsFixableDiagnostic = new Diagnostic() + private static readonly Diagnostic s_removeUnnecessaryImportsFixableDiagnostic = new Diagnostic() { Range = new Range() { @@ -78,17 +78,17 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp Source = "DocumentPullDiagnosticHandler", }; - private static readonly DiagnosticReport[] RoslynDiagnosticResponse = new DiagnosticReport[] + private static readonly DiagnosticReport[] s_roslynDiagnosticResponse = new DiagnosticReport[] { new DiagnosticReport() { ResultId = "5", Diagnostics = new Diagnostic[] { - ValidDiagnostic_UnknownName, - ValidDiagnostic_InvalidExpression, - UnusedUsingsDiagnostic, - RemoveUnnecessaryImportsFixableDiagnostic + s_validDiagnostic_UnknownName, + s_validDiagnostic_InvalidExpression, + s_unusedUsingsDiagnostic, + s_removeUnnecessaryImportsFixableDiagnostic } } }; @@ -135,7 +135,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var documentManager = CreateDocumentManager(); var requestInvoker = GetRequestInvoker( - RoslynDiagnosticResponse, + s_roslynDiagnosticResponse, (method, serverContentType, diagnosticParams, ct) => { Assert.Equal(MSLSPMethods.DocumentPullDiagnosticName, method); @@ -143,7 +143,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp called = true; }); - var diagnosticsProvider = GetDiagnosticsProvider(ValidDiagnostic_UnknownName_MappedRange, ValidDiagnostic_InvalidExpression_MappedRange); + var diagnosticsProvider = GetDiagnosticsProvider(s_validDiagnostic_UnknownName_MappedRange, s_validDiagnostic_InvalidExpression_MappedRange); var documentSynchronizer = CreateDocumentSynchronizer(); var documentDiagnosticsHandler = new DocumentPullDiagnosticsHandler(requestInvoker, documentManager, documentSynchronizer, diagnosticsProvider, LoggerProvider); @@ -159,17 +159,17 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // Assert Assert.True(called); var diagnosticReport = Assert.Single(result); - Assert.Equal(RoslynDiagnosticResponse.First().ResultId, diagnosticReport.ResultId); + Assert.Equal(s_roslynDiagnosticResponse.First().ResultId, diagnosticReport.ResultId); Assert.Collection(diagnosticReport.Diagnostics, d => { - Assert.Equal(ValidDiagnostic_UnknownName.Code, d.Code); - Assert.Equal(ValidDiagnostic_UnknownName_MappedRange, d.Range); + Assert.Equal(s_validDiagnostic_UnknownName.Code, d.Code); + Assert.Equal(s_validDiagnostic_UnknownName_MappedRange, d.Range); }, d => { - Assert.Equal(ValidDiagnostic_InvalidExpression.Code, d.Code); - Assert.Equal(ValidDiagnostic_InvalidExpression_MappedRange, d.Range); + Assert.Equal(s_validDiagnostic_InvalidExpression.Code, d.Code); + Assert.Equal(s_validDiagnostic_InvalidExpression_MappedRange, d.Range); }); } @@ -181,7 +181,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var documentManager = CreateDocumentManager(); var requestInvoker = GetRequestInvoker( - RoslynDiagnosticResponse, + s_roslynDiagnosticResponse, (method, serverContentType, diagnosticParams, ct) => { Assert.Equal(MSLSPMethods.DocumentPullDiagnosticName, method); @@ -189,7 +189,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp called = true; }); - var diagnosticsProvider = GetDiagnosticsProvider(ValidDiagnostic_UnknownName_MappedRange, ValidDiagnostic_InvalidExpression_MappedRange); + var diagnosticsProvider = GetDiagnosticsProvider(s_validDiagnostic_UnknownName_MappedRange, s_validDiagnostic_InvalidExpression_MappedRange); var documentSynchronizer = new Mock(MockBehavior.Strict); documentSynchronizer @@ -357,7 +357,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var documentManager = CreateDocumentManager(hostDocumentVersion: 1); var requestInvoker = GetRequestInvoker( - RoslynDiagnosticResponse, + s_roslynDiagnosticResponse, (method, serverContentType, diagnosticParams, ct) => { Assert.Equal(MSLSPMethods.DocumentPullDiagnosticName, method); @@ -367,7 +367,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // Note the HostDocumentVersion provided by the DiagnosticsProvider = 0, // which is different from document version (1) from the DocumentManager - var diagnosticsProvider = GetDiagnosticsProvider(ValidDiagnostic_UnknownName_MappedRange, ValidDiagnostic_InvalidExpression_MappedRange); + var diagnosticsProvider = GetDiagnosticsProvider(s_validDiagnostic_UnknownName_MappedRange, s_validDiagnostic_InvalidExpression_MappedRange); var documentSynchronizer = CreateDocumentSynchronizer(); var documentDiagnosticsHandler = new DocumentPullDiagnosticsHandler(requestInvoker, documentManager, documentSynchronizer, diagnosticsProvider, LoggerProvider); @@ -383,7 +383,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // Assert Assert.True(called); var returnedReport = Assert.Single(result); - Assert.Equal(RoslynDiagnosticResponse.First().ResultId, returnedReport.ResultId); + Assert.Equal(s_roslynDiagnosticResponse.First().ResultId, returnedReport.ResultId); Assert.Null(returnedReport.Diagnostics); } @@ -395,7 +395,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var documentManager = CreateDocumentManager(); var requestInvoker = GetRequestInvoker( - RoslynDiagnosticResponse, + s_roslynDiagnosticResponse, (method, serverContentType, diagnosticParams, ct) => { Assert.Equal(MSLSPMethods.DocumentPullDiagnosticName, method); @@ -419,7 +419,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp // Assert Assert.True(called); var returnedReport = Assert.Single(result); - Assert.Equal(RoslynDiagnosticResponse.First().ResultId, returnedReport.ResultId); + Assert.Equal(s_roslynDiagnosticResponse.First().ResultId, returnedReport.ResultId); Assert.Null(returnedReport.Diagnostics); } diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/OnTypeRenameHandlerTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/OnTypeRenameHandlerTest.cs index 9ddbe73b96..0323513888 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/OnTypeRenameHandlerTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/HtmlCSharp/OnTypeRenameHandlerTest.cs @@ -14,7 +14,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp { public class OnTypeRenameHandlerTest : HandlerTestBase { - private static readonly Uri Uri = new Uri("C:/path/to/file.razor"); + private static readonly Uri s_uri = new Uri("C:/path/to/file.razor"); [Fact] public async Task HandleRequestAsync_DocumentNotFound_ReturnsNull() @@ -27,7 +27,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var onTypeRenameHandler = new OnTypeRenameHandler(documentManager, requestInvoker, projectionProvider, documentMappingProvider, LoggerProvider); var onTypeRenameRequest = new DocumentOnTypeRenameParams() { - TextDocument = new TextDocumentIdentifier() { Uri = Uri }, + TextDocument = new TextDocumentIdentifier() { Uri = s_uri }, Position = new Position(0, 1) }; @@ -43,7 +43,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp { // Arrange var documentManager = new TestDocumentManager(); - documentManager.AddDocument(Uri, Mock.Of(MockBehavior.Strict)); + documentManager.AddDocument(s_uri, Mock.Of(MockBehavior.Strict)); var requestInvoker = Mock.Of(MockBehavior.Strict); var projectionProvider = new Mock(MockBehavior.Strict).Object; Mock.Get(projectionProvider).Setup(projectionProvider => projectionProvider.GetProjectionAsync(It.IsAny(), It.IsAny(), CancellationToken.None)) @@ -52,7 +52,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var onTypeRenameHandler = new OnTypeRenameHandler(documentManager, requestInvoker, projectionProvider, documentMappingProvider, LoggerProvider); var onTypeRenameRequest = new DocumentOnTypeRenameParams() { - TextDocument = new TextDocumentIdentifier() { Uri = Uri }, + TextDocument = new TextDocumentIdentifier() { Uri = s_uri }, Position = new Position(0, 1) }; @@ -68,7 +68,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp { // Arrange var documentManager = new TestDocumentManager(); - documentManager.AddDocument(Uri, Mock.Of(d => d.Version == 0, MockBehavior.Strict)); + documentManager.AddDocument(s_uri, Mock.Of(d => d.Version == 0, MockBehavior.Strict)); var requestInvoker = Mock.Of(MockBehavior.Strict); var documentMappingProvider = Mock.Of(MockBehavior.Strict); @@ -81,7 +81,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var onTypeRenameHandler = new OnTypeRenameHandler(documentManager, requestInvoker, projectionProvider, documentMappingProvider, LoggerProvider); var onTypeRenameRequest = new DocumentOnTypeRenameParams() { - TextDocument = new TextDocumentIdentifier() { Uri = Uri }, + TextDocument = new TextDocumentIdentifier() { Uri = s_uri }, Position = new Position(10, 5) }; @@ -99,7 +99,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var invokerCalled = false; var expectedResponse = GetMatchingHTMLBracketRange(5); var documentManager = new TestDocumentManager(); - documentManager.AddDocument(Uri, Mock.Of(d => d.Version == 0, MockBehavior.Strict)); + documentManager.AddDocument(s_uri, Mock.Of(d => d.Version == 0, MockBehavior.Strict)); var htmlResponse = GetMatchingHTMLBracketRange(10); var requestInvoker = GetRequestInvoker( @@ -123,7 +123,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var onTypeRenameHandler = new OnTypeRenameHandler(documentManager, requestInvoker, projectionProvider, documentMappingProvider, LoggerProvider); var onTypeRenameRequest = new DocumentOnTypeRenameParams() { - TextDocument = new TextDocumentIdentifier() { Uri = Uri }, + TextDocument = new TextDocumentIdentifier() { Uri = s_uri }, Position = new Position(10, 5) }; @@ -145,7 +145,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var invokerCalled = false; var expectedResponse = GetMatchingHTMLBracketRange(5); var documentManager = new TestDocumentManager(); - documentManager.AddDocument(Uri, Mock.Of(d => d.Version == 1, MockBehavior.Strict)); + documentManager.AddDocument(s_uri, Mock.Of(d => d.Version == 1, MockBehavior.Strict)); var htmlResponse = GetMatchingHTMLBracketRange(10); var requestInvoker = GetRequestInvoker( @@ -169,7 +169,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var onTypeRenameHandler = new OnTypeRenameHandler(documentManager, requestInvoker, projectionProvider, documentMappingProvider, LoggerProvider); var onTypeRenameRequest = new DocumentOnTypeRenameParams() { - TextDocument = new TextDocumentIdentifier() { Uri = Uri }, + TextDocument = new TextDocumentIdentifier() { Uri = s_uri }, Position = new Position(10, 5) }; @@ -188,7 +188,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var invokerCalled = false; var expectedResponse = GetMatchingHTMLBracketRange(5); var documentManager = new TestDocumentManager(); - documentManager.AddDocument(Uri, Mock.Of(d => d.Version == 0, MockBehavior.Strict)); + documentManager.AddDocument(s_uri, Mock.Of(d => d.Version == 0, MockBehavior.Strict)); var htmlResponse = GetMatchingHTMLBracketRange(10); var requestInvoker = GetRequestInvoker( @@ -208,13 +208,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp var projectionProvider = GetProjectionProvider(projectionResult); var documentMappingProvider = new Mock(MockBehavior.Strict).Object; - Mock.Get(documentMappingProvider).Setup(p => p.MapToDocumentRangesAsync(RazorLanguageKind.Html, Uri, It.IsAny(), CancellationToken.None)) + Mock.Get(documentMappingProvider).Setup(p => p.MapToDocumentRangesAsync(RazorLanguageKind.Html, s_uri, It.IsAny(), CancellationToken.None)) .Returns(Task.FromResult(null)); var onTypeRenameHandler = new OnTypeRenameHandler(documentManager, requestInvoker, projectionProvider, documentMappingProvider, LoggerProvider); var onTypeRenameRequest = new DocumentOnTypeRenameParams() { - TextDocument = new TextDocumentIdentifier() { Uri = Uri }, + TextDocument = new TextDocumentIdentifier() { Uri = s_uri }, Position = new Position(10, 5) }; @@ -253,7 +253,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp HostDocumentVersion = expectedVersion }; var documentMappingProvider = new Mock(MockBehavior.Strict); - documentMappingProvider.Setup(d => d.MapToDocumentRangesAsync(languageKind, Uri, It.IsAny(), It.IsAny())). + documentMappingProvider.Setup(d => d.MapToDocumentRangesAsync(languageKind, s_uri, It.IsAny(), It.IsAny())). Returns(Task.FromResult(remappingResult)); return documentMappingProvider.Object; diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorHtmlPublishDiagnosticsInterceptorTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorHtmlPublishDiagnosticsInterceptorTest.cs index b0b6cb3716..a398f327ae 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorHtmlPublishDiagnosticsInterceptorTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorHtmlPublishDiagnosticsInterceptorTest.cs @@ -21,12 +21,12 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { public class RazorHtmlPublishDiagnosticsInterceptorTest { - private static readonly Uri RazorUri = new Uri("C:/path/to/file.razor"); - private static readonly Uri CshtmlUri = new Uri("C:/path/to/file.cshtml"); - private static readonly Uri RazorVirtualHtmlUri = new Uri("C:/path/to/file.razor__virtual.html"); - private static readonly Uri RazorVirtualCssUri = new Uri("C:/path/to/file.razor__virtual.css"); + private static readonly Uri s_razorUri = new Uri("C:/path/to/file.razor"); + private static readonly Uri s_cshtmlUri = new Uri("C:/path/to/file.cshtml"); + private static readonly Uri s_razorVirtualHtmlUri = new Uri("C:/path/to/file.razor__virtual.html"); + private static readonly Uri s_razorVirtualCssUri = new Uri("C:/path/to/file.razor__virtual.css"); - private static readonly Diagnostic ValidDiagnostic_HTML = new Diagnostic() + private static readonly Diagnostic s_validDiagnostic_HTML = new Diagnostic() { Range = new Range() { @@ -36,7 +36,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor Code = null }; - private static readonly Diagnostic ValidDiagnostic_CSS = new Diagnostic() + private static readonly Diagnostic s_validDiagnostic_CSS = new Diagnostic() { Range = new Range() { @@ -46,10 +46,10 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor Code = "expectedSemicolon", }; - private static readonly Diagnostic[] Diagnostics = new Diagnostic[] + private static readonly Diagnostic[] s_diagnostics = new Diagnostic[] { - ValidDiagnostic_HTML, - ValidDiagnostic_CSS + s_validDiagnostic_HTML, + s_validDiagnostic_CSS }; public RazorHtmlPublishDiagnosticsInterceptorTest() @@ -76,7 +76,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { TextDocument = new TextDocumentIdentifier() { - Uri = RazorUri + Uri = s_razorUri } }; @@ -98,9 +98,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var htmlDiagnosticsInterceptor = new RazorHtmlPublishDiagnosticsInterceptor(documentManager, diagnosticsProvider, LoggerProvider); var diagnosticRequest = new VSPublishDiagnosticParams() { - Diagnostics = Diagnostics, + Diagnostics = s_diagnostics, Mode = null, - Uri = RazorUri + Uri = s_razorUri }; var token = JToken.FromObject(diagnosticRequest); @@ -122,9 +122,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var htmlDiagnosticsInterceptor = new RazorHtmlPublishDiagnosticsInterceptor(documentManager, diagnosticsProvider, LoggerProvider); var diagnosticRequest = new VSPublishDiagnosticParams() { - Diagnostics = Diagnostics, + Diagnostics = s_diagnostics, Mode = null, - Uri = CshtmlUri + Uri = s_cshtmlUri }; var token = JToken.FromObject(diagnosticRequest); @@ -146,9 +146,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var htmlDiagnosticsInterceptor = new RazorHtmlPublishDiagnosticsInterceptor(documentManager, diagnosticsProvider, LoggerProvider); var diagnosticRequest = new VSPublishDiagnosticParams() { - Diagnostics = Diagnostics, + Diagnostics = s_diagnostics, Mode = null, - Uri = RazorVirtualCssUri + Uri = s_razorVirtualCssUri }; var token = JToken.FromObject(diagnosticRequest); @@ -170,9 +170,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var htmlDiagnosticsInterceptor = new RazorHtmlPublishDiagnosticsInterceptor(documentManager, diagnosticsProvider, LoggerProvider); var diagnosticRequest = new VSPublishDiagnosticParams() { - Diagnostics = Diagnostics, + Diagnostics = s_diagnostics, Mode = null, - Uri = RazorVirtualHtmlUri + Uri = s_razorVirtualHtmlUri }; // Act @@ -181,7 +181,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Assert var updatedParams = result.UpdatedToken.ToObject(); Assert.Empty(updatedParams.Diagnostics); - Assert.Equal(RazorUri, updatedParams.Uri); + Assert.Equal(s_razorUri, updatedParams.Uri); Assert.True(result.ChangedDocumentUri); } @@ -191,8 +191,8 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Arrange var diagnosticsProvider = Mock.Of(MockBehavior.Strict); - var testVirtualDocument = new TestVirtualDocumentSnapshot(RazorUri, hostDocumentVersion: 0); - LSPDocumentSnapshot testDocument = new TestLSPDocumentSnapshot(RazorUri, version: 0, testVirtualDocument); + var testVirtualDocument = new TestVirtualDocumentSnapshot(s_razorUri, hostDocumentVersion: 0); + LSPDocumentSnapshot testDocument = new TestLSPDocumentSnapshot(s_razorUri, version: 0, testVirtualDocument); var documentManager = new Mock(MockBehavior.Strict); documentManager.Setup(manager => manager.TryGetDocument(It.IsAny(), out testDocument)) .Returns(true); @@ -200,9 +200,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var htmlDiagnosticsInterceptor = new RazorHtmlPublishDiagnosticsInterceptor(documentManager.Object, diagnosticsProvider, LoggerProvider); var diagnosticRequest = new VSPublishDiagnosticParams() { - Diagnostics = Diagnostics, + Diagnostics = s_diagnostics, Mode = null, - Uri = RazorVirtualHtmlUri + Uri = s_razorVirtualHtmlUri }; // Act @@ -211,7 +211,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Assert var updatedParams = result.UpdatedToken.ToObject(); Assert.Empty(updatedParams.Diagnostics); - Assert.Equal(RazorUri, updatedParams.Uri); + Assert.Equal(s_razorUri, updatedParams.Uri); Assert.True(result.ChangedDocumentUri); } @@ -227,7 +227,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { Diagnostics = Array.Empty(), Mode = null, - Uri = RazorVirtualHtmlUri + Uri = s_razorVirtualHtmlUri }; // Act @@ -236,7 +236,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Assert var updatedParams = result.UpdatedToken.ToObject(); Assert.Empty(updatedParams.Diagnostics); - Assert.Equal(RazorUri, updatedParams.Uri); + Assert.Equal(s_razorUri, updatedParams.Uri); Assert.True(result.ChangedDocumentUri); } @@ -250,9 +250,9 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var htmlDiagnosticsInterceptor = new RazorHtmlPublishDiagnosticsInterceptor(documentManager, diagnosticsProvider, LoggerProvider); var diagnosticRequest = new VSPublishDiagnosticParams() { - Diagnostics = Diagnostics, + Diagnostics = s_diagnostics, Mode = null, - Uri = RazorVirtualHtmlUri + Uri = s_razorVirtualHtmlUri }; // Act @@ -260,17 +260,17 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Assert var updatedParams = result.UpdatedToken.ToObject(); - Assert.Equal(Diagnostics, updatedParams.Diagnostics); - Assert.Equal(RazorUri, updatedParams.Uri); + Assert.Equal(s_diagnostics, updatedParams.Diagnostics); + Assert.Equal(s_razorUri, updatedParams.Uri); Assert.True(result.ChangedDocumentUri); } private static TrackingLSPDocumentManager CreateDocumentManager(int hostDocumentVersion = 0) { - var testVirtualDocUri = RazorVirtualHtmlUri; - var testVirtualDocument = new TestVirtualDocumentSnapshot(RazorUri, hostDocumentVersion); + var testVirtualDocUri = s_razorVirtualHtmlUri; + var testVirtualDocument = new TestVirtualDocumentSnapshot(s_razorUri, hostDocumentVersion); var htmlVirtualDocument = new HtmlVirtualDocumentSnapshot(testVirtualDocUri, Mock.Of(MockBehavior.Strict), hostDocumentVersion); - LSPDocumentSnapshot testDocument = new TestLSPDocumentSnapshot(RazorUri, hostDocumentVersion, testVirtualDocument, htmlVirtualDocument); + LSPDocumentSnapshot testDocument = new TestLSPDocumentSnapshot(s_razorUri, hostDocumentVersion, testVirtualDocument, htmlVirtualDocument); var documentManager = new Mock(MockBehavior.Strict); documentManager.Setup(manager => manager.TryGetDocument(It.IsAny(), out testDocument)) .Returns(true); @@ -289,7 +289,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor diagnosticsProvider.Setup(d => d.TranslateAsync( RazorLanguageKind.Html, - RazorUri, + s_razorUri, It.IsAny(), It.IsAny())) .Returns((RazorLanguageKind lang, Uri uri, Diagnostic[] diagnostics, CancellationToken ct) => diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLSPSpanMappingServiceTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLSPSpanMappingServiceTest.cs index 54320382db..d2bc5732f8 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLSPSpanMappingServiceTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLSPSpanMappingServiceTest.cs @@ -19,13 +19,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { public class RazorLSPSpanMappingServiceTest { - private readonly Uri MockDocumentUri = new Uri("C://project/path/document.razor"); + private readonly Uri _mockDocumentUri = new Uri("C://project/path/document.razor"); - private static readonly string MockGeneratedContent = $"Hello {Environment.NewLine} This is the source text in the generated C# file. {Environment.NewLine} This is some more sample text for demo purposes."; - private static readonly string MockRazorContent = $"Hello {Environment.NewLine} This is the {Environment.NewLine} source text {Environment.NewLine} in the generated C# file. {Environment.NewLine} This is some more sample text for demo purposes."; + private static readonly string s_mockGeneratedContent = $"Hello {Environment.NewLine} This is the source text in the generated C# file. {Environment.NewLine} This is some more sample text for demo purposes."; + private static readonly string s_mockRazorContent = $"Hello {Environment.NewLine} This is the {Environment.NewLine} source text {Environment.NewLine} in the generated C# file. {Environment.NewLine} This is some more sample text for demo purposes."; - private readonly SourceText SourceTextGenerated = SourceText.From(MockGeneratedContent); - private readonly SourceText SourceTextRazor = SourceText.From(MockRazorContent); + private readonly SourceText _sourceTextGenerated = SourceText.From(s_mockGeneratedContent); + private readonly SourceText _sourceTextRazor = SourceText.From(s_mockRazorContent); [Fact] public async Task MapSpans_WithinRange_ReturnsMapping() @@ -37,11 +37,11 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var spans = new TextSpan[] { textSpan }; var documentSnapshot = new Mock(MockBehavior.Strict); - documentSnapshot.SetupGet(doc => doc.Uri).Returns(MockDocumentUri); + documentSnapshot.SetupGet(doc => doc.Uri).Returns(_mockDocumentUri); - var textSnapshot = new StringTextSnapshot(MockGeneratedContent, 1); + var textSnapshot = new StringTextSnapshot(s_mockGeneratedContent, 1); - var textSpanAsRange = textSpan.AsLSPRange(SourceTextGenerated); + var textSpanAsRange = textSpan.AsLSPRange(_sourceTextGenerated); var mappedRange = new Range() { Start = new Position(2, 1), @@ -54,10 +54,10 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor Ranges = new Range[] { mappedRange } }; documentMappingProvider.Setup(dmp => dmp.MapToDocumentRangesAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((languageKind, Uri, ranges, ct) => + .Callback((languageKind, uri, ranges, ct) => { Assert.Equal(RazorLanguageKind.CSharp, languageKind); - Assert.Equal(MockDocumentUri, Uri); + Assert.Equal(_mockDocumentUri, uri); Assert.Single(ranges, textSpanAsRange); called = true; }) @@ -65,13 +65,13 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var service = new RazorLSPSpanMappingService(documentMappingProvider.Object, documentSnapshot.Object, textSnapshot); - var expectedSpan = mappedRange.AsTextSpan(SourceTextRazor); - var expectedLinePosition = SourceTextRazor.Lines.GetLinePositionSpan(expectedSpan); - var expectedFilePath = MockDocumentUri.LocalPath; + var expectedSpan = mappedRange.AsTextSpan(_sourceTextRazor); + var expectedLinePosition = _sourceTextRazor.Lines.GetLinePositionSpan(expectedSpan); + var expectedFilePath = _mockDocumentUri.LocalPath; var expectedResult = (expectedFilePath, expectedLinePosition, expectedSpan); // Act - var result = await service.MapSpansAsyncTest(spans, SourceTextGenerated, SourceTextRazor).ConfigureAwait(false); + var result = await service.MapSpansAsyncTest(spans, _sourceTextGenerated, _sourceTextRazor).ConfigureAwait(false); // Assert Assert.True(called); @@ -88,18 +88,18 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var spans = new TextSpan[] { textSpan }; var documentSnapshot = new Mock(MockBehavior.Strict); - documentSnapshot.SetupGet(doc => doc.Uri).Returns(MockDocumentUri); + documentSnapshot.SetupGet(doc => doc.Uri).Returns(_mockDocumentUri); - var textSnapshot = new StringTextSnapshot(MockGeneratedContent, 1); + var textSnapshot = new StringTextSnapshot(s_mockGeneratedContent, 1); - var textSpanAsRange = textSpan.AsLSPRange(SourceTextGenerated); + var textSpanAsRange = textSpan.AsLSPRange(_sourceTextGenerated); var documentMappingProvider = new Mock(MockBehavior.Strict); documentMappingProvider.Setup(dmp => dmp.MapToDocumentRangesAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((languageKind, Uri, ranges, ct) => + .Callback((languageKind, uri, ranges, ct) => { Assert.Equal(RazorLanguageKind.CSharp, languageKind); - Assert.Equal(MockDocumentUri, Uri); + Assert.Equal(_mockDocumentUri, uri); Assert.Single(ranges, textSpanAsRange); called = true; }) @@ -108,7 +108,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor var service = new RazorLSPSpanMappingService(documentMappingProvider.Object, documentSnapshot.Object, textSnapshot); // Act - var result = await service.MapSpansAsyncTest(spans, SourceTextGenerated, SourceTextRazor).ConfigureAwait(false); + var result = await service.MapSpansAsyncTest(spans, _sourceTextGenerated, _sourceTextRazor).ConfigureAwait(false); // Assert Assert.True(called); @@ -120,7 +120,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor { // Arrange var documentSnapshot = new Mock(MockBehavior.Strict); - documentSnapshot.SetupGet(doc => doc.Uri).Returns(MockDocumentUri); + documentSnapshot.SetupGet(doc => doc.Uri).Returns(_mockDocumentUri); var sourceTextRazor = SourceText.From(""); var response = new RazorMapToDocumentRangesResponse { Ranges = new Range[] { RangeExtensions.UndefinedRange } }; diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLanguageService`IVsLanguageDebugInfoTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLanguageService`IVsLanguageDebugInfoTest.cs index e7f74f3071..e35bc59127 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLanguageService`IVsLanguageDebugInfoTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServerClient.Razor.Test/RazorLanguageService`IVsLanguageDebugInfoTest.cs @@ -168,7 +168,7 @@ namespace Microsoft.VisualStudio.LanguageServerClient.Razor // Assert Assert.Equal(VSConstants.S_OK, result); var concreteResolvedExpressions = Assert.IsType(resolvedExpressions); - Assert.Equal(expressions, concreteResolvedExpressions._values); + Assert.Equal(expressions, concreteResolvedExpressions.Values); } [Fact] diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/DocumentGenerator/BackgroundDocumentGeneratorTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/DocumentGenerator/BackgroundDocumentGeneratorTest.cs index 1b091bc506..d4fd4bce3e 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/DocumentGenerator/BackgroundDocumentGeneratorTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/DocumentGenerator/BackgroundDocumentGeneratorTest.cs @@ -296,7 +296,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem for (var i = 0; i < documents.Length; i++) { var key = new DocumentKey(HostProject1.FilePath, documents[i].FilePath); - Assert.True(queue._work.ContainsKey(key)); + Assert.True(queue.Work.ContainsKey(key)); } // Allow the background work to start. @@ -348,7 +348,7 @@ namespace Microsoft.CodeAnalysis.Razor.ProjectSystem Assert.True(queue.IsScheduledOrRunning, "Queue should be scheduled during Enqueue"); Assert.True(queue.HasPendingNotifications, "Queue should have a notification created during Enqueue"); - var kvp = Assert.Single(queue._work); + var kvp = Assert.Single(queue.Work); var expectedKey = new DocumentKey(HostProject1.FilePath, TestProjectData.SomeProjectComponentFile1.FilePath); Assert.Equal(expectedKey, kvp.Key); diff --git a/src/Shared/BenchmarkRunner/Program.cs b/src/Shared/BenchmarkRunner/Program.cs index 44b914c1ea..1f13382616 100644 --- a/src/Shared/BenchmarkRunner/Program.cs +++ b/src/Shared/BenchmarkRunner/Program.cs @@ -18,8 +18,8 @@ namespace Microsoft.AspNetCore.BenchmarkDotNet.Runner { partial class Program { - private static TextWriter _standardOutput; - private static StringBuilder _standardOutputText; + private static TextWriter s_standardOutput; + private static StringBuilder s_standardOutputText; static partial void BeforeMain(string[] args); @@ -74,7 +74,7 @@ namespace Microsoft.AspNetCore.BenchmarkDotNet.Runner private static int Fail(object o, string message) { - _standardOutput?.WriteLine(_standardOutputText.ToString()); + s_standardOutput?.WriteLine(s_standardOutputText.ToString()); Console.Error.WriteLine("'{0}' failed, reason: '{1}'", o, message); return 1; @@ -113,9 +113,9 @@ namespace Microsoft.AspNetCore.BenchmarkDotNet.Runner private static void SuppressConsole() { - _standardOutput = Console.Out; - _standardOutputText = new StringBuilder(); - Console.SetOut(new StringWriter(_standardOutputText)); + s_standardOutput = Console.Out; + s_standardOutputText = new StringBuilder(); + Console.SetOut(new StringWriter(s_standardOutputText)); } } }