开发者

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

开发者 https://www.devze.com 2022-12-22 14:05 出处:网络
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()

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(开发者_如何学JAVA) });
        Problems.Add(new Problem(resolu));
    }
    return Problems;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消