Joe Rohde - MSFT

I am a program manager for our Code Analysis system. I want to know what kind of custom rules you would like to write. Ignore what you may or may not know about what's in FxCop already. If you could track anything - tell me what you want!

I don't care if it's things you know we can't do - except maybe 'find my bugs'. Smile Tell your friends, tell anyone who has ever said: I wish this thing could...

The reason I want everything is both to help plan the rules we should just plain provide; and how to best provide an actual supported extensibility feature.

Please send what you would like to see to: JRohde@Microsoft.com

Thanks!

Joe




Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

Claudio Lassala

Hi Joe,

Here's a list with rules that I wrote here at the company:

  • Rules to check for XML comments (we know that the compiler can enforce that public members have XML comments, even though it doesn't check whether the XML comments actually have something typed in it... we wanted to make sure developers aren't just getting away with empty XML comments, and we also want developer to put comments on every type and type's member, no matter what the visibility is):
    • All type members must have xml comments
    • All types must have xml comments
    • Assembly libraries need to have valid XML docs (this one I borrowed from an MSDN article)
  • Rules for naming conventions:
    • Variables should have meaningful names: we don't like variables named like "i" or "j" for counters in for-loops, so I wrote this rule that asks the developer to give variables some more meaningful names.
  • Rules specific to users of our framework:
    • Business Entities must not have public constructors (those objects are meant to be instantiated through Factory methods)
    • Business Objects must not have public constructors (same reason as above)
    • Do not create DB Command objects directly (developers shouldn't do data access directly using ado.net stuff... they should always use our biz objs or DAL instead).
    • Do not create DB connection objects directly (same reason as above)
    • Local variables should always use generic data interfaces (this is to make sure developers don't declare variables of type SqlCommand or OracleCommand. Instead, they should declare it as IDbCommand or IDbConnection, and use our framework factory methods that give them the appropriate concrete types)
    • Only Milos (our framework) Configuration System Should be used (we wrote our own Configuration system, which wraps up the standard .NET one, but adds more functionality, so we don't developers using the native .NET one).
    • Public methods on business objects must only return serializable types (since the biz obj may sit on a different server, we need to make sure the objects it returns can be serialized).
    • Business Objects must follow naming convention (any class inheriting from our BusinessObject, BusinessEntity, BusinessRule, BusinessCollection, etc., should follow our naming conventions for it)
    • Avoid enabling "allow save with violations" on business objects (this is a recommendation to the developer)
    • Avoid instantiating Business Objects in Business Entities (we already have a special method on the entity to get to the biz obj).
    • Command parameters must be added using milos (we don't want developer adding parameters to DbCommand objects directly, we want them to use a method in our framework instead. That way we can handle things like the fact that only the SqlDbCommand.Parameters has the AddWithValue method).
    • Do never discard return values from save methods (we want to make sure that developers always check the return value of Save method, and not just discard it).
    • Properties should not be set outside business objects (our biz objs should be stateless objects, so we don't want developers setting state outside of it)

And here are some rules we have in our to-do list to create:

  • Standard Windows Form controls or ASP.NET controls should not be used directly. Subclasses should be used instead.
  • Is there a way we can make sure that people do not query data in the database every time a property is accessed
  • Disallow cyclic references between assemblies
  • Verify that all SurpressMessage attributes have the Justification attribute set.
  • Discourage use of hungarian notation, such as nNumber or cString or lcString or intCounter.

Also, for many of our custom rules, we want to make them configurable so that our clients can adapt them to their own needs. We're thinking of dropping XML files on the Rules folder and read settings out of there, kinda like the CustomDictionary.xml, but we haven't got to that yet.

Well, I think that's some feedback to get you started. Smile

Thank you for working close to the community on this.






Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

Piyush Gajrani

I am a senior developer in Software Company. I recently came to know about this magnificent code analysis tool. It was really exciting to use the tool with inbuilt rules. But my motive to get on to this tool was something which was not present in this tool (FxCop). And let me be more honest to you, I am very new to this great code analysis tool.

Now coming to my motive, I want to track a particular Line of Code (which may be infact a call to some other method or be just some simple line of code). And this line of code would be written in each and every method of the page and/or solution (In presentation layer out of our 3 layer architecture). I know this may sound a bit weird, but it is just our requirement. I need to be sure that my developers have written that particular line of code in each and every method in Presentation layer of our web application. It would be really helpful, if you could provide me the code (or sample of code) or just the idea that how to write that custom rule to track specific line of code in every method of the my application.

I hope you can help me in this regard. Waiting for your suggestion! Smile

Thanks in advance.

Note: Joe - I have already written mail to you in this regard, but you gave refernce for this forum. I could not find the solution over here, so needed to post it on here.

Best Regards

Piyush






Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

sasikumar_kl

Hi

I just started playing around the methods provided by the Introsepction rule engine. I have created some custom rules on my own. In some of the code snippetts i have come accross the implementation of two methods called BeforeAnalysis() and AfterAnalysis(). I would like to know the usage of overriding the above two methods.

Regards,

Sasikumar.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

Nishant Pant

Hi,

I am also looking to implement custom rules using the FxCop introspection engine. I did find quite a few examples. But they are so cryptic and I just cannot find any documentation which explains the API in detail.

I am leaning towards thinking that maybe I should have use reflection to parse through the code. I have managed to create a lot of rules, but without really understanding what I am doing. I have tweaked code here and there to make it work. But I am looking for some documentation which I can read and be able to write code on my own rather than copying /pasting from MSDN resources.

eg. I just want to find out if the developer is using pre-defined keywords in his code. Session object for example. I just cannot find a way to do this without Reflection

-Thanks

Nishant





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

sasikumar_kl

Hi Nishant,

Microsoft has not released any documentation for FxCop tool. Only thing one has to do is create some of custom rules by overriding one of Check method and get the details of the node you are getting.

If you want to visit any of the node or field in your managed code, just see the dll's IL code accordingly write your code to check those kind of variables.

In the above post i have not got what is your requirement. I have created few custom rules to check if the user is instantiating SqlConnection object. If you tell your requirement let me see i can help you.

Regards,

Sasikumar.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

amar

Joe,

Can you help me with this

Requirement 1 :

I have a fxcop requirement where in I need to check that there should be 1 class derived from xyz class in the whole assembly.

So, I should be able to see 1 class that inherits from xyz in the whole assembly, And there can not be more than one class that is derived from xyz class in the whole assembly.

Requirement 2 :

Inside every method I should see whether there is a call to LogHandler method in the beginning of the method and at the end of the method as well.

Can you guide me as to what logic is needed to achieve these 2 requirements.

Thanks

Amar





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

sasikumar_kl

Hi Amar,

For your 2nd requirement you can try some thing like below. The below code will check the method call for "LogHeader" at the beginning of your method, before performing any operation in the method. Except initialization of the variables.

Similarly you can try to loop the MSIL instructions from the end to check whether is there a method call to LogHeader at the end of the method.

public override ProblemCollection Check(Member member)

{

Method method = member as Method;

string instruction;

bool loopContinue = true;

bool properLogHeaderCall = true;

int i = 0;

if (method.Name.Name.StartsWith("LogHeader"))

{

return null;

}

if (method.Name.Name.StartsWith(".ctor"))

{

return null;

}

while (i <= method.Instructions.Length - 1 &&

method.InstructionsIdea.OpCode != OpCode.Call &&

properLogHeaderCall)

{

if (method.InstructionsIdea.OpCode.ToString().ToUpper().StartsWith("LD") ||

method.InstructionsIdea.OpCode.ToString().ToUpper().StartsWith("STLOC") ||

method.InstructionsIdea.OpCode.ToString().ToUpper().StartsWith("_LOCALS") ||

method.InstructionsIdea.OpCode.ToString().ToUpper().StartsWith("NOP"))

{

properLogHeaderCall = true;

}

else

{

properLogHeaderCall = false;

}

i++;

}

if (properLogHeaderCall == false)

{

Problems.Add(new Problem(GetResolution(method.Name.Name)));

}

return Problems;

}

I hope this will help you.

Regards,

Sasikumar.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

amar

Thanks so much for sending me the sample.

I tried to run this sample and to my surprise, it didnt return any results. I ran this rule on a project which has some methods with loghandler but some doesnt have loghandler. But the test didnt result in any results.

Please let me know.


Thanks

Amar





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

Nishant Pant

Sasikumar,

Appreciate your quick reply. I will post a few requirements that I would like an answer for. But on a different note, I attended dotnetroadshow today and found that Juval Lowy has some C# coding standards that several companies are using. I went to Idesign.net and found out that, not only are the standards available there but there is an engine based on DxCore called "Code style enforcer" available too, which integrates into Visual Studio and enforces every single rule the Juval has in his coding conventions. This is really cool stuff.

Now, I am at a point, where I am thinking ..should I abandon all the research that I have done with FxCop (Code Analysis) and adopt DxCore or not If you can tell me how does FxCop compare with Code Style enforcer that will be great.

-Thanks much

Nishant





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

sasikumar_kl

It all depends purely on our requirement. It is like comparison between two tools and whichever is best matching for our requirement we can adapt the respective tool. May be each tool may own its tradeoffs. But i have not gone through the tool you have mentioned above.

For FxCop we do have rich user community to support and especially the Microsoft FxCop Team itself.

Regards,

Sasikumar.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

sasikumar_kl

Hi Amar,

To my surprise i have misspelled the the word "loghandler" as "LogHeader". Please the do the change and run it. It should work. Moreover the above code does not check for the methods which do not have "LogHandler" method call. The above method has to be tuned. The above method just check whether "LogHandler" method is called at the beginning of the method.

If you put your class file here, i may look into that.

Regards,

Sasikumar.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

sasikumar_kl

Hi Piyush,

You can very well go through ecah line of MISL. The MISL code will be referred as instrcutions. Override the Check method and get the instruction list in the visited method. As per your requirement check whether particular line of code is existing or not. If not add to the problem collection and return.

Code Snippet

public override ProblemCollection Check(Member member)

{

Method mainMethod = member as Method;

Local local;

Instruction instruction;

string instructionname;

if (mainMethod == null)

{

return null;

}

if (mainMethod.Instructions == null)

{

return null;

}

for (int count = 0; count <= mainMethod.Instructions.Length - 1; count++)

{

instruction = mainMethod.Instructions[count];

if (instruction.OpCode == OpCode.Newobj)

{

if (((Microsoft.Cci.Method)(instruction.Value)).

FullName.Contains("System.Data.SqlClient.SqlConnection.#ctor"))

{

Problems.Add(new Problem(GetResolution("SqlConnection","Cafe.net connection")));

}

if (((Microsoft.Cci.Method)(instruction.Value)).

FullName.Contains("System.Data.SqlClient.SqlCommand.#ctor"))

{

Problems.Add(new Problem(GetResolution("SqlCommand", "Cafe.net command")));

}

}

}

return Problems;

}

The above method walks through MSIL to check whether SqlConnection object is instantiated or not. If SqlConnection or SqlCommand object is instantiated, it will be added to the Problems collection and shown up as rule violation.

I hope this will help you.

Regards,

Sasikumar.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

amar

Well, I got it. Infact it became easier once I set the debugger and went thru the methods,comparing it with ildasm. It was an easy thing in the end. My requirement is different so your code would nt work, its not about the spelling.Anyways thanks so much for giving me insight.





Re: Visual Studio Code Analysis and Code Metrics Tell me what kind of Custom Rule you want to write!!!

Nishant Pant

Sasikumar,

Since, I can't find much help anywhere else, I was wondering if you could tell me how to check if a programmer has used SQLDataSource or ObjectDataSource object in his code.

-Thanks

Nishant