How to validate DataReader is actually closed usin

2020-07-18 02:55发布

问题:

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.