public MainWindow() { InitializeComponent(); CommonLibrary.MinBookToCountVote = 15; bgwNews = new BackgroundWorker(); bgwPopular = new BackgroundWorker(); bgwHighRated = new BackgroundWorker(); bgwRecommended = new BackgroundWorker(); LoginWindow loginWindow = new LoginWindow(); if (!CheckConnection()) { this.Close(); } InitializeBackgroundWorkers(); loginWindow.ShowDialog(); if (loginWindow.LoggedIn) { if (loginWindow.User.IsAdmin) { AdminPanel.AdminPanel adminPanel = new AdminPanel.AdminPanel(); adminPanel.Show(); } CommonLibrary.LogInUser(loginWindow.User); lblGreeting.Content = $"Welcome {CommonLibrary.LoggedInUser.Username},"; bgwNews.RunWorkerAsync(); bgwPopular.RunWorkerAsync(); bgwHighRated.RunWorkerAsync(); bgwRecommended.RunWorkerAsync(); } else { this.Close(); } }
internal static Response.BaseResponse UpdateAllWeights(BackgroundWorker bgw) { Response.BaseResponse response = new Response.BaseResponse(); string queryUpdate = "UPDATE `bx-books` SET `RatingWeight` = @Weight WHERE ISBN = @ISBN"; string queryGetSum = "SELECT SUM(`Book-Rating`), COUNT(`Book-Rating`) FROM `bx-book-ratings` WHERE ISBN = @ISBN"; var responseC = GetTotalAverageVotes(); double C = 0.0; if (responseC.Success) { C = responseC.Content; } else { response.ErrorText += responseC.ErrorText + ".\n"; } using (MySqlConnection conn = new MySqlConnection(connectionString)) { try { var allBooksResponse = GetAllBooks(); conn.Open(); if (allBooksResponse.Success) { int bookCount = allBooksResponse.Content.Count, index = 0; foreach (Book item in allBooksResponse.Content) { MySqlCommand commandUpdate = new MySqlCommand(queryUpdate, conn); commandUpdate.Parameters.AddWithValue("@ISBN", item.ISBN); MySqlCommand commandGetSum = new MySqlCommand(queryGetSum, conn); commandGetSum.Parameters.AddWithValue("@ISBN", item.ISBN); int count = 0; double sum = 0.0; try { using (MySqlDataReader reader = commandGetSum.ExecuteReader()) { if (reader.Read()) { sum = GetSafeField <double>(reader, 0); count = (int)GetSafeField <Int64>(reader, 1); } else { throw new Exception("Can't read count and sum values for book " + item.ISBN + "."); } } } catch (Exception e) { response.ErrorText += e.Message + " Error occured on update at " + item.ISBN + ".\n"; continue; } double weight; if (count == 0) { weight = 0; } else { double avg = sum / count; weight = CommonLibrary.GetWeightRate(count, avg, C, CommonLibrary.MinBookToCountVote); } commandUpdate.Parameters.AddWithValue("@Weight", weight); int rowsAffected = commandUpdate.ExecuteNonQuery(); if (rowsAffected != 1) { throw new Exception("Error weight update. Rows affected: " + rowsAffected); } bgw.ReportProgress((100 * index++) / bookCount); } } else { throw new Exception(allBooksResponse.ErrorText); } response.Success = true; } catch (Exception e) { response.ErrorText = e.Message; } } return(response); }