Ask a questionAsk a question
 

StickyTell me what kind of Custom Rule you want to write!!!

  • Wednesday, July 04, 2007 1:35 AMJoe Rohde Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

     

All Replies

  • Wednesday, July 18, 2007 5:09 PMClaudio LassalaMVPUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

     

     

     

  • Thursday, August 23, 2007 2:55 PMPiyush Gajrani Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

     

  • Tuesday, September 04, 2007 10:43 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

     

    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.

  • Friday, September 07, 2007 4:37 PMNishant Pant Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

     

    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

  • Monday, September 10, 2007 6:55 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

     

  • Wednesday, September 12, 2007 8:33 PMamarSSIS Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

  • Thursday, September 13, 2007 9:50 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

  • Thursday, September 13, 2007 5:17 PMamarSSIS Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

  • Friday, September 14, 2007 2:44 AMNishant Pant Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

  • Friday, September 14, 2007 5:38 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

  • Friday, September 14, 2007 5:42 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

     

  • Friday, September 14, 2007 5:52 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

  • Friday, September 14, 2007 10:37 PMamarSSIS Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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.

  • Monday, September 17, 2007 9:31 PMNishant Pant Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    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

     

  • Monday, September 17, 2007 10:47 PMNishant Pant Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Sasikumar,

     

    I also had one more request. I am trying to deploy my FxCop rules to all the developers machines in my company. I know that I can drop my custom dll under C:\Program Files\Microsoft Visual Studio 8\Team Tools\Static Analysis Tools\FxCop\Rules folder, and it will start showing in VStudio.

     

    But, how do I configure it so that if I select/deselect certain rules, they apply to all projects on my machine. What I have found out is that Visual Studio stores my selections in the .csproj or .vbproj file under the <CodeAnalysis> xml node like below. But then this becomes project specific. How do I apply these rules to all projects by default ?

     

        <CodeAnalysisRules>-Microsoft.Design#CA2210;-Microsoft.Design#CA1020;+!Microsoft.Design#CA1045;+!Microsoft.Design#CA1044;+!Microsoft.Design#CA1001;-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;-Microsoft.Globalization#CA1303;-Microsoft.Globalization#CA1306;-Microsoft.Globalization#CA1304;-Microsoft.Globalization#CA1305;-Microsoft.Globalization#CA1300;+!HSG.Naming#HSG0001;+!HSG.Data#HSG0008;+!HSG.Security#HSG0010;+!HSG.Performance#HSG0015;-Microsoft.Mobility#CA1600;-Microsoft.Mobility#CA1601;-Microsoft.Naming#CA1705;+!Microsoft.Performance#CA1811;+!Microsoft.Performance#CA1823;-!Microsoft.Performance#CA1818;+!Microsoft.Performance#CA1804;-Microsoft.Portability#CA1901;-Microsoft.Portability#CA1900;+!Microsoft.Reliability#CA2000;+!Microsoft.Reliability#CA2004;-Microsoft.Security#CA2116;-Microsoft.Security#CA2117;-Microsoft.Security#CA2105;-Microsoft.Security#CA2115;-Microsoft.Security#CA2104;-Microsoft.Security#CA2122;-Microsoft.Security#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Security#CA2108;-Microsoft.Security#CA2107;-Microsoft.Security#CA2103;-Microsoft.Security#CA2100;-Microsoft.Security#CA2118;-Microsoft.Security#CA2109;-Microsoft.Security#CA2119;-Microsoft.Security#CA2106;-Microsoft.Security#CA2112;-Microsoft.Security#CA2110;-Microsoft.Security#CA2120;-Microsoft.Security#CA2101;-Microsoft.Security#CA2121;-Microsoft.Security#CA2126;-Microsoft.Security#CA2124;-Microsoft.Usage#CA2209;+!Microsoft.Usage#CA2202;+!Microsoft.Usage#CA2200;+!Microsoft.Usage#CA1801</CodeAnalysisRules>
        <RunCodeAnalysis>true</RunCodeAnalysis>

     

    -Thanks much

    Nishant Pant

  • Tuesday, September 18, 2007 5:29 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Nishant,

     

    One easy way to get acquainted with the custom rule creation is to debug your custom rule and visit all the methods and properties of the Assembly, TypeNodeList or Member etc. Then it is easy for you to create the custom rules.

     

    I have created the custom rule to check in the code whether SqlConnection object is instantiated or not. Please find the code below.

    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;

    }

     

     

    Regards,

    Sasikumar.

  • Wednesday, September 19, 2007 2:07 PMNishant Pant Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Thanks. I figured out how to write my custom rule. I hope the below example helps others as well. Although, I am not looping through instructions as in your example, because I wanted to catch class level declarations.

     

    [CLSCompliant(false)]

    class DoNotUseSqlObjDataSources : BaseFXCopRule

    {

    public DoNotUseSqlObjDataSources() : base("DoNotUseSqlObjDataSources") { }

    public override ProblemCollection Check(Member member)

    {

    Field field = member as Field;

    if (field == null)

    return null;

    string controlName = field.Type.FullName.ToUpper();

    if (controlName.StartsWith("SYSTEM.WEB.UI.WEBCONTROLS.SQLDATASOURCE"))

    Problems.Add(new Problem(GetResolution("SQLDataSource", field.Name.Name)));

    if (controlName.StartsWith("SYSTEM.WEB.UI.WEBCONTROLS.OBJECTDATASOURCE"))

    Problems.Add(new Problem(GetResolution("ObjectDataSource", field.Name.Name)));

    return Problems;

    }

     

    bool IsProhibitedType(string Name, out string type)

    {

    if (Name.IndexOf("System.Web.UI.WebControls.SqlDataSource") > 0)

    {

    type = "SQLDataSource";

    return true;

    }

    else if (Name.IndexOf("System.Web.UI.WebControls.ObjectDataSource") > 0)

    {

    type = "ObjectDataSource";

    return true;

    }

    type = "";

    return false;

    }

    }

  • Friday, September 28, 2007 12:43 PMLearner.example Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi

     

    Can you just show me the code of custom rules developed by you.

    I have the same requirement to check for XML comments and naming standards of fileds.

    I could write the naming standards rule and it works fine. Plz pass on the code if you have it with you.

     

    And one more requirement is naming standards for all the UI elements.

    Suppose if I declare a checkbox then it should be like chk<fieldname>, dropdown ddl<fieldname> 

    How can i achieve this???

  • Saturday, September 29, 2007 5:46 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi

     

    Code For validating Xml comments

     

    Override ProblemCollection Check(Module module). Get the xml file using the property module.Documentation. If xml comments are available for your dll, Documentation returns XmlDocument. Traverse through this xml document as per your requirement. The below code checks for four xml nodes in the xml comments ( xml nodes are mentioned in the code). It also check for any of the xml element is left blank. For example the below code checks for the "MethodName" element in the xml comment block and also if "MethodName" is left blank this code check for the same.

    Code Block

    using System;

    using System.Collections.Generic;

    using System.Text;

    using Microsoft.Cci;

    using Microsoft.FxCop.Sdk;

    using Microsoft.FxCop.Sdk.Introspection;

    using System.Xml;

    using System.Collections;

    namespace CtsCustomRules

    {

    class ValidatingXMLComments : CtsCustomBaseRule

    {

    string methodName = "MethodName";

    string methodDescription = "MethodDescription";

    string methodParameters = "MethodParameters";

    string methodReturnType = "MethodReturnType";

    Hashtable methodNameComment;

    public ValidatingXMLComments()

    : base("ValidatingXMLComments")

    {

    }

    public override void BeforeAnalysis()

    {

    methodNameComment = new Hashtable();

    }

    public override ProblemCollection Check(Module module)

    {

    XmlDocument document = module.Documentation;

    int methodCount = 0;

    string missedNodes = string.Empty;

    string innerXmlString;

    bool proceedToCheckForValidXmlComments = true;

    XmlNodeList commentStructure = document.GetElementsByTagName("members");

    //methodNameComment = new string[commentStructure[0].ChildNodes.Count - 1];

    for (int count = 0; count <= commentStructure[0].ChildNodes.Count - 1; count++)

    {

    // Check Whether xml structure is uniform and as per the defined

    // structure

    ValidXmlStructure(commentStructure[0].ChildNodes[count],

    commentStructure[0].ChildNodes[count].Attributes["name"].

    InnerText.Substring(2, commentStructure[0].ChildNodes[count].

    Attributes["name"].InnerText.Length - 2), ref missedNodes);

    }

    if (missedNodes.Length > 0)

    {

    Problems.Add(new Problem(GetResolution(missedNodes)));

    }

    return Problems;

    }

    private void ValidXmlStructure(XmlNode xmlNode,string methodName,ref string missedNodes)

    {

    StringBuilder missedOutNodes = new StringBuilder();

    if (xmlNode["MethodName"] == null)

    {

    missedOutNodes.Append("MethodName,");

    }

    if (xmlNode["MethodDescription"] == null)

    {

    missedOutNodes.Append("MethodDescription,");

    }

    if (xmlNode["MethodParameters"] == null)

    {

    missedOutNodes.Append("MethodParameters,");

    }

    if (xmlNode["MethodReturnType"] == null)

    {

    missedOutNodes.Append("MethodReturnType,");

    }

    if (missedOutNodes.Length > 0)

    {

    missedOutNodes.Insert(0, " The method: " + methodName + " is missing these xml nodes ");

    }

    missedNodes = missedNodes + " " + missedOutNodes.ToString();

    }

    }

    }

     

     

    Validating Web controls

     

    Override Check(Member member) method as mentioned below. The below code validates the check box control to be started with "chk". You can write the code to validate other type of controls.

     

    Code Block

    public override ProblemCollection Check(Member member)

    {

    Field field = member as Field;

    if (field == null)

    {

    return null;

    }

    Method method = member as Method;

    if (method == null)

    {

    return null;

    }

    InstructionList instructionList = method.Instructions;

    string controlName = field.Type.FullName;

     

    if (controlName.StartsWith("System.Web.UI.WebControls.CheckBox"))

    {

    if (!field.Name.Name.StartsWith("chk"))

    {

    Problems.Add(new Problem(GetResolution("chk", "System.Web.UI.WebControls.CheckBox", field.Name.Name)));

    }

    }

    return Problems;

    }

     

     

  • Saturday, September 29, 2007 10:35 AMLearner.example Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Thanks sasikumar it really helped me lot.

    But the method for validating webcontrols doesn't wrk for declarations done inside the method.

  • Monday, October 01, 2007 6:39 AMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    small correction in the above code

     

    Class level variables are treated as fields they can be traversed through each of the fields. Method level variables are treated as local and they need to be traversed through method instructions.

     

    public override ProblemCollection Check(Member member)

    {

    Field field = member as Field;

    Method method = member as Method;

    InstructionList instructionList;

    LocalList locals;

    if (field != null)

    {

    //do your validation for control naming convention

    }

    else if (method !=  null)

    {

    instructionList = method.Instructions;

    // Loop through each of the locals from the instruction

    locals = method.Instructions[0].Value as LocalList;

    // Loop through each of the locals for validating web control naming convention.

    }

    Method method = member as Method;

    if (method == null)

    {

    return null;

    }

     

    string controlName = field.Type.FullName;

     

    if (controlName.StartsWith("System.Web.UI.WebControls.CheckBox"))

    {

    if (!field.Name.Name.StartsWith("chk"))

    {

    Problems.Add(new Problem(GetResolution("chk", "System.Web.UI.WebControls.CheckBox", field.Name.Name)));

    }

    }

    return Problems;

    } 

     

    I hope this will be helpful for you.

     

    Regards,

    Sasikumar.

  • Thursday, October 11, 2007 1:57 PMKai Wang Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    We consider finishing our own FxCop custom rules before converting our projects to C#. Here are some types of rules we would like to have:

    1. Naming conventions for type, method, member, parameter etc
    2. Coding style
    3. Limited file size and method size
    4. Enforced Xml comments

    I read that FAQ post and realize FxCop SDK is supposed to have breaking changes. Should we wait for the next version of SDK?

    Thanks.

    Kai
  • Wednesday, October 17, 2007 8:45 AMFranck Jeannin Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    I would love to be able to use/customize/write - in that order ;-) - rules in relation to race condition detection... Things like a variable is accessed outside a lock block, function called inside a lock block that acquires new locks (may lead to deadlocks), consistent lock leveling order, checking that some shared data is immutable, etc.

    I know that some work on the subject has been done at MSR (RaceTrack, Spec#, ...) but I'm not sure what the outcome is/will be.
    To me, FxCop is definitively the place where those techniques belong.

    Thanks
  • Thursday, October 18, 2007 1:54 AMSridhar Ramaswamy Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Joe

     

    I work as a senior programmer and am trying to perform some code review for satndards set by one of our clients.One such rule is Data Encapsulation: Using Properties Instead of Public Variables.

     

    I have been trying to write an FxCOP rule for the above so that I can check against our code. I haven’t been too successful on the same. I would be highly obliged if you could help me out in writing an FxCOP rule that checks to see if public variables are being used in a class.

     

    Regards

    Sridhar

     

  • Monday, October 22, 2007 8:36 AMSwati Agrawal Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi,

     

    I have a custom rule requirement where in I need to check that there should be only one public class(excluding inner classes) present in a source file.

     

    The following scenario should not occur inside the same file:

     

    Public Class Class1

     

    End Class

     

    Public Class Class2

     

    End Class

     

    If 2 or more public classes are present one below the other, we need to show an error message.

     

    Or, Is there a way to get the source file name.

     

    Thanks,

    ~Swati

  • Wednesday, October 24, 2007 10:46 PMovatsus Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Greetings,

     

    I have serveral types of objects that implement 2 interfaces, a read-only interface and a complete interface. The read-only interfaces are defined in the namespace Model.ReadOnly, while the complete interfaces and the classes that implement both interfaces are defined in the namespace Model. I would like to make a rule that checks that no class defined in the namespace View access a type defined in the Model namespace, that it only accesses types defined in Model.ReadOnly and namespaces externals to the project. Is this possible to do with FxCop? Can anybody help me?

     

    Best Regards,

    Gustavo Guerra

     

  • Friday, October 26, 2007 3:09 PMsasikumar_kl Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi

     

    If you create such file and see the IL code, the two classess are treated as separateley. I don't think there is way to check this.

     

    Just check the IL code for your sample code.

     

    Regards,

    Sasikumar.

  • Wednesday, January 09, 2008 7:23 PMWizard_01 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     


    Hi,

    I am a senior developer in the software company and we miss advanced static code analysis tools like a lot of for Java.

    a) The first one ... A rule should be able to find problematic parts of code like (a very simple example!):

    Instance a(int i) {
       if(i == 0) return null;
       else return new Instance();
    }

    void Main() {
       a(2).DoSomething(); // ok
       a(0).DoSomething(); // failed

    }

    according to our internal statistics this kind of bug occurs in 95% cases of NullReferenceException() Sad That means advanced call-tree and creating database - what shouldnt be called. Another example:

    class A () {
      Instance instance;
      void Init() {instance = new Instance();}
      void Show() {instance.DoSomething();}
    }

    void Main() {
      new A().Init() -> Show() // OK
      new A().Show() // failed
    }

    Rule should know that the field "instance" is not initialized before calling Show method and popups a warning message. This is very advanced topics but tools for Java have this Sad

    b) Developers are usualy very relaxed, easy going to remember to all possibilities even is their own code. The same problems is with exception handling (I miss very much Java's keyword "throws" in C# ) - a rule should be able to detect, that this method throws this and that exception and caller have to handle or rethrow that exception. You maybe think is unnesseccery but this avoids about 50% of our exceptions in the software.

    c) I saw that in the thread above. You should provide more advanced rules for XML documentation: checking parameters name in ArgumentException, forcing to specify LOCALIZED message - not simply "You shouldnt do that, hahahahaha Smile". Checking permissions, exceptions + exceptions thrown by called functions. And also provide automated mechanism for updating XML documentation based on suggestions - like: Misspelled parameter name in throw new ArgumentNu..("Param") insted of simply "param" and also if possible insert documentation for exceptions and permissions automatically if missing !!!!

    d) I miss some kind of "code constraints" - imagine the example in a) - constaint like [ParameterRange("i",1,int.MaxValue)] would allow everyone to create rules that checks ranges. That would be really NICE!


    btw: Do you know a advanced static analyzer for .NET ? I really need that Smile Developers are sometimes pig (sorry everyoneSmile )

  • Thursday, May 08, 2008 5:57 PMwacm161 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Joe

     

    I have started to delve into FXCop a bit and have noticed that there are not many custom rules out there for mass consumption.

    I have created a few simple ones to handle naming webcontrols and SQL data objects but thats it so far.

     

    Rules I am looking for examples on

    1) how to determine if a helper class was used to create a db connection string

    2) How to ensure that a catch block is logging the exception

    3) That all connections are closed and disposed

    4) That all datasets and adapters are disposed

     

    Thanks alot

     

  • Monday, May 12, 2008 4:04 PMMC3659680 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    hi Claudio,

    Is it possible that you can share the rules you have written with me? If not all, then some will be wonderful. I wrote some rules which are similar to yours such as 'No direct access to SQLCommand'

    Thanks,

     MC

     

  • Thursday, May 29, 2008 3:13 AMMeiX-mm Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi Joe,

    Can I write cutom rules to check following requirements?


    1. Avoid function calls in Boolean conditional statements. Assign into local variables

    and check on them.

    bool IsEverythingOk()

    {

    }

    //Avoid:

    if(IsEveryThingOk())

    {

    }

    //Correct:

    bool ok = ISEveryThingOk();

    if(ok)

    {

    }

    2.
    Always use C# predefined types rather than the aliases in the System namespace. For example:

    <!--[if !supportLists]-->a.    object (not Object)<!--[endif]-->

    <!--[if !supportLists]-->b.    string (not String)<!--[endif]-->

                      c. int (not Int32)

    3.
    Avoid putting a using directive inside a namespace.

    4.
    Group all framework namespaces together and put custom or third-party namespaces underneath.

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using MyCompany;

    using MyControls;

    5.
    All member variables shall be declared at the top.
    6. Avoid files with more than 500 lines (excluding machine-generated code).
    7.
    Avoid methods with more than 200 lines.

    Thanks.
  • Wednesday, October 08, 2008 12:25 PMS.N.Raj Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Sasikumar ,

     

    I have one requirement - Object null check  before using them

    can you  give suggestion on this how we can develop custom rule

  • Wednesday, October 08, 2008 1:04 PMS.N.Raj Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Joe,

     

    I have the following Fxcop custom rules development

     

    1.Object null check before using them

     

    2.finding ternary operator used in method instructions

     

    3.finding default present in switch case.

     

     

     

     

     

     

     

    please provide your suggestion on the above requirements

     

     

     

    Thanks

  • Friday, December 26, 2008 7:08 AMShanky09 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi Sasikumar,

    The code you gave for checking xml tags doesn't work on FXCOP integrated with VSTS 2008. Infact in the problemcollection method, module isn't available at all. Can you kindly suggest how i can get this code to work on VSTS 2008?

     

  • Wednesday, February 11, 2009 5:54 PMankcaliber Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
     

    Hi All,

    I want the code and some instruction or links for below rule.

     Rules for naming conventions:

    Variables should have meaningful names: we don't like variables named like "i" or "j" for counters in for-loops.

    Is this rule already in FxCop1.36?

    Some one plz tell me how can I see the source code of FxCop .

    Is it possible?

    Another problem I have that I m trying to write custom rule but not getting how to write C# code for that. While I m comfortable with XML.

    Some one helps me for understanding the code of custom rules.

    u can mail me on ankcaliber@gmail.com

     

  • Friday, March 13, 2009 7:45 AMnabendu Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
     

    Hi Rohde,

     

    I had written this rule utilizing the FxCop 1.35 SDK when I was in Microsoft India. I hope this interests you. This is a custom rule not a part of the standard set of MS FxCop rules. I hope it can be shipped as a part of the rules under the Design category.

     

     

    using Microsoft.Cci;

    using Microsoft.FxCop.Sdk;

    using Microsoft.FxCop.Sdk.Introspection;

    using Realogy.TRG.FxCop.CommonUtilities;

    using System;

    using System.Collections.Generic;

    using System.Text;

     

    namespace Microsoft.FxCop.Rules

    {

        //**************************************************************************

        /// <summary>

          /// Checks for Singletons to be instantiated in a thread safe

          /// manner.

        /// </summary>

        /// <remarks>

          /// Rule operates this check by analyzing the code pattern in the following

          /// manner.

          /// <list type="bullet">

          /// <item>

          /// <description>

          /// First determines whether a given class is singleton. This is done by

          /// checking whether the constructor accessor type is private and there

          /// exists atleast one public method whose return type is the class type.

          /// </description>

          /// </item>

          /// <item>

          /// <description>

          /// The instruction list of the public method identified as the instantiator

          /// is iterated to check for a sequentially occuring pattern of "lock"

          /// expression, within which "If-else" expression occurs and within which this

          /// class type is instantiated.

          /// </description>

          /// </item>

          /// <item>

          /// <description>

          /// Lastly it is also checked whether the code leaves the "lock" block. Once

          /// it is affirmed that we have parsed through the singleton pattern of IL code,

          /// then the following class type being analyzed is passed or else is reported.

          /// </description>

          /// </item>

          /// </list>

        /// <para>$Id</para>

        /// <author>Author:Nabendu Misra</author>

        /// </remarks>

        class SingletonsShouldbeInstantiatedInAThreadSafeManner:BaseTRGRule

        {

                //**********************************************************************

                /// <summary>

                /// Instantiates the rule object and passes the rule name as an indentifier

                /// to the FxCop rule engine.

                /// </summary>

                public SingletonsShouldbeInstantiatedInAThreadSafeManner ()

                :base("SingletonsShouldbeInstantiatedInAThreadSafeManner")

            {

            } // end constructor.

     

            //**********************************************************************

                /// <summary>

            /// FxCop SDK's base introspection's check method override for reporting

                /// problems on the rule "SingletonsShouldbeInstantiatedInAThreadSafeManner"

            /// </summary>

            /// <param name="classType">The class type being analyzed.</param>

            /// <returns>The problem collection to be reported.</returns>

                public override Microsoft.FxCop.Sdk.Introspection.ProblemCollection

                      Check (Microsoft.Cci.Class classType)

                {

                     

                      #region Flags for validating a singleton.

     

                      // Flag states whether the constructor of the

                      // class type being analyzed is private.

                      bool _isConstructorPrivate = false;

     

                      // Flag states whether the class type being analyzed

                      // is a singleton implementation.

                      bool _isSingleton = false;

     

                      #endregion // end Flags for validating a singleton.

     

                      // The public class instantiator

                      // method or property.

                      Method _singletonInstantiator = null;

     

                      #region Milestones within a singleton code pattern.

     

                      // Flag states that "lock" enter IL

                      // has been parsed.

                      bool _parsedEnterLockZoneCode = false;

     

                      // Flag states that "If-else" IL

                      // has been parsed.

                      bool _parsedIfElseBlock = false;

     

                      // Flag states that the single instantion

                      // IL has been parsed.

                      bool _singletonInstantiated = false;

     

                      // Flag state that the "lock" exit IL

                      // has been parsed.

                      bool _parsedExitLockZoneCode = false;

     

                      #endregion // end Milestones within a singleton code pattern.

     

                      // Get the list of members

                      // associated with this class type.

                      MemberList _classMembers = classType.Members;

     

                      #region Validate whether this class type is a singleton

     

                      // iterate through the list of members

                      // for this class type element.

                      foreach(Member _member in _classMembers)

                {

                            if(_member.NodeType.Equals(NodeType.InstanceInitializer)

                                  && _member.IsPrivate)

                            {

                                  // The constructor has been

                                  // found to be private.

                                  _isConstructorPrivate = true;

                                  continue;

                            }

                            if (_isConstructorPrivate && RuleUtilities.GetMethod(_member) != null &&

                                  RuleUtilities.GetMethod(_member).IsPublic &&

                                  RuleUtilities.GetMethod(_member).ReturnType.FullName.StartsWith(classType.FullName))

                            {

                                  // The constructor is private as well

                                  // as there exist atleast one public method / property

                                  // whose return type is same as this class type being analyzed.

                                  // This class type has to be a singleton implementation.

                                  _isSingleton = true;

                                  _singletonInstantiator = RuleUtilities.GetMethod(_member);

                                  break;

                            }

                      } // end foreach(Member)

     

                      #endregion // end Validate whether this class type is a singleton

     

                      #region Check whether the milestones within the singleton pattern are getting parsed.

     

                      if (_isSingleton)

                      {

                            // Get the instruction list

                            // of the Instatiator.

                            InstructionList _instructionList =

                                  _singletonInstantiator.Instructions;

     

                            // iterate through the instruction list.

                            foreach (Instruction _instruction in _instructionList)

                            {

                                  if (_instruction.OpCode.Equals(OpCode.Call))

                                  {

                                        if (((Microsoft.Cci.Method)(_instruction.Value)).FullName.StartsWith

                                              ("System.Threading.Monitor.Enter"))

                                        {

                                              // parsed the "lock" enter IL.

                                              _parsedEnterLockZoneCode = true;

                                              continue;

                                        }

                                        if (((Microsoft.Cci.Method)(_instruction.Value)).FullName.StartsWith

                                              ("System.Threading.Monitor.Exit") && _singletonInstantiated)

                                        {

                                              // parsed the "lock" exit IL.

                                              _parsedExitLockZoneCode = true;

                                              break;

                                        }

                                  }

                                  if (_parsedEnterLockZoneCode && _instruction.OpCode.Equals(OpCode.Brtrue_S) ||

                                        _instruction.OpCode.Equals(OpCode.Brfalse_S))

                                  {

                                        // parsed the "If-else" block.

                                        _parsedIfElseBlock = true;

                                        continue;

                                  }

                                  if (_parsedIfElseBlock && _instruction.OpCode.Equals(OpCode.Newobj) &&

                                        ((Microsoft.Cci.Method)(_instruction.Value)).FullName.StartsWith

                                        (classType.FullName))

                                  {

                                        // parsed the instantiation of the

                                        //singleton class IL

                                        _singletonInstantiated = true;

                                        continue;

                                  }

                            } // end foreach(Instruction)

                      } // end if(_isSingleton)

     

                      #endregion // end Check whether the milestones within the singleton pattern are getting parsed.

     

                      #region Singleton not being instatiated in a thread safe manner. Report problem

     

                      // Since this class type was

                      // a singleton check for the last milestone flag.

                      if (_isSingleton && !_parsedExitLockZoneCode)

                      {

                            Problems.Add(new Problem(GetNamedResolution(

                                  "InstantiateThreadSafeSingletons", classType.FullName)));

     

                            return Problems;

                      }

     

                      #endregion // end Singleton not being instatiated in a thread safe manner. Report problem

     

                      return base.Check(classType);

                } // end Check(classType)

          } // end class SingletonsShouldBeThreadSafe

    } // end namespace Microsoft.FxCop.Rules

     

     

    The Rule Description in the Rules.xml file

     

    <Rule TypeName="SingletonsShouldbeInstantiatedInAThreadSafeManner" Category="Microsoft.FxCop" CheckId="FxCop001">

        <Name>SingletonsShouldBeImplementedThreadSafe</Name>

        <Description>Classes implemented as Singletons are to be instantiated in a threadsafe manner. In other words the entire public instantiator code should be bounded within the "lock" scope like the following

          public ThreadSafeSingleton GetInstance

          {

                get

                {

                      lock(typeof(ThreadSafeSingleton))

                      {

                            if(_instance == null)

                            {

                                  _instance = new ThreadSafeSingleton();

                                  return _instance;

                            }

                            else

                            {

                                  return _instance;

                            }

                      }

                }

          }</Description>

        <Owner>Nabendu Misra </Owner>

        <Url>http://www.microsoft.com/</Url>

        <Resolution Name = "InstantiateThreadSafeSingletons">Class '{0}' should be instantiated in a thread safe manner if it is to be implemented as a singleton pattern.</Resolution>

        <Email>mail at nabendu.misra@gmail.com</Email>

        <MessageLevel Certainty="75">CriticalWarning</MessageLevel>

        <FixCategories>Breaking</FixCategories>

      </Rule>

     

    Thanks and Regards

    Nabendu Misra, Technical Lead || RSG Media Systems


    -------------------------------------------------------------------
    Mobile: +91 -987 167 9062 | Landline: +91 124 431 4500 extn: 554 |
    Email: nabendmi@rsgsystems.com | |

     


    nabendu misra
  • Monday, May 04, 2009 7:43 PMzil_iram Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,

    I have a requirement to create an fx cop rule that checks the aspx files for accessibility?
    Are there existing rules for this?

    Thanks,
    zil
  • Thursday, September 10, 2009 9:41 AMsapanagarud Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

     

    hey ,
    i have a query ,FXCOP do not have any rule for missing Try catch block in the event handler?
    if dont have then how can we create a custom rule for it?say if i forgot to put try catch block in my code (event handler) then FXCOP should prompt me for it..please help me its very urgent..
    thanks
    rahul

  • Saturday, October 03, 2009 10:07 PMNishant Bamb Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Hi Sapanagarud,

    You can use following fxcop custum rule code for checking existence of try catch block:

    public class NoTryCatchImplemented : BaseIntrospectionRule
        {
            public NoTryCatchImplemented()
                :
                base(@"NoTryCatchImplemented", "PegasusCustomRules.Rules", typeof(NoTryCatchImplemented).Assembly)
            { }
    
            public override ProblemCollection Check(TypeNode type)
            {
                MemberList members = type.Members;
                bool CatchExits=true;
    
                for (int i = 0, n = members.Length; i < n; i++)
                {
                    Method method = members[i] as Method;
                    if (method != null)
                    {
                        CatchExits = false;
                        for (int j = 0; j < method.Instructions.Length; j++)
                        {
                            Instruction inst = method.Instructions[j];
                            if (inst.OpCode == OpCode.Catch)
                            {
                                CatchExits = true;
                            }
                        }
                        if (CatchExits == false)
                        {
                            base.Problems.Add(new Problem(base.GetResolution(method.Name.Name), method.Name.Name));
                        }
                    }
                }
                return base.Problems;
            }
        }