public static void SaveHolidays(DSModel db, KeyBinder key, List<HolidayModel> model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");

            var holidaysToDelete = db.Holidays.ToList();
            foreach (var h in holidaysToDelete.ToList())
            {
                var check = model.Where(hh => hh.HolidayDate == h.HolidayDate).FirstOrDefault();
                if (check == null)
                    db.Delete(h);
                else
                    model.Remove(check);
            }

            foreach (var h in model)
            {
                Holiday poco = new Holiday();
                poco.HolidayDate = h.HolidayDate;
                db.Add(poco);
                key.AddKey(poco, h, h.GetName(p => p.HolidayDate));
            }
        }
        public CheckResult SaveFile(FileBlobModel model)
        {
            if (!model.IsChanged)
                return new CheckResult(model);

            using (DSModel db = DB.GetContext())
            {
                var check = FileBlobValidator.ValidateSave(db, model);
                if (check.Failed)
                    return check;

                KeyBinder key = new KeyBinder();
                try
                {
                    FileBlobRepository.SaveBlob(db, key, model);
                    db.SaveChanges();
                    key.BindKeys();
                    model.IsChanged = false;
                    return new CheckResult(model);
                }
                catch (Exception ex)
                {
                    key.RollbackKeys();
                    return new CheckResult(ex);
                }
            }
        }
 private static void UpdateBlob(DSModel db, KeyBinder key, FileBlobModel model)
 {
     FileBlob poco = db.FileBlobs.Where(b => b.BlobID == model.BlobID).FirstOrDefault();
     if (poco == null)
         throw new ArgumentException("File does not exist!", "BlobID");
     model.Map(poco);
 }
        private static void InsertDriver(DSModel db, KeyBinder key, DriverModel model)
        {
            Driver poco = new Driver();
            if (model.DriverCode == string.Empty)
                poco.DriverCode = "D" + DriverRepository.PeekDriverCode(db, "D");
            else
                poco.DriverCode = model.DriverCode;
            poco.FirstName = model.FirstName;
            poco.SecondName = model.SecondName;
            poco.LastName = model.LastName;
            poco.DateOfBirth = model.DateOfBirth;
            poco.DateOfHire = model.DateOfHire;
            poco.CellPhone = model.CellPhone;
            poco.EmergencyPhone = model.EmergencyPhone;
            poco.Email = model.Email;
            poco.PayRateOverride = model.PayRateOverride;
            poco.IsEnabled = model.IsEnabled;
            foreach (var l in model.Locations)
            {
                poco.LocationsDrivers.Add(
                    new LocationsDriver()
                    {
                        LocationID = l.LocationID,
                        Driver = poco,
                        TravelPay = l.TravelPay
                    });
                key.AddKey(poco, l, poco.GetName(p => p.DriverID));
            }
            db.Add(poco);

            key.AddKey(poco, model, poco.GetName(p => p.DriverID));
        }
        private static void InsertBlob(DSModel db, KeyBinder key, FileBlobModel model)
        {
            key.AddRollback(model.BlobID, model, model.GetName(p => p.BlobID));
            FileBlob poco = new FileBlob();
            model.Map(poco);
            db.Add(poco);

            key.AddKey(poco, model, model.GetName(p => p.BlobID));
        }
 private static Contact InsertContact(DSModel db, KeyBinder key, ContactModel model)
 {
     Contact poco = new Contact();
     poco.ContactName = model.ContactName;
     poco.ContactPhone = model.ContactPhone;
     poco.ContactEmail = model.ContactEmail;
     db.Add(poco);
     key.AddKey(poco, model, model.GetName(p => p.ContactID));
     return poco;
 }
        private static void UpdateMedical(DSModel db, KeyBinder key, DriverMedicalModel model)
        {
            var poco = db.DriversMedicals
                .Where(m => m.DriverMedicalID == model.DriverMedicalID)
                .FirstOrDefault();
            model.Map(poco);
            db.FlushChanges();

            SaveReminders(db, key, model, poco);
        }
        private static void InsertMedical(DSModel db, KeyBinder key, DriverMedicalModel model)
        {
            DriversMedical poco = new DriversMedical();
            model.Map(poco);
            db.Add(poco);

            key.AddKey(poco, model, model.GetName(p => p.DriverMedicalID));
            db.FlushChanges();
            SaveReminders(db, key, model, poco);
        }
        private static void InsertDriverLicense(DSModel db, KeyBinder key, DriverLicenseModel model)
        {
            var poco = new DriversLicense();
            model.Map(poco);
            db.Add(poco);
            key.AddKey(poco, model, model.GetName(p => p.DriverLicenseID));
            db.FlushChanges();

            SaveDriverLicensePermits(db, key, poco, model);
            SaveDriverLicenseReminders(db, key, poco, model);
        }
        private static Contact UpdateContact(DSModel db, KeyBinder key, ContactModel model)
        {
            var poco = db.Contacts.Where(c => c.ContactID == model.ContactID).FirstOrDefault();
            if (poco == null)
                throw new ArgumentException("No contact with the specified ID!");

            poco.ContactName = model.ContactName;
            poco.ContactPhone = model.ContactPhone;
            poco.ContactEmail = model.ContactEmail;
            return poco;
        }
        private static void UpdateDriverLicense(DSModel db, KeyBinder key, DriverLicenseModel model)
        {
            var poco = db.DriversLicenses.Where(d => d.DriverLicenseID == model.DriverLicenseID).FirstOrDefault();
            if (poco == null)
                throw new ArgumentNullException("poco");

            model.Map(poco);
            db.FlushChanges();

            SaveDriverLicensePermits(db, key, poco, model);
            SaveDriverLicenseReminders(db, key, poco, model);
        }
        public static void DeleteBlob(DSModel db, KeyBinder key, FileBlobModel model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");

            db.FileBlobs
                .Where(b => b.BlobID == model.BlobID)
                .DeleteAll();
        }
        public static Contact SaveContact(DSModel db, KeyBinder key, ContactModel model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");

            if (model.ContactID == 0)
                return InsertContact(db, key, model);
            else
                return UpdateContact(db, key, model);
        }
        private static void SaveReminders(DSModel db, KeyBinder key, DriverMedicalModel model, DriversMedical poco)
        {
            string sqlDelete = @"DELETE FROM drivers_medicals_reminders WHERE DriverMedicalID = @DriverMedicalID AND DriverMedicalReminderID NOT IN (@DriverMedicalReminderID);";
            string ids = "0";
            if (model.Reminders.Count > 0)
                ids = string.Join<uint>(",", model.Reminders.Select(r => r.DriverMedicalReminderID));

            sqlDelete = sqlDelete.Replace("@DriverMedicalReminderID", ids);

            db.ExecuteNonQuery(sqlDelete, new MySqlParameter("DriverMedicalID", poco.DriverMedicalID));
            string sqlInsert = @"
                INSERT INTO drivers_medicals_reminders
                  (DriverMedicalID, ReminderID, ReminderType, ShouldRemind) VALUES (@DriverMedicalID, @ReminderID, @ReminderType, @ShouldRemind);
                SELECT LAST_INSERT_ID();";
            string sqlUpdate = @"
                UPDATE drivers_medicals_reminders
                SET
                  DriverMedicalID = @DriverMedicalID, 
                  ReminderID = @ReminderID, 
                  ReminderType = @ReminderType, 
                  ShouldRemind = @ShouldRemind
                WHERE
                  DriverMedicalReminderID = @DriverMedicalReminderID;";

            foreach (var rem in model.Reminders)
            {
                if (rem.DriverMedicalReminderID == 0)
                {
                    rem.DriverMedicalID = poco.DriverMedicalID;
                    UtilityModel<uint> temp = new UtilityModel<uint>();
                    temp.Value = db.ExecuteQuery<uint>(sqlInsert,
                        new MySqlParameter("DriverMedicalID", rem.DriverMedicalID),
                        new MySqlParameter("ReminderID", rem.ReminderID),
                        new MySqlParameter("ReminderType", rem.ReminderType),
                        new MySqlParameter("ShouldRemind", rem.ShouldRemind))
                        .First();
                    key.AddKey(temp, rem, "Value", rem.GetName(p => p.DriverMedicalReminderID));
                }
                else
                {
                    rem.DriverMedicalID = poco.DriverMedicalID;
                    db.ExecuteNonQuery(sqlUpdate,
                        new MySqlParameter("DriverMedicalReminderID", rem.DriverMedicalReminderID),
                        new MySqlParameter("DriverMedicalID", rem.DriverMedicalID),
                        new MySqlParameter("ReminderID", rem.ReminderID),
                        new MySqlParameter("ReminderType", rem.ReminderType),
                        new MySqlParameter("ShouldRemind", rem.ShouldRemind));
                }
            }
        }
        public static void SaveDriver(DSModel db, KeyBinder key, DriverModel model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");

            if (model.DriverID == 0)
                InsertDriver(db, key, model);
            else
                UpdateDriver(db, key, model);
        }
        public static void SaveBlob(DSModel db, KeyBinder key, FileBlobModel model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");

            model.UserID = GLOB.User.UserID;
            model.LastUpdateTime = DateTime.Now;
            if (model.BlobID == 0)
                InsertBlob(db, key, model);
            else
                UpdateBlob(db, key, model);
        }
 public CheckResult SaveHolidays(List<HolidayModel> model)
 {
     try
     {
         using (var db = DB.GetContext())
         {
             KeyBinder key = new KeyBinder();
             HolidayRepository.SaveHolidays(db, key, model);
             db.SaveChanges();
             key.BindKeys();
             model.ForEach(f => f.IsChanged = false);
             return new CheckResult();
         }
     }
     catch (Exception ex)
     {
         return new CheckResult(ex);
     }
 }
        public CheckResult SaveDispatch(DispatchModel model)
        {
            try
            {
                using (var db = DB.GetContext())
                {
                    var check = DispatchValidator.ValidateSave(db, model);
                    if (check.Failed)
                        return check;

                    KeyBinder key = new KeyBinder();
                    DispatchRepository.SaveDispatch(db, key, model);
                    db.SaveChanges();
                    key.BindKeys();
                    return check;
                }
            }
            catch (Exception ex)
            {
                return new CheckResult(ex);
            }
        }
        public CheckResult SaveUser(UserModel user)
        {
            try
            {
                using (var db = DB.GetContext())
                {
                    var check = UserValidator.ValidateSave(db, user);
                    if (check.Failed)
                        return check;

                    KeyBinder key = new KeyBinder();
                    UserRepository.SaveUser(db, key, user);
                    db.SaveChanges();
                    key.BindKeys();
                    user.IsChanged = false;
                    return check;
                }
            }
            catch (Exception ex)
            {
                return new CheckResult(ex);
            }
        }
        public static void SaveBlobView(DSModel db, KeyBinder key, FileBlobViewModel model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");
            if (model.BlobID == 0)
                throw new ArgumentException("BlobID cannot be 0!", "model");

            string sql = @"
                UPDATE file_blobs f
                SET
                  f.BlobName = @BlobName, f.BlobDescription = @BlobDescription, f.BlobExtension = @BlobExtension
                WHERE
                  f.BlobID = @BlobID;";
            db.ExecuteNonQuery(sql,
                new MySqlParameter("BlobID", model.BlobID),
                new MySqlParameter("BlobName", model.BlobName),
                new MySqlParameter("BlobDescription", model.BlobDescription),
                new MySqlParameter("BlobExtension", model.BlobExtension));
        }
        public CheckResult SaveCompany(CompanyModel model, List<CompanyLicensePayRateModel> licenseRates, List<CompanyInvoicingPayRateModel> invoiceRates)
        {
            try
            {
                using (var db = DB.GetContext())
                {
                    var check = CompanyValidator.ValidateSave(db, model);
                    if (check.Failed)
                        return check;

                    var checkLicense = CompanyValidator.ValidateDriverRates(db, licenseRates);
                    if (checkLicense.Failed)
                        return checkLicense;

                    var checkInvoice = CompanyValidator.ValidateInvoiceRates(db, invoiceRates);
                    if (checkInvoice.Failed)
                        return checkInvoice;

                    KeyBinder key = new KeyBinder();
                    CompanyRepository.SaveCompany(db, key, model);
                    if (model.CompanyID != 0)
                    {
                        CompanyRepository.SaveLicensesPayRates(db, key, licenseRates);
                        CompanyRepository.SaveInvoicePayRates(db, key, invoiceRates);
                    }
                    db.SaveChanges();
                    key.BindKeys();
                    model.IsChanged = false;

                    return check;
                }
            }
            catch (Exception ex)
            {
                return new CheckResult(ex);
            }
        }
        public CheckResult Save()
        {
            var mod = this.ActiveModel;
            try
            {
                using (var db = DB.GetContext())
                {
                    var check = DriverMedicalValidator.ValidateSave(db, mod);
                    if (check.Failed)
                        return check;

                    KeyBinder key = new KeyBinder();
                    DriverMedicalRepository.SaveMedical(db, key, mod);
                    db.SaveChanges();
                    key.BindKeys();
                    mod.IsChanged = false;
                    return check;
                }
            }
            catch (Exception ex)
            {
                return new CheckResult(ex);
            }
        }
        public CheckResult Save()
        {
            var model = this.ActiveModel;

            try
            {
                using (var db = DB.GetContext())
                {
                    KeyBinder key = new KeyBinder();

                    model.Permits.Clear();
                    var permits = this.Permits
                        .Where(p => p.IsCheck)
                        .Select(p =>
                            new DriverLicensePermitModel()
                            {
                                PermitID = p.Value
                            });
                    model.Permits.AddRange(permits);

                    var check = DriverLicenseValidator.ValidateSave(db, model);
                    if (check.Failed)
                        return check;

                    DriverLicenseRepository.SaveDriverLicense(db, key, model);
                    db.SaveChanges();
                    key.BindKeys();
                    model.IsChanged = false;
                    return check;
                }
            }
            catch (Exception ex)
            {
                return new CheckResult(ex);
            }
        }
        public static void SaveDispatch(DSModel db, KeyBinder key, DispatchModel disp)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (disp == null)
                throw new ArgumentNullException("disp");

            disp.UserID = GLOB.User.UserID;
            disp.LastUpdateTime = DateTime.Now;
            if (disp.DispatchID == 0)
                InsertDispatch(db, key, disp);
            else
                UpdateDispatch(db, key, disp);
        }
        private static void InsertCompany(DSModel db, KeyBinder key, CompanyModel model)
        {
            Company poco = new Company();
            poco.CompanyID = model.CompanyID;
            poco.CompanyName = model.CompanyName;
            if (model.CompanyCode == string.Empty)
                poco.CompanyCode = "C" + CompanyRepository.PeekCompanyCode(db, "C");
            else
                poco.CompanyCode = model.CompanyCode;
            poco.CompanyAddress1 = model.CompanyAddress1;
            poco.CompanyAddress2 = model.CompanyAddress2;
            poco.CompanyCity = model.CompanyCity;
            poco.CompanyState = model.CompanyState;
            poco.CompanyPostCode = model.CompanyPostCode;
            poco.CompanyContactName = model.CompanyContactName;
            poco.CompanyFax = model.CompanyFax;
            poco.CompanyPhone = model.CompanyPhone;
            poco.CompanyEmail = model.CompanyEmail;
            poco.LunchTime = model.LunchTime;
            poco.TrainingTime = model.TrainingTime;
            poco.IsEnabled = model.IsEnabled;

            foreach (var loc in model.Locations)
            {
                Location l = LocationRepository.SaveLocation(db, key, loc, poco);
                poco.Locations.Add(l);
                key.AddKey(l, loc, loc.GetName(p => p.LocationID));
                key.AddKey(poco, loc, loc.GetName(p => p.CompanyID));
            }

            db.Add(poco);

            key.AddKey(poco, model, model.GetName(p => p.CompanyID));
        }
 private static void InsertDispatch(DSModel db, KeyBinder key, DispatchModel model)
 {
     Dispatch poco = new Dispatch();
     poco.DriverID = model.DriverID;
     poco.CompanyID = model.CompanyID;
     poco.LocationID = model.LocationID;
     poco.FromDateTime = model.FromDateTime;
     poco.ToDateTime = model.ToDateTime;
     poco.LunchTime = model.LunchTime;
     poco.TrainingTime = model.TrainingTime;
     poco.SpecialPayRate = model.SpecialPayRate;
     poco.MiscCharge = model.MiscCharge;
     poco.Note = model.Note;
     poco.IsCancelled = model.IsCancelled;
     poco.IsConfirmed = model.IsConfirmed;
     poco.HasLunch = model.HasLunch;
     poco.HasTraining = model.HasTraining;
     poco.UserID = model.UserID;
     poco.LastUpdateTime = model.LastUpdateTime;
     db.Add(poco);
     key.AddKey(poco, model, model.GetName(p => p.DispatchID));
 }
        private static void UpdateDispatch(DSModel db, KeyBinder key, DispatchModel model)
        {
            var poco = db.Dispatches.Where(d => d.DispatchID == model.DispatchID).FirstOrDefault();
            if (poco == null)
                throw new ArgumentNullException("No dispatch with the specified ID!");

            poco.DriverID = model.DriverID;
            poco.CompanyID = model.CompanyID;
            poco.LocationID = model.LocationID;
            poco.FromDateTime = model.FromDateTime;
            poco.ToDateTime = model.ToDateTime;
            poco.LunchTime = model.LunchTime;
            poco.TrainingTime = model.TrainingTime;
            poco.SpecialPayRate = model.SpecialPayRate;
            poco.MiscCharge = model.MiscCharge;
            poco.Note = model.Note;
            poco.IsCancelled = model.IsCancelled;
            poco.IsConfirmed = model.IsConfirmed;
            poco.HasLunch = model.HasLunch;
            poco.HasTraining = model.HasTraining;
            poco.UserID = model.UserID;
            poco.LastUpdateTime = model.LastUpdateTime;
        }
        public static void SaveCompany(DSModel db, KeyBinder key, CompanyModel model)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (model == null)
                throw new ArgumentNullException("model");

            if (model.CompanyID == 0)
                InsertCompany(db, key, model);
            else
                UpdateCompany(db, key, model);
        }
        private static void UpdateCompany(DSModel db, KeyBinder key, CompanyModel model)
        {
            Company poco = db.Companies.Where(c => c.CompanyID == model.CompanyID).FirstOrDefault();
            if (poco == null)
                throw new ArgumentException("No company with the specified ID!");

            poco.CompanyID = model.CompanyID;
            poco.CompanyName = model.CompanyName;
            poco.CompanyCode = model.CompanyCode;
            poco.CompanyAddress1 = model.CompanyAddress1;
            poco.CompanyAddress2 = model.CompanyAddress2;
            poco.CompanyCity = model.CompanyCity;
            poco.CompanyState = model.CompanyState;
            poco.CompanyPostCode = model.CompanyPostCode;
            poco.CompanyContactName = model.CompanyContactName;
            poco.CompanyFax = model.CompanyFax;
            poco.CompanyPhone = model.CompanyPhone;
            poco.CompanyEmail = model.CompanyEmail;
            poco.LunchTime = model.LunchTime;
            poco.TrainingTime = model.TrainingTime;
            poco.IsEnabled = model.IsEnabled;

            List<Location> locationsToBeDeleted = poco.Locations.Where(dl => !model.Locations.Any(ml => ml.LocationID == dl.LocationID)).ToList();
            foreach (var del in locationsToBeDeleted)
            {
                db.Delete(del);
                poco.Locations.Remove(del);
            }

            foreach (var ins in model.Locations)
            {
                Location loc = LocationRepository.SaveLocation(db, key, ins, poco);
                poco.Locations.Add(loc);
                key.AddKey(loc, ins, ins.GetName(p => p.LocationID));
            }
        }
        public static void SaveInvoicePayRates(DSModel db, KeyBinder key, List<CompanyInvoicingPayRateModel> rates)
        {
            if (db == null)
                throw new ArgumentNullException("db");
            if (key == null)
                throw new ArgumentNullException("key");
            if (rates == null)
                throw new ArgumentNullException("rates");

            if (rates.Count == 0)
                return;

            uint[] distCompanies = rates.Select(c => c.CompanyID).Distinct().ToArray();
            uint[] oldIDs = rates.Select(c => c.CompanyInvoicingID).ToArray();
            db.CompaniesInvoicingPayrates.Where(c => distCompanies.Contains(c.CompanyID) && !oldIDs.Contains(c.CompanyInvoicingID)).DeleteAll();

            foreach (var pay in rates.Where(r => r.CompanyInvoicingID == 0))
            {
                CompaniesInvoicingPayrate poco = new DAL.CompaniesInvoicingPayrate();
                poco.CompanyID = pay.CompanyID;
                poco.LicenseID = pay.LicenseID;
                poco.PayRate = pay.PayRate;
                poco.PayRateOT = pay.PayRateOT;
                poco.FromDate = pay.FromDate;
                poco.ToDate = pay.ToDate;
                key.AddKey(poco, pay, pay.GetName(p => p.CompanyInvoicingID));
                db.Add(poco);
            }

            foreach (var pay in rates.Where(r => r.CompanyInvoicingID != 0))
            {
                CompaniesInvoicingPayrate poco = db.CompaniesInvoicingPayrates.Where(r => r.CompanyInvoicingID == pay.CompanyInvoicingID).FirstOrDefault();
                poco.CompanyID = pay.CompanyID;
                poco.LicenseID = pay.LicenseID;
                poco.PayRate = pay.PayRate;
                poco.PayRateOT = pay.PayRateOT;
                poco.FromDate = pay.FromDate;
                poco.ToDate = pay.ToDate;
            }
        }