The method SaveGroupStepPermissions(...)
is a database API class.
If an error occurs within the method the exception is trapped. Whether this is good design or not is not the scope of this question as I need to adhere to product guidelines.
I feel that this method is to complex and too lenghty. The obvious solution is to break out code into new functions, but I'm not sure how to do that in a way that is logical.
Important! If an error occurs the method should stop processing and return. That means both foreach
loops must be exited.
Note: Input validation is performed in InsertGroupStepPermission()
and UpdateGroupStepPermission()
.
Feel free to suggest improvements to code and comments beside the main question!
public static List<EventItem> SaveGroupStepPermissions(string connectionString, int companyID, List<Group> groups, List<GroupStepPermissions> gsp)
{
var result = new List<EventItem>();
result.Add(new EventItem("Insert Step permissions"));
result.Add(new EventItem("Update Step permissions"));
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction tran = conn.BeginTransaction("ProductName.GSP.cid" + companyID.ToString()))
{
foreach (Group group in groups)
{
foreach (GroupStepPermissions stepPermission in gsp)
{
if (stepPermission.RowID == 0) //new permission that does not exist in the database. (INSERT)
{
try
{
InsertGroupStepPermission(conn, tran, stepPermission, companyID, group.ID);
result[0].SubEvents.Add(new EventSubItem("Added rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.OK, "Insert OK", stepPermission));
}
catch (Exception x)
{
result[0].SubEvents.Add(new EventSubItem("Failed to add rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.Failed, x.Message, stepPermission));
throw;
}
}
else //Existing stepPermission. (UPDATE)
{
try
{
UpdateGroupStepPermission(conn, tran, stepPermission, companyID, group.ID);
result[1].SubEvents.Add(new EventSubItem("Updated rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.OK, "Update OK", stepPermission));
}
catch (Exception x)
{
result[1].SubEvents.Add(new EventSubItem("Failed to update rights for '" + group.Name + "' in step '" + stepPermission.StepTitle + "'", StatusEnum.Failed, x.Message, stepPermission));
throw;
}
}
}
} //End outer for
tran.Commit(); //important :)
}
}
}
catch(Exception x)
{
var eItem = new EventItem("Failed to save step permissions");
eItem.SubEvents.Add(new EventSubItem("Error: " + x.Message));
result.Add(eItem);
}
return result;
}
x.message
should bex.Message
. There's also nothing as upsetting as only having an exception message when debugging - don't throw away my stack trace! \$\endgroup\$