How to validate DataReader is actually closed using FxCop custom rule?

感情迁移 提交于 2019-12-06 06:30:12

问题


I have written couple of custom rules in for FxCop 1.36. I have written code to find weather an opened DataReader is closed or not. But it does not check which DataReader object is calling the Close() method so I can't be sure if all opened DataReader objects are closed!!

2nd: If I am a DataReader in an 'if/else' like

if 1=2
 dr = cmd.ExecuteReader();
else
 dr = cmd2.ExecuteReader();
end if

In this case it will search for 2 DataReader objects to be closed.

I am putting my code for more clarity.

public override ProblemCollection Check(Member member)
{
    Method method = member as Method;
    int countCatch =0;
    int countErrLog = 0;
    Instruction objInstr = null;
    if (method != null)
    {
        for (int i = 0; i < method.Instructions.Count; i++)
        {
            objInstr = method.Instructions[i];
            if (objInstr.Value != null)
            {
                if (objInstr.Value.ToString()
                    .Contains("System.Data.SqlClient.SqlDataReader"))
                {
                    countCatch += 1;
                }
                if (countCatch>0)
                {
                    if (objInstr.Value.ToString().Contains(
                        "System.Data.SqlClient.SqlDataReader.Close"))
                    {          
                        countErrLog += 1;
                    }
                }
            }
        }
    }
    if (countErrLog!=countCatch)
    {
        Resolution resolu = 
            GetResolution(new string[] { method.ToString() });
        Problems.Add(new Problem(resolu));
    }
    return Problems;
}

回答1:


With FxCop this actually very hard (if not possible). Microsoft found this out too when they wanted to add some security analysis rules to FxCop for VS2010. The problem is that the Dataflow Analysis of FxCop isn't good enough. For this reason Microsoft built a new analysis engine that actually can do this. it is called Phoenix, but I only the Visual Studio 2010 Ultimate edition contains this engine (there is no free version available). Read more about it here.



来源:https://stackoverflow.com/questions/2408546/how-to-validate-datareader-is-actually-closed-using-fxcop-custom-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!