public User GetUser(int id) { try { var innUser = _db.UserTable.Find(id); var outUser = new User() { fornavn = innUser.Fornavn, etternavn = innUser.Etternavn, adresse = innUser.Adresse, epost = innUser.Epost, postnr = innUser.Poststeder.Postnummer, accessLevel = innUser.AccessLevel }; return(outUser); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, GetUser, ingen bruker funnet"); } var errorUser = new User() { errorMessage = "Ingen bruker funnet" }; return(errorUser); }
/// <summary> /// Gets a user from the user table based on the id in the database. The user from the database is turned into a UserViewModel to display in the views. /// </summary> /// <returns> /// User as a UserViewModel /// </returns> /// <param name="id">Users id in the database</param> public UserViewModel GetUser(int id) { try { // Gets user from database var innUser = _db.UserTable.Find(id); // Turns it into a UserViewModel fit for display in views var outUser = new UserViewModel() { Username = innUser.Username, Name = innUser.Name, ValidPayment = innUser.ValidPayment, Membership = innUser.Membership }; return(outUser); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, UserViewModel GetUser(int id)"); } // Returns a user with an errormessage var errorUser = new UserViewModel() { Response = "Ingen bruker funnet" }; return(errorUser); }
/// <summary> /// Redirects an administrator from the admin site to Vismas authentication server to get an access token. /// </summary> /// <returns> /// <c>True</c> if it is successful. /// </returns> /// <param name="customer">A user gotten from the Visma eAccounting API.</param> public bool RequestToken() { try { // Creates a list of scopes needed to access the right token var scopes = new List <string> { "offline_access", "ea:api", "ea:sales" }; // Gets the redirect URI in this application from the web.config file var redirectUri = new Uri(WebConfigurationManager.AppSettings["RedirectUri"]); // Creates a new WebServerClient var client = VismaAuthProvider.CreateClient(); // Requests a brand new access token from Visma client.RequestUserAuthorization(scopes, redirectUri); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, bool AskForToken()"); return(false); } }
/// <summary> /// Updates the payment details of the user determined in the BLL, if the payment details are set to be updated automatically. /// </summary> /// <returns> /// <c>True</c> if it is successful /// </returns> /// <param name="user">User from view</param> /// <param name="paymentStatus">Users paymentstatus determined in the BLL</param> public bool UpdatePaymentDetails(User user, bool paymentStatus) { try { var editUser = _db.UserTable.Find(user.Id); if (user.ManualValidPayment == false) { editUser.ValidPayment = paymentStatus; } _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool UpdatePaymentDetails(User user, bool paymentStatus)"); return(false); } }
public bool UpdateMovie(Movie innMovie, string ImagePath) { try { var editMovie = GetMovie(innMovie.Id); editMovie.Title = innMovie.Title; editMovie.Actor = innMovie.Actor; editMovie.Director = innMovie.Director; editMovie.ReleasedYear = innMovie.ReleasedYear; editMovie.Genre = innMovie.Genre; editMovie.Image = ImagePath; editMovie.Price = innMovie.Price; _db.SaveChanges(); return(true); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, UpdateMovie"); } return(false); }
/// <summary> /// Updates an existing user with info from a NAS member from Visma. /// </summary> /// <returns> /// <c>True</c> if the update was successful. /// </returns> /// <param name="innUser">NAS member from Visma</param> /// <param name="membership">Type of membership determined in the BLL</param> public bool UpdateUserFromVisma(DataCustomer innUser, string membership) { try { // Gets the user to be edited from the user table var editUser = _db.UserTable.FirstOrDefault(d => d.UserId == innUser.Id.ToString()); // Sets the fields from the Customer to user to be updated in the user table. editUser.Username = innUser.EmailAddress; editUser.Name = innUser.Name; editUser.Membership = membership; _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool UpdateUserFromVisma(DataCustomer innUser, string membership)"); return(false); } }
/// <summary> /// Gets the token from the token table. /// </summary> /// <returns> /// Access token for Visma eAccounting API /// </returns> public IAuthorizationState GetToken() { try { // Gets the token from the token table var dbToken = _db.TokenTable.FirstOrDefault(); // Turns the token into an Authorization state used to access the Visma eAccounting API IAuthorizationState setToken = new AuthorizationState() { AccessToken = dbToken.AccessToken, AccessTokenExpirationUtc = dbToken.AccessTokenExpirationUtc, AccessTokenIssueDateUtc = dbToken.AccessTokenIssueDateUtc, RefreshToken = dbToken.RefreshToken }; return(setToken); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, IAuthorizationState GetToken()"); return(null); } }
/// <summary> /// Validates an admin from the database if the username given exists and the password matches. /// </summary> /// <returns> /// A validated Admin if validation is successful, else null /// </returns> /// <param name="username">Admin to be validated</param> /// <param name="password">Password for the user</param> public Admin ValidatedAdmin(string username, string password) { try { // Gets the admin based on the username var user = _db.AdminTable.FirstOrDefault(d => d.Username == username); // Creates hash from the password given as parameter and salt registered in the database var testPassword = CreateHash(password, user.Salt); // Checks if created hash matches the hash in the database and returns true if it matches if (user.Password.SequenceEqual(testPassword)) { return(user); } } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool ValidateAdmin(string username, string password)"); } return(null); }
/// <summary> /// Turns a view model user into database model user and adds in to the user table in the database. /// </summary> /// <returns> /// <c>True</c> if the adding was successful. /// </returns> /// <param name="customer">User from Visma to be added to the database.</param> /// <param name="membership">Type of membership the customer has.</param> public bool AddUser(DataCustomer customer, string membership) { try { var newUser = new User() { UserId = customer.Id.ToString(), Name = customer.Name, Username = customer.EmailAddress, Membership = membership }; _db.UserTable.Add(newUser); _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool AddUser(DataCustomer customer, string membership)"); return(false); } }
public ActionResult AddMovie(Movie movieInn, HttpPostedFileBase file) { StringBuilder ImagePath = new StringBuilder("jpg/"); if (ModelState.IsValid) { try { file.SaveAs(HttpContext.Server.MapPath(@"~\Content\jpg\") + file.FileName); ImagePath.Append(file.FileName); var success = _db.AddMovie(movieInn, ImagePath.ToString()); if (success) { return(RedirectToAction("Dashbord")); } } catch (Exception e) { var error = new ErrorFiler(); error.WriteError(e.GetType().FullName, "Failure in file upload"); } } return(View()); }
/// <summary> /// Adds a password to a user in the usertable and sets the user as active if it is a new registration. /// </summary> /// <returns> /// A <c>string</c> containing "Success" if successful or an error message describing what went wrong. /// </returns> /// <param name="innUser">User to be updated in the database</param> /// <param name="password">Password for the user</param> public string RegisterUser(User innUser, string password) { try { // Creates salt for the password var salt = CreateSalt(); // Hashes the given password string with the salt created var hash = CreateHash(password, salt); // Sets the fields of the user before saving changes in the database innUser.Password = hash; innUser.Salt = salt; innUser.ActiveUser = true; _db.SaveChanges(); return("Success"); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, string RegisterUser(User innUser, string password)"); return("Det har oppstått en feil, vennligst prøv igjen senere"); } }
/// <summary> /// Requests an updated invoice list from the Visma eAccounting API, and uses it to update the users marked as active in the database. /// </summary> /// <returns> /// <c>True</c> if it is successful /// </returns> /// <para> A user is marked as active if it has been registered in the mobile app or the admin site.</para> private bool UpdateActiveUsersFromVisma() { try { // Gets a list of active users from the database var userList = _db.GetActiveUserList(); // Sends a request for a list of invoices from Visma var invoiceList = GetInvoiceListFromVisma(); // Iterates through the list of active users and updates their payment status foreach (var user in userList) { var paymentStatus = DeterminePaymentStatus(user, invoiceList); _db.UpdatePaymentDetails(user, paymentStatus); } return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, bool UpdateActiveUsersFromVisma()"); return(false); } }
/// <summary> /// Determines the payment status of the user from an updated list of invoices from Visma using the the userId and the type of membership the user has. /// </summary> /// <returns> /// <c>True</c> if the user has valid payment status based on information from Visma /// </returns> /// <param name="user">The user to be evaluated by the method</param> /// <param name="invoiceList">An updated list of invoices from Visma.</param> private bool DeterminePaymentStatus(User user, InvoiceResponse invoiceList) { try { // Returns true if the membership is marked as livsvarig if (user.Membership == "Livsvarig") { return(true); } // Finds an invoice from the invoice list with matching userId from the parameters var userInvoice = invoiceList.Data.ToList().Find(x => x.CustomerId.ToString() == user.UserId); // If the user has been issued an invoice this year and the remaining amount is 0 or less the user has valid payment if (userInvoice.DueDate.Year == DateTime.Now.Year && userInvoice.RemainingAmount <= 0) { return(true); } return(false); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, bool DeterminePaymentStatus(User user, InvoiceResponse invoiceList)"); } return(false); }
/// <summary> /// Turns an authorization state from Visma into a token and adds it to the database. /// </summary> /// <returns> /// <c>True</c> if it is successful /// </returns> /// <param name="state">Access token from Visma</param> public bool SaveToken(IAuthorizationState state) { try { var dbToken = new Token() { RefreshToken = state.RefreshToken, AccessToken = state.AccessToken, AccessTokenIssueDateUtc = state.AccessTokenIssueDateUtc, AccessTokenExpirationUtc = state.AccessTokenExpirationUtc }; _db.TokenTable.Add(dbToken); _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool SaveToken(IAuthorizationState state)"); return(false); } }
/// <summary> /// Updates the user from the admin site. This method also sets if the payment status of the user should be determined /// automatically or manually with the <c>string</c> field AutoUpdatePayment. /// </summary> /// <returns> /// <c>True</c> if it is successful /// </returns> /// <param name="user">User from view</param> public bool UpdateUserAsAdmin(UserViewModel user) { try { // Gets user from the database var editUser = GetUserDb(user.Username); // Checks if the payment status should be automatic or not. If not the payment status is set based on AutoUpdatePayment if (user.AutoUpdatePayment == "automatic") { editUser.ManualValidPayment = false; } else { if (user.AutoUpdatePayment == "true") { editUser.ValidPayment = true; editUser.ManualValidPayment = true; } else if (user.AutoUpdatePayment == "false") { editUser.ValidPayment = false; editUser.ManualValidPayment = true; } } // If the password is not null or empty it is used to update the user and set the users status to active if (!string.IsNullOrEmpty(user.Password)) { // Creates salt for the password var salt = CreateSalt(); // Hashes the given password string with the salt created var hash = CreateHash(user.Password, salt); // Sets the fields of the user to be updated editUser.Password = hash; editUser.Salt = salt; editUser.ActiveUser = true; } _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool UpdateUserAsAdmin(UserViewModel user)"); return(false); } }
public string GetZipCode(string postnummer) { var jsonSerializer = new JavaScriptSerializer(); try { string json = jsonSerializer.Serialize(_db.GetZipCode(postnummer)); return(json); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "HomeController, GetZipCode"); string json = jsonSerializer.Serialize("Ugyldig postnummer"); return(json); } }
public bool AddMovie(Movie movie, string ImagePath) { try { movie.Image = ImagePath; _db.MovieTable.Add(movie); _db.SaveChanges(); return(true); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, AddMovie"); } return(false); }
public bool Update() { var startDb = new DBInit(); if (!_db.CityTable.Any()) { try { startDb.Init(_db); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "DBinit"); } } return(true); }
public bool DeleteOrder(int id) { try { var order = _db.OrderTable.Find(id); _db.OrderTable.Remove(order); _db.SaveChanges(); return(true); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, DeleteOrder"); } return(false); }
public bool AdminRegistrer(User userInn) { try { var newUser = new Users() { Fornavn = userInn.fornavn, Etternavn = userInn.etternavn, Adresse = userInn.adresse, Epost = userInn.epost }; byte[] salt = LagSalt(); byte[] hash = LagHash(userInn.passord, salt); newUser.Passord = hash; newUser.Salt = salt; newUser.AccessLevel = userInn.accessLevel.ToString(); try { var findCity = _db.CityTable.Find(userInn.postnr); newUser.Poststeder = findCity; } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, AdminRegistrer, FindCity"); } _db.UserTable.Add(newUser); _db.SaveChanges(); return(true); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, AdminRegistrer, Legg til ny bruker"); } return(false); }
/// <summary> /// Sends a request to the DAL to register a password to an existing member from the mobile application. This is after determining if the member has a user in the database as well as valid payment. /// </summary> /// <returns> /// <c>string</c> containing "Success" if successful or an error message describing what went wrong. /// </returns> /// <para>Users are added from Vismas servers so a user needs to be a member before registering in the mobile app. The user is updated in the database after registration. </para> /// <param name="innUser">A user with username and password to be registered.</param> public string RegisterUser(UserViewModel innUser) { try { // Gets the user from the database var user = _db.GetUserDb(innUser.Username); // Returns an error message if the user does not have a registered membership in the database and therefore Visma eAccounting if (user == null) { return("Det er ingen aktive medlemmer med den eposten"); } // If a user is already an active user the registration is not valid and an error message is returned if (user.ActiveUser) { return("En bruker er allerede registrert med den eposten"); } // Sends a request for a list of invoices from Visma var invoiceList = GetInvoiceListFromVisma(); // Determines the payment status of the user from the database var paymentStatus = DeterminePaymentStatus(user, invoiceList); // Sets the new payment status for the user before registration. user.ValidPayment = paymentStatus; // Registers the user return(_db.RegisterUser(user, innUser.Password)); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, string RegisterUser(UserViewModel innUser)"); return("Det har oppstått en feil, vennligst prøv igjen senere"); } }
public bool DeleteMovie(int id) { try { var movie = GetMovie(id); Debug.WriteLine("movie: " + movie); _db.MovieTable.Remove(movie); _db.SaveChanges(); return(true); } catch (Exception e) { Debug.WriteLine("ERROR"); var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, DeleteMovie"); } return(false); }
/// <summary> /// Gets a user for the web api based on the username provided. This is after determining if the user has valid payment status and updating the user in the database. /// </summary> /// <returns> /// User in the form of web api model /// </returns> /// <param name="username">Username of the user trying to access their info in the database.</param> public UserApiModel GetUser(string username) { try { // Gets a user from the DAL var user = _db.GetUserDb(username); // Sends a request for a list of invoices from Visma var invoiceList = GetInvoiceListFromVisma(); // Determines the payment status of the user trying to access their information from the database var paymentStatus = DeterminePaymentStatus(user, invoiceList); // Alters the user from database model to the web api model var outUser = new UserApiModel() { Username = user.Username, Name = user.Name, ValidPayment = user.ValidPayment, Membership = user.Membership }; // Updates the payment status of the user in the database _db.UpdatePaymentDetails(user, paymentStatus); return(outUser); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, UserApiModel GetUser(string username)"); return(null); } }
/// <summary> /// Adds a new admin to the database. /// </summary> /// <returns> /// <c>True</c> if it is successful. /// </returns> /// <param name="innAdmin">Admin to be added to the database</param> public bool RegisterAdmin(AdminViewModel innAdmin) { try { // Turns the view model admin into a database model admin var newAdmin = new Admin() { Name = innAdmin.Name, Username = innAdmin.Username, }; // Creates salt for the password var salt = CreateSalt(); // Hashes the given password string with the salt created var hash = CreateHash(innAdmin.Password, salt); // Sets the fields of the admin before adding the admin and saving changes in the database newAdmin.Password = hash; newAdmin.Salt = salt; _db.AdminTable.Add(newAdmin); _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool RegisterAdmin(AdminViewModel innAdmin)"); return(false); } }
/// <summary> /// Requests an updated member list from the Visma eAccounting API, and uses it to update current users or add new users. /// </summary> /// <returns> /// <c>True</c> if it is successful /// </returns> private bool AddUsersFromVisma() { try { // Sends a request for a list of customers from Visma var customerList = GetCustomerListFromVisma(); // Iterates through the list of customers from Visma. The user is added if it is new and updated if it already exists foreach (var customer in customerList.Data.ToList()) { var userExist = _db.CheckUser(customer.Id); // Determines what kind of membership the user has var membership = DetermineMembership(customer); if (userExist) { _db.UpdateUserFromVisma(customer, membership); } else { _db.AddUser(customer, membership); } } return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, bool AddUsersFromVisma()"); return(false); } }
public bool UpdateUser(User innUser) { try { var editUser = GetUser(innUser); editUser.Fornavn = innUser.fornavn; editUser.Etternavn = innUser.etternavn; editUser.Adresse = innUser.adresse; editUser.Poststeder.Postnummer = innUser.postnr; editUser.AccessLevel = innUser.accessLevel; _db.SaveChanges(); return(true); } catch (Exception e) { var errorLog = new ErrorFiler(); errorLog.WriteError(e.GetType().FullName, "UserDAL, UpdateUser"); } return(false); }
/// <summary> /// Updates the token in the database if it exists or adds a new one if it the database is empty. /// </summary> /// <returns> /// <c>True</c> if it is successful /// </returns> /// <param name="state">Access token from Visma </param> public bool UpdateVismaToken(IAuthorizationState state) { try { // Adds the token if the database is empty if (!_db.TokenTable.Any()) { SaveToken(state); return(true); } // Gets the token in the database var dbToken = _db.TokenTable.FirstOrDefault(); // Updates the fields and saves the changes in the database dbToken.AccessToken = state.AccessToken; dbToken.AccessTokenExpirationUtc = state.AccessTokenExpirationUtc; dbToken.AccessTokenIssueDateUtc = state.AccessTokenIssueDateUtc; dbToken.RefreshToken = state.RefreshToken; _db.SaveChanges(); return(true); } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasDAL, bool UpdateVismaToken(IAuthorizationState state)"); return(false); } }
/// <summary> /// Determines the type of membership the user has from customer details from Visma. /// </summary> /// <returns> /// A <c>string</c> containing the type of membership the user has. /// </returns> /// <para> The method is used to turn 11 types of membership from Visma into 4 types to be displayed in the mobile app.</para> /// <param name="customer">A user gotten from the Visma eAccounting API.</param> public string DetermineMembership(DataCustomer customer) { string membership = "Ikke aktivt medlemskap"; try { // Iterates through the list of customer labes from a member in Visma and determines what membership the user has. foreach (var label in customer.CustomerLabels) { switch (label.Name) { case "Enkeltmedlemskap": membership = "Enkeltmedlemskap"; break; case "vikingredaksjonen": membership = "Enkeltmedlemskap"; break; case "sekretær enkeltmedlem": membership = "Enkeltmedlemskap"; break; case "enkeltmedlem uten epost": membership = "Enkeltmedlemskap"; break; case "utland enkeltmedlem": membership = "Enkeltmedlemskap"; break; case "støttemedlem": membership = "Enkeltmedlemskap"; break; case "Familiemedlemskap": membership = "Familiemedlemskap"; break; case "Familiemedlemskap 2": membership = "Familiemedlemskap"; break; case "Studentmedlemskap": membership = "Studentmedlemskap"; break; case "Studentrepresentant": membership = "Studentmedlemskap"; break; case "Livsvarig": membership = "Livsvarig"; break; } } } catch (Exception e) { // Creates a new error filer object var errorLog = new ErrorFiler(); // Logs the error to the error log, with the name of the exception and where it occured errorLog.WriteError(e.GetType().FullName, "NasBLL, string DetermineMembership(DataCustomer customer)"); } return(membership); }