Ejemplo n.º 1
0
    public JsonResult GrantAccessToGuestTeller(int electionId, string secretCode)
    {
      var model = new ElectionModel();

      var desiredElection = model.VisibleElections().SingleOrDefault(e => e.C_RowId == electionId
                                                              && e.ElectionPasscode == secretCode);

      if (desiredElection == null)
      {
        return new
                 {
                   Error = "Sorry, unable to join that election"
                 }.AsJsonResult();
      }


      var fakeUserName = HttpContext.Current.Session.SessionID.Substring(0, 5) + Guid.NewGuid().ToString().Substring(0, 5);

      FormsAuthentication.SetAuthCookie(fakeUserName, false);
      UserSession.ProcessLogin();

      UserSession.IsGuestTeller = true;


      model.JoinIntoElection(desiredElection.ElectionGuid);

      return new
               {
                 LoggedIn = true
               }.AsJsonResult();
    }
 public HtmlString VisibleElectionsOptions()
 {
   const string template = "<option value=\"{0}\">{1}</option>";
   var visibleElections = new ElectionModel().VisibleElections();
   var listing = visibleElections.OrderBy(e => e.Name).Select(x => template.FilledWith(x.C_RowId, x.Name)).JoinedAsString();
   return listing
     .DefaultTo(template.FilledWith(0, "(Sorry, no elections are active right now.)"))
     .AsRawHtml();
 }
Ejemplo n.º 3
0
        public JsonResult GrantAccessToGuestTeller(Guid electionGuid, string codeToTry, Guid oldComputerGuid)
        {
            var electionModel = new ElectionModel();

            var passcode = new PublicElectionLister().GetPasscodeIfAvailable(electionGuid);

            if (passcode == null)
            {
                return(new
                {
                    Error = "Sorry, unknown election id"
                }.AsJsonResult());
            }
            if (passcode != codeToTry)
            {
                return(new
                {
                    Error = "Sorry, invalid code entered"
                }.AsJsonResult());
            }

            if (!UserSession.IsLoggedInTeller)
            {
                var fakeUserName = "******" + HttpContext.Current.Session.SessionID.Substring(0, 5) + Guid.NewGuid().ToString().Substring(0, 5);
                //        FormsAuthentication.SetAuthCookie(fakeUserName, true);

                var claims = new List <Claim>
                {
                    new Claim("UserName", fakeUserName),
                    new Claim("IsGuestTeller", "true"),
                    new Claim("UniqueID", fakeUserName),
                };

                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);

                var authenticationProperties = new AuthenticationProperties()
                {
                    AllowRefresh = true,
                    IsPersistent = false,
                    ExpiresUtc   = DateTime.UtcNow.AddDays(7)
                };

                HttpContext.Current.GetOwinContext().Authentication.SignIn(authenticationProperties, identity);

                UserSession.IsGuestTeller = true;
            }

            electionModel.JoinIntoElection(electionGuid, oldComputerGuid);

            return(new
            {
                LoggedIn = true,
                CompGuid = UserSession.CurrentComputer.ComputerGuid
            }.AsJsonResult());
        }
    public JsonResult SelectElection(Guid guid)
    {
      var electionModel = new ElectionModel();

      if (electionModel.JoinIntoElection(guid))
      {
        return new
                 {
                   Locations = ContextItems.LocationModel.Locations.OrderBy(l => l.SortOrder).Select(l => new { l.Name, l.C_RowId }),
                   Selected = true,
                   ElectionName = UserSession.CurrentElectionName,
                   Pulse = new PulseModel(this).Pulse()
                 }.AsJsonResult();
      }
      return new {Selected = false}.AsJsonResult();
    }
Ejemplo n.º 5
0
        public JsonResult GrantAccessToGuestTeller(Guid electionGuid, string codeToTry, Guid oldComputerGuid)
        {
            var electionModel = new ElectionModel();

            var passcode = new PublicElectionLister().GetPasscodeIfAvailable(electionGuid);

            if (passcode == null)
            {
                return(new
                {
                    Error = "Sorry, unknown election id"
                }.AsJsonResult());
            }
            if (passcode != codeToTry)
            {
                return(new
                {
                    Error = "Sorry, invalid code entered"
                }.AsJsonResult());
            }

            if (!UserSession.IsLoggedIn)
            {
                var fakeUserName = HttpContext.Current.Session.SessionID.Substring(0, 5) + Guid.NewGuid().ToString().Substring(0, 5);
                FormsAuthentication.SetAuthCookie(fakeUserName, true);
                UserSession.IsGuestTeller = true;
            }

            electionModel.JoinIntoElection(electionGuid, oldComputerGuid);

            return(new
            {
                LoggedIn = true,
                CompGuid = UserSession.CurrentComputer.ComputerGuid
            }.AsJsonResult());
        }
 public JsonResult CreateElection()
 {
   var model = new ElectionModel();
   return model.Create();
 }
 public JsonResult CopyElection(Guid guid)
 {
   var model = new ElectionModel();
   return model.Copy(guid);
 }
Ejemplo n.º 8
0
        public JsonResult Import(int rowId)
        {
            var file =
                Db.ImportFile.SingleOrDefault(
                    fi => fi.ElectionGuid == UserSession.CurrentElectionGuid && fi.C_RowId == rowId);

            if (file == null)
            {
                return(new
                {
                    failed = true,
                    result = new[] { "File not found" }
                }.AsJsonResult());
            }

            var columnsToRead = file.ColumnsToRead;

            if (columnsToRead == null)
            {
                return(new
                {
                    failed = true,
                    result = new[] { "Mapping not defined" }
                }.AsJsonResult());
            }

            var start      = DateTime.Now;
            var textReader = new StringReader(file.Contents.AsString(file.CodePage));
            var csv        = new CsvReader(textReader, true)
            {
                SkipEmptyLines = true
            };

            //mapping:   csv->db,csv->db
            var currentMappings =
                columnsToRead.DefaultTo("").SplitWithString(",").Select(s => s.SplitWithString("->")).ToList();
            var dbFields      = DbFieldsList.ToList();
            var validMappings = currentMappings.Where(mapping => dbFields.Contains(mapping[1])).ToList();

            if (validMappings.Count == 0)
            {
                return(new
                {
                    failed = true,
                    result = new[] { "Mapping not defined" }
                }.AsJsonResult());
            }

            var mappedFields = dbFields.Where(f => validMappings.Select(m => m[1]).Contains(f)).ToList();

            if (!mappedFields.Contains("LastName"))
            {
                return(new
                {
                    failed = true,
                    result = new[] { "Last Name must be mapped" }
                }.AsJsonResult());
            }

            var currentPeople = new PersonCacher(Db).AllForThisElection.ToList();
            var personModel   = new PeopleModel();
            var defaultReason = new ElectionModel().GetDefaultIneligibleReason();

            var rowsProcessed          = 0;
            var rowsSkipped            = 0;
            var peopleAdded            = 0;
            var peopleSkipped          = 0;
            var peopleSkipWarningGiven = false;

            var hub          = new ImportHub();
            var peopleToLoad = new List <Person>();
            var result       = new List <string>();

            var unexpectedReasons = new Dictionary <string, int>();
            var validReasons      = 0;

            csv.ReadNextRecord();
            while (!csv.EndOfStream)
            {
                rowsProcessed++;

                var valuesSet       = false;
                var namesFoundInRow = false;

                var query = currentPeople.AsQueryable();

                var person = new Person();
                var reason = defaultReason;

                foreach (var currentMapping in validMappings)
                {
                    var dbFieldName = currentMapping[1];
                    var value       = csv[currentMapping[0]];

                    switch (dbFieldName)
                    {
                    case "IneligibleReasonGuid":
                        // match value to the list of Enums
                        value = value.Trim();
                        if (value.HasContent())
                        {
                            var match = IneligibleReasonEnum.GetFor(value);
                            if (match != null)
                            {
                                reason        = match;
                                validReasons += 1;
                            }
                            else
                            {
                                // tried but didn't match a valid reason!
                                reason = defaultReason;
                                value  = HttpUtility.HtmlEncode(value);
                                result.Add("Invalid Eligibility Status reason on line {0}: {1}".FilledWith(rowsProcessed + 1, value));

                                if (unexpectedReasons.ContainsKey(value))
                                {
                                    unexpectedReasons[value] += 1;
                                }
                                else
                                {
                                    unexpectedReasons.Add(value, 1);
                                }
                            }
                        }
                        break;

                    default:
                        person.SetPropertyValue(dbFieldName, value);
                        break;
                    }
                    ;
                    valuesSet = true;

                    switch (dbFieldName)
                    {
                    case "LastName":
                        query           = query.Where(p => p.LastName == value);
                        namesFoundInRow = namesFoundInRow || value.HasContent();
                        break;

                    case "FirstName":
                        query           = query.Where(p => p.FirstName == value);
                        namesFoundInRow = namesFoundInRow || value.HasContent();
                        break;

                    case "OtherLastNames":
                        query = query.Where(p => p.OtherLastNames == value);
                        break;

                    case "OtherNames":
                        query = query.Where(p => p.OtherNames == value);
                        break;

                    case "OtherInfo":
                        query = query.Where(p => p.OtherInfo == value);
                        break;

                    case "Area":
                        query = query.Where(p => p.Area == value);
                        break;

                    case "BahaiId":
                        query = query.Where(p => p.BahaiId == value);
                        break;

                    case "IneligibleReasonGuid":
                        //if (reason != defaultReason)
                        //{
                        //  query = query.Where(p => p.IneligibleReasonGuid == reason.Value);
                        //}
                        break;

                    default:
                        throw new ApplicationException("Unexpected: " + dbFieldName);
                    }
                }

                if (!valuesSet || !namesFoundInRow)
                {
                    rowsSkipped++;
                    result.Add("Skipping line " + rowsProcessed);
                }
                else if (query.Any())
                {
                    peopleSkipped++;
                    if (peopleSkipped < 10)
                    {
                        result.Add("Duplicate on line " + (rowsProcessed + 1));
                    }
                    else
                    {
                        if (!peopleSkipWarningGiven)
                        {
                            result.Add("More duplicates... (Only the first 10 are noted.)");
                            peopleSkipWarningGiven = true;
                        }
                    }
                }
                else
                {
                    //get ready for DB
                    person.ElectionGuid = UserSession.CurrentElectionGuid;
                    person.PersonGuid   = Guid.NewGuid();

                    personModel.SetCombinedInfoAtStart(person);
                    personModel.SetInvolvementFlagsToDefault(person, reason);

                    //Db.Person.Add(person);
                    currentPeople.Add(person);
                    peopleToLoad.Add(person);

                    peopleAdded++;

                    if (peopleToLoad.Count >= 500)
                    {
                        //Db.SaveChanges();

                        Db.BulkInsert(peopleToLoad);
                        peopleToLoad.Clear();
                    }
                }

                if (rowsProcessed % 100 == 0)
                {
                    hub.ImportInfo(rowsProcessed, peopleAdded);
                }

                csv.ReadNextRecord();
            }

            if (peopleToLoad.Count != 0)
            {
                Db.BulkInsert(peopleToLoad);
            }

            file.ProcessingStatus = "Imported";

            Db.SaveChanges();

            new PersonCacher().DropThisCache();

            result.AddRange(new[]
            {
                "Processed {0} data line{1}".FilledWith(rowsProcessed, rowsProcessed.Plural()),
                "Added {0} {1}.".FilledWith(peopleAdded, peopleAdded.Plural("people", "person"))
            });
            if (peopleSkipped > 0)
            {
                result.Add("{0} duplicate{1} ignored.".FilledWith(peopleSkipped, peopleSkipped.Plural()));
            }
            if (rowsSkipped > 0)
            {
                result.Add("{0} line{1} skipped or blank.".FilledWith(rowsSkipped, rowsSkipped.Plural()));
            }
            if (validReasons > 0)
            {
                result.Add("{0} {1} with recognized Eligibility Status Reasons.".FilledWith(validReasons, validReasons.Plural("people", "person")));
            }
            if (unexpectedReasons.Count > 0)
            {
                result.Add("{0} Eligibility Status Reason{1} not recognized: ".FilledWith(unexpectedReasons.Count, unexpectedReasons.Count.Plural()));
                foreach (var r in unexpectedReasons)
                {
                    result.Add("&nbsp; &nbsp; \"{0}\"{1}".FilledWith(r.Key, r.Value == 1 ? "" : " x" + r.Value));
                }
            }

            result.Add("Import completed in " + (DateTime.Now - start).TotalSeconds.ToString("0.0") + " s.");

            new LogHelper().Add("Imported file #" + rowId + ": " + result.JoinedAsString(" "), true);

            return(new
            {
                result,
                count = NumberOfPeople
            }.AsJsonResult());
        }
Ejemplo n.º 9
0
    public JsonResult RegisterVoteJson(int personId, string voteType, int lastRowVersion)
    {
      if (!VotingMethodEnum.Exists(voteType))
      {
        return new { Message = "Invalid type" }.AsJsonResult();
      }

      var person =
        Db.People.SingleOrDefault(p => p.ElectionGuid == CurrentElectionGuid && p.C_RowId == personId);
      if (person == null)
      {
        return new { Message = "Unknown person" }.AsJsonResult();
      }


      if (person.VotingMethod == voteType)
      {
        // already set this way...turn if off
        person.VotingMethod = null;
        person.VotingLocationGuid = null;
        person.RegistrationTime = null;
      }
      else
      {
        person.VotingMethod = voteType;
        person.VotingLocationGuid = UserSession.CurrentLocationGuid;
        person.RegistrationTime = DateTime.Now;

        if (voteType != VotingMethodEnum.InPerson)
        {
          if (person.EnvNum == null)
          {
            // create a new env number

            // get election from DB, not session, as we need to update it now
            var election = new ElectionModel().GetFreshFromDb(CurrentElectionGuid);
            var nextNum = election.LastEnvNum.AsInt() + 1;

            person.EnvNum = nextNum;
            election.LastEnvNum = nextNum;

          }
        }
      }

      person.TellerAtKeyboard = UserSession.GetCurrentTeller(1);
      person.TellerAssisting = UserSession.GetCurrentTeller(2);

      Db.SaveChanges();

      List<Person> people;
      if (lastRowVersion == 0)
      {
        people = new List<Person> { person };
      }
      else
      {
        people = Db.People
  .Where(p => p.ElectionGuid == CurrentElectionGuid && p.C_RowVersionInt > lastRowVersion)
  .ToList();
      }

      var updateInfo = new
      {
        PersonLines = FrontDeskPersonLines(people),
        LastRowVersion
      };

      FrontDeskHub.UpdateAllConnectedClients(updateInfo);

      return updateInfo.AsJsonResult();
    }