/// <summary> /// Saves the candidates chosen to the user /// </summary> /// <param name="sender">Model list containing the list of candidate vote result</param> /// <returns>Returns a -1 for a fail result and a 1 for a success result</returns> internal int AddCandidateVote(List <CandidateTable> sender) { List <UserVoteTable> users = new List <UserVoteTable>(); users = this.db.Query <UserVoteTable>("SELECT * FROM UserVoteTable WHERE Active = 1"); if (users.Count != 1) { return(-1); } List <int> choosenCandidates = new List <int>(); foreach (CandidateTable item in sender) { choosenCandidates.Add(item.Id); } string json = JsonConvert.SerializeObject(choosenCandidates); UserVoteTable user = new UserVoteTable(); user = users[0]; user.CandidateIds = json; this.db.Update(user); return(1); }
/// <summary> /// Initializes a new instance of the <see cref="VoteSubmittedViewModel"/> class. /// </summary> /// <param name="navigationService">Passes the Navigation Property from the View to the ViewModel</param> /// <param name="user">Receives the user data from the view</param> public VoteSubmittedViewModel(INavigationService navigationService, UserVoteTable user) { this.navigation = navigationService; this.user = user; this.resource = new ResourceLoader(); this.Title = this.resource.GetString("SubmittedTitle"); this.VoteText = this.resource.GetString("VoteText"); this.ElectorateText = this.resource.GetString("ElectorateText"); this.CandidateText = this.resource.GetString("CandidateText"); this.PartyText = this.resource.GetString("PartyText"); this.ReferendumText = this.resource.GetString("ReferendumText"); this.SubmittedText = this.resource.GetString("SubmittedText"); this.LoginButton = this.resource.GetString("VoteButton"); this.ConnectionText = this.resource.GetString("ConnectionText"); this.LoginCommand = new CommandService(this.Login); ElectorateTable electorateData = new ElectorateTable(); List <CandidateTable> candidateData = new List <CandidateTable>(); PartyTable partyData = new PartyTable(); List <string> candidateList = JsonConvert.DeserializeObject <List <string> >(this.user.CandidateIds); electorateData = this.db.GetElectorateFromId(this.user.ElectorateId); foreach (string item in candidateList) { int id = int.Parse(item); CandidateTable candidate = new CandidateTable(); candidate = this.db.GetCandidateFromId(id); candidateData.Add(candidate); } partyData = this.db.GetPartyFromId(this.user.PartyId); this.Electorate = electorateData.Name; string candidateNames = string.Empty; foreach (CandidateTable item in candidateData) { if (candidateNames == string.Empty) { candidateNames = item.Name; } else { candidateNames = string.Join(Environment.NewLine, candidateNames, item.Name); } } this.Candidates = candidateNames; this.Party = partyData.Name; this.Referendum = this.user.Referendum.ToString(); }
/// <summary> /// Updates the user to having the vote being sent to the server and to deactive /// </summary> /// <param name="voteToSend">Model containing the user details for status update</param> /// <returns>Returns the updated user details</returns> internal UserVoteTable VoteSent(UserVoteTable voteToSend) { voteToSend.VoteSaved = true; voteToSend.Active = false; this.db.Update(voteToSend); return(voteToSend); }
/// <summary> /// Sends the vote results to the server /// </summary> /// <returns>Returns the updated user details or a null result if it fails</returns> internal async Task <UserVoteTable> SendVote() { string url = this.resource.GetString("BaseUrl") + "/api/UserContoller/SaveVoteAsync"; string contentType = this.resource.GetString("ContentType"); UserVoteTable voteToSend = new UserVoteTable(); voteToSend = this.db.GetVoteToSend(); VoteSendRequestModel sendRequest = new VoteSendRequestModel() { Id = voteToSend.ServerId, ElectorateId = voteToSend.ElectorateId, CandidateIds = voteToSend.CandidateIds, PartyId = voteToSend.PartyId, Referendum = voteToSend.Referendum }; string json = JsonConvert.SerializeObject(sendRequest); HttpContent content = new StringContent(json, Encoding.UTF8, contentType); HttpResponseMessage response; using (HttpClient client = new HttpClient()) { try { response = await client.PostAsync(url, content); } catch { return(voteToSend); } } if (response.IsSuccessStatusCode) { VoteSentResponseModel result = JsonConvert.DeserializeObject <VoteSentResponseModel>(response.Content.ReadAsStringAsync().Result); if (result.Success) { voteToSend = this.db.VoteSent(voteToSend); return(voteToSend); } else { return(voteToSend); } } else { return(voteToSend); } }
/// <summary> /// Takes the result passed from the button and saves it to the user, then navigates to the next view /// </summary> /// <param name="obj">Contains a Yes or No value depending on what button was pressed</param> internal async void Next(object obj) { int result = -1; switch ((string)obj) { case "yes": result = this.db.AddReferendumVote(true); break; case "no": result = this.db.AddReferendumVote(false); break; } if (result == -1) { ContentDialog error = new ContentDialog() { Title = "Error Getting User", Content = "Unable to get current user, returning to login", PrimaryButtonText = "OK" }; await error.ShowAsync(); this.navigation.Navigate(typeof(LoginView)); } else { UserVoteTable voteSent = await this.restAPI.SendVote(); if (!voteSent.VoteSaved) { ContentDialog connectionError = new ContentDialog() { Title = "Unable to Send Vote", Content = "Problem sending vote to ElectionsNZ, will try again later", PrimaryButtonText = "OK" }; await connectionError.ShowAsync(); } this.navigation.Navigate(typeof(VoteSubmittedView), voteSent); } }
/// <summary> /// Saves the party chosen to the user /// </summary> /// <param name="sender">Model containing the party vote result</param> /// <returns>Returns a -1 for a fail result and a 1 for a success result</returns> internal int AddPartyVote(PartyTable sender) { List <UserVoteTable> users = new List <UserVoteTable>(); users = this.db.Query <UserVoteTable>("SELECT * FROM UserVoteTable WHERE Active = 1"); if (users.Count != 1) { return(-1); } UserVoteTable user = new UserVoteTable(); user = users[0]; user.PartyId = sender.Id; this.db.Update(user); return(1); }
/// <summary> /// Saves the referendum result to the user /// </summary> /// <param name="result">Bool containing the referendum result</param> /// <returns>Returns an int that is either -1 for a fail and a 1 for a success</returns> internal int AddReferendumVote(bool result) { List <UserVoteTable> users = new List <UserVoteTable>(); users = this.db.Query <UserVoteTable>("SELECT * FROM UserVoteTable WHERE Active = 1"); if (users.Count != 1) { return(-1); } UserVoteTable user = new UserVoteTable(); user = users[0]; user.Referendum = result; this.db.Update(user); return(1); }
/// <summary> /// Sets login status of user to active /// </summary> /// <param name="user">Model containing current user data</param> internal void VoterLoggedIn(UserVoteTable user) { this.db.Query <UserVoteTable>("UPDATE UserVoteTable SET Active = 0"); this.db.Insert(user); }
/// <summary> /// Changes the active state of the user /// </summary> /// <param name="user">Model containing the users data</param> /// <returns>Returns the updated user data</returns> internal UserVoteTable SwitchActive(UserVoteTable user) { this.db.Query <UserVoteTable>("UPDATE UserVoteTable SET Active = '" + !user.Active + "' WHERE Id = '" + user.Id + "'"); return(user); }
/// <summary> /// Sends login details to server for login /// </summary> /// <param name="firstName">String containing first name</param> /// <param name="lastName">String containing last name</param> /// <param name="dob">DateTime object containing date of birth</param> /// <param name="electoralId">String containing electora id</param> /// <returns>Returns User details from server or a null result if it fails</returns> internal async Task <UserVoteTable> Login(string firstName, string lastName, DateTime dob, string electoralId) { string url = this.resource.GetString("BaseUrl") + "/api/UserContoller/LoginAsync"; string contentType = this.resource.GetString("ContentType"); LoginRequestModel loginModel = new LoginRequestModel() { FirstName = firstName, LastName = lastName, Dob = dob.Date.ToString("D"), ElectoralId = electoralId }; string json = JsonConvert.SerializeObject(loginModel); HttpContent content = new StringContent(json, Encoding.UTF8, contentType); HttpResponseMessage response; using (HttpClient client = new HttpClient()) { try { response = await client.PostAsync(url, content); } catch { return(null); } } if (response.IsSuccessStatusCode) { LoginUserResponse result = JsonConvert.DeserializeObject <LoginUserResponse>(response.Content.ReadAsStringAsync().Result); if (result.Success) { UserVoteTable newUser = new UserVoteTable() { ServerId = result.Result.Id, FirstName = result.Result.FirstName, LastName = result.Result.LastName, DoB = result.Result.DoB, ElectoralId = result.Result.ElectoralId, ElectorateId = result.Result.ElectorateId, CandidateIds = result.Result.CandidateIds, PartyId = result.Result.PartyId, Referendum = result.Result.Referendum, VoteSaved = result.Result.VoteSaved }; return(newUser); } else { return(null); } } else { return(null); } }
/// <summary> /// Validates the user entry and if the entry is valid sends the data to the Rest Service to check if user details are correct and logs in the user. /// When the user has been logged in and has received the user details navigates user to appropriate view /// </summary> /// <param name="sender">Empty Object</param> internal async void Login(object sender) { this.LoggingIn = true; if (string.IsNullOrEmpty(this.FirstName) || string.IsNullOrEmpty(this.LastName) || string.IsNullOrEmpty(this.ElectoralId)) { ContentDialog emptyEntry = new ContentDialog() { Title = "No Login Information", Content = "No information has been entered. Please enter your firstname, last name, date of birth and electoral ID.", PrimaryButtonText = "OK" }; await emptyEntry.ShowAsync(); this.LoggingIn = false; return; } MatchCollection firstNameResult = Regex.Matches(this.FirstName, @"^[a-zA-Z]+$"); MatchCollection lastNameResult = Regex.Matches(this.LastName, @"^[a-zA-Z]+$"); MatchCollection electoralIdResult = Regex.Matches(this.ElectoralId, @"^[A-Z]{3}[0-9]{6}$"); if (firstNameResult.Count == 0) { ContentDialog invalidEntry = new ContentDialog() { Title = "Invalid Entry", Content = this.FirstName + " is not a valid name, Please enter your correct first name", PrimaryButtonText = "OK" }; await invalidEntry.ShowAsync(); this.LoggingIn = false; return; } if (lastNameResult.Count == 0) { ContentDialog invalidEntry = new ContentDialog() { Title = "Invalid Entry", Content = this.LastName + " is not a valid name, Please enter your correct last name", PrimaryButtonText = "OK" }; await invalidEntry.ShowAsync(); this.LoggingIn = false; return; } DateTime validationDate = DateTime.Now; validationDate = validationDate.AddYears(-18); if (this.DoB.Date > validationDate.Date) { ContentDialog invalidEntry = new ContentDialog() { Title = "Invalid Entry", Content = "Only 18 years and older are allowed to vote", PrimaryButtonText = "OK" }; await invalidEntry.ShowAsync(); this.LoggingIn = false; return; } if (electoralIdResult.Count == 0) { ContentDialog invalidEntry = new ContentDialog() { Title = "Invalid Entry", Content = "Please enter a valid Electoral ID", PrimaryButtonText = "OK" }; await invalidEntry.ShowAsync(); this.LoggingIn = false; return; } if (!(await this.UpdateVoteData())) { ContentDialog noData = new ContentDialog() { Title = "No Data", Content = "Unable to get Voting Data, Please Try Again Later", PrimaryButtonText = "OK" }; await noData.ShowAsync(); this.LoggingIn = false; return; } UserVoteTable user = this.db.CheckVoter(this.FirstName, this.LastName, this.DoB, this.ElectoralId); if (user != null) { if (user.VoteSaved) { this.navigation.Navigate(typeof(VoteSubmittedView), user); return; } if (!user.Active) { this.db.DeactivateUsers(); user = this.db.SwitchActive(user); } if (user.ElectorateId == default(int)) { this.navigation.Navigate(typeof(ElectorateView)); } else if (user.CandidateIds == null) { this.navigation.Navigate(typeof(CandidateView)); } else if (user.PartyId == default(int)) { this.navigation.Navigate(typeof(PartyView)); } else { this.navigation.Navigate(typeof(ReferendumView)); } return; } UserVoteTable loggedIn = await this.restAPI.Login(this.FirstName, this.LastName, this.DoB, this.ElectoralId); if (loggedIn != null) { loggedIn.Active = true; this.db.VoterLoggedIn(loggedIn); this.LoggingIn = false; if (loggedIn.VoteSaved) { this.navigation.Navigate(typeof(VoteSubmittedView), loggedIn); return; } if (!loggedIn.Active) { this.db.DeactivateUsers(); loggedIn = this.db.SwitchActive(loggedIn); } this.navigation.Navigate(typeof(ElectorateView)); } else { ContentDialog invalidLogin = new ContentDialog() { Title = "Incorrect Login", Content = "Incorrect Login Details", PrimaryButtonText = "OK" }; await invalidLogin.ShowAsync(); this.LoggingIn = false; } }