/// <summary> /// Constructor for frmMain. /// Run Splash Screen. Load/setup dgvTable. /// </summary> public frmMain() { try { InitializeComponent(); RunSplash(); // get a list of employees from the db ordered by last,first names // and set it to the datasource of dgvTable dgvTable.DataSource = DbFunctions.GetListOfEmployeesFromDB().OrderBy(p => p.LastName) .ThenBy(p => p.FirstName).ToList(); //don't show row headers dgvTable.RowHeadersVisible = false; //make column headers bold dgvTable.ColumnHeadersDefaultCellStyle.Font = new Font(dgvTable.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold); //Hide These Columns //We still want to use them - but no need to show them dgvTable.Columns["ID"].Visible = false; dgvTable.Columns["FirstName"].Visible = false; dgvTable.Columns["MiddleName"].Visible = false; dgvTable.Columns["LastName"].Visible = false; //give these column headers more user friendly names dgvTable.Columns["FullName"].HeaderText = "Full Name"; dgvTable.Columns["JobTitle"].HeaderText = "Job Title"; } catch (Exception ex) { // I don't anticipate an error here but just in case, we'll log it LogFunctions.LogException(ex); } }
/// <summary> /// Resizes an image. /// </summary> /// <param name="image">The image to resize</param> /// <param name="width">The width to resize to</param> /// <param name="height">The height to resize to</param> /// <returns>The resized image</returns> public static Bitmap ResizeImage(Image image, int width, int height) { try { Rectangle destRect = new Rectangle(0, 0, width, height); Bitmap destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (Graphics graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (ImageAttributes wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } return(destImage); } catch (Exception ex) { LogFunctions.LogException(ex); return(null); } }
/// <summary> /// Gets a List of all Employees from the Database. /// </summary> /// <returns>List of all Employee Objects</returns> public static List <Employee> GetListOfEmployeesFromDB() { //count number of database access attempts int AttemptCount = 0; do { try { AttemptCount++; using (EmpManEntities db = new EmpManEntities()) { return(db.Employees.ToList()); } } catch (Exception ex) { //log all errors that occur LogFunctions.LogException(ex); } }while ((AttemptCount < MAX_NUMBER_OF_ATTEMPTS) || ConfirmContinue(AttemptCount)); //give notice to exit application if user decides to not keep trying Application.Exit(); //return empty list return(new List <Employee>()); }
/// <summary> /// Deletes an employee from the database. /// </summary> /// <param name="employeeIn">The employee to delete from the db</param> public async static void DeleteEmployeeFromDB(Employee employeeIn) { //count number of database access attempts int AttemptCount = 0; do { try { AttemptCount++; using (EmpManEntities db = new EmpManEntities()) { // find and remove employee from the db with the same ID as employeeIn db.Employees.RemoveRange(db.Employees.Where(p => p.ID == employeeIn.ID)); // save changes to the database asynchronously for better responsiveness await db.SaveChangesAsync(); //return here if successful return; } } catch (Exception ex) { //log all errors that occur LogFunctions.LogException(ex); } }while ((AttemptCount < MAX_NUMBER_OF_ATTEMPTS) || ConfirmContinue(AttemptCount)); //give notice to exit application if user decides to not keep trying Application.Exit(); }
/// <summary> /// Used to insert test data from a local directory 'c:\projects\images' along with some random data. /// </summary> public static void InsertTestDataToSQLDB() { try { using (EmpManEntities db = new EmpManEntities()) { int i = 1; foreach (string fileName in Directory.GetFiles("C:\\projects\\IMAGES")) { { Image img = Image.FromFile(fileName); img = ImageFunctions.ResizeImage(img, (int)(100.0m * img.Width / img.Height), 100); Random rnd = new Random(); db.Employees.Add(new Employee { FirstName = "Test" + i.ToString(), MiddleName = ((char)(rnd.Next(65 + 6, 65 + 15))).ToString(), LastName = ((char)(rnd.Next(65 + 16, 65 + 25))).ToString() + "Test" + i.ToString(), Email = "email" + i.ToString() + "@testemail.com", Phone = (new Random().Next(111111111, 999999999).ToString() + "5").Insert(3, "-").Insert(7, "-"), JobTitle = "Job" + i.ToString(), Photo = ImageFunctions.GetByteArrayFromBitMapImage(img) }); db.SaveChanges(); } i++; } } } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Event Handler for BtnBrowseForPictureFile.Click event. /// Browse for Picture file and set pictureBoxPhoto Image and Tag(byte array). /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> private void BtnBrowseForPictureFile_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Multiselect = false; ofd.Title = "Browse for a Picture File"; // browse for the file if (ofd.ShowDialog() == DialogResult.OK) { try { // get image from file Image img = Image.FromFile(ofd.FileName); // resize image so that height=100 pictureBoxPhoto.Image = ImageFunctions.ResizeImage(img, (int)(100.0m * img.Width / img.Height), 100); // set tag to byte array of image in bitmap format pictureBoxPhoto.Tag = ImageFunctions.GetByteArrayFromBitMapImage(pictureBoxPhoto.Image); } catch (Exception ex) { LogFunctions.LogException(ex); _ = MessageBox.Show("A problem occurred while loading the photo from the file.", "Invalid Photo File", MessageBoxButtons.OK); } } } }
/// <summary> /// Adds a new employee to the database. /// </summary> /// <param name="employeeIn">The employee to add to the db</param> public async static void AddEmployeeToDB(Employee employeeIn) { //count number of database access attempts int AttemptCount = 0; do { try { AttemptCount++; using (EmpManEntities db = new EmpManEntities()) { // add the employee to the db db.Employees.Add(employeeIn); // save changes to the database asynchronously for better responsiveness await db.SaveChangesAsync(); //return here if successful return; } } catch (Exception ex) { //log all errors that occur LogFunctions.LogException(ex); } }while ((AttemptCount < MAX_NUMBER_OF_ATTEMPTS) || ConfirmContinue(AttemptCount)); //give notice to exit application if user decides to not keep trying Application.Exit(); }
/// <summary> /// Gets Bitmap From Webcam. /// Requires Emgu.CV version 3.3.0.2824 /// </summary> /// <returns>Bitmap from Webcam</returns> public static Bitmap GetBitmapFromWebcam() { try { //create a camera capture VideoCapture capture = new VideoCapture(); //get the bitmap from the camera capture Bitmap BMP = capture.QueryFrame().Bitmap; //turn camera off capture.Dispose(); //resize bitmap so that height is 100 pixels BMP = ResizeBitmap(BMP, (int)(100m * BMP.Width / BMP.Height), 100); return(BMP); } catch (Exception ex) { LogFunctions.LogException(ex); _ = MessageBox.Show("There was a problem taking the photo :(", "Camera not found or ready", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } }
/// <summary> /// Handler for mnuRightClick event. mnuEmailEmployee is enabled if selected employee has a valid email. /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> private void MnuRightClick_Opening(object sender, System.ComponentModel.CancelEventArgs e) { try { if (dgvTable.SelectedRows.Count > 0) { mnuEmailEmployee.Enabled = Validation.IsValidEmail(((Employee)(dgvTable.SelectedRows[0].DataBoundItem)).Email); } } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Event Handler for dgvTable.MouseClick event. /// Select employee under right-click. Then show right-click menu. /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> private void DgvTable_MouseClick(object sender, MouseEventArgs e) { try { if (e.Button == MouseButtons.Right) { // make sure the row under a right-click is selected dgvTable.Rows[dgvTable.HitTest(e.X, e.Y).RowIndex].Selected = true; //show the right-click menu mnuRightClick.Show(dgvTable, e.Location, ToolStripDropDownDirection.BelowRight); } } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Resizes a Bitmap object. /// </summary> /// <param name="bmp">The bitmap to resize</param> /// <param name="width">The width to resize to</param> /// <param name="height">The height to resize to</param> /// <returns>The resized bitmap</returns> public static Bitmap ResizeBitmap(Bitmap bmp, int width, int height) { try { Bitmap result = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(result)) { g.DrawImage(bmp, 0, 0, width, height); } return(result); } catch (Exception ex) { LogFunctions.LogException(ex); return(null); } }
/// <summary> /// Handles mnuDeleteEmployee.Click, btnDeleteEmployee.click events. /// Deletes employee from the datagridview and database. /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> public void DeleteEmployee(object sender, EventArgs e) { try { if (dgvTable.SelectedRows.Count > 0) { Employee selectedEmployee = (Employee)dgvTable.SelectedRows[0].DataBoundItem; string employeeName = selectedEmployee.FullName; if (MessageBox.Show($"Are you sure you want to delete '{employeeName}' ?", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes) { this.Cursor = Cursors.WaitCursor; //remove the employee from the datagridview ((List <Employee>)dgvTable.DataSource).Remove(selectedEmployee); //refresh & reorder the list by lastname, firstname dgvTable.DataSource = ((List <Employee>)dgvTable.DataSource).OrderBy(p => p.LastName) .ThenBy(p => p.FirstName).ToList(); //delete the employee from the Azure DB DbFunctions.DeleteEmployeeFromDB(selectedEmployee); _ = MessageBox.Show($"'{employeeName}' was successfully Deleted :)", "Success!", MessageBoxButtons.OK); } } else { _ = MessageBox.Show("Please select an Employee to delete first.", "Select an Employee To Delete", MessageBoxButtons.OK); } } catch (Exception ex) { LogFunctions.LogException(ex); } finally { this.Cursor = Cursors.Default; } }
/// <summary> /// Ensures employee is selected in dgvTable and visible to the user. /// </summary> /// <param name="employeeIn">The employee to select and ensure visible.</param> public void EnsureEmployeeIsSelectedAndVisible(Employee employeeIn) { try { foreach (DataGridViewRow dgvr in dgvTable.Rows) { if (((Employee)dgvr.DataBoundItem).ID == employeeIn.ID) { dgvr.Selected = true; dgvTable.FirstDisplayedScrollingRowIndex = dgvr.Index; break; } } } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Handles mnuEditEmployee.Click, btnEditEmployee.click, dgvTable.MouseDoubleClick events. /// Edits employee in the datagridview and database. /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> public void EditEmployee(object sender, EventArgs e) { try { if (dgvTable.SelectedRows.Count > 0) { Employee employeeToEdit = (Employee)dgvTable.SelectedRows[0].DataBoundItem; using (frmAddEditEmployee frmEditEmployee = new frmAddEditEmployee(employeeToEdit)) { frmEditEmployee.Text = "Edit Employee"; if (frmEditEmployee.ShowDialog() == DialogResult.OK) { this.Cursor = Cursors.WaitCursor; //refresh & reorder the list by lastname, firstname dgvTable.DataSource = ((List <Employee>)dgvTable.DataSource).OrderBy(p => p.LastName) .ThenBy(p => p.FirstName).ToList(); EnsureEmployeeIsSelectedAndVisible(employeeToEdit); DbFunctions.SaveEmployeeEditsToDB(employeeToEdit); _ = MessageBox.Show( $"'{employeeToEdit.FullName}' was successfully Edited in the Employee database :)", "Success!", MessageBoxButtons.OK); } } } else { _ = MessageBox.Show("Please select an Employee to Edit first.", "Select an Employee to edit", MessageBoxButtons.OK); } } catch (Exception ex) { LogFunctions.LogException(ex); } finally { this.Cursor = Cursors.Default; } }
/// <summary> /// Copy the selected employee's name, job title, phone, email to clipboard. /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> private void CopyToClipboard(object sender, EventArgs e) { try { if (dgvTable.SelectedRows.Count > 0) { Employee employeeToCopy = (Employee)(dgvTable.SelectedRows[0].DataBoundItem); Clipboard.SetText(string.Join("\n", employeeToCopy.FullName, employeeToCopy.JobTitle, employeeToCopy.Phone, employeeToCopy.Email, "")); } } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Saves Edits to a current employee in the database. /// </summary> /// <param name="employeeIn">An edited employee object</param> public async static void SaveEmployeeEditsToDB(Employee employeeIn) { //count number of database access attempts int AttemptCount = 0; do { try { AttemptCount++; using (EmpManEntities db = new EmpManEntities()) { //find the employee in the db with the same ID as employeeIn Employee EmployeeToEdit = db.Employees.Where(p => p.ID == employeeIn.ID).FirstOrDefault(); //set all db employee properties = employeeIn's properties EmployeeToEdit.FirstName = employeeIn.FirstName; EmployeeToEdit.MiddleName = employeeIn.MiddleName; EmployeeToEdit.LastName = employeeIn.LastName; EmployeeToEdit.Phone = employeeIn.Phone; EmployeeToEdit.JobTitle = employeeIn.JobTitle; EmployeeToEdit.Photo = employeeIn.Photo; EmployeeToEdit.Email = employeeIn.Email; EmployeeToEdit.FullName = employeeIn.FullName; // save changes to the database asynchronously for better responsiveness await db.SaveChangesAsync(); //return here if successful return; } } catch (Exception ex) { //log all errors that occur LogFunctions.LogException(ex); } }while ((AttemptCount < MAX_NUMBER_OF_ATTEMPTS) || ConfirmContinue(AttemptCount)); //give notice to exit application if user decides to not keep trying Application.Exit(); }
/// <summary> /// Constructor for frmAddEditEmployee. /// Set EmployeeToAddOrEdit and all fields. /// </summary> /// <param name="employeeIn">The employee to Add or Edit.</param> public frmAddEditEmployee(Employee employeeIn) { try { InitializeComponent(); // set EmployeeToAddOrEdit property this.EmployeeToAddOrEdit = employeeIn; // set all text fields txtFirstName.Text = this.EmployeeToAddOrEdit.FirstName; txtMiddleName.Text = this.EmployeeToAddOrEdit.MiddleName; txtLastName.Text = this.EmployeeToAddOrEdit.LastName; txtJobTitle.Text = this.EmployeeToAddOrEdit.JobTitle; txtPhone.Text = this.EmployeeToAddOrEdit.Phone; txtEmail.Text = this.EmployeeToAddOrEdit.Email; pictureBoxPhoto.Image = ImageFunctions.GetImageFromByteArray(this.EmployeeToAddOrEdit.Photo); // store the byte array of the photo in the tag of pictureBoxPhoto pictureBoxPhoto.Tag = this.EmployeeToAddOrEdit.Photo; } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Event Handler for btnSave.Click event. /// Checks to see if values are valid before saving and returning control back to the calling form. /// </summary> /// <param name="sender">Sender of Event</param> /// <param name="e">Event Arguments</param> private void BtnSave_Click(object sender, EventArgs e) { try { if (ValuesAreValid()) { this.EmployeeToAddOrEdit.FirstName = txtFirstName.Text; this.EmployeeToAddOrEdit.MiddleName = txtMiddleName.Text; this.EmployeeToAddOrEdit.LastName = txtLastName.Text; this.EmployeeToAddOrEdit.FullName = $"{txtLastName.Text}, {txtFirstName.Text} {txtMiddleName.Text}".Trim(); this.EmployeeToAddOrEdit.JobTitle = txtJobTitle.Text; this.EmployeeToAddOrEdit.Phone = txtPhone.Text; this.EmployeeToAddOrEdit.Email = txtEmail.Text; this.EmployeeToAddOrEdit.Photo = (byte[])pictureBoxPhoto.Tag; this.DialogResult = DialogResult.OK; } } catch (Exception ex) { LogFunctions.LogException(ex); } }
public static void Main() { try { // using a mutex, we can force this to be a single-instance app Mutex objMutex = new Mutex(false, "EmployeeManagement"); //if already running, if (objMutex.WaitOne(0, false) == false) { //close mutex objMutex.Close(); // and terminate process immediately Environment.Exit(1); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Gets the byte array from an Image in Bitmap format. /// </summary> /// <param name="imageIn">An Image object</param> /// <returns>The byte array of a Bitmap Image</returns> public static byte[] GetByteArrayFromBitMapImage(Image imageIn) { try { if (imageIn != null) { //create a new memory stream MemoryStream ms = new MemoryStream(); // here, we save image as a bitmap to a memory stream imageIn.Save(ms, ImageFormat.Bmp); //return the array of bytes in the memory stream return(ms.ToArray()); } else { return(null); } } catch (Exception ex) { LogFunctions.LogException(ex); return(null); } }
/// <summary> /// Search Datagridview and find the best employee match to Search text. /// </summary> private void SearchDataGridAndSelectBestMatch() { try { //initialize search results to entire list List <Employee> lstEmployeeSearch = (List <Employee>)dgvTable.DataSource; //split search string into each word and search for the presence of any/all them foreach (string strSearch in txtSearch.Text.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)) { //if less than 4 characters and not an integer search last names that start with the characters if (txtSearch.Text.Length < 4 && !int.TryParse(PrepStringForComparing(txtSearch.Text), out _)) { lstEmployeeSearch = lstEmployeeSearch.Where(p => PrepStringForComparing(p.LastName) .StartsWith(PrepStringForComparing(strSearch))).ToList(); } else { //enables you to search by any combination of fields except photo lstEmployeeSearch = lstEmployeeSearch.Where(p => PrepStringForComparing(p.LastName + p.FirstName + p.MiddleName + p.Phone + p.Email + p.JobTitle) .Contains(PrepStringForComparing(strSearch))).ToList(); } if (lstEmployeeSearch.Count() > 0) { EnsureEmployeeIsSelectedAndVisible(lstEmployeeSearch.First()); } } } catch (Exception ex) { LogFunctions.LogException(ex); } }
/// <summary> /// Gets an Image from a Byte Array. /// </summary> /// <param name="byteArrayIn">The byte array for an Image</param> /// <returns>An Image object</returns> public static Image GetImageFromByteArray(byte[] byteArrayIn) { try { if (byteArrayIn != null) { // use a memory stream object buit from the byte array using (MemoryStream ms = new MemoryStream(byteArrayIn)) { // to return the image return(Image.FromStream(ms)); } } else { return(null); } } catch (Exception ex) { LogFunctions.LogException(ex); return(null); } }
/// <summary> /// Handles mnuAddEmployee.Click and btnAddEmployee.click events. /// Adds employee to the datagridview and database. /// </summary> /// <param name="sender">Sender of event</param> /// <param name="e">Event arguments</param> public void AddEmployee(object sender, EventArgs e) { try { using (frmAddEditEmployee frmAddEmployee = new frmAddEditEmployee(new Employee())) { frmAddEmployee.Text = "Add Employee"; if (frmAddEmployee.ShowDialog() == DialogResult.OK) { this.Cursor = Cursors.WaitCursor; // add employee to datagridview ((List <Employee>)dgvTable.DataSource).Add(frmAddEmployee.EmployeeToAddOrEdit); //refresh & reorder the list by lastname, firstname dgvTable.DataSource = ((List <Employee>)dgvTable.DataSource).OrderBy(p => p.LastName) .ThenBy(p => p.FirstName).ToList(); EnsureEmployeeIsSelectedAndVisible(frmAddEmployee.EmployeeToAddOrEdit); DbFunctions.AddEmployeeToDB(frmAddEmployee.EmployeeToAddOrEdit); _ = MessageBox.Show( $"'{frmAddEmployee.EmployeeToAddOrEdit.FullName}' was successfully added to the Employee database :)", "Success!", MessageBoxButtons.OK); } } } catch (Exception ex) { LogFunctions.LogException(ex); } finally { this.Cursor = Cursors.Default; } }