/*************************** * My Files populate data ***************************/ private void PopulateMyFiles(object sender, MouseButtonEventArgs e) { VersionCol.Visibility = Visibility.Visible; InMyFiles = true; SidebarReviseButton.Visibility = Visibility.Visible; DatabaseCon con = new DatabaseCon(); con.OpenConnection(); List <string> paths = FileData.GetMyFilePath(); DataGridController data = new DataGridController(); ObservableCollection <FileAndDirAttributes> GridData = new ObservableCollection <FileAndDirAttributes>(); FileProperties file; if (paths.Count > 0) { foreach (string dir in paths) { file = new FileProperties(dir); GridData.Add(new FileAndDirAttributes { Type = false, FileIcon = "/Resources/Icons/file.png", FileName = file.GetFileName(), FileSize = file.GetFileSize(), FileDirectory = file.GetDirectory(), FileCreated = file.GetFileCreated(), FileAccessed = file.GetFileLastAccess(), FileModified = file.GetFileLastModify(), Versions = FileData.VersionCount(dir) }); } DirsAndFiles.ItemsSource = GridData; items.Content = (GridData.Count - 1) + " items"; size.Content = "No file selected."; } else { MessageBox.Show("Error", "No file found!"); } }
// The parameters are formatted like that because it's just way too long otherwise. /// <summary> /// Functions like `populateDropDownWithT` but also populates a `Panel` using `TInfoControl`. /// /// Note: `TInfoControl` must have a constructor that takes `T` as it's only parameter. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TInfoControl"></typeparam> /// <param name="panel"></param> public static void populateDropDownAndPanelWithT <T, TInfoControl>(this DatabaseCon db, System.Windows.Controls.ComboBox dropDown, System.Windows.Controls.Panel panel, out List <T> list, Action <T> additionalProcessing = null) where T : class { if (panel == null) { throw new ArgumentNullException("panel"); } Action <T> action = (tValue) => { if (additionalProcessing != null) { additionalProcessing(tValue); } var info = Activator.CreateInstance(typeof(TInfoControl), tValue) as System.Windows.Controls.UserControl; info.Margin = new Thickness(0, 2, 0, 0); info.Width = double.NaN; // auto width panel.Children.Add(info); }; db.populateDropDownWithT <T>(dropDown, out list, action); }
/// <summary> /// [A very dirty-feeling function] /// Given a description, and a type, attempts to find an entry in the database for the given type that has a certain description. /// /// For example, `getFromDescription<language>("C++")` would look for a language (in the language table) with the description of `C++` and then returns it. /// </summary> /// <typeparam name="T">The type to look for. This must be a database type.</typeparam> /// <param name="db">The database connection.</param> /// <param name="description">The description to look for.</param> /// <returns>Either null, if the value wasn't found, or the value that was found.</returns> public static T getFromDescription <T>(this DatabaseCon db, string description) where T : class { if (db == null) { throw new ArgumentNullException("db"); } if (description == null) { throw new ArgumentNullException("description"); } // Get the right set that represetns `T` var set = db._getSetFromT <T>(); // Then look through all of the values in the DbSet for it. foreach (var value in set) { // This is dirty... dynamic dyValue = value; if (dyValue.description == description) { return(value); } } return(null); }
public ActionResult VerifyAccount(string id) { bool Status = false; DatabaseCon con = new DatabaseCon(); var dc = con.Access(); dc.Configuration.ValidateOnSaveEnabled = false; var v = dc.Users.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault(); if (v != null) { v.IsEmailVerified = true; dc.SaveChanges(); Status = true; } else { ViewBag.Message = "Invalid Request"; } ViewBag.Status = Status; return(View()); }
private error_code _createObjectFromData(DatabaseCon db) { // Fun fact: If we don't get the data from the database, and use the cache instead (for the severity) then it randomly duplicates entries. var error = new error_code(); error.error_code_mneumonic = this.textboxMneumonic.Text; error.error_code1 = this.textboxCode.Text; error.narrative = this.textboxNarrative.Text; var severityName = this.dropDownSeverity.SelectedItem?.ToString(); if (severityName == null) { throw new Exception("No default severity was chosen"); } var defaultSeverity = db.severities.SingleOrDefault(s => s.description == severityName); if (defaultSeverity == null) { throw new Exception("Bug"); } error.default_severity_id = defaultSeverity.severity_id; error.device_ids = this._createBitmask(this.panelDevices); error.application_ids = this._createBitmask(this.panelApplications); return(error); }
private void generate(string application, string device, string language) { this._window.updateStatus("Generating..."); using (var db = new DatabaseCon()) { var dbApp = db.getFromDescription <application>(application); var dbLang = db.getFromDescription <language>(language); var errors = db.getFilteredErrors(application, device).ToList(); this.showExportedErrors(db, errors); switch (dbLang.description) { case "C++": this.copyTemplates( dbLang.path_to_templates, dbApp.path_to_output_file, this.generateCPP(db, errors), (uint)errors.Count(), "Template.cpp", "Template.h" ); break; default: throw new Exception($"Unsupported language: {language}"); } } }
private void _updateDropdowns() { this.dropDownErrors.Items.Clear(); this.dropDownApplications.Items.Clear(); this.dropDownDevices.Items.Clear(); this.dropDownSeverity.Items.Clear(); this.panelApplications.Children.Clear(); this.panelDevices.Children.Clear(); this.panelErrors.Children.Clear(); // populteDropDownWithT will clear the other lists for us. this._errors.Clear(); this.dropDownErrors.Items.Add(NEW_ITEM_TEXT); using (var db = new DatabaseCon()) { foreach (var error in db.error_code.OrderBy(e => e.error_code_mneumonic)) { this.panelErrors.Children.Add( new ErrorInfoControl(db, error) { Margin = new Thickness(0, 2, 0, 0), Width = double.NaN }); this.dropDownErrors.Items.Add(error.error_code_mneumonic); this._errors.Add(error); } ViewHelper.populateDropDownWithT <application>(db, this.dropDownApplications, out this._applications); ViewHelper.populateDropDownWithT <device_type>(db, this.dropDownDevices, out this._devices); ViewHelper.populateDropDownWithT <severity>(db, this.dropDownSeverity, out this._severity); } }
private void _enforceMneumonicIsUnique(DatabaseCon db, string mneumonic) { if (db.error_code.Count(ec => ec.error_code_mneumonic == mneumonic) != 0) { throw new Exception($"There is already an error using the mneumonic of '{mneumonic}'"); } }
private void buttonUpdateDatabase_Click(object sender, RoutedEventArgs e) { try { if (this.dropDownApplications.SelectedItem == null) { throw new Exception("No application was selected!"); } var name = this.textboxName.Text; var bitIndex = (byte)this.sliderBitIndex.Value; var path = this.textboxPath.Text; if (string.IsNullOrEmpty(name)) { throw new Exception("No name has been given"); } if (path.Length > this._maxPathLength) { throw new Exception($"The output path is too large, it has ${path.Length} characters while the limit is ${this._maxPathLength} characters"); } if (!Directory.Exists(path)) { throw new Exception("The output path does not exist"); } using (var db = new DatabaseCon()) { if (this.dropDownApplications.SelectedItem.ToString() == NEW_ITEM_TEXT) { db.enforceNameIsUnique <application>(name); db.enforceBitIndexIsUnique <application>(bitIndex); this._addApplication(db, name, bitIndex, path); } else { var cached = this._applications.Single(a => a.description == this.dropDownApplications.SelectedItem.ToString()); if (name != cached.description) { db.enforceNameIsUnique <application>(name); } if (bitIndex != cached.bit_index) { db.enforceBitIndexIsUnique <application>(bitIndex); } this._updateApplication(db, name, bitIndex, path); } } } catch (Exception ex) { this._window.updateStatus($"[ERROR] {ex.ToString()}"); } }
public IActionResult SignUp(LoginData a) { DatabaseCon z = new DatabaseCon(); z.InsertUsers(a.name, a.email, a.password); return(Redirect("/")); }
private void _updateLanguages() { this.dropDownLanguages.Items.Clear(); this.panelLanguages.Children.Clear(); this.dropDownLanguages.Items.Add(NEW_ITEM_TEXT); using (var db = new DatabaseCon()) ViewHelper.populateDropDownAndPanelWithT <language, LanguageInfoControl>(db, this.dropDownLanguages, this.panelLanguages, out this._languages); }
private void _updateApplications() { this.dropDownApplications.Items.Clear(); this.panelApplications.Children.Clear(); this.dropDownApplications.Items.Add(NEW_ITEM_TEXT); using (var db = new DatabaseCon()) ViewHelper.populateDropDownAndPanelWithT <application, ApplicationInfoControl>(db, this.dropDownApplications, this.panelApplications, out this._applications); }
public void AddTask(Models.Task task) { DatabaseCon con = new DatabaseCon(); var context = con.Access(); context.Tasks.Add(task); context.SaveChanges(); }
private void _updateDevices() { this.dropDownDevices.Items.Clear(); this.panelDevices.Children.Clear(); this.dropDownDevices.Items.Add(NEW_ITEM_TEXT); using (var db = new DatabaseCon()) ViewHelper.populateDropDownAndPanelWithT <device_type, DeviceInfoControl>(db, this.dropDownDevices, this.panelDevices, out this._devices); }
private void buttonApply_Click(object sender, RoutedEventArgs e) { try { var selectedErrorName = this.dropDownErrors.SelectedItem?.ToString(); if (selectedErrorName == null) { throw new Exception("No error was selected"); } using (var db = new DatabaseCon()) { var error = this._createObjectFromData(db); if (selectedErrorName == NEW_ITEM_TEXT) { this._enforceMneumonicIsUnique(db, error.error_code_mneumonic); this._enforceErrorCodeIsUnique(db, error.error_code1); this._window.updateStatus($"Adding new error called '{error.error_code_mneumonic}' to the database"); db.error_code.Add(error); db.SaveChanges(); } else { this._window.updateStatus($"Updating error called '{selectedErrorName}'"); var dbError = db.error_code.SingleOrDefault(er => er.error_code_mneumonic == selectedErrorName); // If we're changing the mneumonic/error code, make sure it's fine to do. if (dbError.error_code1 != error.error_code1) { this._enforceErrorCodeIsUnique(db, error.error_code1); } if (dbError.error_code_mneumonic != error.error_code_mneumonic) { this._enforceMneumonicIsUnique(db, error.error_code_mneumonic); } dbError.application_ids = error.application_ids; dbError.default_severity_id = error.default_severity_id; dbError.device_ids = error.device_ids; dbError.error_code1 = error.error_code1; dbError.error_code_mneumonic = error.error_code_mneumonic; dbError.narrative = error.narrative; db.SaveChanges(); } } this._updateDropdowns(); } catch (Exception ex) { this._window.updateStatus($"[ERROR] {ex.ToString()}"); } }
public bool IsEmailExist(string emailID) { DatabaseCon con = new DatabaseCon(); var dc = con.Access(); var v = dc.Users.Where(a => a.EnailID == emailID).FirstOrDefault(); return(v != null); }
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user) { bool Status = false; string message = ""; // //Model Validation if (ModelState.IsValid) { //Email is already exist var isExist = userService.IsEmailExist(user.EnailID); if (isExist) { ModelState.AddModelError("EmailExist", "Email already exist"); return(View(user)); } #region Generate Activation Code user.ActivationCode = Guid.NewGuid(); #endregion #region Password Hashing user.Password = Crypto.Hash(user.Password); user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword);; #endregion user.IsEmailVerified = false; #region Save to Datebase DatabaseCon con = new DatabaseCon(); var dc = con.Access(); dc.Users.Add(user); dc.SaveChanges(); //send email to user SendVerificationLink(user.EnailID, user.ActivationCode.ToString()); message = "Registration successfully done. Account activation link has been sent to your email id :" + user.EnailID; Status = true; #endregion } else { message = "invalid request"; } ViewBag.Message = message; ViewBag.Status = Status; //send email to user return(View(user)); }
private void _enforceErrorCodeIsUnique(DatabaseCon db, string code) { // Using a foreach loop so I can get the name of the offending error. foreach (var error in db.error_code) { if (error.error_code1 == code) { throw new Exception($"The error '{error.error_code_mneumonic}' is already using the error code '{code}'"); } } }
private void showExportedErrors(DatabaseCon db, List <error_code> errors) { this.panelErrors.Children.Clear(); foreach (var error in errors.OrderBy(e => e.error_code1)) { var info = new ErrorInfoControl(db, error) { Margin = new Thickness(0, 2, 0, 0) }; this.panelErrors.Children.Add(info); } }
private void _addLanguage(DatabaseCon db, string name, string path) { this._window.updateStatus($"Adding new language '{name}'"); db.languages.Add( new language() { description = name, path_to_templates = path }); db.SaveChanges(); this._updateLanguages(); }
public IActionResult Login(LoginData a) { DatabaseCon z = new DatabaseCon(); LoginData b = z.getUser(a.email, a.password); if (b == null) { ViewBag.Message = "error wrong username/or passwrod"; return(View("~/Views/Login/Login.cshtml")); } ViewBag.Message = b.name; return(View("~/Views/Home/index.cshtml")); }
private void _addDevice(DatabaseCon db, string name, byte bitIndex) { this._window.updateStatus($"Adding new device '{name}'"); db.device_type.Add( new device_type() { bit_index = bitIndex, description = name }); db.SaveChanges(); this._updateDevices(); }
/// <summary> /// Throws an exception if the given name/description (the field is called 'description' but is used more as a name) is already being used. /// /// NOTE: The type `T` must contain a field called 'description'. /// </summary> /// <typeparam name="T">The type to check with. (this determines which table is used)</typeparam> /// <param name="db">The database connection.</param> /// <param name="name_description">The name/description to check for.</param> public static void enforceNameIsUnique <T>(this DatabaseCon db, string name_description) where T : class { var set = db._getSetFromT <T>(); foreach (var record in set) { dynamic dyRecord = record; if (dyRecord.description == name_description) { throw new Exception($"The name/description '{name_description}' is already being used by another {typeof(T).Name}"); } } }
/// <summary> /// Throws an exception if the given bit index is already being used. /// /// NOTE: The type `T` must contain fields called `bit_index` and `description`. /// </summary> /// <typeparam name="T">The type to check with. (this determines which table is used)</typeparam> /// <param name="db">The database connection</param> /// <param name="index">The index to check</param> public static void enforceBitIndexIsUnique <T>(this DatabaseCon db, byte index) where T : class { var set = db._getSetFromT <T>(); foreach (var record in set) { dynamic dyRecord = record; if (dyRecord.bit_index == index) { throw new Exception($"The bit index {index} is being used by the {typeof(T).Name} '{dyRecord.description}'"); } } }
private void buttonApply_Click(object sender, RoutedEventArgs e) { try { if (this.dropDownLanguages.SelectedItem == null) { throw new Exception("No language was selected!"); } var name = this.textboxName.Text; var path = this.textboxPath.Text; if (string.IsNullOrEmpty(name)) { throw new Exception("No name has been given"); } if (path.Length > 255) { throw new Exception($"The output path is too large, it has ${path.Length} characters while the limit is 255 characters"); } if (!Directory.Exists(path)) { throw new Exception("The output path does not exist"); } using (var db = new DatabaseCon()) { if (this.dropDownLanguages.SelectedItem.ToString() == NEW_ITEM_TEXT) { db.enforceNameIsUnique <language>(name); this._addLanguage(db, name, path); } else { var cached = this._languages.Single(l => l.description == this.dropDownLanguages.SelectedItem.ToString()); if (name != cached.description) { db.enforceNameIsUnique <application>(name); } this._updateLanguage(db, name, path); } } } catch (Exception ex) { this._window.updateStatus($"[ERROR] {ex.ToString()}"); } }
// The reason this function is in ViewHelper, instead of DataHelper, is because of the user-interaction is requires, as well as the requirement of the MainWindow, making it specialised for use in views. /// <summary> /// Deletes a `T` from the database that has a description matching the given description. /// (note: in a lot of cases the description is just a name, hence 'name_description') /// /// This function will first prompt the user with a message box, asking them to confirm the deletion of the object. /// /// It is a requirement that `T` has a field called `description`. /// </summary> /// <typeparam name="T">The database type to remove (and also determines the database table that's used)</typeparam> /// <param name="window">The main window, so it's status can be updated</param> /// <param name="name_description">The name/description of the object to remove</param> /// <returns>True if something was delete.</returns> public static bool deleteTByDescription <T>(MainWindow window, string name_description) where T : class { if (window == null) { throw new ArgumentNullException("window"); } if (name_description == null) { throw new ArgumentNullException("name_description"); } var TName = typeof(T).Name; var result = System.Windows.Forms.MessageBox.Show($"Are you sure you want to remove the {TName} '{name_description}'?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { window.updateStatus($"Not going through with removal of the {TName}"); return(false); } using (var db = new DatabaseCon()) { var set = db._getSetFromT <T>(); T value = null; // I need to use dynamic, so can't use SingleOrDefault since it doesn't like lambdas apparently foreach (var val in set) { dynamic dyVal = val; if (dyVal.description == name_description) { value = val; break; } } if (value == null) { window.updateStatus($"Can't delete a(n) {TName} that doesn't exist"); return(false); } window.updateStatus($"Removing {TName} '{name_description}' from the database"); set.Remove(value); db.SaveChanges(); } return(true); }
public ActionResult Login(UserLogin login, string ReturnUrl = "") { string message = ""; DatabaseCon con = new DatabaseCon(); var dc = con.Access(); var v = userService.FindByEmail(login.EnailID); if (v != null) { if (!v.IsEmailVerified) { ViewBag.Message = "Please verify your email first"; return(View()); } if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0) { int timeout = login.RememberMe ? 525600 : 20; // 525600 min = 1 year var ticket = new FormsAuthenticationTicket(login.EnailID, login.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { return(RedirectToAction("Index", "Home")); } } else { message = "Invalid credential provided"; } } else { message = "Invalid credential provided"; } ViewBag.Message = message; return(View()); }
private void _addApplication(DatabaseCon db, string name, byte bitIndex, string path) { this._window.updateStatus($"Adding new application '{name}'"); db.applications.Add( new application() { bit_index = bitIndex, description = name, path_to_output_file = path }); db.SaveChanges(); this._updateApplications(); }
/// <summary> /// Gets a filtered set of error codes from the database. /// </summary> /// <param name="db">The database connection.</param> /// <param name="application">The application to filter by.</param> /// <param name="device">The device type to filter by.</param> /// <returns>All error codes that can be used by the chosen application and device type.</returns> public static IQueryable <error_code> getFilteredErrors(this DatabaseCon db, string application, string device) { var dbApp = db.getFromDescription <application>(application); var dbDevice = db.getFromDescription <device_type>(device); // These are variables since LINQ doesn't like it when I do it inside the query. var dbAppBit = (1 << dbApp.bit_index); var dbDevBit = (1 << dbDevice.bit_index); var query = from error in db.error_code where ((error.application_ids & dbAppBit) > 0 || error.application_ids == 0) && ((error.device_ids & dbDevBit) > 0 || error.device_ids == 0) select error; return(query); }
public Models.Task findById(int?id) { Models.Task foundTask = new Models.Task(); DatabaseCon con = new DatabaseCon(); var context = con.Access(); foundTask = context.Tasks.FirstOrDefault(x => x.TaskID == id); return(foundTask); }