// // Swap(): // // If possible, function swaps the courses for two student. // So, if student s1 was enrolled in course c1, and student s2 // was enrolled in course c2, after succesful execution // student s1 is enrolled in s2, and student s2 is enrolled in s1. // // Return values: // 0 - failure // 1 - success // private int Swap(int s1, int s2, int c1, int c2) { int retries = 0; using (var db = new CoursemoDataContext()) { while (retries < 3) { try { var txOptions = new TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { // both students must be enrolled if (StudentEnrolled(s1, c1) && StudentEnrolled(s2, c2)) { db.UnregisterStudent(s1, c1); db.RegisterStudent(s2, c1); System.Threading.Thread.Sleep(_delay); db.UnregisterStudent(s2, c2); db.RegisterStudent(s1, c2); db.SubmitChanges(); transaction.Complete(); return(1); } else { return(0); } } } catch (SqlException exc) { // deadlock if (exc.Number == 1205) { retries++; } } catch (Exception e) { MessageBox.Show("Swap(): " + e.Message); return(0); } } // while } return(0); } // Swap()
// // Drop(): // // If possible, function drops the student from the course. // // Return values: // -1 - error // 0 - dropped, no waitlist // 1 - dropped, enrolled student from waitlist // 2 - not enrolled, dropped from waitlist // 3 - student was not either enrolled or waitlisted // private int Drop(int sid, int cid) { int retries = 0; // make sure parameters are valid if (sid < 0 || cid < 0) { return(-1); } using (var db = new CoursemoDataContext()) { while (retries < 3) { try { var txOptions = new TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { // student enrolled, drop course and enroll first student on waitlist if (StudentEnrolled(sid, cid)) { db.UnregisterStudent(sid, cid); // candidate on waitlist exists int sidFromWaitList = GetFirstStudentFromWaitlist(cid); System.Threading.Thread.Sleep(_delay); if (sidFromWaitList != 0) { db.RegisterStudent(sidFromWaitList, cid); db.UnwaitlistStudent(sidFromWaitList, cid); db.SubmitChanges(); transaction.Complete(); return(1); } db.SubmitChanges(); transaction.Complete(); return(0); } // student not enrolled, but waitlisted, remove from waitlist else if (StudentWaitlisted(sid, cid)) { db.UnwaitlistStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(2); } else { return(3); } } } catch (SqlException exc) { // deadlock if (exc.Number == 1205) { retries++; } } catch (Exception e) { MessageBox.Show("Drop(): " + e.Message); return(-1); } } // while } return(-1); } // Drop()