Search code examples
fxcopfxcop-customrules

Custom FxCop rules to check attributes in MVC application


Is there a reasonably simple way to get FxCop to check whether there is any usage of ViewBag, ViewData in MVC application.


Solution

  • The very simplest approach would be to screen for MemberBinding instances with the name "ViewBag" or "ViewData" (with get_ and set_ prefixes). This may lead to quite a few false positives, so the next level of complexity/completeness would be to check the type of the MemberBinding target to see if it's a view or controller. e.g.:

    private readonly string[] _forbiddenNames = new string[] { "get_ViewBag", "set_ViewBag", "get_ViewData", "set_ViewData" };
    
    public override ProblemCollection Check(Member member)
    {
        var method = member as Method;
        if (method != null)
        {
            this.Visit(method.Body);
        }
    
        return this.Problems;
    }
    
    public override void VisitMemberBinding(MemberBinding memberBinding)
    {
        base.VisitMemberBinding(memberBinding);
    
        var memberName = memberBinding.BoundMember.Name.Name;
        if (this._forbiddenNames.Contains(memberName))
        {
            this.Problems.Add(new Problem(this.GetResolution(memberBinding.BoundMember), memberBinding, memberName));
        }
    }