public IEnumerable<string> GetColumnsAfter(MissionReadyColumns column, Member member)
        {
            if (column == MissionReadyColumns.WorkerType)
              {
            var courses = member.ComputedAwards.Where(f =>
              f.Course.Unit != null && f.Course.Unit.Id == this.unit.Id
              && (f.Expiry == null || f.Expiry > DateTime.Now))
              .Select(f => f.Course.DisplayName)
              .ToArray();

            var ranks = new[] { "OL", "FL", "TL" };
            foreach (var rank in ranks)
            {
              if (courses.Any(f => f == this.unit.DisplayName + " " + rank))
              {
            return new [] { rank };
              }
            }

            if (member.WacLevel == WacLevel.Field
              || (member.WacLevel == WacLevel.Novice && member.Memberships.Any(
            f => f.Status.StatusName == "Active"
              && f.Unit.Id == unit.Id
              && (f.EndTime == null || f.EndTime > DateTime.Now))))
            {
              return new[] { "TM" };
            }

            return new[] { string.Empty };
              }
              else
              {
            return new string[0];
              }
        }
Ejemplo n.º 2
0
        public void PromoteContact()
        {
            string name = string.Format("Clareece {0}", Guid.NewGuid());
              Guid memberId;

              using (var db = context.GetDb())
              {
            Member a = new Member { FirstName = name, LastName = "TestUser" };
            db.Members.Add(a);
            a.ContactNumbers.Add(new PersonContact { Type = "email", Value = "*****@*****.**", Priority = 0 });
            a.ContactNumbers.Add(new PersonContact { Type = "email", Value = "*****@*****.**", Priority = 1 });
            db.SaveChanges();
            memberId = a.Id;
              }

              try
              {
            d.Url = string.Format("{0}/members/detail/{1}", context.Url, memberId);
            var table = d.FindElement(By.Id("contacts_table"));
            var link = table.FindElement(By.LinkText("Promote"));
            Assert.IsTrue(link.FindElement(By.XPath("../..")).Text.Contains("*****@*****.**"), "promote link on correct entry");
            link.Click();

            WaitFor(10, f => table.FindElement(By.LinkText("Promote"))
              .FindElement(By.XPath("../..")).Text.Contains("*****@*****.**"));
              }
              finally
              {
            CleanupEntry(name);
              }
        }
Ejemplo n.º 3
0
        public void LogObjectDeleted()
        {
            Guid memberId;
              string reportHtml;
              using (var db = new KcsarContext(this.databaseLocation))
              {
            Member m = new Member { FirstName = "RemoveMe" };
            db.Members.Add(m);
            db.SaveChanges();
            memberId = m.Id;
            reportHtml = m.GetReportHtml();
              }

              DateTime checkpoint = GetCheckpoint();

              using (var db = new KcsarContext(this.databaseLocation))
              {
            Member m = db.Members.Single(f => f.Id == memberId);
            db.Members.Remove(m);
            db.SaveChanges();
            var log = db.GetLog(checkpoint);

            Assert.AreEqual(1, log.Length, "log entries");
            Assert.AreEqual("Deleted", log[0].Action, "action: " + log[0].Action);
            Assert.AreEqual(reportHtml, log[0].Comment, "log msg: " + log[0].Comment);
              }
        }
Ejemplo n.º 4
0
        public void DeleteMember()
        {
            string name = string.Format("George {0}", Guid.NewGuid());
              Guid id;
              using (var db = context.GetDb())
              {
            Member a = new Member { FirstName = name, LastName = "TestUser" };
            db.Members.Add(a);
            db.SaveChanges();
            id=a.Id;
              }

              try
              {
            d.Url = string.Format("{0}/members/detail/{1}", context.Url, id);

            d.FindElement(By.Id("card"))
              .FindElement(By.LinkText("Delete")).Click();
            d.FindElement(By.XPath("//input[@type='submit']")).Click();

            Assert.AreEqual(context.Url.ToLowerInvariant() + "/members", d.Url.ToLowerInvariant());
            Assert.IsFalse(d.FindElements(By.TagName("a")).Any(f => f.Text == name), "is on page");

            using (var db = context.GetDb())
            {
              Assert.IsNull(db.Members.SingleOrDefault(f => f.Id == id), "not in database");
            }
              }
              catch
              {
            CleanupEntry(name);
            throw;
              }
        }
Ejemplo n.º 5
0
        public static CompositeTrainingStatus Compute(Member m, IEnumerable<TrainingCourse> courses, DateTime when)
        {
            //if (!m.ComputedAwards.IsLoaded)
            //{
            //    throw new InvalidOperationException("Must pre-load member's .ComputedAwards.Course");
            //}

            return CompositeTrainingStatus.Compute(m, m.ComputedAwards, courses, when);
        }
Ejemplo n.º 6
0
 internal static void RegisterApplication(Data.IKcsarContext db, Guid id, Data.Member member)
 {
     Data.UnitApplicant application = new Data.UnitApplicant
     {
         Unit      = db.Units.Single(f => f.Id == id),
         Applicant = member,
         Started   = DateTime.Now,
         IsActive  = true,
     };
     db.UnitApplicants.Add(application);
 }
Ejemplo n.º 7
0
        public void GetPrimaryOwner()
        {
            var owner = new Member { FirstName = "Mary", LastName = "Smith" };
              var animal = new Animal();

              animal.Owners.Add(new AnimalOwner { Animal = animal, Owner = new Member { FirstName = "Joe", LastName = "Smith" } });
              animal.Owners.Add(new AnimalOwner { Animal = animal, Owner = owner, IsPrimary = true });

              var primary = animal.GetPrimaryOwner();
              Assert.AreSame(owner, primary);
        }
        public IEnumerable <TrainingRecord> FindComputedForMember(Guid id)
        {
            if (!User.IsInRole("cdb.users"))
            {
                ThrowAuthError();
            }

            Data.Member m = GetObjectOrNotFound(() => db.Members.SingleOrDefault(f => f.Id == id));

            var model = GetComputedTrainingRecordViews(f => f.Member.Id == id, false, m.WacLevel);

            return(model);
        }
        public IEnumerable <TrainingRecord> FindForMember(Guid id)
        {
            if (!User.IsInRole("cdb.users"))
            {
                ThrowAuthError();
            }

            Data.Member m = GetObjectOrNotFound(() => db.Members.SingleOrDefault(f => f.Id == id));

            int mask = (1 << (((int)m.WacLevel - 1) * 2 + 1));

            var model = GetTrainingRecords(f => f.Member.Id == id, false, m.WacLevel);

            return(model);
        }
Ejemplo n.º 10
0
        public void ReportFormat()
        {
            string animalName = "Animal Bob";
              DateTime starting = DateTime.Now;
              DateTime? ending = null;
              var owner = new Member { FirstName = "Fred", LastName = "Rider" };
              var ao = new AnimalOwner {
            Owner = owner,
            Animal = new Animal { Name = animalName },
            Starting = starting,
            Ending = ending
              };

              var html = ao.GetReportHtml();
              Assert.IsTrue(html.Contains(animalName), "animal name");
              Assert.IsTrue(html.Contains(owner.FullName), "owner name");
              Assert.IsTrue(html.Contains(starting.ToString()), "starting");
        }
Ejemplo n.º 11
0
        public void AddAddress()
        {
            string name = string.Format("Angus {0}", Guid.NewGuid());
              Guid memberId;

              using (var db = context.GetDb())
              {
            Member a = new Member { FirstName = name, LastName = "TestUser" };
            db.Members.Add(a);
            db.SaveChanges();
            memberId = a.Id;
              }

              try
              {
            d.Url = string.Format("{0}/members/detail/{1}", context.Url, memberId);
            d.FindElement(By.LinkText("Add Address")).Click();

            SwitchToPopup();
            d.FindElement(By.XPath("//input[@type='submit']")).Click();
            var fieldErrors = d.FindElements(By.ClassName("field-validation-error"));
            Assert.AreEqual(3, fieldErrors.Count, "error count");
            Assert.IsTrue(fieldErrors.All(f => f.Text.EndsWith("field is required.")), "error text");

            d.FindElement(By.Id("Street")).SendKeys("1234 Main St");
            d.FindElement(By.Id("City")).SendKeys("Anytown");
            d.FindElement(By.Id("Zip")).SendKeys("12345");
            d.FindElement(By.XPath("//input[@type='submit']")).Click();
            // popup closes

            d.SwitchTo().Window(mainWindow);
            Assert.IsTrue(d.FindElement(By.Id("address_table"))
              .Text.Contains("1234 Main St"), "detail page refreshed");

            using (var db = context.GetDb())
            {
              Assert.AreEqual(1, db.Members.Single(f => f.Id == memberId).Addresses.Count, "address count");
            }
              }
              finally
              {
            CleanupEntry(name);
              }
        }
Ejemplo n.º 12
0
        public void AddContact()
        {
            string name = string.Format("Clarence {0}", Guid.NewGuid());
              Guid memberId;

              using (var db = context.GetDb())
              {
            Member a = new Member { FirstName = name, LastName = "TestUser" };
            db.Members.Add(a);
            db.SaveChanges();
            memberId = a.Id;
              }

              try
              {
            d.Url = string.Format("{0}/members/detail/{1}", context.Url, memberId);
            d.FindElement(By.Id("addContact")).Click();

            var form = d.FindElement(By.Id("contactform"));
            new SelectElement(d.FindElement(By.Id("contactType"))).SelectByText("phone");
            new SelectElement(d.FindElement(By.Id("contactSubtype"))).SelectByText("work");
            form.FindElements(By.XPath("..//div[@class='ui-dialog-buttonset']/button")).First().Click();
            var tips = form.FindElement(By.ClassName("validateTips"));
            Assert.AreEqual(1, tips.FindElements(By.TagName("span")).Count);
            Assert.AreEqual("Value: Required", tips.Text, "tip text");
            Assert.IsTrue(tips.Displayed, "err tips displayed");

            form.FindElement(By.Id("contactValue")).SendKeys("123-456-7890");
            form.FindElements(By.XPath("..//div[@class='ui-dialog-buttonset']/button")).First().Click();

            WaitFor(10, f => (f.FindElement(By.Id("contactform")).Displayed == false));

            Assert.IsTrue(d.FindElement(By.Id("contacts_table")).Text.Contains("123-456-7890"), "table has number");

            using (var db = context.GetDb())
            {
              Assert.AreEqual(1, db.Members.Single(f => f.Id == memberId).ContactNumbers.Count, "contact count");
            }
              }
              finally
              {
            CleanupEntry(name);
              }
        }
Ejemplo n.º 13
0
        public void AddMembership()
        {
            string name = string.Format("Eustace {0}", Guid.NewGuid());
              Guid memberId;

              using (var db = context.GetDb())
              {
            Member a = new Member { FirstName = name, LastName = "TestUser" };
            db.Members.Add(a);
            db.SaveChanges();
            memberId = a.Id;
              }

              try
              {
            d.Url = string.Format("{0}/members/detail/{1}", context.Url, memberId);
            d.FindElement(By.LinkText("Add/Change Membership")).Click();

            SwitchToPopup();
            d.FindElement(By.Id("Activated")).Clear();
            d.FindElement(By.XPath("//input[@type='submit']")).Click();
            var fieldErrors = d.FindElements(By.ClassName("field-validation-error"));
            Assert.AreEqual(1, fieldErrors.Count, "error count");
            Assert.IsTrue(fieldErrors.All(f => f.Text == "The Activated field is required."), "error text");

            d.FindElement(By.Id("Activated")).SendKeys(DateTime.Today.ToString("yyyy-MM-dd"));
            d.FindElement(By.XPath("//input[@type='submit']")).Click();

            using (var db = context.GetDb())
            {
              Assert.AreEqual(1, db.Members.Single(f => f.Id == memberId).Memberships.Count, "membership count");
            }
              }
              finally
              {
            CleanupEntry(name);
              }
        }
Ejemplo n.º 14
0
        public void LogObjectCreated()
        {
            Guid memberId;
              DateTime checkpoint;
              checkpoint = GetCheckpoint();

              using (var db = new KcsarContext(this.databaseLocation))
              {
            Member m = new Member { FirstName = "NewUser" };
            db.Members.Add(m);
            db.SaveChanges();
            memberId = m.Id;
              }

              using (var db = new KcsarContext(this.databaseLocation))
              {
            var member = db.Members.Single(f => f.Id == memberId);
            var logs = db.GetLog(checkpoint);
            Assert.AreEqual(1, logs.Length, "log entries");
            Assert.AreEqual(member.GetReportHtml(), logs[0].Comment, "log msg: " + logs[0].Comment);
            Assert.AreEqual("Added", logs[0].Action, "action: " + logs[0].Action);
              }
        }
 public static Member FilterPersonal(Member member)
 {
     member.BirthDate = null;
       return member;
 }
        public ActionResult Create(FormCollection fields)
        {
            if (!Permissions.IsAdmin) return this.CreateLoginRedirect();

              if (Session["NewUserGuid"] != null && Session["NewUserGuid"].ToString() != fields["NewUserGuid"])
              {
            throw new InvalidOperationException("Invalid operation. Are you trying to re-create a user?");
              }
              Session.Remove("NewUserGuid");

              ViewData["PageTitle"] = "New Member";

              Member m = new Member();
              this.db.Members.Add(m);
              return InternalSave(m, fields, RedirectToAction("Detail", new { id = m.Id }));
        }
        public ActionResult Create()
        {
            if (!Permissions.IsAdmin) return this.CreateLoginRedirect();

              ViewData["PageTitle"] = "New Member";

              Member m = new Member();
              m.WacLevel = WacLevel.None;
              Session["NewUserGuid"] = Guid.NewGuid();
              ViewData["NewUserGuid"] = Session["NewUserGuid"];
              return InternalEdit(m);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool LoadMember()
        {
            if (member == null && searchedForMember == false)
            {
                searchedForMember = true;

                string key = this.LinkKey;
                if (string.IsNullOrEmpty(key))
                {
                    return false;
                }

                Guid id = new Guid(key);
                using (var context = new KcsarContext())
                {
                    member = (from m in context.Members where m.Id == id select m).FirstOrDefault();
                 //   this.db.Detach(member);
                }
                if (member == null)
                {
                    this.LinkKey = null;
                }
            }
            return member != null;
        }
Ejemplo n.º 19
0
        public void LogPrincipalChanged()
        {
            Member first;
              Member second;
              PersonAddress address;
              using (var db = new KcsarContext(this.databaseLocation))
              {
            first = new Member { FirstName = "First" };
            db.Members.Add(first);
            second = new Member { FirstName = "Second" };
            db.Members.Add(second);
            address = new PersonAddress { Person = first, Street = "123", City = "Any", State = "WA", Zip = "98765" };
            first.Addresses.Add(address);

            db.SaveChanges();
              }

              var checkpoint = GetCheckpoint();
              using (var db = new KcsarContext(this.databaseLocation))
              {
            address = db.Members.Where(f => f.Id == first.Id).SelectMany(f => f.Addresses).Single();
            address.Person = db.Members.Single(f => f.Id == second.Id);
            db.SaveChanges();
              }

              using (var db = new KcsarContext(this.databaseLocation))
              {
            var logs = db.GetLog(checkpoint);
            Assert.AreEqual(1, logs.Length, "log count");
            Assert.AreEqual(string.Format("{0}<br/>{1} => {2}",
              address, first, second), logs[0].Comment);
            Assert.AreEqual("Modified", logs[0].Action);
              }
        }
Ejemplo n.º 20
0
        private static void Render_BackContent(PdfContentByte canvas, Member member, bool passport)
        {
            Font f = new Font(baseFont, 12, Font.BOLD);
            int bottom = CARD_HEIGHT - 32;
            Phrase p = new Phrase(member.FullName, f);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);

            if (passport)
            {
                bottom = CARD_HEIGHT - 170;
                f = new Font(baseFont, 16f, Font.BOLD);
                p = new Phrase("PASSPORT", f);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);
            }
            else
            {
                bottom = CARD_HEIGHT - 159;
                f = new Font(baseFont, 11f);
                p = new Phrase(member.WacLevel.ToString(), f);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);

                bottom -= 12;
                p = new Phrase("KCSO DEM# " + member.DEM, f);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);
            }

            BarcodePDF417 barcode = new BarcodePDF417();
            barcode.SetText(string.Format("Unknown Text. To be added. KCSAR{0}{1}{2}", member.LastName, member.FirstName, member.DEM));
            barcode.CodeRows = 9;
            barcode.CodeColumns = 7;
            barcode.Options = BarcodePDF417.PDF417_FIXED_RECTANGLE;
            var img = barcode.GetImage();
            img.ScaleAbsolute(CARD_WIDTH - 30, 14);
            img.SetAbsolutePosition((CARD_WIDTH - img.ScaledWidth) / 2, 50);
            canvas.AddImage(img);
        }
 public void Setup()
 {
     using (var db = new KcsarContext())
     {
         this.member = db.Members.Where(f => f.ContactNumbers.Count > 1
             && f.Addresses.Count > 1
             && f.MissionRosters.Count > 1
             && f.TrainingRosters.Count > 1).First();
     }
     this.browser = UIAutomation.GetAdminBrowser();
     this.browser.NavigateToPath("/Members/Detail/" + this.member.Id.ToString());
 }
Ejemplo n.º 22
0
        public string Signup(AccountSignup data)
        {
            if (string.IsNullOrWhiteSpace(data.Firstname))
            return "First name is required";
              if (string.IsNullOrWhiteSpace(data.Lastname))
            return "Last name is required";

              if (data.BirthDate > DateTime.Today.AddYears(-14))
            return "Applicants must be 14 years or older";
              if (data.BirthDate < DateTime.Today.AddYears(-120))
            return "Invalid birthdate";

              if (!(new[] { "m", "f", null }.Contains(data.Gender)))
            return "Invalid gender";

              if (data.Units.Length == 0)
            return "Must select at least one unit";

              return AddNewMember(data, () =>
              {
            Member newMember = new Member
            {
              FirstName = data.Firstname,
              MiddleName = data.Middlename,
              LastName = data.Lastname,
              BirthDate = data.BirthDate,
              Gender = (data.Gender == "m") ? Gender.Male
                  : (data.Gender == "f") ? Gender.Female
                  : Gender.Unknown,
              Status = MemberStatus.Applicant,
              Username = data.Username
            };
            db.Members.Add(newMember);

            PersonContact email = new PersonContact
            {
              Person = newMember,
              Type = "email",
              Value = data.Email,
              Priority = 0
            };
            db.PersonContact.Add(email);

            foreach (Guid unitId in data.Units)
            {
              UnitsController.RegisterApplication(db, unitId, newMember);
            }

            if (!System.Web.Security.Roles.RoleExists(APPLICANT_ROLE))
            {
              System.Web.Security.Roles.CreateRole(APPLICANT_ROLE);
            }
            System.Web.Security.Roles.AddUserToRole(data.Username, APPLICANT_ROLE);

            return newMember;
              }, "new-account-verification.html");
        }
Ejemplo n.º 23
0
        public string SaveMedical(MemberMedical data)
        {
            if (data == null || data.Member == null || data.Member.Id == Guid.Empty)
            {
                ThrowSubmitErrors(new[] { new Web.Model.SubmitError {
                                              Error = "No user specified"
                                          } });
            }

            if (!(Permissions.IsAdmin || Permissions.IsMembershipForPerson(data.Member.Id) || Permissions.IsSelf(data.Member.Id)))
            {
                ThrowAuthError();
            }


            Model.Member        member  = db.Members.Include("MedicalInfo", "EmergencyContacts").Single(f => f.Id == data.Member.Id);
            Model.MemberMedical medical = member.MedicalInfo;
            if (medical == null)
            {
                medical            = new Model.MemberMedical();
                member.MedicalInfo = medical;
            }

            medical.EncryptedAllergies   = string.IsNullOrWhiteSpace(data.Allergies) ? null : EncryptionService.Protect(EncryptionService.MEMBER_SENSITIVE, data.Allergies);
            medical.EncryptedMedications = string.IsNullOrWhiteSpace(data.Medications) ? null : EncryptionService.Protect(EncryptionService.MEMBER_SENSITIVE, data.Medications);
            medical.EncryptedDisclosures = string.IsNullOrWhiteSpace(data.Disclosure) ? null : EncryptionService.Protect(EncryptionService.MEMBER_SENSITIVE, data.Disclosure);

            var existingContacts = db.Members.Where(f => f.Id == data.Member.Id).SelectMany(f => f.EmergencyContacts).ToDictionary(f => f.Id, f => f);

            List <EmergencyContact> desiredContacts = new List <EmergencyContact>(data.Contacts);

            foreach (var contact in desiredContacts)
            {
                var cData = new Model.EmergencyContactData
                {
                    Name     = contact.Name,
                    Relation = contact.Relation,
                    Type     = contact.Type,
                    Number   = contact.Number
                };

                Model.MemberEmergencyContact memberContact;
                if (existingContacts.TryGetValue(contact.Id, out memberContact))
                {
                    existingContacts.Remove(contact.Id);
                }

                if (string.IsNullOrWhiteSpace(contact.Name))
                {
                    // If there's no name, delete it.
                    if (memberContact != null)
                    {
                        member.EmergencyContacts.Remove(memberContact);
                    }
                    continue;
                }

                if (string.IsNullOrWhiteSpace(contact.Number))
                {
                    return(string.Format("{0}'s number is blank", contact.Name));
                }

                if (memberContact == null)
                {
                    memberContact = new Model.MemberEmergencyContact();
                    member.EmergencyContacts.Add(memberContact);
                }

                memberContact.EncryptedData = EncryptionService.Protect(EncryptionService.MEMBER_SENSITIVE, JsonConvert.SerializeObject(cData));
            }

            foreach (var leftover in existingContacts.Values)
            {
                member.EmergencyContacts.Remove(leftover);
            }
            db.SaveChanges();

            return("OK");
        }
Ejemplo n.º 24
0
        private bool RewardTraining(Member m, Dictionary<Guid, TrainingCourse> courses, Dictionary<Guid, ComputedTrainingAward> awards, TrainingRule rule, DateTime? completed, DateTime? expiry, string newAwardsString)
        {
            IEnumerable<string> results = newAwardsString.Split('+');
              bool awarded = false;

              foreach (string result in results)
              {
            string[] parts = result.Split(':');
            Guid course = new Guid(parts[0]);

            if (!courses.ContainsKey(course))
            {
              throw new InvalidOperationException("Found bad rule: Adds course with ID" + course.ToString());
            }

            if (parts.Length > 1)
            {
              if (parts[1] == "default")
              {
            if (courses[course].ValidMonths.HasValue)
            {
              expiry = completed.Value.AddMonths(courses[course].ValidMonths.Value);
            }
            else
            {
              expiry = null;
            }
              }
              else
              {
            expiry = completed.Value.AddMonths(int.Parse(parts[1]));
              }
            }

            if (awards.ContainsKey(course) && expiry > awards[course].Expiry)
            {
              awards[course].Completed = completed;
              awards[course].Expiry = expiry;
              awards[course].Rule = rule;
              awarded = true;
              System.Diagnostics.Debug.WriteLineIf(m.LastName == "Kedan", string.Format("Updating existing record {0}, new expiry: {1}", courses[course].DisplayName, expiry));
            }
            else if (!awards.ContainsKey(course))
            {
              ComputedTrainingAward newAward = new ComputedTrainingAward { Course = courses[course], Member = m, Completed = completed, Expiry = expiry, Rule = rule };
              awards.Add(course, newAward);
              this.ComputedTrainingAwards.Add(newAward);
              awarded = true;
              System.Diagnostics.Debug.WriteLineIf(m.LastName == "Kedan", string.Format("Add new record {0}, new expiry: {1}", courses[course].DisplayName, expiry));
            }
              }
              return awarded;
        }
Ejemplo n.º 25
0
        private static void Render_FrontContent(PdfContentByte canvas, Member member)
        {
            Font f = new Font(baseFont, 12, Font.BOLD) { Color = BaseColor.WHITE };
            int bottom = CARD_HEIGHT - (UPPER_BAR_HEIGHT + PHOTO_BAR_HEIGHT) - 12 - 2;
            Phrase p = new Phrase(member.FullName, f);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);

            bottom -= 14;
            f = new Font(baseFont, 12) { Color = BaseColor.WHITE };
            p = new Phrase(member.WacLevel.ToString(), f);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);

            bottom -= 12;
            f = new Font(baseFont, 10, Font.BOLD) { Color = BaseColor.WHITE };
            p = new Phrase("KCSO DEM# " + member.DEM, f);
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_CENTER, p, CARD_WIDTH / 2, bottom, 0);

            BarcodePDF417 barcode = new BarcodePDF417();
            barcode.SetText(string.Format("Unknown Text. To be added. King County Search and Rescue{0}{1}{2}", member.LastName, member.FirstName, member.DEM));
            barcode.CodeRows = 20;
            barcode.CodeColumns = 7;
            barcode.Options = BarcodePDF417.PDF417_FIXED_RECTANGLE;
            var img = barcode.GetImage();
            img.ScaleAbsolute(CARD_WIDTH - 30, 28);
            img.SetAbsolutePosition((CARD_WIDTH - img.ScaledWidth) / 2, CARD_HEIGHT - UPPER_BAR_HEIGHT - PHOTO_BAR_HEIGHT - LOWER_BAR_HEIGHT - img.ScaledHeight - 8);
            canvas.AddImage(img);

            if (!string.IsNullOrWhiteSpace(member.PhotoFile))
            {
                var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content", "auth", "members", member.PhotoFile);
                if (File.Exists(file))
                {
                    img = Image.GetInstance(file);
                    img.ScaleToFit(PHOTO_WIDTH, PHOTO_BAR_HEIGHT);
                    img.SetAbsolutePosition(CARD_WIDTH - img.ScaledWidth, CARD_HEIGHT - (UPPER_BAR_HEIGHT + img.ScaledHeight));
                    canvas.AddImage(img);
                }
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Internal method to create the user
        /// </summary>
        /// <param name="user">Membershipuser created in the controller</param>
        /// <param name="context">Instance of Db Context</param>
        /// <param name="log">Instance of the logManager</param>
        /// <returns>true if the user creation succeeds, false otherwise. Deletes the created user on failure</returns>
        internal bool CreateUser(MembershipUser user, KcsarContext context, ILog log)
        {
            try
            {
                user.IsApproved = false;
                System.Web.Security.Membership.UpdateUser(user);

                System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(this.Username, false, 5);
                Thread.CurrentPrincipal = new System.Web.Security.RolePrincipal(new System.Web.Security.FormsIdentity(ticket));

                Member newMember = new Member
                        {
                            FirstName = this.Firstname,
                            LastName = this.Lastname,
                            Status = MemberStatus.Applicant,
                            Username = this.Email
                        };

                context.Members.Add(newMember);

                var email = new PersonContact
                {
                    Person = newMember,
                    Type = "email",
                    Value = this.Email,
                    Priority = 0
                };

                context.PersonContact.Add(email);

                if (this.Units != null)
                {
                    foreach (Guid unitId in this.Units)
                    {
                        UnitsController.RegisterApplication(context, unitId, newMember);
                    }
                }

                var profile = ProfileBase.Create(this.Username) as KcsarUserProfile;
                if (profile != null)
                {
                    profile.FirstName = this.Firstname;
                    profile.LastName = this.Lastname;
                    profile.LinkKey = newMember.Id.ToString();
                    profile.Save();
                }

                if (!System.Web.Security.Roles.RoleExists(APPLICANT_ROLE))
                {
                    System.Web.Security.Roles.CreateRole(APPLICANT_ROLE);
                }
                System.Web.Security.Roles.AddUserToRole(this.Username, APPLICANT_ROLE);

                context.SaveChanges();
            }
            catch(Exception ex)
            {
                log.Error(ex.ToString());
                var existingUser = Membership.GetUser(this.Username);
                if (existingUser != null)
                {
                    Membership.DeleteUser(existingUser.UserName);
                }

                return false;
            }

            return true;
        }
Ejemplo n.º 27
0
        public void LogPropertyChanged()
        {
            Guid memberId;
              using (var db = new KcsarContext(this.databaseLocation))
              {
            Member m = new Member {
              FirstName = "Log property",
              Gender = Gender.Female,
              BirthDate = new DateTime(2000, 12, 19)
            };
            db.Members.Add(m);
            db.SaveChanges();
            memberId = m.Id;
              }

              DateTime checkpoint = GetCheckpoint();
              using (var db = new KcsarContext(this.databaseLocation))
              {
            Member m = db.Members.Single(f => f.Id == memberId);
            m.FirstName = "Fixed";
            m.BirthDate = new DateTime(1990, 3, 5);
            m.Gender = Gender.Male;
            db.SaveChanges();
            var log = db.GetLog(checkpoint);

            Assert.AreEqual(1, log.Length, "log entries");
            Console.WriteLine(log[0].Comment);
            Assert.IsTrue(log[0].Comment.Contains("FirstName: Log property => Fixed"), "log msg: " + log[0].Comment);
            Assert.IsTrue(log[0].Comment.Contains("Gender: Female => Male"), "log msg gender: " + log[0].Comment);
            Assert.IsTrue(log[0].Comment.Contains("BirthDate: 12/19/2000 => 3/5/1990"), "log msg date: " + log[0].Comment);
            Assert.AreEqual("Modified", log[0].Action, "action: " + log[0].Action);
              }
        }
        private ActionResult InternalSave(Member m, FormCollection fields, ActionResult successAction)
        {
            if (Permissions.IsAdmin)
              {
            TryUpdateModel(m, new string[] { "DEM", "WacLevel", "WacLevelDate", "BackgroundDate", "SheriffApp" });

            // When creating a new user, the above methods will set ModelState to Invalid
            // and the call below doesn't clear it. Reset it now and the method
            // below will flag it Invalid if neededd.
            ModelState.Remove("FirstName");
              }

              if (Permissions.IsAdmin || Permissions.IsMembershipForPerson(m.Id))
              {
            TryUpdateModel(m, new string[] { "FirstName", "LastName", "MiddleName", "Gender", "BirthDate", "ExternalKey1" });
              }

              if (ModelState.IsValid)
              {
            this.db.SaveChanges();
            TempData["message"] = "Saved";
            return successAction;
              }

              return InternalEdit(m);
        }
        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 string PersonDescription(Member m, IKcsarContext ctx)
 {
     return string.Format("{0} [{1}] <a href=\"{2}\" target=\"_blank\">Detail</a><br/>",
               m.FullName,
               string.Join("][", m.Memberships.Where(ctx.GetActiveMembershipFilter(null, DateTime.Now)).Select(f => f.Unit.DisplayName).OrderBy(f => f).ToArray()),
               Url.Action("Detail", new { id = m.Id }));
 }
Ejemplo n.º 31
0
 private ActionResult InternalSave(Member m, FormCollection fields, ActionResult successAction)
 {
     try
       {
     if (Permissions.IsAdmin)
     {
       TryUpdateModel(m, new string[] { "DEM", "WacLevel", "BackgroundDate", "SheriffApp" });
       // Force WacLevelDate to be set after WacLevel
       TryUpdateModel(m, new string[] { "WacLevelDate" });
     }
     if (Permissions.IsAdmin || Permissions.IsMembershipForPerson(m.Id))
     {
       TryUpdateModel(m, new string[] { "FirstName", "LastName", "MiddleName", "Gender", "BirthDate", "ExternalKey1" });
     }
     if (ModelState.IsValid)
     {
       this.db.SaveChanges();
       TempData["message"] = "Saved";
       return successAction;
     }
       }
       catch (RuleViolationsException ex)
       {
     this.CollectRuleViolations(ex, fields);
       }
       return InternalEdit(m);
 }
Ejemplo n.º 32
0
 public MemberSummary(Member member)
 {
     this.Id = member.Id;
     this.Name = member.ReverseName;
     this.WorkerNumber = member.DEM;
 }
Ejemplo n.º 33
0
        public static CompositeTrainingStatus Compute(Member m, IEnumerable<ComputedTrainingAward> awards, IEnumerable<TrainingCourse> courses, DateTime when)
        {
            CompositeTrainingStatus result = new CompositeTrainingStatus();

            foreach (TrainingCourse course in courses)
            {
                TrainingStatus status = new TrainingStatus { CourseId = course.Id, CourseName = course.DisplayName, Expires = null, Status = ExpirationFlags.Unknown };

                bool mustHave = m.IsTrainingRequired(course);
                bool keepCurrent = m.ShouldKeepCourseCurrent(course);
                ComputedTrainingAward award = awards.Where(f => f.Course.Id == course.Id).FirstOrDefault();
                if (award == null)
                {
                    // No record - member has not completed the training
                    status.Status = mustHave ? ExpirationFlags.Missing : ExpirationFlags.NotNeeded;
                }
                else if ((course.ValidMonths ?? 0) == 0)
                {
                    // A record without an expiration
                    status.Status = ExpirationFlags.Complete;
                    status.Completed = award.Completed;
                }
                else
                {
                    // A record that has an expiration

                    status.Expires = award.Expiry;
                    status.Completed = award.Completed;
                    status.Status = (mustHave && keepCurrent)
                                     ? ((award.Expiry < when) ? ExpirationFlags.Expired : ExpirationFlags.NotExpired)
                                     : ExpirationFlags.Complete;
                }
                result.Expirations.Add(course.Id, status);

                // Ugh. Now we get to perpetuate a hack for a change in requirements for crime scene with a period when we ignored expired crime scene.
                if (!(course.DisplayName == "Crime Scene" && status.Expires > new DateTime(2007, 03, 01) && when > new DateTime(2010, 6, 3) && when < new DateTime(2010, 11, 12)))
                result.IsGood = result.IsGood && ((status.Status & ExpirationFlags.Okay) == ExpirationFlags.Okay);
            }
            return result;
        }
        private ActionResult InternalEdit(Member m)
        {
            ViewData["AdminEdit"] = Permissions.IsAdmin;

              ViewData["Gender"] = new SelectList(Enum.GetNames(typeof(Gender)), m.Gender.ToString());
              ViewData["WacLevel"] = new SelectList(Enum.GetNames(typeof(WacLevel)), m.WacLevel.ToString());

              return View("Edit", m);
        }