I am trying to get a return value and it keeps giving me an error.
I am trying to grab the “roleid” after the username has been validated by sending it the username– I can’t figure out what I am doing wrong?
public string ValidateRole(string sUsername)
{
string matchstring = "SELECT roleid FROM tblUserRoles WHERE UserName='" + sUsername +"'";
SqlCommand cmd = new SqlCommand(matchstring);
cmd.Connection = new SqlConnection("Data Source=(local);Initial Catalog=samplename;Integrated Security=True");
cmd.Connection.Open();
cmd.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter();
DataTable dt = new DataTable();
sda.SelectCommand = cmd;
sda.Fill(dt);
string match;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
match = row["roleid"].ToString();
return match;
}
}
else
{
match = "fail";
return match;
}
}
The “Not all code paths return a value” error you are seeing is a compiler error, not a runtime error, so the problem is with your C# code not being correct.
In this case it is because you have a return statement in a foreach loop and the compiler is not quite smart enough to see that your code would go down the ‘else’ path if there were no rows in the datatable. I.e. the compiler cannot see that the ‘If (true)’ branch will always return a value.
Best practice is to always have a return statement at the end of the function, and to initialize you variables (‘match’ is not initialized). If you return part way through, your code is less readable too.
The simplest fix is:
However, there are several other issues with the code you may not be aware of:
You have a SQL Injection vulnerability that makes your
application completely insecure. This is because you have
concatenated SQL strings to make a query rather than writing a
parametized query.
You should get in the habit of using a ADO.NET DataReader over a DataAdapters and DataTables. Or better, avoid DataTables altogether as
they are legacy. Use Linq2Sql or Entity Framework for your data
access layer and you will write far less code.
You should seriously consider using ASP.NET Membersip API for your authorization and roles etc. If you did that, your function would not even be required – you’d just write: Roles.IsUserInRole(sUserName, “User”) to check whether a user is in a certain role.
When you use a resource that implements IDisposable, like SQLConnection, you should wrap its use in a using() {} block so that you always release the resource as soon as possible.