public ActionResult FixUnitMemberships()
        {
            Kcsar.Database.Model.UnitMembership lastUm = null;

            foreach (Kcsar.Database.Model.UnitMembership um in (from u in this.db.UnitMemberships.Include("Person").Include("Unit") select u).OrderBy(f => f.Person.Id).ThenBy(f => f.Unit.Id).ThenBy(f => f.Activated))
            {
                if (lastUm != null && um.Person.Id == lastUm.Person.Id && um.Unit.Id == lastUm.Unit.Id)
                {
                    lastUm.EndTime = um.Activated;
                }
                lastUm = um;
            }
            this.db.SaveChanges();

            return(new ContentResult {
                Content = "OK"
            });
        }
        public ActionResult CreateMembership(Guid personId, FormCollection fields)
        {
            if (Session["NewMembershipGuid"] != null && Session["NewMembershipGuid"].ToString() != fields["NewMembershipGuid"])
              {
            throw new InvalidOperationException("Invalid operation. Are you trying to re-create a status change?");
              }
              Session.Remove("NewMembershipGuid");

              ViewData["PageTitle"] = "New Unit Membership";

              UnitMembership um = new UnitMembership();
              um.Person = (from p in this.db.Members where p.Id == personId select p).First();
              this.db.UnitMemberships.Add(um);
              return InternalSaveMembership(um, fields);
        }
        public ActionResult CreateMembership(Guid personId)
        {
            ViewData["PageTitle"] = "New Unit Membership";

              UnitMembership s = new UnitMembership();
              s.Person = (from p in this.db.Members where p.Id == personId select p).First();
              s.Activated = DateTime.Today;

              Session.Add("NewMembershipGuid", s.Id);
              ViewData["NewMembershipGuid"] = Session["NewMembershipGuid"];

              return InternalEditMembership(s);
        }
        private Member NewEsarTrainee_Internal(FormCollection fields)
        {
            Member m = new Member();
              TryUpdateModel(m, new[] { "FirstName", "LastName", "MiddleName", "BirthDate", "SheriffApp", "Gender" });
              this.db.Members.Add(m);

              SarUnit esar = (from u in this.db.Units where u.DisplayName == "ESAR" select u).First();
              UnitStatus status = (from s in this.db.UnitStatusTypes where s.Unit.Id == esar.Id && s.StatusName == "trainee" select s).First();

              if (!string.IsNullOrEmpty(fields["Street"]))
              {
            PersonAddress address = new PersonAddress { Person = m, Type = PersonAddressType.Mailing };
            TryUpdateModel(address, new[] { "Street", "City", "State" });

            GeographyServices.RefineAddressWithGeography(address);
            if (address.Quality < 8)
            {
              try
              {
            ModelState.SetModelValue("Zip", new ValueProviderResult(fields["Zip"], fields["Zip"], CultureInfo.CurrentUICulture));
            // This is supposed to be UpdateModel, not TryUpdate
            UpdateModel(address, new[] { "Zip" });
              }
              catch (Exception)
              {
            ModelState.AddModelError("Zip", "Can't locate address. ZIP is required");
              }
            }

            this.db.PersonAddress.Add(address);
              }

              foreach (string contact in new[] { "Home", "Work", "Cell" })
              {
            if (string.IsNullOrEmpty(fields[contact + "Phone"]))
            {
              continue;
            }

            ModelState.SetModelValue(contact + "Phone", new ValueProviderResult(fields[contact + "Phone"], fields[contact + "Phone"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "phone", Subtype = contact.ToLower(), Value = fields[contact + "Phone"] };
            this.db.PersonContact.Add(pc);
              }

              if (!string.IsNullOrEmpty(fields["HamCall"]))
              {
            ModelState.SetModelValue("HamCall", new ValueProviderResult(fields["HamCall"], fields["HamCall"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "hamcall", Value = fields["HamCall"] };
            this.db.PersonContact.Add(pc);
              }

              if (!string.IsNullOrEmpty(fields["Email"]))
              {
            ModelState.SetModelValue("Email", new ValueProviderResult(fields["Email"], fields["Email"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "email", Value = fields["Email"] };
            this.db.PersonContact.Add(pc);
              }

              if (!string.IsNullOrEmpty(fields["Email2"]))
              {
            ModelState.SetModelValue("Email2", new ValueProviderResult(fields["Email2"], fields["Email2"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "email", Value = fields["Email2"] };
            this.db.PersonContact.Add(pc);
              }

              DateTime courseDate = new DateTime(1900, 1, 1);
              ModelState.SetModelValue("CourseDate", new ValueProviderResult(fields["CourseDate"], fields["CourseDate"], CultureInfo.CurrentUICulture));
              if (string.IsNullOrEmpty(fields["CourseDate"]))
              {
            ModelState.AddModelError("CourseDate", "Required");
            return null;
              }
              else if (!DateTime.TryParse(fields["CourseDate"], out courseDate))
              {
            ModelState.AddModelError("CourseDate", "Unknown format. Try yyyy-mm-dd");
            return null;
              }
              courseDate = courseDate.Date;

              UnitMembership um = new UnitMembership { Person = m, Status = status, Unit = esar, Activated = courseDate };
              this.db.UnitMemberships.Add(um);

              TrainingCourse courseA = (from tc in this.db.TrainingCourses where tc.DisplayName == "Course A" select tc).First();
              DateTime nextDate = courseDate.AddDays(1);

              Training t = (from trn in this.db.Trainings where trn.StartTime >= courseDate && trn.StartTime < nextDate && trn.Title == "Course A" select trn).FirstOrDefault();
              if (t == null)
              {
            t = new Training();
            t.OfferedCourses.Add(courseA);
            t.StartTime = courseDate.AddHours(19);
            t.StopTime = courseDate.AddHours(21);
            t.County = "King";
            t.Title = "Course A";
            t.Location = "Eastside Fire Headquarters";
            this.db.Trainings.Add(t);
              }

              TrainingRoster tr = new TrainingRoster { Person = m, TimeIn = courseDate.AddHours(18), TimeOut = courseDate.AddHours(22) };
              this.db.TrainingRosters.Add(tr);
              t.Roster.Add(tr);

              TrainingAward ta = new TrainingAward();
              ta.Completed = courseDate.AddHours(21);
              if ((courseA.ValidMonths ?? 0) > 0)
              {
            ta.Expiry = ta.Completed.AddMonths(courseA.ValidMonths.Value);
              }
              ta.Course = courseA;
              ta.Member = m;
              this.db.TrainingAward.Add(ta);
              tr.TrainingAwards.Add(ta);
              return m;
        }
        private ActionResult InternalSaveMembership(UnitMembership um, FormCollection fields)
        {
            TryUpdateModel(um, new string[] { "Activated", "Comments" });

              Guid unitId = new Guid(fields["Unit"]);
              SarUnit unit = (from u in this.db.Units where u.Id == unitId select u).First();
              um.Unit = unit;

              Guid statusId = new Guid(fields["Status"]);
              UnitStatus status = (from s in this.db.UnitStatusTypes where s.Id == statusId select s).First();
              um.Status = status;

              Guid personId = new Guid(fields["Person"]);
              Member person = (from m in this.db.Members where m.Id == personId select m).First();
              um.Person = person;

              if (ModelState.IsValid)
              {
            this.db.SaveChanges();
            TempData["message"] = "Saved";
            UpdateMemberships(um.Person.Id);

            return RedirectToAction("ClosePopup");
              }

              return InternalEditMembership(um);
        }
        private ActionResult InternalEditMembership(UnitMembership um)
        {
            SarUnit[] units = (from u in this.db.Units orderby u.DisplayName select u).ToArray();

              Guid selectedUnit = (um.Unit != null) ? um.Unit.Id : Guid.Empty;

              // MVC RC BUG - Have to store list in a unique key in order for SelectedItem to work
              ViewData["Unit"] = new SelectList(units, "Id", "DisplayName", selectedUnit);

              if (selectedUnit == Guid.Empty && units.Length > 0)
              {
            selectedUnit = units.First().Id;
              }

              ViewData["Status"] = new SelectList(
              (from s in this.db.UnitStatusTypes.Include("Unit") where s.Unit.Id == selectedUnit orderby s.StatusName select s).ToArray(),
              "Id",
              "StatusName",
              (um.Status != null) ? (Guid?)um.Status.Id : null);

              return View("EditMembership", um);
        }