Ejemplo n.º 1
0
    public static void ReportDiagnostic(GeneratorExecutionContext context, string id, string title, string message, string description, DiagnosticSeverity severity, Location?location, params object?[] messageArgs)
    {
        LocalizableString    ltitle       = new LocalizableResourceString(title, AutoInterfaceResource.ResourceManager, typeof(AutoInterfaceResource));
        LocalizableString    lmessage     = new LocalizableResourceString(message, AutoInterfaceResource.ResourceManager, typeof(AutoInterfaceResource));
        LocalizableString?   ldescription = new LocalizableResourceString(description, AutoInterfaceResource.ResourceManager, typeof(AutoInterfaceResource));
        string               category     = typeof(AutoInterfaceSourceGenerator).Namespace;
        string?              link         = "https://github.com/beakona/AutoInterface";
        DiagnosticDescriptor dd           = new(id, ltitle, lmessage, category, severity, true, ldescription, link, WellKnownDiagnosticTags.NotConfigurable);
        Diagnostic           d            = Diagnostic.Create(dd, location, messageArgs);

        context.ReportDiagnostic(d);
    }
        private protected RequiredAttributeAnalyzer(string diagonsticID, string typeName, string attributeName, bool checkParents, bool requiredOnAbstracts)
        {
            LocalizableString Title         = new LocalizableResourceString(nameof(Resources.MissingAttributeTitle), Resources.ResourceManager, typeof(Resources), attributeName);
            LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.MissingAttributeMessage), Resources.ResourceManager, typeof(Resources));
            LocalizableString Description   = new LocalizableResourceString(nameof(Resources.MissingAttributeDescription), Resources.ResourceManager, typeof(Resources));

            Rule                     = new DiagnosticDescriptor(diagonsticID, Title, MessageFormat, "Design", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
            this.typeName            = typeName;
            this.attributeName       = attributeName;
            this.checkParents        = checkParents;
            this.requiredOnAbstracts = requiredOnAbstracts;
        }
 private static DiagnosticDescriptor CreateDiagnosticDescriptor(LocalizableResourceString messageFormat, LocalizableResourceString description, string helpLink = null)
 {
     return(new DiagnosticDescriptor(RuleId,
                                     SecurityDiagnosticHelpers.GetLocalizableResourceString(nameof(MicrosoftNetFrameworkAnalyzersResources.InsecureXsltScriptProcessingMessage)),
                                     messageFormat,
                                     DiagnosticCategory.Security,
                                     DiagnosticHelpers.DefaultDiagnosticSeverity,
                                     isEnabledByDefault: true,
                                     description: description,
                                     helpLinkUri: helpLink,
                                     customTags: WellKnownDiagnosticTags.Telemetry));
 }
Ejemplo n.º 4
0
 private static DiagnosticDescriptor CreateDiagnosticDescriptor(LocalizableResourceString messageFormat, LocalizableResourceString description, string helpLink = null)
 {
     return(new DiagnosticDescriptor(RuleId,
                                     SecurityDiagnosticHelpers.GetLocalizableResourceString(nameof(DesktopAnalyzersResources.InsecureDtdProcessingInApiDesign)),
                                     messageFormat,
                                     DiagnosticCategory.Security,
                                     DiagnosticSeverity.Warning,
                                     isEnabledByDefault: true,
                                     description: description,
                                     helpLinkUri: helpLink,
                                     customTags: WellKnownDiagnosticTags.Telemetry));
 }
Ejemplo n.º 5
0
        public void LocalizableResourceStringEquality()
        {
            var resourceManager = GetTestResourceManagerInstance();
            var unit            = EqualityUnit
                                  .Create(
                new LocalizableResourceString(
                    @"ResourceWithArguments",
                    resourceManager,
                    typeof(CustomResourceManager),
                    "arg"
                    )
                )
                                  .WithEqualValues(
                new LocalizableResourceString(
                    @"ResourceWithArguments",
                    resourceManager,
                    typeof(CustomResourceManager),
                    "arg"
                    )
                )
                                  .WithNotEqualValues(
                new LocalizableResourceString(
                    @"ResourceWithArguments",
                    resourceManager,
                    typeof(CustomResourceManager),
                    "otherarg"
                    ),
                new LocalizableResourceString(
                    @"Resource1",
                    resourceManager,
                    typeof(CustomResourceManager)
                    )
                );

            EqualityUtil.RunAll(unit, checkIEquatable: false);

            var str = new LocalizableResourceString(
                @"ResourceWithArguments",
                resourceManager,
                typeof(CustomResourceManager),
                "arg"
                );
            var threw = false;

            str.OnException += (sender, e) =>
            {
                threw = true;
            };
            Assert.False(str.Equals(42));
            Assert.False(str.Equals(42));
            Assert.False(threw);
        }
 protected AbstractUseConditionalExpressionDiagnosticAnalyzer(
     string descriptorId,
     EnforceOnBuild enforceOnBuild,
     LocalizableResourceString message,
     PerLanguageOption2 <CodeStyleOption2 <bool> > option)
     : base(descriptorId,
            enforceOnBuild,
            option,
            new LocalizableResourceString(nameof(AnalyzersResources.Convert_to_conditional_expression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
            message)
 {
     _option = option;
 }
        protected override async Task <IEnumerable <CodeActionOperation> > ComputeOperationsAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Project project = Context.Document?.Project;

            if (project == null)
            {
                return(null);
            }

            SemanticModel semanticModel = await Context.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            if (semanticModel == null)
            {
                return(null);
            }

            SuppressionFile suppressionFile = SuppressionManager.Instance.GetSuppressionFile(project.AssemblyName);

            if (suppressionFile == null)
            {
                IEnumerable <CodeActionOperation> operationsToCreateSuppresionFile = GetOperationsToCreateSuppressionFile(project);

                if (operationsToCreateSuppresionFile == null)
                {
                    return(null);
                }

                var operationsWithSuppressionFileCreation = new List <CodeActionOperation>(4);
                operationsWithSuppressionFileCreation.AddRange(operationsToCreateSuppresionFile);
                operationsWithSuppressionFileCreation.Add(new SuppressInSuppressionFileOperation(Diagnostic, project.AssemblyName, semanticModel));
                return(operationsWithSuppressionFileCreation);
            }
            else
            {
                // For some reason the changes in suppression file will immediately reflect in the code editor
                // only if we call suppress diagnostic in code action manually, not via code action operation
                if (!SuppressionManager.SuppressDiagnostic(semanticModel, Diagnostic.Id, Diagnostic.Location.SourceSpan,
                                                           Diagnostic.DefaultSeverity, cancellationToken))
                {
                    var errorMessage = new LocalizableResourceString(nameof(Resources.DiagnosticSuppression_FailedToAddToSuppressionFile),
                                                                     Resources.ResourceManager, typeof(Resources), suppressionFile.Path);
                    System.Diagnostics.Debug.WriteLine($"{SharedConstants.PackageName.ToUpperInvariant()}: {errorMessage}");
                }

                return(new List <CodeActionOperation>(1)
                {
                    new ApplyChangesOperation(project.Solution)
                });
            }
        }
        protected AbstractFileHeaderDiagnosticAnalyzer(string language)
            : base(
                IDEDiagnosticIds.FileHeaderMismatch,
                CodeStyleOptions.FileHeaderTemplate,
                language,
                new LocalizableResourceString(nameof(FeaturesResources.The_file_header_is_missing_or_not_located_at_the_top_of_the_file), FeaturesResources.ResourceManager, typeof(FeaturesResources)),
                new LocalizableResourceString(nameof(FeaturesResources.A_source_file_is_missing_a_required_header), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
        {
            RoslynDebug.AssertNotNull(DescriptorId);

            var invalidHeaderTitle   = new LocalizableResourceString(nameof(FeaturesResources.The_file_header_does_not_match_the_required_text), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            var invalidHeaderMessage = new LocalizableResourceString(nameof(FeaturesResources.A_source_file_contains_a_header_that_does_not_match_the_required_text), FeaturesResources.ResourceManager, typeof(FeaturesResources));

            InvalidHeaderDescriptor = CreateDescriptorWithId(DescriptorId, invalidHeaderTitle, invalidHeaderMessage);
        }
Ejemplo n.º 9
0
        public AG0019PreventUseOfInternalsVisibleToAttribute()
        {
            var info = new LocalizableResourceString(nameof(CustomRulesResources.AG0019Title), CustomRulesResources.ResourceManager, typeof(CustomRulesResources));

            _diagnosticDescriptor = new DiagnosticDescriptor(
                DIAGNOSTIC_ID,
                info,
                info,
                AnalyzerCategory.MaintainabilityRules,
                DiagnosticSeverity.Error,
                AnalyzerConstants.EnabledByDefault,
                DescriptionContentLoader.GetAnalyzerDescription(nameof(AG0019PreventUseOfInternalsVisibleToAttribute)),
                "https://github.agodadev.io/pages/standards-c-sharp/code-standards/unit-testing/only-test-the-public-interface.html",
                WellKnownDiagnosticTags.EditAndContinue);
        }
Ejemplo n.º 10
0
        public AG0013LimitNumberOfTestMethodParametersTo5()
        {
            var info = new LocalizableResourceString(nameof(CustomRulesResources.AG0013Title), CustomRulesResources.ResourceManager, typeof(CustomRulesResources));

            _diagnosticDescriptor = new DiagnosticDescriptor(
                DIAGNOSTIC_ID,
                info,
                info,
                AnalyzerCategory.CustomQualityRules,
                DiagnosticSeverity.Warning,
                AnalyzerConstants.EnabledByDefault,
                DescriptionContentLoader.GetAnalyzerDescription(nameof(AG0013LimitNumberOfTestMethodParametersTo5)),
                "https://github.agodadev.io/pages/standards-c-sharp/code-standards/unit-testing/use-test-cases-appropriately.html",
                WellKnownDiagnosticTags.EditAndContinue
                );
        }
        public static DiagnosticDescriptor Create(string code, DiagnosticSeverity severity = DiagnosticSeverity.Warning, DiagnosticCategory category = DiagnosticCategory.Security)
        {
            LocalizableString title       = new LocalizableResourceString(string.Format("Analyzer_{0}_Title", code), Resources.ResourceManager, typeof(Resources));
            LocalizableString description = new LocalizableResourceString(string.Format("Analyzer_{0}_Description", code), Resources.ResourceManager, typeof(Resources));
            LocalizableString message     = new LocalizableResourceString(string.Format("Analyzer_{0}_MessageFormat", code), Resources.ResourceManager, typeof(Resources));
            LocalizableString anchor      = new LocalizableResourceString(string.Format("Analyzer_{0}_Anchor", code), Resources.ResourceManager, typeof(Resources));

            return(new DiagnosticDescriptor(
                       code
                       , title
                       , message
                       , getCategoryResource(category)
                       , severity
                       , true
                       , description
                       , string.Format("https://www.pumascan.com/rules/#{0}", anchor)));
        }
        private static DiagnosticDescriptor GetDescriptorWithLocalizableResourceStringsThatThrow()
        {
            var resourceManager = GetTestResourceManagerInstance();

            // Test localizable title that throws.
            var localizableTitle       = new LocalizableResourceString("NonExistentTitleResourceName", resourceManager, typeof(CustomResourceManager));
            var localizableMessage     = new LocalizableResourceString("NonExistentMessageResourceName", resourceManager, typeof(CustomResourceManager));
            var localizableDescription = new LocalizableResourceString("NonExistentDescriptionResourceName", resourceManager, typeof(CustomResourceManager));

            return(new DiagnosticDescriptor(
                       "Id",
                       localizableTitle,
                       localizableMessage,
                       "Category",
                       DiagnosticSeverity.Warning,
                       isEnabledByDefault: true,
                       description: localizableDescription));
        }
Ejemplo n.º 13
0
        private static DiagnosticDescriptor CreateRule(string id, string titleName, string descriptionName, string messageFormatName, string category, DiagnosticSeverity severity, bool isEnabledByDefault, string[] customTags)
        {
            var title         = new LocalizableResourceString(titleName, Resources.ResourceManager, typeof(Resources));
            var description   = new LocalizableResourceString(descriptionName, Resources.ResourceManager, typeof(Resources));
            var messageFormat = new LocalizableResourceString(messageFormatName, Resources.ResourceManager, typeof(Resources));

            var rule = new DiagnosticDescriptor(
                id,
                title,
                messageFormat,
                category,
                severity,
                isEnabledByDefault,
                description: description,
                helpLinkUri: $"https://wormiecorp.github.io/Cake.Addin.Analyzer/rules/{id.ToLowerInvariant()}",
                customTags: customTags);

            return(rule);
        }
Ejemplo n.º 14
0
        private static DiagnosticDescriptor GetDescriptorWithLocalizableResourceStringsThatThrow()
        {
            var resourceManager = GetTestResourceManagerInstance();
            var enCulture       = CultureInfo.CreateSpecificCulture("en-US");
            var arCulture       = CultureInfo.CreateSpecificCulture("ar-SA");
            var enResourceSet   = resourceManager.GetResourceSet(enCulture, false, false);
            var arResourceSet   = resourceManager.GetResourceSet(arCulture, false, false);

            // Test localizable title that throws.
            var localizableTitle       = new LocalizableResourceString("NonExistentTitleResourceName", resourceManager, typeof(CustomResourceManager));
            var localizableMessage     = new LocalizableResourceString("NonExistentMessageResourceName", resourceManager, typeof(CustomResourceManager));
            var localizableDescription = new LocalizableResourceString("NonExistentDescriptionResourceName", resourceManager, typeof(CustomResourceManager));

            return(new DiagnosticDescriptor(
                       "Id",
                       localizableTitle,
                       localizableMessage,
                       "Category",
                       DiagnosticSeverity.Warning,
                       isEnabledByDefault: true,
                       description: localizableDescription));
        }
Ejemplo n.º 15
0
        private static ImmutableArray <DiagnosticDescriptor> CreateDescriptors(bool forceEnableRules)
        {
            // TODO: Enable these rules by default once we have designed the Tools|Option location and UI for such code quality rules.
            // https://github.com/dotnet/roslyn/issues/29519

            // IDE0051: "Remove unused members" (Symbol is declared but never referenced)
            var removeUnusedMembersTitle   = new LocalizableResourceString(nameof(FeaturesResources.Remove_unused_private_members), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            var removeUnusedMembersMessage = new LocalizableResourceString(nameof(FeaturesResources.Type_0_has_an_unused_private_member_1_which_can_be_removed), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            var removeUnusedMembersRule    = CreateDescriptor(
                IDEDiagnosticIds.RemoveUnusedMembersDiagnosticId, removeUnusedMembersTitle, removeUnusedMembersMessage, configurable: true, enabledByDefault: forceEnableRules);
            var removeUnusedMembersRuleWithFadingRule = CreateUnnecessaryDescriptor(
                IDEDiagnosticIds.RemoveUnusedMembersDiagnosticId, removeUnusedMembersTitle, removeUnusedMembersMessage, configurable: true, enabledByDefault: forceEnableRules);

            // IDE0052: "Remove unread members" (Value is written and/or symbol is referenced, but the assigned value is never read)
            var removeUnreadMembersTitle   = new LocalizableResourceString(nameof(FeaturesResources.Remove_unread_private_members), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            var removeUnreadMembersMessage = new LocalizableResourceString(nameof(FeaturesResources.Type_0_has_a_private_member_1_that_can_be_removed_as_the_value_assigned_to_it_is_never_read), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            var removeUnreadMembersRule    = CreateDescriptor(
                IDEDiagnosticIds.RemoveUnreadMembersDiagnosticId, removeUnreadMembersTitle, removeUnreadMembersMessage, configurable: true, enabledByDefault: forceEnableRules);
            var removeUnreadMembersRuleUnnecessaryWithFadingRule = CreateUnnecessaryDescriptor(
                IDEDiagnosticIds.RemoveUnreadMembersDiagnosticId, removeUnreadMembersTitle, removeUnreadMembersMessage, configurable: true, enabledByDefault: forceEnableRules);

            return(ImmutableArray.Create(removeUnusedMembersRule, removeUnusedMembersRuleWithFadingRule,
                                         removeUnreadMembersRule, removeUnreadMembersRuleUnnecessaryWithFadingRule));
        }
Ejemplo n.º 16
0
        static EditAndContinueDiagnosticDescriptors()
        {
            s_moduleDiagnosticDescriptorsGuard = new object();

            s_rudeEditLocString = new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            s_encLocString      = new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources));
            s_encDisallowedByProjectLocString = new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources));

            var builder = ImmutableArray.CreateBuilder <DiagnosticDescriptor>();

            void add(int index, int id, string resourceName, LocalizableResourceString title, DiagnosticSeverity severity)
            {
                if (index >= builder.Count)
                {
                    builder.Count = index + 1;
                }

                builder[index] = new DiagnosticDescriptor(
                    $"ENC{id:D4}",
                    title,
                    messageFormat: new LocalizableResourceString(resourceName, FeaturesResources.ResourceManager, typeof(FeaturesResources)),
                    DiagnosticCategory.EditAndContinue,
                    severity,
                    isEnabledByDefault: true,
                    customTags: DiagnosticCustomTags.EditAndContinue);
            }

            void AddRudeEdit(RudeEditKind kind, string resourceName)
            => add(GetDescriptorIndex(kind), (int)kind, resourceName, s_rudeEditLocString, DiagnosticSeverity.Error);

            void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, DiagnosticSeverity severity = DiagnosticSeverity.Error)
            => add(GetDescriptorIndex(code), GeneralDiagnosticBaseId + (int)code, resourceName, s_encLocString, severity);

            //
            // rude edits
            //

            AddRudeEdit(RudeEditKind.InsertAroundActiveStatement, nameof(FeaturesResources.Adding_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeleteAroundActiveStatement, nameof(FeaturesResources.Deleting_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeleteActiveStatement, nameof(FeaturesResources.Removing_0_that_contains_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdateAroundActiveStatement, nameof(FeaturesResources.Updating_a_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdateExceptionHandlerOfActiveTry, nameof(FeaturesResources.Modifying_a_catch_finally_handler_with_an_active_statement_in_the_try_block_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdateTryOrCatchWithActiveFinally, nameof(FeaturesResources.Modifying_a_try_catch_finally_statement_when_the_finally_block_is_active_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdateCatchHandlerAroundActiveStatement, nameof(FeaturesResources.Modifying_a_catch_handler_around_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.Update, nameof(FeaturesResources.Updating_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ModifiersUpdate, nameof(FeaturesResources.Updating_the_modifiers_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.VarianceUpdate, nameof(FeaturesResources.Updating_the_variance_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.TypeUpdate, nameof(FeaturesResources.Updating_the_type_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InitializerUpdate, nameof(FeaturesResources.Updating_the_initializer_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.FixedSizeFieldUpdate, nameof(FeaturesResources.Updating_the_size_of_a_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.EnumUnderlyingTypeUpdate, nameof(FeaturesResources.Updating_the_underlying_type_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.BaseTypeOrInterfaceUpdate, nameof(FeaturesResources.Updating_the_base_class_and_or_base_interface_s_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.TypeKindUpdate, nameof(FeaturesResources.Updating_the_kind_of_a_type_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.AccessorKindUpdate, nameof(FeaturesResources.Updating_the_kind_of_an_property_event_accessor_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.MethodKindUpdate, nameof(FeaturesResources.Updating_the_kind_of_a_method_Sub_Function_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeclareAliasUpdate, nameof(FeaturesResources.Updating_the_alias_of_Declare_Statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeclareLibraryUpdate, nameof(FeaturesResources.Updating_the_library_name_of_Declare_Statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.FieldKindUpdate, nameof(FeaturesResources.Updating_a_field_to_an_event_or_vice_versa_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.Renamed, nameof(FeaturesResources.Renaming_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.Insert, nameof(FeaturesResources.Adding_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertVirtual, nameof(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertOverridable, nameof(FeaturesResources.Adding_a_MustOverride_0_or_overriding_an_inherited_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertExtern, nameof(FeaturesResources.Adding_an_extern_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertDllImport, nameof(FeaturesResources.Adding_an_imported_method_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertOperator, nameof(FeaturesResources.Adding_a_user_defined_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertIntoStruct, nameof(FeaturesResources.Adding_0_into_a_1_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertIntoClassWithLayout, nameof(FeaturesResources.Adding_0_into_a_class_with_explicit_or_sequential_layout_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertGenericMethod, nameof(FeaturesResources.Adding_a_generic_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.Move, nameof(FeaturesResources.Moving_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.Delete, nameof(FeaturesResources.Deleting_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.MethodBodyAdd, nameof(FeaturesResources.Adding_a_method_body_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.MethodBodyDelete, nameof(FeaturesResources.Deleting_a_method_body_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.GenericMethodUpdate, nameof(FeaturesResources.Modifying_a_generic_method_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.GenericMethodTriviaUpdate, nameof(FeaturesResources.Modifying_whitespace_or_comments_in_a_generic_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.GenericTypeUpdate, nameof(FeaturesResources.Modifying_a_method_inside_the_context_of_a_generic_type_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.GenericTypeTriviaUpdate, nameof(FeaturesResources.Modifying_whitespace_or_comments_in_0_inside_the_context_of_a_generic_type_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.GenericTypeInitializerUpdate, nameof(FeaturesResources.Modifying_the_initializer_of_0_in_a_generic_type_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, nameof(FeaturesResources.Adding_a_constructor_to_a_type_with_a_field_or_property_initializer_that_contains_an_anonymous_function_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.RenamingCapturedVariable, nameof(FeaturesResources.Renaming_a_captured_variable_from_0_to_1_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.StackAllocUpdate, nameof(FeaturesResources.Modifying_0_which_contains_the_stackalloc_operator_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ExperimentalFeaturesEnabled, nameof(FeaturesResources.Modifying_source_with_experimental_language_features_enabled_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.AwaitStatementUpdate, nameof(FeaturesResources.Updating_a_complex_statement_containing_an_await_expression_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingVisibility, nameof(FeaturesResources.Changing_visibility_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.CapturingVariable, nameof(FeaturesResources.Capturing_variable_0_that_hasn_t_been_captured_before_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.NotCapturingVariable, nameof(FeaturesResources.Ceasing_to_capture_variable_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeletingCapturedVariable, nameof(FeaturesResources.Deleting_captured_variable_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingCapturedVariableType, nameof(FeaturesResources.Changing_the_type_of_a_captured_variable_0_previously_of_type_1_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingCapturedVariableScope, nameof(FeaturesResources.Changing_the_declaration_scope_of_a_captured_variable_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingLambdaParameters, nameof(FeaturesResources.Changing_the_parameters_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingLambdaReturnType, nameof(FeaturesResources.Changing_the_return_type_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingQueryLambdaType, nameof(FeaturesResources.Changing_the_type_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.AccessingCapturedVariableInLambda, nameof(FeaturesResources.Accessing_captured_variable_0_that_hasn_t_been_accessed_before_in_1_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.NotAccessingCapturedVariableInLambda, nameof(FeaturesResources.Ceasing_to_access_captured_variable_0_in_1_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertLambdaWithMultiScopeCapture, nameof(FeaturesResources.Adding_0_that_accesses_captured_variables_1_and_2_declared_in_different_scopes_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeleteLambdaWithMultiScopeCapture, nameof(FeaturesResources.Removing_0_that_accessed_captured_variables_1_and_2_declared_in_different_scopes_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ActiveStatementUpdate, nameof(FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ActiveStatementLambdaRemoved, nameof(FeaturesResources.Removing_0_that_contains_an_active_statement_will_prevent_the_debug_session_from_continuing));
            // TODO: change the error message to better explain what's going on
            AddRudeEdit(RudeEditKind.PartiallyExecutedActiveStatementUpdate, nameof(FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.PartiallyExecutedActiveStatementDelete, nameof(FeaturesResources.Removing_0_that_contains_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertFile, nameof(FeaturesResources.Adding_a_new_file_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, nameof(FeaturesResources.Updating_async_or_iterator_modifier_around_an_active_statement_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, nameof(FeaturesResources.Attribute_0_is_missing_Updating_an_async_method_or_an_iterator_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, nameof(FeaturesResources.Switching_between_lambda_and_local_function_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, nameof(FeaturesResources.Adding_method_with_explicit_interface_specifier_will_prevernt_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertIntoInterface, nameof(FeaturesResources.Adding_0_into_an_interface_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, nameof(FeaturesResources.Adding_0_into_an_interface_method_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InternalError, nameof(FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_due_to_internal_error));
            AddRudeEdit(RudeEditKind.ChangingFromAsynchronousToSynchronous, nameof(FeaturesResources.Changing_0_from_asynchronous_to_synchronous_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ChangingStateMachineShape, nameof(FeaturesResources.Changing_0_to_1_will_prevent_the_debug_session_from_continuing_because_it_changes_the_shape_of_the_state_machine));
            AddRudeEdit(RudeEditKind.ComplexQueryExpression, nameof(FeaturesResources.Modifying_0_which_contains_an_Aggregate_Group_By_or_Join_query_clauses_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.MemberBodyInternalError, nameof(FeaturesResources.Modifying_body_of_member_will_prevent_the_debug_session_from_continuing_due_to_internal_error));
            AddRudeEdit(RudeEditKind.MemberBodyTooBig, nameof(FeaturesResources.Modifying_body_of_member_will_prevent_the_debug_session_from_continuing_because_the_body_has_too_many_statements));
            AddRudeEdit(RudeEditKind.SourceFileTooBig, nameof(FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_because_the_file_is_too_big));
            AddRudeEdit(RudeEditKind.InsertIntoGenericType, nameof(FeaturesResources.Adding_0_into_a_generic_type_will_prevent_the_debug_session_from_continuing));

            AddRudeEdit(RudeEditKind.ImplementRecordParameterAsReadOnly, nameof(FeaturesResources.Implementing_a_record_positional_parameter_0_as_read_only_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ImplementRecordParameterWithSet, nameof(FeaturesResources.Implementing_a_record_positional_parameter_0_with_a_set_accessor_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.AddRecordPositionalParameter, nameof(FeaturesResources.Adding_a_positional_parameter_to_a_record_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.DeleteRecordPositionalParameter, nameof(FeaturesResources.Deleting_a_positional_parameter_from_a_record_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, nameof(FeaturesResources.Explicitly_implemented_methods_of_records_must_have_parameter_names_that_match_the_compiler_generated_equivalent_0));

            AddRudeEdit(RudeEditKind.NotSupportedByRuntime, nameof(FeaturesResources.Edit_and_continue_is_not_supported_by_the_runtime));
            AddRudeEdit(RudeEditKind.MakeMethodAsync, nameof(FeaturesResources.Making_a_method_async_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.MakeMethodIterator, nameof(FeaturesResources.Making_a_method_an_iterator_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertNotSupportedByRuntime, nameof(FeaturesResources.Adding_0_will_prevent_the_debug_session_from_continuing));

            // VB specific
            AddRudeEdit(RudeEditKind.HandlesClauseUpdate, nameof(FeaturesResources.Updating_the_Handles_clause_of_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ImplementsClauseUpdate, nameof(FeaturesResources.Updating_the_Implements_clause_of_a_0_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.ConstraintKindUpdate, nameof(FeaturesResources.Changing_the_constraint_from_0_to_1_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.InsertHandlesClause, nameof(FeaturesResources.Adding_0_with_the_Handles_clause_will_prevent_the_debug_session_from_continuing));
            AddRudeEdit(RudeEditKind.UpdateStaticLocal, nameof(FeaturesResources.Modifying_0_which_contains_a_static_variable_will_prevent_the_debug_session_from_continuing));

            //
            // other Roslyn reported diagnostics:
            //

            s_diagnosticBaseIndex = builder.Count;

            AddGeneralDiagnostic(EditAndContinueErrorCode.ErrorReadingFile, nameof(FeaturesResources.ErrorReadingFile));
            AddGeneralDiagnostic(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError, nameof(FeaturesResources.CannotApplyChangesUnexpectedError));
            AddGeneralDiagnostic(EditAndContinueErrorCode.ChangesDisallowedWhileStoppedAtException, nameof(FeaturesResources.ChangesDisallowedWhileStoppedAtException));
            AddGeneralDiagnostic(EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee, nameof(FeaturesResources.DocumentIsOutOfSyncWithDebuggee), DiagnosticSeverity.Warning);
            AddGeneralDiagnostic(EditAndContinueErrorCode.UnableToReadSourceFileOrPdb, nameof(FeaturesResources.UnableToReadSourceFileOrPdb), DiagnosticSeverity.Warning);

            s_descriptors = builder.ToImmutable();
        }
        public void TestDiagnosticLocalization()
        {
            var resourceManager           = GetTestResourceManagerInstance();
            var arCulture                 = CultureInfo.CreateSpecificCulture("ar-SA");
            var defaultCultureResourceSet = resourceManager.GetResourceSet(CustomResourceManager.DefaultCulture, false, false);
            var arResourceSet             = resourceManager.GetResourceSet(arCulture, false, false);

            var nameOfResource1 = @"Resource1";
            var nameOfResource2 = @"Resource2";
            var nameOfResource3 = @"Resource3";

            var fixedTitle         = defaultCultureResourceSet.GetString(nameOfResource1);
            var fixedMessageFormat = defaultCultureResourceSet.GetString(nameOfResource2);
            var fixedDescription   = defaultCultureResourceSet.GetString(nameOfResource3);

            var localizedTitle         = arResourceSet.GetString(nameOfResource1);
            var localizedMessageFormat = arResourceSet.GetString(nameOfResource2);
            var localizedDescription   = arResourceSet.GetString(nameOfResource3);

            // Test descriptor localization.

            // Test non-localizable title, description and message.
            var descriptor = new DiagnosticDescriptor(
                "Id",
                fixedTitle,
                fixedMessageFormat,
                "Category",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                description: fixedDescription);

            Assert.Equal(fixedTitle, descriptor.Title.ToString(arCulture));
            Assert.Equal(fixedMessageFormat, descriptor.MessageFormat.ToString(arCulture));
            Assert.Equal(fixedDescription, descriptor.Description.ToString(arCulture));

            // Test localizable title, description and message.
            var localizableTitle         = new LocalizableResourceString(nameOfResource1, resourceManager, typeof(CustomResourceManager));
            var localizableMessageFormat = new LocalizableResourceString(nameOfResource2, resourceManager, typeof(CustomResourceManager));
            var localizableDescription   = new LocalizableResourceString(nameOfResource3, resourceManager, typeof(CustomResourceManager));

            descriptor = new DiagnosticDescriptor(
                "Id",
                localizableTitle,
                localizableMessageFormat,
                "Category",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                description: localizableDescription);

            if (EnsureEnglishUICulture.PreferredOrNull == null)
            {
                Assert.Equal <string>(fixedTitle, descriptor.Title.ToString());
                Assert.Equal <string>(fixedMessageFormat, descriptor.MessageFormat.ToString());
                Assert.Equal <string>(fixedDescription, descriptor.Description.ToString());
            }

            Assert.Equal <string>(fixedTitle, descriptor.Title.ToString(CustomResourceManager.DefaultCulture));
            Assert.Equal <string>(fixedMessageFormat, descriptor.MessageFormat.ToString(CustomResourceManager.DefaultCulture));
            Assert.Equal <string>(fixedDescription, descriptor.Description.ToString(CustomResourceManager.DefaultCulture));

            Assert.Equal(localizedTitle, descriptor.Title.ToString(arCulture));
            Assert.Equal(localizedMessageFormat, descriptor.MessageFormat.ToString(arCulture));
            Assert.Equal(localizedDescription, descriptor.Description.ToString(arCulture));

            // Test diagnostic localization.
            var localizableDiagnostic = Diagnostic.Create(descriptor, Location.None);

            if (EnsureEnglishUICulture.PreferredOrNull == null)
            {
                // Test non-localized title, description and message.
                Assert.Equal(fixedTitle, localizableDiagnostic.Descriptor.Title.ToString());
                Assert.Equal(fixedMessageFormat, localizableDiagnostic.GetMessage());
                Assert.Equal(fixedDescription, localizableDiagnostic.Descriptor.Description.ToString());
            }

            Assert.Equal(fixedTitle, localizableDiagnostic.Descriptor.Title.ToString(CustomResourceManager.DefaultCulture));
            Assert.Equal(fixedMessageFormat, localizableDiagnostic.GetMessage(CustomResourceManager.DefaultCulture));
            Assert.Equal(fixedDescription, localizableDiagnostic.Descriptor.Description.ToString(CustomResourceManager.DefaultCulture));

            // Test localized title, description and message.
            Assert.Equal(localizedTitle, localizableDiagnostic.Descriptor.Title.ToString(arCulture));
            Assert.Equal(localizedMessageFormat, localizableDiagnostic.GetMessage(arCulture));
            Assert.Equal(localizedDescription, localizableDiagnostic.Descriptor.Description.ToString(arCulture));

            // Test argument formatting for localized string
            var nameOfResourceWithArguments = @"ResourceWithArguments";
            var argument            = "formatted";
            var localizableResource = new LocalizableResourceString(nameOfResourceWithArguments, resourceManager, typeof(CustomResourceManager), argument);

            // Verify without culture
            var defaultCultureLocalizedStringWithArguments = defaultCultureResourceSet.GetString(nameOfResourceWithArguments);
            var expected = string.Format(defaultCultureLocalizedStringWithArguments, argument);

            if (EnsureEnglishUICulture.PreferredOrNull == null)
            {
                Assert.Equal(expected, localizableResource.ToString());
            }

            Assert.Equal(expected, localizableResource.ToString(CustomResourceManager.DefaultCulture));

            // Verify with loc culture
            var arLocalizedStringWithArguments = arResourceSet.GetString(nameOfResourceWithArguments);

            expected = string.Format(arLocalizedStringWithArguments, argument);
            Assert.Equal(expected, localizableResource.ToString(arCulture));
        }
Ejemplo n.º 18
0
        private static DiagnosticDescriptor GetDescriptorWithLocalizableResourceStringsThatThrow()
        {
            var resourceManager = GetTestResourceManagerInstance();

            // Test localizable title that throws.
            var localizableTitle = new LocalizableResourceString("NonExistentTitleResourceName", resourceManager, typeof(CustomResourceManager));
            var localizableMessage = new LocalizableResourceString("NonExistentMessageResourceName", resourceManager, typeof(CustomResourceManager));
            var localizableDescription = new LocalizableResourceString("NonExistentDescriptionResourceName", resourceManager, typeof(CustomResourceManager));

            return new DiagnosticDescriptor(
                "Id",
                localizableTitle,
                localizableMessage,
                "Category",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                description: localizableDescription);
        }
Ejemplo n.º 19
0
        public void LocalizableResourceStringEquality()
        {
            var resourceManager = GetTestResourceManagerInstance();
            var unit = EqualityUnit
                .Create(new LocalizableResourceString(@"ResourceWithArguments", resourceManager, typeof(CustomResourceManager), "arg"))
                .WithEqualValues(
                    new LocalizableResourceString(@"ResourceWithArguments", resourceManager, typeof(CustomResourceManager), "arg"))
                .WithNotEqualValues(
                    new LocalizableResourceString(@"ResourceWithArguments", resourceManager, typeof(CustomResourceManager), "otherarg"),
                    new LocalizableResourceString(@"Resource1", resourceManager, typeof(CustomResourceManager)));
            EqualityUtil.RunAll(unit, checkIEquatable: false);


            var str = new LocalizableResourceString(@"ResourceWithArguments", resourceManager, typeof(CustomResourceManager), "arg");
            var threw = false;
            str.OnException += (sender, e) => { threw = true; };
            Assert.False(str.Equals(42));
            Assert.False(str.Equals(42));
            Assert.False(threw);
        }
Ejemplo n.º 20
0
        public void TestDiagnosticLocalization()
        {
            var resourceManager = GetTestResourceManagerInstance();
            var arCulture = CultureInfo.CreateSpecificCulture("ar-SA");
            var defaultCultureResourceSet = resourceManager.GetResourceSet(CustomResourceManager.DefaultCulture, false, false);
            var arResourceSet = resourceManager.GetResourceSet(arCulture, false, false);

            var nameOfResource1 = @"Resource1";
            var nameOfResource2 = @"Resource2";
            var nameOfResource3 = @"Resource3";

            var fixedTitle = defaultCultureResourceSet.GetString(nameOfResource1);
            var fixedMessageFormat = defaultCultureResourceSet.GetString(nameOfResource2);
            var fixedDescription = defaultCultureResourceSet.GetString(nameOfResource3);

            var localizedTitle = arResourceSet.GetString(nameOfResource1);
            var localizedMessageFormat = arResourceSet.GetString(nameOfResource2);
            var localizedDescription = arResourceSet.GetString(nameOfResource3);

            // Test descriptor localization.

            // Test non-localizable title, description and message.
            var descriptor = new DiagnosticDescriptor(
                "Id",
                fixedTitle,
                fixedMessageFormat,
                "Category",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                description: fixedDescription);

            Assert.Equal(fixedTitle, descriptor.Title.ToString(arCulture));
            Assert.Equal(fixedMessageFormat, descriptor.MessageFormat.ToString(arCulture));
            Assert.Equal(fixedDescription, descriptor.Description.ToString(arCulture));

            // Test localizable title, description and message.
            var localizableTitle = new LocalizableResourceString(nameOfResource1, resourceManager, typeof(CustomResourceManager));
            var localizableMessageFormat = new LocalizableResourceString(nameOfResource2, resourceManager, typeof(CustomResourceManager));
            var localizableDescription = new LocalizableResourceString(nameOfResource3, resourceManager, typeof(CustomResourceManager));

            descriptor = new DiagnosticDescriptor(
                "Id",
                localizableTitle,
                localizableMessageFormat,
                "Category",
                DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                description: localizableDescription);

            if (EnsureEnglishUICulture.PreferredOrNull == null)
            {
                Assert.Equal<string>(fixedTitle, descriptor.Title.ToString());
                Assert.Equal<string>(fixedMessageFormat, descriptor.MessageFormat.ToString());
                Assert.Equal<string>(fixedDescription, descriptor.Description.ToString());
            }

            Assert.Equal<string>(fixedTitle, descriptor.Title.ToString(CustomResourceManager.DefaultCulture));
            Assert.Equal<string>(fixedMessageFormat, descriptor.MessageFormat.ToString(CustomResourceManager.DefaultCulture));
            Assert.Equal<string>(fixedDescription, descriptor.Description.ToString(CustomResourceManager.DefaultCulture));

            Assert.Equal(localizedTitle, descriptor.Title.ToString(arCulture));
            Assert.Equal(localizedMessageFormat, descriptor.MessageFormat.ToString(arCulture));
            Assert.Equal(localizedDescription, descriptor.Description.ToString(arCulture));

            // Test diagnostic localization.
            var localizableDiagnostic = Diagnostic.Create(descriptor, Location.None);

            if (EnsureEnglishUICulture.PreferredOrNull == null)
            {
                // Test non-localized title, description and message.
                Assert.Equal(fixedTitle, localizableDiagnostic.Descriptor.Title.ToString());
                Assert.Equal(fixedMessageFormat, localizableDiagnostic.GetMessage());
                Assert.Equal(fixedDescription, localizableDiagnostic.Descriptor.Description.ToString());
            }

            Assert.Equal(fixedTitle, localizableDiagnostic.Descriptor.Title.ToString(CustomResourceManager.DefaultCulture));
            Assert.Equal(fixedMessageFormat, localizableDiagnostic.GetMessage(CustomResourceManager.DefaultCulture));
            Assert.Equal(fixedDescription, localizableDiagnostic.Descriptor.Description.ToString(CustomResourceManager.DefaultCulture));

            // Test localized title, description and message.
            Assert.Equal(localizedTitle, localizableDiagnostic.Descriptor.Title.ToString(arCulture));
            Assert.Equal(localizedMessageFormat, localizableDiagnostic.GetMessage(arCulture));
            Assert.Equal(localizedDescription, localizableDiagnostic.Descriptor.Description.ToString(arCulture));

            // Test argument formatting for localized string
            var nameOfResourceWithArguments = @"ResourceWithArguments";
            var argument = "formatted";
            var localizableResource = new LocalizableResourceString(nameOfResourceWithArguments, resourceManager, typeof(CustomResourceManager), argument);

            // Verify without culture
            var defaultCultureLocalizedStringWithArguments = defaultCultureResourceSet.GetString(nameOfResourceWithArguments);
            var expected = string.Format(defaultCultureLocalizedStringWithArguments, argument);

            if (EnsureEnglishUICulture.PreferredOrNull == null)
            {
                Assert.Equal(expected, localizableResource.ToString());
            }

            Assert.Equal(expected, localizableResource.ToString(CustomResourceManager.DefaultCulture));

            // Verify with loc culture
            var arLocalizedStringWithArguments = arResourceSet.GetString(nameOfResourceWithArguments);
            expected = string.Format(arLocalizedStringWithArguments, argument);
            Assert.Equal(expected, localizableResource.ToString(arCulture));
        }
Ejemplo n.º 21
0
        protected void ShowLocalizedError(string resourceName, params string[] formatArgs)
        {
            var errorMessage = new LocalizableResourceString(resourceName, Resources.ResourceManager, typeof(Resources), formatArgs);

            ShowError(errorMessage.ToString());
        }
 private static DiagnosticDescriptor CreateDiagnosticDescriptor(LocalizableResourceString messageFormat, LocalizableResourceString description)
 {
     return(DiagnosticDescriptorHelper.Create(RuleId,
                                              SecurityDiagnosticHelpers.GetLocalizableResourceString(nameof(MicrosoftNetFrameworkAnalyzersResources.InsecureDtdProcessingInApiDesign)),
                                              messageFormat,
                                              DiagnosticCategory.Security,
                                              RuleLevel.IdeHidden_BulkConfigurable,
                                              description,
                                              isPortedFxCopRule: false,
                                              isDataflowRule: false));
 }
Ejemplo n.º 23
0
            private void AnalyzeNodeForXslCompiledTransformLoad(SyntaxNodeAnalysisContext context)
            {
                SyntaxNode    node         = context.Node;
                SemanticModel model        = context.SemanticModel;
                IMethodSymbol methodSymbol = _syntaxNodeHelper.GetCalleeMethodSymbol(node, model);

                if (SecurityDiagnosticHelpers.IsXslCompiledTransformLoad(methodSymbol, _xmlTypes))
                {
                    bool isSecureResolver;
                    bool isSecureSettings;
                    bool isSetInBlock;

                    int xmlResolverIndex  = SecurityDiagnosticHelpers.GetXmlResolverParameterIndex(methodSymbol, _xmlTypes);
                    int xsltSettingsIndex = SecurityDiagnosticHelpers.GetXsltSettingsParameterIndex(methodSymbol, _xmlTypes);

                    // Overloads with no XmlResolver and XstlSettings specified are secure since they all have folowing behavior:
                    //  1. An XmlUrlResolver with no user credentials is used to process any xsl:import or xsl:include elements.
                    //  2. The document() function is disabled.
                    //  3. Embedded scripts are not supported.
                    if (xmlResolverIndex >= 0 &&
                        xsltSettingsIndex >= 0)
                    {
                        IEnumerable <SyntaxNode> argumentExpressionNodes = _syntaxNodeHelper.GetInvocationArgumentExpressionNodes(node);
                        SyntaxNode resolverNode = argumentExpressionNodes.ElementAt(xmlResolverIndex);

                        isSecureResolver = SyntaxNodeHelper.NodeHasConstantValueNull(resolverNode, model) ||
                                           SecurityDiagnosticHelpers.IsXmlSecureResolverType(model.GetTypeInfo(resolverNode).Type, _xmlTypes);

                        SyntaxNode settingsNode   = argumentExpressionNodes.ElementAt(xsltSettingsIndex);
                        ISymbol    settingsSymbol = SyntaxNodeHelper.GetSymbol(settingsNode, model);

                        // 1. pass null or XsltSettings.Default as XsltSetting : secure
                        if (settingsSymbol == null || SecurityDiagnosticHelpers.IsXsltSettingsDefaultProperty(settingsSymbol as IPropertySymbol, _xmlTypes))
                        {
                            isSetInBlock     = true;
                            isSecureSettings = true;
                        }
                        // 2. XsltSettings.TrustedXslt : insecure
                        else if (SecurityDiagnosticHelpers.IsXsltSettingsTrustedXsltProperty(settingsSymbol as IPropertySymbol, _xmlTypes))
                        {
                            isSetInBlock     = true;
                            isSecureSettings = false;
                        }
                        // 3. check xsltSettingsEnvironments, if IsScriptDisabled && IsDocumentFunctionDisabled then secure, else insecure
                        else if (_xsltSettingsEnvironments.TryGetValue(settingsSymbol, out XsltSettingsEnvironment env))
                        {
                            isSetInBlock     = false;
                            isSecureSettings = env.IsDocumentFunctionDisabled && env.IsScriptDisabled;
                        }
                        //4. symbol for settings is not found => passed in without any change => assume insecure
                        else
                        {
                            isSetInBlock     = true;
                            isSecureSettings = false;
                        }

                        if (!isSecureSettings && !isSecureResolver)
                        {
                            LocalizableResourceString message = SecurityDiagnosticHelpers.GetLocalizableResourceString(
                                isSetInBlock ? nameof(MicrosoftNetFrameworkAnalyzersResources.XslCompiledTransformLoadInsecureConstructedMessage) :
                                nameof(MicrosoftNetFrameworkAnalyzersResources.XslCompiledTransformLoadInsecureInputMessage),
                                SecurityDiagnosticHelpers.GetNonEmptyParentName(node, model, context.CancellationToken)
                                );

                            context.ReportDiagnostic(
                                Diagnostic.Create(
                                    RuleDoNotUseInsecureXSLTScriptExecution,
                                    node.GetLocation(),
                                    message
                                    )
                                );
                        }
                    }
                }
            }
 private static DiagnosticDescriptor CreateDiagnosticDescriptor(LocalizableResourceString messageFormat, LocalizableResourceString description)
 {
     return(DiagnosticDescriptorHelper.Create(RuleId,
                                              SecurityDiagnosticHelpers.GetLocalizableResourceString(nameof(MicrosoftNetFrameworkAnalyzersResources.InsecureXsltScriptProcessingMessage)),
                                              messageFormat,
                                              DiagnosticCategory.Security,
                                              RuleLevel.BuildWarning,
                                              description,
                                              isPortedFxCopRule: false,
                                              isDataflowRule: false));
 }