sticky
Tell me what kind of Custom Rule you want to write!!!

    General discussion

  • 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

     

    Wednesday, July 04, 2007 1:35 AM

All replies

  • 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.

     

     

     

    Wednesday, July 18, 2007 5:09 PM
  • 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

     

    Thursday, August 23, 2007 2:55 PM
  •  

    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.

    Tuesday, September 04, 2007 10:43 AM
  •  

    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

    Friday, September 07, 2007 4:37 PM
  • 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.

     

    Monday, September 10, 2007 6:55 AM
  • 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

    Wednesday, September 12, 2007 8:33 PM
  • 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 9:50 AM
  • 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

    Thursday, September 13, 2007 5:17 PM
  • 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 2:44 AM
  • 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:38 AM
  • 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:42 AM
  • 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 5:52 AM
  • 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.

    Friday, September 14, 2007 10:37 PM
  • 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 9:31 PM
  • 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

    Monday, September 17, 2007 10:47 PM
  • 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.

    Tuesday, September 18, 2007 5:29 AM
  • 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;

    }

    }

    Wednesday, September 19, 2007 2:07 PM
  • 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???

    Friday, September 28, 2007 12:43 PM
  • 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 5:46 AM
  • Thanks sasikumar it really helped me lot.

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

    Saturday, September 29, 2007 10:35 AM
  • 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.

    Monday, October 01, 2007 6:39 AM
  • 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
    Thursday, October 11, 2007 1:57 PM
  • 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
    Wednesday, October 17, 2007 8:45 AM
  • 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

     

    Thursday, October 18, 2007 1:54 AM
  • 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

    Monday, October 22, 2007 8:36 AM
  • 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

     

    Wednesday, October 24, 2007 10:46 PM
  • 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.

    Friday, October 26, 2007 3:09 PM


  • 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 )

    Wednesday, January 09, 2008 7:23 PM
  • 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

     

    Thursday, May 08, 2008 5:57 PM
  • 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

     

    Monday, May 12, 2008 4:04 PM
  • 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.
    Thursday, May 29, 2008 3:13 AM
  • 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 12:25 PM
  • 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

    Wednesday, October 08, 2008 1:04 PM
  • 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?

     

    Friday, December 26, 2008 7:08 AM
  •  

    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

     

    Wednesday, February 11, 2009 5:54 PM
  •  

    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
    Friday, March 13, 2009 7:45 AM
  • 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
    Monday, May 04, 2009 7:43 PM
  •  

    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

    Thursday, September 10, 2009 9:41 AM
  • 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;
            }
        }
    Saturday, October 03, 2009 10:07 PM
  • Hi, I need to find out whether there is any hard-coding in the method. i.e. whether the developer has written string str = "Test" instead of creating a constant "Test" and then assigning this constant to the string str. In both the cases, I can only find the LDSTR in the assembly code. How do I go about it?
    Wednesday, December 23, 2009 7:00 AM
  • Hi,

    As per our coding standard we need to make sure that each method must comply with the following two statements ...
    1. Try/Catch must be present
    2. if (InvokeRequired) check must be present.

    I am trying to create a fxCop custom rule for this.

    I am able to write a custom rule for checking try/catch in fxCop. But the issue comes when code has both try/catch inside InvokeRequired ... e.g.

            private void Form1_Load(object sender, EventArgs e)
            {
                if (!InvokeRequired)
                {
                    try
                    {
                        string s = "";
                        s = "50";

                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                else
                {
                    Invoke(new System.EventHandler(Form1_Load), sender, e);
                }

            }

    In this case method.Instruction doesnot give me try/catch statements. Please help me in creating custom rule for checking this type of coding.

    Thanks,
    Pankil

    Thursday, February 18, 2010 5:46 PM
  • I need a rule which checks all the methods and report a violation if the method takes more than 3 parameters .

    cal any1 pls help in dis?

    Thanks in advance

    Wednesday, April 28, 2010 6:55 AM
  • Hi,

    Can you tell me what will be the problem if XML file is not loading in DLL in Microsoft FxCop

    Below is my code for XML file and .Cs file

    .CS File

     

    public class ClsForSpellCheck : BaseIntrospectionRule

    {

     

    public ClsForSpellCheck()

    :

    base("ClsForSpellCheck1", "DllForSpellCheck.RuleForSpellCheck", typeof(ClsForSpellCheck).Assembly)

    { }

     

     

    public override ProblemCollection Check(Resource resource)

    {

     

    using (MemoryStream mStream = new MemoryStream(resource.Data, false))

    {

     

    using (ResourceReader reader = new ResourceReader(mStream))

    {

     

    foreach (DictionaryEntry entry in reader)

    {

     

    string s = Convert.ToString(entry.Value);

     

    if (s != null)

    {

     

    foreach (String sWord in WordParser.Parse(s, WordParserOptions.None))

    {

     

    if (NamingService.DefaultNamingService.CheckSpelling(sWord) != WordSpelling.SpelledCorrectly)

    {

     

    this.Problems.Add(new Problem(this.GetResolution(sWord), sWord));

    }

    }

    }

    }

    }

    }

     

    //return base.Check(resource);

     

    return this.Problems;

    }

    }

     

    XML File:-

    <?

     

    xml version="1.0" encoding="utf-8" ?>

    <

     

    Rules FriendlyName="Spell Check Rule">

    <

     

    Rule TypeName="ClsForSpellCheck" Category="SpellChecking" CheckId="S100">

    <

     

    Name>Check For Correct Spelling</Name>

    <

     

    Description>It will check spelling</Description>

    <

     

    Owner>Aastha Pallav</Owner>

    <

     

    Url></Url>

    <

     

    Resolution>Rectify the spelling where you got the exception</Resolution>

    <

     

    Email></Email>

    <

     

    MessageLevel Certainty="99">Error</MessageLevel>

    <

     

    FixCategories>Breaking</FixCategories>

    </

     

    Rule>

    </

     

    Rules>

    I had set the property of xml file in build action as a Embedded Resources

    Monday, June 21, 2010 12:31 PM
  • Joe,

    we have a bunch of rules, some of which are probably sufficiently general to be present in the product. Some examples:

     - Do not use System.Diagnostics.Trace for logging or asserts (For logging, use the Syste.Diagnostics.TraceSource class. Replace Trace asserts with regular if statements and exception throwing.)

    - Prefer generic collections over non-generic ones

    - Non-public interfaces should have more than one implementation.

    - Public API's should not depend on nested namespaces

    - Do not throw NotImplementedException

    - Fields should be private

    - Optional parameters should have a default default value (SomeMethod (int i = 0) is ok, but SomeMethod(int i = -1) is not)

    - Non derived internal types should be sealed

    - Compare strings correctly (tests for s1.ToUpper() == s2.ToUpper() and similar stuff)

    - Use LINQ correctly (tests for .Where(condition).Any() instead of .Any(condition), .Coun() == 0 instead of .Any(), and several others)

    Some examples from our WCF rules:

    - ServiceContractShouldSpecifyNamespace (A ServiceContractAttribute attribute should explicitely specify a Namespace, and it should be a valid URI.)

    - DataContractShouldSpecifyNamespace (A DataContractAttribute attribute should explicitely specify a Namespace, and it should be a valid absolute URI.)

    - CollectionDataContractShouldSpecifyNamespace

    - ServiceBehaviorShouldNotIncludeExceptionDetailInFaults

    - ImplementBehaviorsCorrectly (Implementations of IContractBehavior, IOperationBehavior or IServiceBehavior should be sealed attributes with a correct AttributeUsageAttribute.)

    - DataMemberShouldNotThrow (DataMember properties should not throw exceptions)

    Similar rules can be created for many technologies in the .NET framework. They capture "best practices" and are a great learning tool for newcommers to the technology. In some cases they can actually capture common "bugs". This is especially true for attributes, as they typically do not (and often cannot) validate their properties. For example, the IsDefaultCollection property on ConfigurationPropertyAttribute set to true will only work if the name parameter is the emtpy string.

    Hope this helps.

    BTW, I have noticed that some suggestions offered here are already covered in StyleCop. Some of them could be handled in FxCop/CA too. I would suggest avoiding duplication between the two tools, and prefering FxCop/CA when possible.

    Tuesday, July 20, 2010 12:31 PM
  • Cheers for all the nice new rules, guys. I only have a few minor niggles really, but it'd be great if you could consider these improvements:

    I'm glad to see the back of CA1805 (don't initialise unnecessarily) because I advocate programmers being explicit: An uninitialised variable might mean that a programmer intended it to take on the default value, or it may mean that they forgot to assign the correct default value. If they explicitly set a value to false then you know that was a deliberate intention. So I'd love to see a rule which is the opposite of 1805: "All variables must be explicitly initialised with a default value". C# already enforces this for local variables (attempt to use an uninitialised variable), so it'd be great to get something equivalent for members as well.

    I'd like to improve the spell-checking rules. The principle of ensuring consistent spelling across a project is great. However, it's very annoying that it ignores words in the dictionary if they are 3 or fewer characters: We use a "Grl" company namespace, so we get thousands of spurious warnings that we cannot suppress globally. Similarly, we use a lot of short industry-standard abbreviations, which again we can't treat as valid "words". I agree that abbreviations are generally a bad thing, but in many cases you can make code more compact and therefore more easily readable by using a few carefully chosen and intuitive abbreviations across a project - Things like 'num', 'ptr', and 'obj' are extremely common, (especially as 'object' is a reserved word, so you have to find an alternative - I prefer the use of 'obj' to ghastly contrived names like 'theObject', although one could argue weakly that 'object' is too generalised a name and a more specific name should be used)). Similarly, "x" is not an abbreviation or a hungarian notation, it is the name of a mathematical symbol, and in most cases it represents the most sensible and expressive name for an "x" that can be used. Basically, if I put something in the dictionary to indicate that it I wish it to be allowed, then please allow it without exceptions - the rule just needs to be more flexible/less prescriptive!

    The new rule for checking spelling in string literals (CA2204) is sadly rather useless for us. The only string literals in our code should be text that the end-user will never see (internal exceptions, assertion messgaes, and strings used in XML serialisation for example).  So one new rule to consider would be something that can pick up the use of a string literal and complain if it's not in a resource, except if it is in an exception/assert call. Unfortunately, the existing rule fails because these are all cases where camel-case tokens (as opposed to plain English text) are prevalent, and unfortunately the spelling checker uses a different algorithm (why?) than the other spelling rule, so it falls over on every type-name it hits. That is, it gives an error on pretty much every string literal in our code - ergo it was turned off 5 seconds after we upgraded to 2010. It would therefore be nice to make this spelling checker actually work properly for typical string literals.

    It would be great to have some extra rules for properties (forgive me if I'm mentioning rules that are in there, I can't remember exactly what';s available already off the top of my head. These are just all the things I'd personally apply to properties):

    • Properties must be simple (preferably little more than member access methods, though a small amount of decision logic or caching code is acceptable. Essentially, someone calling a property is treating it like a simple field access, and does not expect massive amounts of performance-sapping code to be executed to return their result)
    • Properties must not have side effects (they should not raise events)
    • Properties should not throw exceptions
    • bool properties should be named according to specific conventions (e.g. "Is...", "Are...", "Can...", or "Should..."). i.e. don't use "File.Open" or "File.Opened", use "File.IsOpen".

     

    Thursday, July 29, 2010 3:10 PM
  • Hello Claudio

    I need some help from you. I have written a custom FxCop rule for identifying a string in my application. But I don't know how to debug Custom FxCop rule and cannot check whether my code is correct or not.

    Here is my code:

    CheckingForWord.cs file

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.FxCop.Sdk;

    [assembly: CLSCompliant(true)]
    namespace CheckingForWord
    {
     
        public class Testing : BaseIntrospectionRule 
        {
            string _str = "glo";
                   
            public Testing(): base("CheckingForWord", "CheckingForWord.CustomRules", typeof(Testing).Assembly)
            {
           
            }
           
             
            /////// writing custom rule for checking string in each namespace
         
            public override ProblemCollection Check(TypeNode type)
            {
                if (type != null)
                {

                    if (type.Namespace.Name.Contains(_str) == true)
                    {
                        Problem problem = new Problem(base.GetResolution(new object[] { type.Namespace.Name.Contains(_str) }));
                        base.Problems.Add(problem);

                    }

                }
                else
                {
                    return null;
                }
                return base.Problems;
              }
             
        }
    }

    CustomRules.xml file

    <?xml version="1.0" encoding="utf-8" ?>
    <Rules>
     
      <Rule TypeName="CheckingForWord" Category="WordChecking" CheckId="ID1">
        <Name>Checking for specified word</Name>
        <Description>Word "glo" cannot be used in NamingConvention or in the code</Description>
        <Resolution>Replace the word "glo" with some other word in your code</Resolution>
        <MessageLevel Certainity="99">Warning</MessageLevel>
        <Message Certainity="99">Warning</Message>
        <FixCategories>Non Breaking</FixCategories>

      </Rule>

    </Rules>

    Note:

    I have set "Build Action" property to "Embedded Resource" for "CustomRules.xml" file

    I have followed these below links for debugging my Custom FxCop Rule. But I am unable to do it . Can you please explain in detail each step and let me know what is the mistake in my code. I would also like to know usage of "Microsoft.FxCop.Sdk" namespace classes,methods and properties

    http://blogs.msdn.com/b/codeanalysis/archive/2007/05/16/faq-how-do-i-debug-a-custom-rule.aspx

    http://www.binarycoder.net/fxcop/html/debugging.html

    http://blogs.msdn.com/b/codeanalysis/archive/2010/03/26/how-to-write-custom-static-code-analysis-rules

    -and-integrate-them-into-visual-studio-2010.aspx?wa=wsignin1.0

     

    Please let me know at the earliest.

     

    Thursday, August 12, 2010 5:20 AM
  • Enforcing maximum limit on number of lines in methods.
    Tuesday, September 07, 2010 8:47 PM
  • As a part of debugging process you need to launch the FxCopCm.exe as an external program. make sure you are referring to the correct target directory and the correct path of the dll of the custom rule you created.

    Tuesday, September 07, 2010 8:50 PM
  • Is there any document as such how to write custom rules in FXCOP, if so then please provide me the document or link to respective document.

    Regards,

    Jack C.


    Coutinho
    Wednesday, September 08, 2010 7:06 AM
  • @Jackson, you can write a custom rule as an assembly and use the same in FXCOP. I build one by following this link. Pretty easy.
    Wednesday, September 08, 2010 8:40 AM
  • Hi Ashish,

    First of all thanks for your prompt reply. That link was some what helpful for me, actually I was searching for examples for setting rule for "Use of try/finally to clean up resources; i.e resources which are used in try block should and need to close in finally block, how can this type of checking will possible in FXCop in the Finally"

    Regards,

    Jack C.


    Coutinho
    Wednesday, September 08, 2010 9:06 AM
  • Jackson, 

    I built a rule for enforcing maximum number of lines and you can find the source of the same here. It is not perfect (YET), however, definitely you can start with the same. Let me know If I could help in this.

    Also, I wanted to point out something very similar existing in VS inbuilt rules. Suppose the developer writes the following code:-

    SqlConnection con = null;
                try
                {
                    con = new SqlConnection("Test");
                    con.Open();
                }

     

                catch (Exception exp)
                {
                    throw;
                }

     

     

    and definitely the developer should have used finally block there and should have closed the connection object there. However, If you enable rule number CA2000 under Microsoft.Reliability on the above code, you will see the following warning:-
    "In method 'Program.Test()', call System.IDisposable.Dispose on object 'con' before all references to it are out of scope."

    So, in order to correct this issue, the developer would write something like below:-

     

     SqlConnection con = null;
                try
                {
                    con = new SqlConnection("Test");
                    con.Open();
                }

     

                catch (Exception exp)
                {
                    throw;
                }

     

                finally
                {
                    if (con != null)
                    {
                        con.Dispose();
                    }                

                }

     

     

    Although the above inbuilt rule does not advice you to use finally block, It actually helps the developer by telling that he should dispose the object.

    HTH,
    Ashish

     

    Wednesday, September 08, 2010 9:28 AM
  • Hi Ashish,

    Thanks a lot, one last query, can i get detail documentation on built in rules of fxcop, as u said C2000 is used for checking for IDisposable. Other CheckID's and their description? And is there any possibility to change existing FxCop rules or modify existing rules to work for my needs..? 

    Regards,

    Jack C.

     


    Coutinho
    Wednesday, September 08, 2010 10:01 AM
  • Documentation on code analysis rules :- Here you go. 
    For changing the existing rules, you can have a look at the assemblies for the same which are located at 

    %program files%Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\Rules
    you can disassemble them to see the source. Its upto you to change them.

    Wednesday, September 08, 2010 11:12 AM
  • Hi,

    I had try'd with 1 Disassembler,  "9Rays.Spices.Net" but it dint worked out for me. Is there good disassembler which you know..?

     

    Regards,

    Jack C.

    Wednesday, September 08, 2010 11:33 AM
  • Try this. This is an add-in to the reflector.
    Wednesday, September 08, 2010 11:41 AM
  • Hi,

     

    I am using FxCop 1.36, in that CA2000 is not being shipped as per the below linked document, will there any other workaround on same CheckID..?

    http://blogs.msdn.com/b/codeanalysis/archive/2008/01/07/faq-which-rules-shipped-in-which-version.aspx

     

    Regards,

    Jack C.

    Wednesday, September 08, 2010 11:52 AM
  • Hi Ashish,

    Thank You very much for diassembler. It Worked out really COOL :)

     

    Thanks N Regards,

    Jack C.

    Wednesday, September 08, 2010 12:39 PM
  • Hi,

     

    I want to write 3 Rules :

    1) Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case.

    2) All switch statements shall have a default label as the last case label

    3) Need to check in all methods, for compulsory TRY,CATCH and Finally block

    How exactly i can achieve this task using fxcop???

     

    Regards,

    Jackson C.

    Monday, September 13, 2010 1:27 PM
  • Hi,

    I have just come across this analysis tool and really want to benefit from it.

    I need to create 3 rules:

    • A rule to pick up hardcoded URLs in a string literal, eg. str = "www.microsoft.com"
    • A rule to pick up redundant using directives, eg. using System.Core (and this is not used)
    • A rule to pick up large blocks of commented code

     

    Any help or guidance would be really appreciated.

    Thanks,

    Navin.

    Tuesday, October 19, 2010 12:04 PM
  • Hi Ashish,

    I have just come across this analysis tool and really want to benefit from it.

    I need to create 3 rules:

    • A rule to pick up hardcoded URLs in a string literal, eg. str = "www.microsoft.com"
    • A rule to pick up redundant using directives, eg. using System.Core (and this is not used)
    • A rule to pick up large blocks of commented code

     

    Any help or guidance would be really appreciated.

    Thanks,

    Navin.

    Tuesday, October 19, 2010 12:06 PM
  • I would like a custom rule to avoid InvalidCastException in foreach statements.  The C# foreach keyword will iterate through all items in an enumeration and implicitly cast each item to the type specified.  This is prone to an InvalidCastException at runtime especially after refactoring.  This can lead to bugs that might only occur during obscure conditions.  The compiler does not detect it presumably due to backwards compatibility for early versions of C# where foreach uses IEnumerable, which doesn't define the type.

    This is a long thread, so I posted a new thread with questions on what I could find debugging an example:

    http://social.msdn.microsoft.com/Forums/en/vstscode/thread/eeb99bae-6105-4104-8f7e-50b698e17619

    Thursday, December 16, 2010 4:03 PM
  • Hi Can we write some Custom rules to suppress some of the regular warnings and errors?

    To suppress those regular warnings and errors, i think we can also 'ignore()deselect' the specific rules which are the possible reasons for the specific errors or warnings. Can we do this? or do we have to write Custom Rules? If so, on what basis we have to write the custom rules?

    Thanks!

    Wednesday, March 23, 2011 9:19 PM
  • Hello Joe,

     

    Considering that many developers in this forum ask how to write custom rules in FxCop, my team has created a code sample for this frequently asked programming task in Microsoft All-In-One Code Framework. You can download the code samples at:

     

    VBCustomCodeAnalysisRule

     

    http://bit.ly/VBCustomCodeAnalysisRule

     

    CSCustomCodeAnalysisRule

     

    http://bit.ly/CSCustomCodeAnalysisRule

     

    With these code samples, we hope to reduce developers’ efforts in solving the frequently asked

    programming tasks. If you have any feedback or suggestions for the code samples, please email us: onecode@microsoft.com.

    ------------

    The Microsoft All-In-One Code Framework (http://1code.codeplex.com) is a free, centralized code sample library driven by developers' needs. Our goal is to provide typical code samples for all Microsoft development technologies, and reduce developers' efforts in solving typical programming tasks.

    Our team listens to developers’ pains in MSDN forums, social media and various developer communities. We write code samples based on developers’ frequently asked programming tasks, and allow developers to download them with a short code sample publishing cycle. Additionally, our team offers a free code sample request service. This service is a proactive way for our developer community to obtain code samples for certain programming tasks directly from Microsoft.

    Thanks

    Microsoft All-In-One Code Framework

    Thursday, March 24, 2011 9:08 AM
  • Hi Claudio,

    I saw in your post that you have written the FxCop custom rule to check if the developers have written appropriate comments or not. I am also in need of similar custom rule. It would be great if you could provide the code for the same.

    I can be reached at anirban_kundu1@yahoo.co.in

     

    Thanks,

    Anirban

    Monday, April 18, 2011 8:34 PM
  • I've had a couple of rule idea's that I might work on, if I do I'll share the code, if someone else makes them, please let me know:

    1. Flag instances of xxx.Parse(yyy.ToString()), xxx.TryParse(yyy.ToString), Convert.ToXXX(yyy.ToString)

    I very often come across code that uses a string/parse roundtrip instead of a simple conversion or cast. This often happens when people use an untyped datasource. The rule should catch not only direct type conversions, but might also check string x = someObject.ToString(); int y = int.Parse(x);

    2. Flag empty catch blocks or try/catch blocks where the catch only contains a throw or rethrow

    During codereviews I often found useless try/catch blocks, where a developer decided error handling might be useful, but didn't know how. Or where it was added because it looked right.

    3. DataContract, CollectionContract, EnumValue attributes should be present on all datacontract members

    additionally, the values of an enum must have the proper EnumValue attributes and enumerations should have a None=0 value

    4. Regex rules

    Check if Regex strings compile (if the regex is passed a constant string) Flag regex instances that should be re-used, Flag Regex instances with a Compiled flag but a non-constant expression unless it is used in a loop afterwards or stored in an instance or static member.

    5. String Format pattern check

    Check constant String.Format arguments to see if the number of arguments is higher or equal to the {0}..{n} in the format string

    6. verify SPMetal and Azure Linq2tables expressions

    These linq providers only support a very limited subset of functions and these only show at runtime. It would be nice if the set of methods could be specified per IQueryable implementation. This does have limitations if the base type cannot be resolved.

    7. Flag methods that use lots of bools to set flags instead of using a Flags enumeration.

    Due to the lack of readability, methods that look like string auch = PainfulMethod(true, false, true, true, true); should be flagged  and an enum should be suggested, might even pre-generate a proper enum definition in the error message.

    8. WCF Dispose pattern.

    Verify that WCF Channel objects are disposed properly, that the ConnectionState is checked and that either Abort or Dispose is used. In class Dispose method calls to Dispose/Close on a WCF object should always be guarded by a try/catch or replaced by Abort.

    9. Use Properties.Settings or a custom configuration setting instead of AppSettings

    For small scale apps, the AppSettings are fine, but if you need proper validation, have multiple library configurations etc, then it won't do.

    Thursday, August 18, 2011 9:09 PM
  • Hi Ashish,

    I have just come across this analysis tool and really want to benefit from it.

    I need to create 3 rules:

    • A rule to pick up hardcoded URLs in a string literal, eg. str = "www.microsoft.com"
    • A rule to pick up redundant using directives, eg. using System.Core (and this is not used)
    • A rule to pick up large blocks of commented code

     

    Any help or guidance would be really appreciated.

    Thanks,

    Navin.

    Redundant using directives are no longer present after compilation, so they cannot be checked using FxCop. maybe StyleCop can... Resharper and CodeRush offer this as add-ins to the IDE. Large blocks of comments have the same problem, comments are not persisted into the compiled output, so you'll need to parse the sources to check them. Again, StyleCop is your friend here.
    Friday, August 19, 2011 8:52 AM
  • It might be worth noting that: 

    The WebService Software Factory ships with a number of additional rules for checking WCF code: http://servicefactory.codeplex.com/

    MSOCAF ships with a number of additional rules that check for Sharepoint aniti patterns (I've retargetted those rules to support Visual Studio with a few simple steps, see my blog at http://blog.jessehouwing.nl)

    CAT.NET 1.1 ships with a FxCop rule which integrates with older versions of FxCop which does a number of additional security checks on web code (ASP.NET, Sharepoint)

    What I'd really like is for the next version of FxCop to be able to load both old and new rules. There are a lot of other rule sources, but they all use different versions of FxCop and it's hard to integrate them into VisualStudio and msbuild.Targetting the rules against different FxCop versions is required to integrate them properly into different Visual Studio versions at this point in time and the only solution we have at the moment is to run multiple FxCop tasks in the build, one for CAT.NET, one for MSOCAF, one for SPDisposeChecker, one for the regular FxCop. Being able to load different rule versions into one FxCop project would be great, though it probably requires some creative AppDomain coding :).

    Friday, August 19, 2011 9:34 AM
  • Hi,

    Could you plz send me the source code

  • 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)

    since we are alos planning to incorporate that.

    Plz send to dotnetlearner@hotmail.com

     

Monday, October 10, 2011 8:06 AM
  • For XML comments checking, check out: http://www.codeproject.com/KB/cs/FxCop135.aspx You might need to change a few namespaces to get it to work with FxCop 10.
    Monday, October 10, 2011 10:48 AM
  • Hi, I saw lots of example just against the Introsepction rule engine instead of the new Data Flow Engine in the forum.

    So, anybody can  provide an example or /URL for how to write custom rules against the new Data Flow Engine?

    And How integrated them with the VS 2010.

    thank you very much.

     


    • Edited by Jacky_shen Sunday, October 16, 2011 4:07 AM
    Sunday, October 16, 2011 3:49 AM
  • I would like something that will check for a writable shared field with no lock statement so that you don't forget to put in a lock statement and create thread unsafe code.

    chuckdawit

    Friday, February 17, 2012 8:04 PM
  • Hi Joe,

    Could you please give me the code for 

    1. Comments are written properly, wherever required. Defect ID & Developer name should not be specified in code.  

    2. Rule to avoid any hard coded values specifically mentioning local files system names in the code.

    Regards,

    Honey

    Wednesday, February 29, 2012 10:20 AM
  • @Honey

    Rule 1 needs to be a stylecop rule, comments are not persisted in the compiled code and can thus not be checked with FxCop.

    Rule 2 would be very simple if you were able to specify what these values should look like. Just look at all Literal's of type string and check them against your rule. See: http://fxcopcontrib.codeplex.com/SourceControl/changeset/view/7476#37977 for a rule which does something similar with Regex instances. 


    My blog: blog.jessehouwing.nl

    Wednesday, February 29, 2012 10:42 AM
  • Hi,

    I'm wondering if you can help me with a custom FxCop rule I want to write. I have a pair of methods: StartTransaction and EndTransaction. Within a method, StartTransaction should always be called first, followed by EndTransaction.

    I'm looking to author a rule that scans each method and confirms that the EndTransaction call comes after a StartTransaction call. This seems simple at first, but becomes complicated as I need to consider handled exceptions / try-catch-finally blocks, early return statements that may come before the EndTransaction call, etc...

    Are there any samples that demonstrate how to validate that if method A is present, method B is always invoked before the method exits?

    Thanks,

    -Craig


    • Edited by clichten Tuesday, March 13, 2012 1:45 AM
    Tuesday, March 13, 2012 1:44 AM
  • Hi Joe,

    I would like to write a custom rule in SharePoint for checking that caching should not be used  for SPListItemCollection objects

    Can you please help me out?

    Thanks

    Thursday, March 22, 2012 6:52 AM
  • Hi Joe,

    Can u pls help me with the source code for Fxcop rule: do not put more than 1 major class plus its auxillary class such as derived class in one source file..

    I am a begineer so dont have enough knowledge to make this customised rule..

    Pls also let me know if this rule is possible in fxcop "  evry switch statements should have a default labelas the last case label"

    Thnks.

    Thursday, April 19, 2012 9:49 AM
  • fxcope rule for: "do not put more than one major class plus its auxillary class such as derived class in one source file"

    Can u pls provide the source code for this as i m a begineer  and dnt have much idea about it..

    thnks.

    Thursday, April 19, 2012 9:53 AM
  • fxcope rule for: "do not put more than one major class plus its auxillary class such as derived class in one source file"

    Can u pls provide the source code for this as i m a begineer  and dnt have much idea about it..

    thnks.

    That would be a StyleCop rule. FxCop only sees the actual compiled code, and doesn't link those back to the files. (It can under special circumstances, but you shouldn't trust that). StyleCop inspects the source code and should be able to find exactly what you're looking for.

    My blog: blog.jessehouwing.nl

    Thursday, April 19, 2012 10:37 AM
  • Hi Joe,

    Pls also let me know if this rule is possible in fxcop "  evry switch statements should have a default labelas the last case label"

    Thnks.

    Such a rule isn't in there. And again, the last statement is something which will be hard to get from the compiled code, but easy to get from the sources. Again something where StyleCop will come to your rescue, where FxCop cannot.

    My blog: blog.jessehouwing.nl

    Thursday, April 19, 2012 10:38 AM
  • Hi Ashish,

    I have just come across this analysis tool and really want to benefit from it.

    I need to create 3 rules:

    • A rule to pick up hardcoded URLs in a string literal, eg. str = "www.microsoft.com"
    • A rule to pick up redundant using directives, eg. using System.Core (and this is not used)
    • A rule to pick up large blocks of commented code


    1) Should be prette simple, just check all assignments with a new string call. Check the contents of the literal.

    2) and 3) These should be implemented as stylecop rules.


    My blog: blog.jessehouwing.nl

    Thursday, April 19, 2012 10:46 AM
  • I'm having issues creating a rule to check if several variables have been initialized in the same line. For example:

    These would be invalid:

    int i, j ,k = 0;

    These would be valid:

    int i = 0;

    int j = 0;

    If I use "Field" I can't get the SourceContext to get the line number and if I use method.Instructions the SourceContext doesn't help me since I always get the same Start/End line...

    Any ideas?

    Friday, May 11, 2012 7:19 PM