How to validate DataReader is actually closed using FxCop custom rule?
Posted
by tanmay
on Stack Overflow
See other posts from Stack Overflow
or by tanmay
Published on 2010-03-09T11:14:28Z
Indexed on
2010/05/01
17:07 UTC
Read the original article
Hit count: 219
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;
}
© Stack Overflow or respective owner