Prevent using .NET code when calling certain methods?

Is there a way to create compile-time errors if a specific method is called?

As an example, what I would like to do is to prevent the code in a specific project from calling System.Configuration.ConfigurationManager.AppSettings (). Is there a way to mark a project or class file to raise a compile-time error if this method is called?

I don’t think there is, so I think the only way to do this is to create an FxCop rule that will mark these calls and do it this way, but I am open to other ideas.

I am using .NET 3.5. Not sure if contract with code 4.0 can do this.

Updates

I specifically talk about structure methods, not about myself, so I cannot mark them as obsolete.

At this moment, I do not care about reflection.

Another example is System.Web.HttpUtility.HtmlEncode, which I want to find and replace in the Microsoft AntiXss library, but I would like to integrate some kind of verification process on my build server, which would also check the new code.

+6
source share
2 answers

The NDepend tool can be used for this (Disclaimer: I am one of the developers of this tool).

You can write Code Rules over LINQ queries (CQLinq) to check for any dependency, such as a method call. Code rules can be checked in Visual Studio after each successful compilation, or rules can also be checked during the build process .

Such a CQLinq code rule might look like this:

warnif count > 0 from m in Application.Methods where m.IsUsing("System.Configuration.ConfigurationManager.get_AppSettings()") select m 

This rule may be specialized on a whim to prevent, for example, namespaces that match a regular expression from containing methods that call the get_AppSettings() getter method:

 warnif count > 0 from m in Application.Namespaces.WithNameLike("regex").ChildMethods() where m.IsUsing("System.Configuration.ConfigurationManager.get_AppSettings()") select m 

From the Ndepend dependency matrix or dependency graph , you can also right-click the dependency (matrix cell or arrow of the graph) and create a code rule that warns if the dependency exists (and then specializes the rule generated if you need to):

enter image description here

+2
source

You can write your own rules in FxCop , perhaps this is an option.

However, in this case, for the existing code base, you may find that Ctrl-F (Find) in your editor for "ConfigurationManager.AppSettings" can work equally with much less effort ... As for though you might consider a more human route email for the development team ...

As the commentator emphasizes above and it is worth noting for others with similar goals, that if this applies to a function in your own code base (to which this question does not apply), you can use the [Obsolete] attribute.

+4
source

Source: https://habr.com/ru/post/901661/


All Articles