/// <summary> /// /// </summary> /// <param name="requestDto"></param> /// <returns></returns> public async Task <int> AddEmployeeProfile(EmployeeProfileDto requestDto) { try { var employeeProfile = new EmployeeProfile { FirstName = requestDto.FirstName, LastName = requestDto.LastName, CellPhone = requestDto.CellPhone, City = requestDto.City, DateOfBirth = requestDto.DateOfBirth, HomePhone = requestDto.HomePhone, MiddleInitial = requestDto.MiddleInitial, JobTitle = requestDto.JobTitle, State = requestDto.State, StreetAddress = requestDto.StreetAddress, FkInitiatedById = requestDto.FkInitiatedById, WorkEmail = requestDto.WorkEmail, ZipCode = requestDto.ZipCode, FkGenderId = requestDto.GenderId, FkUserId = requestDto.FkUserId, CreatedOn = DateTime.Now, }; _context.EmployeeProfile.Add(employeeProfile); _context.SaveChanges(); return(await Task.FromResult(employeeProfile.PkEmployeeProfileId)); } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// Saves the employee. /// </summary> /// <param name="profile">The profile.</param> /// <returns>a Task</returns> private async Task SaveEmployee(IEmployeeProfile profile) { var tempEmployee = new EmployeeProfile { FirstName = profile.FirstName, LastName = profile.LastName, Salary = profile.Salary, HoursPerDay = profile.HoursPerDay, DaysPerWeek = profile.DaysPerWeek, WeeksPerYear = profile.WeeksPerYear }; var validator = new EmployeeProfileValidator(); var results = validator.Validate(tempEmployee); if (results.IsValid) { SaveButtonEnabled = false; var saveSuccess = await EmployeeProvider.AddEmployee(tempEmployee); //TODO move to resources Message = saveSuccess == 1 ? "Employee details saved" : "Unable able to save employee details"; SaveButtonEnabled = true; } else { foreach (var error in results.Errors) { Message = error.ErrorMessage; } } Message = string.Empty; }
protected void Page_Load(object sender, EventArgs e) { AppConfig.initialize(); EmployeeProfile emp = (EmployeeProfile)Session["EmployeeProfile"]; if (null == emp) { emp = new EmployeeProfile(); emp.Domain = AppConfig.Domain; emp.Machine = GetIPAddress(); Session["EmployeeProfile"] = emp; } Login1.TitleText = "Employee Attendance Generator v1.0"; TextBox TextBox1 = (TextBox)Login1.FindControl("Machine"); if (null != TextBox1 && string.IsNullOrEmpty(TextBox1.Text)) { TextBox1.Text = GetIPAddress(); } if (string.IsNullOrEmpty(Login1.UserName)) { Login1.UserName = emp.Name; } if (!string.IsNullOrEmpty(AppConfig.UserName) && !string.IsNullOrEmpty(AppConfig.Password)) { Session["autologin"] = true; emp.Name = AppConfig.UserName; emp.Password = AppConfig.Password; Session["EventLogReader"] = createEventQuery(emp); FormsAuthentication.RedirectFromLoginPage( String.Format("{0}@{1}", emp.Name, emp.Machine), true); } }
public ActionResult Delete(int?id, EmployeeProfile Employee) { try { EmployeeProfile EmployeeProfile = new EmployeeProfile(); if (ModelState.IsValid) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } EmployeeProfile = db.EmployeeProfile.Find(id); if (EmployeeProfile == null) { return(HttpNotFound()); } db.EmployeeProfile.Remove(db.EmployeeProfile.Find(id)); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(EmployeeProfile)); } catch { return(View()); } }
public static EmployeeProfile DataRowToObject(DataRow dr) { EmployeeProfile TheEmployeeProfile = new EmployeeProfile(); TheEmployeeProfile.EmployeeProfilleID = int.Parse(dr["EmployeeProfileID"].ToString()); TheEmployeeProfile.EmployeeID = int.Parse(dr["EmployeeID"].ToString()); TheEmployeeProfile.EmployeeCode = dr["EmployeeCode"].ToString(); TheEmployeeProfile.EmployeeName = dr["EmployeeName"].ToString(); TheEmployeeProfile.SettingKeyName = dr["SettingKeyName"].ToString(); TheEmployeeProfile.SettingKeyID = int.Parse(dr["SettingKeyID"].ToString()); TheEmployeeProfile.CommonKeyValue = dr["CommonKeyValue"].ToString(); if (dr["SettingKeyValue"].ToString() != "") { TheEmployeeProfile.SettingKeyValue = (byte[])dr["SettingKeyValue"]; //ImageFunctions.ByteToImage((Byte[])(DtRow["SettingKeyValue"])); } TheEmployeeProfile.SettingKeyDescription = dr["SettingKeyDescription"].ToString(); TheEmployeeProfile.IsActive = Boolean.Parse(dr["IsActive"].ToString()); TheEmployeeProfile.IsDeleted = Boolean.Parse(dr["IsDeleted"].ToString()); return(TheEmployeeProfile); }
public void CreateEmployeeProfile(string userId, int age, string aboutMe, int[] skillsId) { var user = _userManager.FindById(userId); if (user == null) { throw new ObjectNotFoundException($"User with id={userId} not found"); } if (user.EmployeeProfile != null) { throw new ArgumentException($"Employee profile with id={userId} already exists", "EmployeeProfile"); } var employeeProfile = new EmployeeProfile() { User = user, Age = age, AboutMe = aboutMe }; foreach (var skillId in skillsId) { Skill skill = _skillRepository.FindById(skillId); if (skill == null) { throw new ObjectNotFoundException($"Skill with id={skillId} not found"); } employeeProfile.Skills.Add(skill); } _employeeRepository.Create(employeeProfile); }
private void button3_Click(object sender, EventArgs e) { EmployeeProfile employeeProfile = new EmployeeProfile(); employeeProfile.Show(); this.Hide(); }
public string UpdateEmployeeProfile(EmployeeProfile profile, Int64 ModifiedBy) { using (var dac = new EmployeeDac()) { return(dac.UpdateEmployeeProfile(profile, ModifiedBy)); } }
public string UpdateEmployeeProfile(EmployeeProfile profile, Int64 ModifiedBy) { using (IEmployeeHelper helper = new EmployeeHelper()) { return(helper.UpdateEmployeeProfile(profile, ModifiedBy)); } }
public ActionResult SaveEmployeeShift(List <Int64> UserId, int Shift, DateTime FromDate, DateTime ToDate, string RequestMenuUser) { string result = ""; EmployeeProfile EmployeeProfileObj = (EmployeeProfile)Session["Profile"]; if (ModelState.IsValid) { if (EmployeeProfileObj.RoleText == "Employee") { if (RequestMenuUser == "Team" && (FromDate <= DateTime.Now.AddDays(-7) || ToDate <= DateTime.Now.AddDays(-7))) { result = "The system restricts modifying shifts earlier than 7 days. Please contact HR for any changes."; } else { using (var client = new ShiftClient()) { result = client.SaveEmployeeShift(UserId, Shift, FromDate, ToDate, this.UserId); } } } else { using (var client = new ShiftClient()) { result = client.SaveEmployeeShift(UserId, Shift, FromDate, ToDate, this.UserId); } } } return(Json(result)); }
public async void GetData() { if (IsBusy) { return; } try { IsBusy = true; try { Basicinfos = await UBI.GetCurentUserDetailsAsync(URLConfig.Currentuserapiurl); } catch (Exception ex) { throw ex; } } finally { IsBusy = false; } }
public MainForm(EmployeeProfile employeeProfile) { InitializeComponent(); EmployeeProfileForm = employeeProfile; exitToolStripMenuItem.Click += ExitToolStripMenuItem_Click; employeeProfileToolStripMenuItem.Click += EmployeeProfileToolStripMenuItem_Click; }
public Employee(EmployeeProfile profile) { EmployeeID = profile.EmployeeId.TrimStart(new char[] { '0' }); TitleName = profile.TitleFullName; FirstName = profile.FirstName; LastName = profile.LastName; JobTitle = profile.PositionDescShort == profile.LevelDesc ? profile.PositionDescShort : profile.PositionDescShort + profile.LevelDesc; JobLevel = 9; CostCenterID = profile.CostCenterCode; Status = RecordStatus.Active; PositionCode = profile.PositionCode; PositionDescShort = profile.PositionDescShort; PostionDesc = profile.Position; LevelCode = profile.LevelCode; Email = profile.Email; int num; DepartmentSap = Int32.TryParse(profile.DepartmentSap, out num) ? num : (int?)null; StaffDate = profile.StaffDate; EntryDate = profile.EntryDate; RetiredDate = profile.RetiredDate.Length > 10 ? "31/12/9999" : profile.RetiredDate; BaCode = profile.BaCode; PeaCode = profile.Peacode; StatusCode = profile.StatusCode; StatusName = profile.Status; EmployeeGroup empgroup; Group = Enum.TryParse <EmployeeGroup>(profile.GroupId, out empgroup) ? empgroup : EmployeeGroup.None; }
public async Task <IActionResult> Edit(int id, [Bind("ID,Title,FirstName,LastName,Department")] EmployeeProfile employeeProfile, [Bind("PhotoFile")] IFormFile photoFile) { if (id != employeeProfile.ID) { return(NotFound()); } if (ModelState.IsValid) { // fetch old data from db var existingProfile = await _repository.ReadAsync(id); if (PhotoFileExists(photoFile)) { await CopyPhotoData(employeeProfile, photoFile); } else { // if no new photo file, keep the old data employeeProfile.PhotoType = existingProfile.PhotoType; employeeProfile.PhotoData = existingProfile.PhotoData; employeeProfile.ThumbnailBase64 = existingProfile.ThumbnailBase64; } await _repository.UpdateAsync(employeeProfile, existingProfile); return(RedirectToAction(nameof(Index))); } return(View(employeeProfile)); }
// Methods .................................. public IActionResult OnGet() { // From Domain EmployeeProfile domainEmpProf = _empPrifileRepo.GetById(1); string imageBase64Data = null; string imageDataURL = "https://via.placeholder.com/200"; if (domainEmpProf.ProfileImageData != null) { imageBase64Data = Convert.ToBase64String(domainEmpProf.ProfileImageData); imageDataURL = string.Format("data:image/jpg;base64,{0}", imageBase64Data); } // Domain to Model - assign full file name to property for HTML page empProfileModel = new EmployeeProfileModel { Id = domainEmpProf.Id, EmployeeName = domainEmpProf.EmployeeName, ProfileImageFilename = imageDataURL, ProfileImage = null }; return(Page()); }
public async Task <IActionResult> OnPostAsync() { // does ProfileImage has contents if (empProfileModel.ProfileImage != null) { // Note: empProfile.ProfileImage is an IFormFile // sync new filenane selected to the string representation in the model // using teh IFormFile.FileName property empProfileModel.ProfileImageFilename = empProfileModel.ProfileImage.FileName; // MAP model to domain // From Domain EmployeeProfile domainEmpProf = _empPrifileRepo.GetById(empProfileModel.Id); // Update the image filename in the Domain entity domainEmpProf.ProfileImageFileName = empProfileModel.ProfileImage.FileName; // Convert image into a memory string and into the Entity byte array using (MemoryStream ms = new MemoryStream()) { await empProfileModel.ProfileImage.CopyToAsync(ms); domainEmpProf.ProfileImageData = ms.ToArray(); } // SAVE - Update Domain Entity domainEmpProf = _empPrifileRepo.Update(domainEmpProf); // Saved, send it back to home return(RedirectToPage("../Index")); } // Refresh the page by redirecting it to itself return(RedirectToPage("")); }
/// <summary> /// Get a collection of profiles based upon a user name matching string and inactivity date. /// </summary> /// <param name="authenticationOption">Current authentication option setting.</param> /// <param name="userNameToMatch">Characters representing user name to match (L to R).</param> /// <param name="userInactiveSinceDate">Inactivity date for deletion.</param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="totalRecords">Total records found (output).</param> /// <returns>Collection of profiles.</returns> public override System.Web.Profile.ProfileInfoCollection FindInactiveProfilesByUserName(System.Web.Profile.ProfileAuthenticationOption authenticationOption, string userNameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { IObjectScope objScope = ORM.GetNewObjectScope(); const string queryInactiveProfilesByUserName = @"SELECT * FROM EmployeeProfileExtent AS o WHERE o.Employee.Name LIKE $1 AND o.Employee.LastActivityDate <= $2"; ProfileInfoCollection pic = new ProfileInfoCollection(); IQuery query = objScope.GetOqlQuery(queryInactiveProfilesByUserName); using (IQueryResult result = query.Execute(userNameToMatch + '*', userInactiveSinceDate)) { totalRecords = result.Count; int counter = 0; int startIndex = pageSize * pageIndex; int endIndex = startIndex + pageSize - 1; foreach (object res in result) { if (counter >= startIndex) { EmployeeProfile ep = res as EmployeeProfile; pic.Add(new ProfileInfo(ep.Employee.Name, false, ep.Employee.LastActivityDate, ep.LastUpdatedDate, 0)); } if (counter >= endIndex) { break; } counter += 1; } } return(pic); }
public async Task <ActionResult <EmployeeDto> > UpdateEmployee(Guid companyId, Guid employeeId , EmployeeUpdateDto employeeUpdate) { if (!await _service.CompanyExistsAsync(companyId)) { return(NotFound()); } var employee = await _service.GetEmployeeAsync(companyId, employeeId); if (employee == null) { var res = EmployeeProfile.InitializeAutoMapper().Map <Employee>(employeeUpdate); res.Id = employeeId; _service.AddEmployee(companyId, res); await _service.SaveAsync(); var employeeDto = EmployeeProfile.InitializeAutoMapper().Map <EmployeeDto>(res); return(CreatedAtRoute(nameof(GetEmployeeForCompany), new { companyId, employeeId = res.Id }, employeeDto)); } EmployeeProfile.InitializeAutoMapper().Map(employeeUpdate, employee); await _service.SaveAsync(); return(NoContent()); }
public async void TestEditPost() { var profile = new EmployeeProfile { ID = 3, FirstName = "Daniel", LastName = "Weber", Title = "CSA", Department = "Technical Sales" }; // test ID mismatch var result = await _controller.Edit(4, profile, null); Assert.IsType <NotFoundResult>(result); // test the change of last name without photo file result = await _controller.Edit(3, profile, null); Assert.IsType <RedirectToActionResult>(result); // test the change of last name with photo file FormFile formFile = CreateFormFile("face2.jpg"); result = await _controller.Edit(3, profile, formFile); Assert.IsType <RedirectToActionResult>(result); // check if the last names match EmployeeProfile profile2 = await _repository.ReadAsync(3); Assert.Equal("Weber", profile2.LastName); }
public int UpdateEmployeeProfile(EmployeeProfile theEmployeeProfile) { int ReturnValue = 0; using (SqlCommand UpdateCommand = new SqlCommand()) { UpdateCommand.CommandType = CommandType.StoredProcedure; UpdateCommand.Parameters.Add(GetParameter("@ReturnValue", SqlDbType.Int, ReturnValue)).Direction = ParameterDirection.Output; UpdateCommand.Parameters.Add(GetParameter("@EmployeeProfileID", SqlDbType.Int, theEmployeeProfile.EmployeeProfilleID)); UpdateCommand.Parameters.Add(GetParameter("@EmployeeID", SqlDbType.Int, theEmployeeProfile.EmployeeID)); UpdateCommand.Parameters.Add(GetParameter("@SettingKeyName", SqlDbType.VarChar, theEmployeeProfile.SettingKeyName)); UpdateCommand.Parameters.Add(GetParameter("@SettingKeyID", SqlDbType.Int, theEmployeeProfile.SettingKeyID)); UpdateCommand.Parameters.Add(GetParameter("@SettingKeyValue", SqlDbType.VarBinary, theEmployeeProfile.SettingKeyValue)); UpdateCommand.Parameters.Add(GetParameter("@SettingKeyDescription", SqlDbType.VarChar, theEmployeeProfile.SettingKeyReference)); UpdateCommand.Parameters.Add(GetParameter("@ModifiedBy", SqlDbType.Int, Micro.Commons.Connection.LoggedOnUser.UserID)); UpdateCommand.CommandText = "pHRM_EmployeeProfiles_Update"; ExecuteStoredProcedure(UpdateCommand); ReturnValue = int.Parse(UpdateCommand.Parameters[0].Value.ToString()); } return(ReturnValue); }
private IList <EmployeeAttendanceModel> GetEmployeeAttendanceList(string ID, string FromDate, string ToDate, string requestLevelPerson, bool IsDirectEmployees, bool getBreakStatus) { IList <EmployeeAttendanceModel> employeeAttendanceModelList = null; DateTime startDateFormatted, endDateFormatted; string tempRequestLevelPerson = requestLevelPerson; EmployeeProfile profile = (EmployeeProfile)Session["Profile"]; Int64 userID = profile.UserId; if (!string.IsNullOrEmpty(ID) && ID != "0") { userID = Convert.ToInt32(ID); requestLevelPerson = "My";// If we are not change the request level person, If we pass any manager ID it will return all timesheet who are all under the manager } if (string.IsNullOrEmpty(FromDate) || FromDate == "Nodate") { startDateFormatted = DateTime.Now.AddDays(-30).Date; endDateFormatted = DateTime.Now; } else { startDateFormatted = DateTime.Parse(FromDate, new CultureInfo("en-GB", true)); endDateFormatted = DateTime.Parse(ToDate, new CultureInfo("en-GB", true)).Add(new TimeSpan(23, 59, 59)); } IEmployeeAttendanceHelper employeeAttendanceHelper = new EmployeeAttendanceClient(); employeeAttendanceModelList = employeeAttendanceHelper.GetAttendanceForRange(userID, startDateFormatted, endDateFormatted, requestLevelPerson, IsDirectEmployees, getBreakStatus); requestLevelPerson = tempRequestLevelPerson; return(employeeAttendanceModelList); }
protected void Page_Load(object sender, EventArgs e) { EventLogReader logReader = (EventLogReader)Session["EventLogReader"]; EmployeeProfile emp = (EmployeeProfile)Session["EmployeeProfile"]; LoginStatus1.Visible = (null == Session["autologin"]); if (null == emp || !this.Page.User.Identity.IsAuthenticated || string.IsNullOrEmpty(emp.Name)) { FormsAuthentication.RedirectToLoginPage(); } else if (logReader != null) { try { Generator testClass = new Generator(logReader); List <TimeEntry> table = testClass.DisplayEventAndLogInformation(logReader); Attendance1.Text = String.Format("Query: {0}", Session["EventLogQuery"]); GridView1.DataSource = table; GridView1.DataBind(); Session["EventLogReader"] = null; TotalOT.Text = "Total Overtime: " + testClass.TotalOvertime; this.StartDate.Culture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); this.StartDate.SelectedDate = (DateTime)Session["DateTime"]; //this.StartDate.SelectedDateChanged += new EventHandler(DatePicker1_DateChanged); } catch (EventLogException err) { Console.WriteLine("Could not query the remote computer! " + err.Message); FormsAuthentication.RedirectToLoginPage(); } } }
public static EmployeeProfile GetEmployeeProfileBySettingKeyID(int employeeId, int settingKeyID) { EmployeeProfile TheEmployeeProfile; try { List <EmployeeProfile> EmployeeProfileList = GetEmployeeProfileByEmployeeID(employeeId); if (EmployeeProfileList.Count > 0) { TheEmployeeProfile = (from EmployeeProfileTable in EmployeeProfileList where EmployeeProfileTable.SettingKeyID == settingKeyID select EmployeeProfileTable).Last(); } else { TheEmployeeProfile = new EmployeeProfile(); } } catch { TheEmployeeProfile = new EmployeeProfile(); } return(TheEmployeeProfile); }
public ActionResult AddNewEmployee() { EmployeeProfile profile = new EmployeeProfile(); if (this.IsAuthorized == "NoAuth") { Response.Redirect("~/Home/Unauthorized"); return(null); } else { using (var client = new OfficeLocationClient()) { var lstOfc = client.GetAllOfficeLocations(); DropDownItem di = new DropDownItem(); ViewBag.EmpOffice = lstOfc.Where(x => x.Key == Convert.ToString(OfficeId)).ToList(); di.Key = ""; di.Value = ""; lstOfc.Insert(0, di); ViewBag.OfficeLocationList = lstOfc; } using (var client = new RoleClient()) { ViewBag.RoleList = client.GetAllRoles(); } using (var client = new ShiftClient()) { ViewBag.ShiftList = client.GetShiftMaster(); } using (var client = new EmployeeClient()) { IList <DropDownItem> reptList = client.GetActiveEmpList(OfficeId, null); DropDownItem di = new DropDownItem { Key = "", Value = "" }; reptList.Insert(0, di); ViewBag.ReportToList = reptList; } profile.EmploymentTypeId = 1; using (var client = new EmployeeClient()) { var lstEmploymentTypes = client.GetEmploymentTypes(); DropDownItem di = new DropDownItem(); ViewBag.EmploymentTypeList = lstEmploymentTypes; } using (var client = new EmployeeClient()) { profile.EmployeeId = client.GetNewEmpId(OfficeId, profile.EmploymentTypeId); } profile.IsActive = true; profile.Mode = "Add"; profile.LogonId = "CORP\\"; profile.Sunday = true; profile.Saturday = true; return(View("EmployeeProfile", profile)); } }
/// <summary> /// Adds the employee. /// </summary> /// <param name="employee">The employee.</param> /// <returns>success result</returns> public async Task <int> AddEmployee(EmployeeProfile employee) { using (var databaseContext = new DatabaseContext()) { databaseContext.EmployeeProfile.Add(employee); return(await databaseContext.SaveChangesAsync()); } }
public static EmployeeProfile GetEmployeeProfileByID(int employeeProfileID) { DataRow EmployeeProfileRow = EmployeeProfileDataAccess.GetInstance.GetEmployeeProfileByID(employeeProfileID); EmployeeProfile TheEmployeeProfile = DataRowToObject(EmployeeProfileRow); return(TheEmployeeProfile); }
public ActionResult DeleteConfirmed(int id) { EmployeeProfile employeeProfile = db.EmployeeProfiles.Find(id); db.EmployeeProfiles.Remove(employeeProfile); db.SaveChanges(); return(RedirectToAction("Index")); }
public UpdateBasicInfoViewModel() { Basicinfos = new EmployeeProfile(); GetData(); //basicinfos //MaxHourRate = (int)basicinfos.maxHourRate; //MinhourRate = (int)basicinfos.minHourRate; }
public ActionResult Edit([Bind(Include = "EmpID,EmpName,EmpSalary")] EmployeeProfile employeeProfile) { if (ModelState.IsValid) { db.Entry(employeeProfile).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(employeeProfile)); }
public async Task <TokenDTO> LoginAsync(string Username, string Password) { try { Employee user = Context.Employee.Where(x => x.Username == Username).FirstOrDefault(); if (user == null) { EmployeeDTO ADUser = LDAPService.LDAP_Authenticate(Username, Password); if (ADUser.Username == null) { tokens.Message = "ไม่พบข้อมูลผู้ใช้งาน"; return(tokens); } else { string SystemCode = await CreateNewUserAsync(ADUser); tokens.empCode = SystemCode; tokens.Message = "Login Success"; return(tokens); } } else { Password = EncryptionService.HashToMD5(Password + user.Passwordsalt); Employee users = Context.Employee.Where(x => x.Username == Username && x.Password == Password).FirstOrDefault(); EmployeeProfile employeeProfile = Context.EmployeeProfile.Where(x => x.Empcode == user.Empcode).FirstOrDefault(); DbPosition dbPosition = Context.DbPosition.Where(x => x.PositonCode == employeeProfile.PositionCode).FirstOrDefault(); if (users == null) { //user.UpdDate = DateTime.Now; //Context.Employee.Update(user); //Context.SaveChanges(); tokens.Message = "ชื่อผู้ใช้ และ รหัสผ่านไม่ถูกต้อง"; return(tokens); } else { //TOKEN tokens.empCode = user.Empcode; tokens.Username = users.Username; tokens.Firstname = employeeProfile.FirstnameEn; tokens.Lastname = employeeProfile.LastnameEn; tokens.PositionCode = dbPosition.PositonCode; tokens.Token = GenerateToken(user.Empcode); tokens.Message = "Login Success"; return(tokens); } } } catch (Exception ex) { throw ex; } }
private EventLogReader createEventQuery(EmployeeProfile emp) { DateTime now = DateTime.Now; DateTime endDate = now; DateTime startDate = DateTime.Today.AddDays(AppConfig.DisplayDays * -1); Session["DateTime"] = startDate; string queryString = String.Format(AppConfig.EventQuery, startDate.ToUniversalTime().ToString("o"), endDate.ToUniversalTime().ToString("o")); EventLogQuery query = new EventLogQuery("System", PathType.LogName, queryString); if (emp.Machine.CompareTo("127.0.0.1") != 0 && AppConfig.RemoteQuery) { // Query the Application log on the remote computer. SecureString pw = new SecureString(); string passwd = emp.Password; if (!string.IsNullOrEmpty(passwd)) { char[] charArray = passwd.ToCharArray(); for (int i = 0; i < passwd.Length; i++) { pw.AppendChar(charArray[i]); } } pw.MakeReadOnly(); query.Session = new EventLogSession( emp.Machine, // Remote Computer emp.Domain, // Domain emp.Name, // Username pw, SessionAuthentication.Default); //pw.Dispose(); Session["SecureString"] = pw; } Session["EventLogQuery"] = queryString; return new EventLogReader(query); }
protected void Page_Load(object sender, EventArgs e) { AppConfig.initialize(); EmployeeProfile emp = (EmployeeProfile)Session["EmployeeProfile"]; if (null == emp) { emp = new EmployeeProfile(); emp.Domain = AppConfig.Domain; emp.Machine = GetIPAddress(); Session["EmployeeProfile"] = emp; } Login1.TitleText = "Employee Attendance Generator v1.0"; TextBox TextBox1 = (TextBox)Login1.FindControl("Machine"); if (null != TextBox1 && string.IsNullOrEmpty(TextBox1.Text)) TextBox1.Text = GetIPAddress(); if (string.IsNullOrEmpty(Login1.UserName)) Login1.UserName = emp.Name; if (!string.IsNullOrEmpty(AppConfig.UserName) && !string.IsNullOrEmpty(AppConfig.Password)) { Session["autologin"] = true; emp.Name = AppConfig.UserName; emp.Password = AppConfig.Password; Session["EventLogReader"] = createEventQuery(emp); FormsAuthentication.RedirectFromLoginPage( String.Format("{0}@{1}", emp.Name, emp.Machine), true); } }