private void btnSave_Click(object sender, EventArgs e) { using (CodeITDL.CodeITDbContext ctx = new CodeITDL.CodeITDbContext(Context.UserId)) { Guid clientId = new Guid(); Guid.TryParse(CodeITLicence.Licence.ClientId, out clientId); Setting tmpLocation = ctx.Settings.Where(x => x.CustomerId == clientId && x.Name == CodeITConstants.SETTINGS_TEMP_LOCATION).FirstOrDefault(); if (tmpLocation != null) { if (tmpLocation.Id > 0) tmpLocation.Value = txtTempLocation.Text.Trim(); else tmpLocation = new Setting() { Value = txtTempLocation.Text.Trim(), Name = CodeITConstants.SETTINGS_TEMP_LOCATION, CustomerId = Guid.Parse(CodeITLicence.Licence.ClientId) }; }else { tmpLocation = new Setting() { Value = txtTempLocation.Text.Trim(), Name = CodeITConstants.SETTINGS_TEMP_LOCATION, CustomerId = clientId }; } if (tmpLocation.Id <= 0) ctx.Settings.Add(tmpLocation); ctx.SaveChanges(); MessageBox.Show("Settings saved successfully"); } }
public frmAuditLog() { InitializeComponent(); this.BackgroundImage = Context.GetImageForCustomer(); List<CodeITDL.User> users = new List<CodeITDL.User>(); using (CodeITDL.CodeITDbContext ctx = new CodeITDL.CodeITDbContext(Context.UserId)) { users = ctx.Users.Where(x => x.CustomerId == Context.CustomerId).ToList(); } users.Insert(0, new CodeITDL.User() { Id = -1, CustomerId = Context.CustomerId, FirstName = "Select All" }); cbName.DisplayMember = "FullName"; cbName.ValueMember = "Id"; cbName.DataSource = users; if (cbName.Items.Count > 0) cbName.SelectedIndex = 0; if (cbAction.Items.Count > 0) cbAction.SelectedIndex = 0; if (cbItems.Items.Count > 0) cbItems.SelectedIndex = 0; }
private void lvUsers_SelectedIndexChanged(object sender, EventArgs e) { if (!isLoaded) return; if (!btnCreate.Visible) return; if (lvUsers.SelectedItems == null) return; if (lvUsers.SelectedItems.Count == 0) return; changeControlsState(gbUserManagement, false); Image img = null; using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) { int selectedId = (int)lvUsers.SelectedItems[0].Tag; User selectedUser = ctx.Users.Where(x => x.Id == selectedId).FirstOrDefault(); if (selectedUser == null) return; byte[] imageArray = ctx.UserPictures.Where(x => x.UserId == selectedUser.Id).Select(x => x.Picture).FirstOrDefault(); if (imageArray != null) if (imageArray.Count() > 0) img = Image.FromStream(new MemoryStream(imageArray)); txtFirstName.Text = selectedUser.FirstName; txtID.Text = selectedUser.IdNumber; txtLastName.Text = selectedUser.LastName; txtMiddleName.Text = selectedUser.MiddleName; txtPassword.Text = selectedUser.Password; txtUserName.Text = selectedUser.UserName; txtDeviceId.Tag = selectedUser.DeviceId; txtDeviceId.Clear(); if (!string.IsNullOrEmpty(selectedUser.DeviceId)) txtDeviceId.Text = Regex.Match(selectedUser.DeviceId, @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b", RegexOptions.IgnoreCase).Value; rbAdministrator.Checked = ((Role)selectedUser.RoleId == Role.Administrator); rbUser.Checked = ((Role)selectedUser.RoleId == Role.User); rbInvestigator.Checked = ((Role)selectedUser.RoleId == Role.Investigator); rbOfficeManager.Checked = ((Role)selectedUser.RoleId == Role.PatrolOfficer); rbProsecutor.Checked = ((Role)selectedUser.RoleId == Role.Prosecutor); rbSergeant.Checked = ((Role)selectedUser.RoleId == Role.Sergeant); } }
private void btnSearch_Click(object sender, EventArgs e) { isLoaded = false; List<AuditLog> auditLog = new List<AuditLog>(); lvResults.Items.Clear(); lvDetails.Items.Clear(); using (CodeITDL.CodeITDbContext ctx = new CodeITDL.CodeITDbContext(Context.UserId)) { DateTime to = dtpTo.Value.Date.AddHours(23).AddMinutes(59); auditLog = ctx.AuditLogs .Where(x => x.ObjectId == ("CodeITDL." + cbItems.SelectedItem.ToString()) || cbItems.SelectedIndex == 0) .Where(x => x.CreatedBy == (int)cbName.SelectedValue || (int)cbName.SelectedValue == -1) .Where(x => x.CreatedOn >= dtpFrom.Value.Date && x.CreatedOn <= to) .Where(x => x.Action == cbAction.SelectedItem.ToString().Substring(0, 1) || cbAction.SelectedIndex == 0) .OrderByDescending(x=>x.CreatedOn) .ToList(); } ListViewItem[] listItems = new ListViewItem[auditLog.Count]; int i = 0; if (auditLog.Count > 0) using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) foreach (AuditLog alItem in auditLog) { lvResults.BeginUpdate(); ListViewItem lvi = new ListViewItem(alItem.CreatedOn.ToString()); if (ctx.Users.Where(x => x.Id == alItem.CreatedBy).Count() > 0) lvi.SubItems.Add(ctx.Users.Where(x => x.Id == alItem.CreatedBy).FirstOrDefault().FullName); else lvi.SubItems.Add("-"); lvi.SubItems.Add((alItem.Action.Equals("I") ? "Insert" : (alItem.Action.Equals("M") ? "Update" : "Delete"))); lvi.SubItems.Add(alItem.OldObject); lvi.SubItems.Add(alItem.NewObject); lvi.Tag = alItem; listItems[i] = lvi; i++; lvResults.Items.Add(lvi); lvResults.EndUpdate(); } isLoaded = true; }
public string GetFilenameFormat(DateTime originalFileDate, string originalFileName, bool increaseCounter = false) { try { using (CodeITDL.CodeITDbContext ctx = new CodeITDL.CodeITDbContext(Context.UserId)) { DateTime yesterday = originalFileDate.Date; DateTime tomorrow = originalFileDate.AddDays(1).Date; var items = ctx.Files.Where(c => c.UserId == Context.UserId && c.OriginalFileDate == originalFileDate && c.OriginalFileName == originalFileName).ToList(); if (items.Count() > 0) { return items.FirstOrDefault().NewFileName; } List<CodeITDL.File> files = ctx.Files.Where(f => f.UserId == Context.UserId && f.OriginalFileDate > yesterday && f.OriginalFileDate < tomorrow).ToList(); int value = 0; if (files != null && files.Count > 0) { if (files.Max(x => x.UploadId).HasValue) { value = files.Max(x => x.UploadId).Value; } } try { if (fileNames.Where(c => c.Split('.')[0] == "#" + originalFileDate.ToString("yyyyMMdd")).Count() > 0) { value = fileNames.Where(c => c.Split('.')[0] == "#" + originalFileDate.ToString("yyyyMMdd")).Max(c => Convert.ToInt32(c.Split('.')[1])); } } catch (Exception ex) { _logger.Error(ex.Message); } return String.Format("#{0}.{1}", originalFileDate.ToString("yyyyMMdd"), (value + 1).ToString().PadLeft(4, '0')); } } catch (Exception ex) { _logger.Error(ex.Message); } return ""; }
private void frmUsers_Shown(object sender, EventArgs e) { isLoaded = true; List<User> users = new List<User>(); using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) { users = ctx.Users.Where(x => x.CustomerId == Context.CustomerId).ToList(); } if (users.Count > 0) { lvUsers.Items.Clear(); BindListView(users); } }
public void testDelete() { using (CodeITDbContext ctx = new CodeITDbContext(3)) { List<Customer> customerList = ctx.Customers.Take(3).ToList(); ctx.Customers.RemoveRange(customerList); ctx.SaveChanges(); } }
public void testModify() { using (CodeITDbContext ctx = new CodeITDbContext(2)) { List<Customer> customerList = ctx.Customers.Take(3).ToList(); foreach (Customer customer in customerList) customer.Name = string.Format("{0}_{1}", "UPDATED", customer.Name); ctx.SaveChanges(); } }
public void testInsert() { using (CodeITDbContext ctx = new CodeITDbContext(1)) { for (int i = 1; i <= 10; i++) { Customer newCustomer = new Customer() { Id = Guid.NewGuid(), Name = string.Format("Customer{0}", i) }; ctx.Customers.Add(newCustomer); } ctx.SaveChanges(); } }
private bool ValidateUserInput() { if (txtFirstName.Text.Trim() == string.Empty) { System.Windows.MessageBox.Show("Please enter first name", "Info", MessageBoxButton.OK, MessageBoxImage.Information); txtFirstName.Focus(); return false; } if (txtLastName.Text.Trim() == string.Empty) { System.Windows.MessageBox.Show("Please enter last name", "Info", MessageBoxButton.OK, MessageBoxImage.Information); txtLastName.Focus(); return false; } if (txtUserName.Text.Trim() == string.Empty) { System.Windows.MessageBox.Show("Please enter user name", "Info", MessageBoxButton.OK, MessageBoxImage.Information); txtUserName.Focus(); return false; } if (txtPassword.Text.Trim() == string.Empty) { System.Windows.MessageBox.Show("Please enter password", "Info", MessageBoxButton.OK, MessageBoxImage.Information); txtPassword.Focus(); return false; } if (editUserId <= 0) using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) { if (ctx.Users.Where(x => x.CustomerId == Context.CustomerId && x.UserName.ToLower() == txtUserName.Text.Trim().ToLower()).Count() > 0) { System.Windows.MessageBox.Show("User with same UserName already exists in the system, please try another UserName", "Info", MessageBoxButton.OK, MessageBoxImage.Information); txtUserName.Focus(); return false; } } return true; }
private void btnSave_Click(object sender, EventArgs e) { User usr = new User(); if (!ValidateUserInput()) return; using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) { using (var transaction = ctx.Database.BeginTransaction()) { if (editUserId != 0) usr = ctx.Users.Where(x => x.Id == editUserId).FirstOrDefault(); if (editUserId == 0) { usr.CreatedBy = Context.UserId; } usr.ModifiedBy = Context.UserId; usr.IdNumber = txtID.Text.Trim(); usr.FirstName = txtFirstName.Text.Trim(); usr.MiddleName = txtMiddleName.Text.Trim(); usr.LastName = txtLastName.Text.Trim(); usr.UserName = txtUserName.Text.Trim(); usr.Password = txtPassword.Text.Trim(); usr.RoleId = getSelectedRole(); usr.CustomerId = Context.CustomerId; usr.DeviceId = txtDeviceId.Tag == null ? string.Empty : txtDeviceId.Tag.ToString(); if (editUserId <= 0) ctx.Users.Add(usr); ctx.SaveChanges(); if (editUserId == 0) { int newUserId = ctx.Users.Where(c=>c.UserName == usr.UserName && c.Password == usr.Password && c.CustomerId == usr.CustomerId).FirstOrDefault().Id; UserLicense usrLic = new UserLicense(); usrLic.LicenseId = ctx.UserLicenses.Where(c => c.UserId == Context.UserId).FirstOrDefault().LicenseId; usrLic.UserId = newUserId; ctx.UserLicenses.Add(usrLic); ctx.SaveChanges(); } if (hasNewImage) { UserPicture userPicture = new UserPicture(); bool isImageInDB = false; if (editUserId != 0) if (ctx.UserPictures.Where(x => x.UserId == editUserId).Count() > 0) { isImageInDB = true; userPicture = ctx.UserPictures.Where(x => x.UserId == editUserId).FirstOrDefault(); } MemoryStream ms = new MemoryStream(); System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; userPicture.Picture = ms.ToArray(); userPicture.UserId = usr.Id; if (!isImageInDB) ctx.UserPictures.Add(userPicture); ctx.SaveChanges(); transaction.Commit(); if (isInitailUserFromLogin && usr.RoleId == (int)Role.Administrator) { System.Windows.MessageBox.Show("You have created your first user, please log in with this credentials now." + Environment.NewLine + "UserName: "******" Password: "******"Info", MessageBoxButton.OK, MessageBoxImage.Information); this.Close(); } } else transaction.Commit(); } } if (editUserId <= 0) System.Windows.MessageBox.Show("User created successfully", "Info", MessageBoxButton.OK, MessageBoxImage.Information); else { System.Windows.MessageBox.Show("User updated successfully", "Info", MessageBoxButton.OK, MessageBoxImage.Information); editUserId = 0; } btnClear.PerformClick(); btnClose.PerformClick(); btnSearch.PerformClick(); }
private void btnSearch_Click(object sender, EventArgs e) { List<User> filteredUsers = new List<User>(); lvUsers.Items.Clear(); using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) { if (txtSearch.Text.Trim().Length > 0) filteredUsers = ctx.Users.Where(x => (x.FirstName + " " + x.MiddleName + " " + x.LastName).ToLower().StartsWith(txtSearch.Text.ToLower()) && x.CustomerId == Context.CustomerId).ToList(); else filteredUsers = ctx.Users.Where(x => x.CustomerId == Context.CustomerId).ToList(); } BindListView(filteredUsers); }
private void btnDelete_Click(object sender, EventArgs e) { if (lvUsers.Items.Count == 0) { System.Windows.MessageBox.Show("There are no users to delete", "Info", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (lvUsers.SelectedItems.Count == 0) { System.Windows.MessageBox.Show("Please select user to delete", "Info", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (System.Windows.MessageBox.Show("Are you sure you want to delete selected user", "User delete confirmation", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { using (CodeITDbContext ctx = new CodeITDbContext(Context.UserId)) { int userId = (int)lvUsers.SelectedItems[0].Tag; ctx.Users.Remove(ctx.Users.Where(x => x.Id == userId).FirstOrDefault()); ctx.SaveChanges(); } ListViewItem lvi = lvUsers.SelectedItems[0]; lvUsers.SelectedItems[0].Selected = false; lvUsers.Items.Remove(lvi); } }
private void UpdateLicenseToDb(string licenseKey) { try { using (CodeITDL.CodeITDbContext ctx = new CodeITDL.CodeITDbContext()) { // Insert customer Guid customerId = new Guid(txtClientId.Text); Customer customer = new Customer(); customer.Id = customerId; customer.Name = txtAdminName.Text; if (ctx.Customers.FirstOrDefault(c => c.Id == customer.Id && c.Name == customer.Name) == null) { ctx.Customers.Add(customer); ctx.SaveChanges(); } else { MessageBox.Show("Failed to create license!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Insert user User currentUser = new User(); currentUser.FirstName = txtAdminName.Text; currentUser.UserName = txtAdminUsername.Text; currentUser.Password = txtAdminPassword.Text; currentUser.CreatedOn = DateTime.Now; currentUser.ModifiedOn = DateTime.Now; currentUser.CreatedBy = 1; currentUser.ModifiedBy = 1; Int32 newUserId = -1; if (ctx.Users.FirstOrDefault(u => u.UserName == currentUser.UserName && u.Password == currentUser.Password) == null) { ctx.Users.Add(currentUser); ctx.SaveChanges(); } else { MessageBox.Show("User already exist in the database, license creation failed!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Insert License if (ctx.Users.FirstOrDefault(u => u.UserName == currentUser.UserName && u.Password == currentUser.Password) != null) { newUserId = ctx.Users.FirstOrDefault(u => u.UserName == currentUser.UserName && u.Password == currentUser.Password).Id; } if (newUserId != -1) { CodeITDL.License license = new CodeITDL.License(); license.CustomerId = customerId; license.LicenseBytes = Encoding.UTF8.GetBytes(licenseKey); ctx.SaveChanges(); } Int32 licenseId = -1; if (ctx.Licenses.FirstOrDefault(l => l.CustomerId == customerId) != null) { licenseId = ctx.Licenses.FirstOrDefault(l => l.CustomerId == customerId).Id; } // Inser UserLicense if (licenseId != -1) { UserLicense userLicense = new UserLicense(); userLicense.LicenseId = licenseId; userLicense.UserId = newUserId; ctx.SaveChanges(); } else { MessageBox.Show("Failed to create license!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } ctx.SaveChanges(); } } catch (Exception ex) { MessageBox.Show("Failed to create license!", "License failed", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void PerformLogin() { DateTime started = DateTime.Now; btnLogin.Enabled = false; System.Windows.Forms.Application.DoEvents(); var loadingCancalationTokenSource = new CancellationTokenSource(); var loadingCancalationToken = loadingCancalationTokenSource.Token; var loadingTask = new Task(() => { var loadingForm = new frmLoading(); loadingForm.TopMost = true; loadingForm.Show(); while (!loadingCancalationToken.IsCancellationRequested) { Thread.Sleep(50); System.Windows.Forms.Application.DoEvents(); } loadingForm.Close(); }, loadingCancalationTokenSource.Token); loadingTask.Start(); string userName = txtUserName.Text.Trim(); string password = txtPassword.Text; bool hasUsers = false; CodeITDL.CodeITDbContext ctx = null; try { ctx = new CodeITDL.CodeITDbContext(0); if (ctx != null) { CodeITDL.License lic = null; string clientLicense = string.Empty; try { User user = ctx.Users.Where(d => d.UserName == userName && d.Password == password).FirstOrDefault(); lic = ctx.Licenses.Where(s => s.Id == (ctx.UserLicenses.Where(c => c.UserId == (user.Id)).FirstOrDefault()).LicenseId).FirstOrDefault(); } catch(Exception) { } if (lic != null) clientLicense = Encoding.UTF8.GetString(lic.LicenseBytes); if (!CodeITLicence.Licence.ValidateLicenceFromDB(clientLicense)) { System.Windows.Forms.MessageBox.Show("You don't have license. Please contact administrator.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { hasUsers = ctx.Users.Where(x => x.RoleId == (int)Role.Administrator && x.CustomerId == Context.CustomerId).Count() > 0; if (!hasUsers && userName.ToLower().Equals("administrator") && password.Equals("intrensic")) { loadingCancalationTokenSource.Cancel(true); System.Windows.MessageBox.Show("You are logged in as administrator, please add user with administrator role first", "Info", MessageBoxButton.OK, MessageBoxImage.Information); Administration.frmUsers frmUsers = new Administration.frmUsers(); frmUsers.ControlBox = true; frmUsers.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; frmUsers.Icon = Intrensic.Properties.Resources.Intrensic; frmUsers.Name = "Initial User Creation Screen"; frmUsers.isInitailUserFromLogin = true; frmUsers.ShowDialog(); } else if (!hasUsers) { loadingCancalationTokenSource.Cancel(true); System.Windows.MessageBox.Show("There are no defined users and initial login information is not correct, please try again", "Info", MessageBoxButton.OK, MessageBoxImage.Information); txtUserName.Clear(); txtPassword.Clear(); txtUserName.Focus(); LoginAudit.WriteLoginAudit(CodeITConstants.LOGIN_INCORECT_CREDENTIALS_NO_USERS); } else if (hasUsers) { User usr = new User(); usr = ctx.Users.FirstOrDefault(x => x.UserName.ToLower().Equals(userName.ToLower()) && x.Password.ToLower().Equals(password.ToLower()) && x.CustomerId == Context.CustomerId); if (usr == null) usr = new User(); if (usr.Id <= 0) { loadingCancalationTokenSource.Cancel(true); LoginAudit.WriteLoginAudit(CodeITConstants.LOGIN_INCORECT_CREDENTIALS_HAS_USERS); System.Windows.MessageBox.Show("Username and/or password are not correct. Please try again", "Info", MessageBoxButton.OK, MessageBoxImage.Information); } else { foreach (Form frm in System.Windows.Forms.Application.OpenForms) { if (frm.Name == "frmProgressStatus") { //check if user trying to login is user with current upload progress if (!((frmProgressStatus)frm).getOwnerOfUploadProcess.UserName.ToLower().Equals(userName.ToLower())) { loadingCancalationTokenSource.Cancel(true); LoginAudit.WriteLoginAudit(CodeITConstants.LOGIN_WHILE_UPLOAD_IN_PROGRESS_BY_DIFFERENT_USER, usr.Id); System.Windows.MessageBox.Show("There is an active upload process initiated by user: "******"Please wait for the upload process to complete before you are able to login", "Info", MessageBoxButton.OK, MessageBoxImage.Information); return; } else { ((frmProgressStatus)frm).DisableCancelButtonsOnLogout(false); } } } Context.UserId = usr.Id; } if (Context.UserId > 0) { Context.UserId = usr.Id; LoginAudit.WriteLoginAudit(CodeITConstants.LOGIN_SUCCESSFULL); ContextMenuItems(true); txtUserName.Clear(); txtPassword.Clear(); frmUserMainScreen frmMain = new frmUserMainScreen(); frmMain.InitialGoToUpload = loginStartedFromGoProDevice; frmMain.InitialUploadPath = uploadPath; frmMain.Show(); Context.mainForm = frmMain; this.uploadPath = string.Empty; this.loginStartedFromGoProDevice = false; this.Hide(); //Thread.Sleep(5000); loadingCancalationTokenSource.Cancel(true); Context.CheckForGoProDevice(); } } } } } catch (Exception ex) { // } finally { if (ctx != null) { ctx.Dispose(); } loadingCancalationTokenSource.Cancel(true); btnLogin.Enabled = true; } }