private bool SendNotifyLetterMethod(HrUnitOfWork _hrUnitOfWork, string UserName, int EmpID, string ID, out string ErrorMessage) { ErrorMessage = ""; int CompanyID = User.Identity.GetDefaultCompany(); string CurrentURL = HttpContext.Request.Url.Authority; string DownloadAPKUrl = System.Configuration.ConfigurationManager.AppSettings["DownloadAPKUrl"]; DateTime Today = DateTime.Now.Date; string Language = HttpContext.User.Identity.GetLanguage(); NotifyLetter NL = new NotifyLetter() { CompanyId = CompanyID, EmpId = EmpID, NotifyDate = Today, NotifySource = MsgUtils.Instance.Trls(Db.Persistence.Constants.Sources.UserProfile, Language), SourceId = ID, Sent = true, EventDate = Today, Description = MsgUtils.Instance.Trls("User Name", Language) + " : " + UserName + " " + MsgUtils.Instance.Trls("Website", Language) + " : " + CurrentURL + " " + MsgUtils.Instance.Trls("Download APK", Language) + " : " + DownloadAPKUrl }; AddNotifyLetters AddNotifyLetters = new AddNotifyLetters(_hrUnitOfWork, NL, Language); bool Result = AddNotifyLetters.Run(out ErrorMessage); return(Result); }
private static string MessageMerge(string message, HrUnitOfWork unitofwork, DataTable table, DataRow row, string tablename, string lang) { if (message == null) { return(""); } int start = message.IndexOf("%"), end; // { StringBuilder result = new StringBuilder(); int index = 0; while (start >= 0) { end = message.Substring(index + start + 1).IndexOf("%"); // } if (end > 0) { result.Append(message.Substring(index, start) + GetColumnValue(message.Substring(index + start + 1, end), unitofwork, table, row, tablename, lang)); index = index + start + end + 2; start = message.Substring(index).IndexOf("%"); // { } else { break; } } result.Append(message.Substring(index, message.Length - index)); return(result.ToString()); }
public List <Model.ViewModel.Error> SaveChanges(string Language) { // use this function only to save main record List <DbEntityEntry> entries = null; var errors = HrUnitOfWork.SaveChanges(Language, out entries); if (errors.Count > 0) { return(errors); } // now send notifications var notifications = entries.Where(e => e.Entity.ToString() == "Model.Domain.Notifications.Notification").Select(e => e.Entity); if (notifications.Count() > 0) // found notifications { foreach (var entity in notifications) { var notification = (Model.Domain.Notifications.Notification)entity; HangFireJobs.SendNotication(notification, notification.Condition, HrUnitOfWork.NotificationRepository); } } return(errors); }
public List <Model.ViewModel.Error> Save(string Language) { // use this function within transaction for any change var errors = HrUnitOfWork.SaveChanges(Language); return(errors); }
public static void SendEmails(IList <UserView> users, Notification notify, string email = null) { if (email != null) { users.Add(new UserView { EmailNotify = true, Email = email }); } HrUnitOfWork unitofwork = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString)); bool modified = false; int counter = 0; EmailAccount emailaccount = null; if (users.Count() > 0) { SendEmails(unitofwork.NotificationRepository, users, notify, ref emailaccount, ref counter, ref modified); if (emailaccount != null && modified) { emailaccount.LastSentDate = DateTime.Now; emailaccount.TodayCount = counter; unitofwork.NotificationRepository.Attach(emailaccount); unitofwork.NotificationRepository.Entry(emailaccount).State = System.Data.Entity.EntityState.Modified; } unitofwork.SaveChanges(); } }
public static void RunNotificationsAlgorithm(string ConnectionString, string Language) { HrUnitOfWork unitofwork = new HrUnitOfWork(new HrContextFactory(ConnectionString)); try { DateTime Today = DateTime.Now.Date; List <EmploymentPaper_ToNotify> EmpPapers_ToNotify = unitofwork.CompanyDocsViewsRepository.EmploymentPapersForNotifications(); string EmpIDs = (EmpPapers_ToNotify.Any()) ? EmpPapers_ToNotify.Select(a => a.EmpID.ToString()).Aggregate <string>((x1, x2) => x1 + "," + x2).ToString() : ""; List <FormDropDown> EmpsLangs = unitofwork.MeetingRepository.GetUsersLang(EmpIDs); List <NotifyLetter> NotifyLettersList = new List <NotifyLetter>(); EmpPapers_ToNotify.ForEach(e => { FormDropDown EmpLang = EmpsLangs.Where(a => a.id == e.EmpID).FirstOrDefault(); string Lang = ""; if (EmpLang != null) { Lang = EmpLang.name; } NotifyLetter NL = new NotifyLetter() { CompanyId = e.CompanyId.Value, EmpId = e.EmpID, NotifyDate = Today, NotifySource = MsgUtils.Instance.Trls(Lang, e.DocTypeName), SourceId = e.Stream_Id.ToString(), Sent = true, EventDate = e.ExpiryDate.Value, Description = MsgUtils.Instance.Trls(Lang, "you must renew") + " " + e.PaperFileName + " " + MsgUtils.Instance.Trls(Lang, "Before") + " " + e.ExpiryDate.Value.ToMyDateString(Lang, "yyyy-MM-dd") }; //unitofwork.NotifyLetterRepository.Add(NL); NotifyLettersList.Add(NL); }); string ErrorMessage; AddNotifyLetters AddNotifyLetters = new AddNotifyLetters(unitofwork, NotifyLettersList, Language); bool Result = AddNotifyLetters.Run(out ErrorMessage); //unitofwork.SaveChanges(); } catch (Exception ex) { unitofwork.HandleDbExceptions(ex); } finally { } }
public JsonResult SendNotifyLetter(string UserName = "", int EmpID = 0, string ID = "") { if (string.IsNullOrEmpty(UserName) || EmpID == 0 || string.IsNullOrEmpty(ID)) { return(Json(new { Result = false })); } var _hrUnitOfWork = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString)); string Message; bool Result = SendNotifyLetterMethod(_hrUnitOfWork, UserName, EmpID, ID, out Message); return(Json(new { Result = Result, Message = Message })); }
private static string GetColumnValue(string columname, HrUnitOfWork unitofwork, DataTable table, DataRow row, string tablename, string lang) { if (row[columname] == null) { return(" .. "); } var datatype = table.Columns[columname].DataType; string value = row[columname].ToString(); if (datatype == typeof(int) || datatype == typeof(short) || datatype == typeof(byte)) { // so this seems to be Id or code so resolve code value = unitofwork.Context.Database.SqlQuery <string>("exec dbo.sp_GetDisplayName '" + tablename + "', '" + columname + "', " + value + ", '" + lang + "'").FirstOrDefault(); } return(value); }
public void RunNotificationsAlgorithm(string ConnectionString, SendFormPageVM model, string Culture) { HrUnitOfWork unitofwork = new HrUnitOfWork(new HrContextFactory(ConnectionString)); try { DateTime Today = DateTime.Now.Date; List <int> EmployeesToNotificate = GetEmpIdList(ConnectionString, model, Culture); string FormName = unitofwork.Repository <FlexForm>().Where(a => a.Id == model.FormId).SingleOrDefault().Name; List <FormDropDown> EmpsLangs = unitofwork.MeetingRepository.GetUsersLang((EmployeesToNotificate.Any()) ? EmployeesToNotificate.Select(a => a.ToString()).Aggregate <string>((x1, x2) => x1 + "," + x2).ToString() : ""); foreach (var e in EmployeesToNotificate.Distinct()) { string Lang; if (EmpsLangs.Select(a => a.id).Contains(e)) { Lang = EmpsLangs.Where(a => a.id == e).FirstOrDefault().name; } else { Lang = Culture; } NotifyLetter NL = new NotifyLetter() { CompanyId = model.CompanyId, EmpId = e, NotifyDate = Today, NotifySource = MsgUtils.Instance.Trls(Lang, "Questionnaire") + " " + MsgUtils.Instance.Trls(Lang, FormName), SourceId = model.FormId.ToString(), Sent = true, EventDate = model.ExpiryDate, Description = MsgUtils.Instance.Trls(Lang, "Please fill") + " " + MsgUtils.Instance.Trls(Lang, FormName) + " " + MsgUtils.Instance.Trls(Lang, "Before") + " " + model.ExpiryDate.ToShortDateString() }; unitofwork.NotifyLetterRepository.Add(NL); } unitofwork.SaveChanges(); } catch (Exception ex) { unitofwork.HandleDbExceptions(ex); } finally { } }
public async Task <IHttpActionResult> ForgotPassword(ForgotPasswordMobileViewModel model) { if (!ModelState.IsValid) { return(BadRequest()); } var user = db.Users.FirstOrDefault(u => u.UserName == model.Username && u.Email == model.Email); if (user == null) { return(NotFound()); } string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); if (code == null) { return(StatusCode(HttpStatusCode.Forbidden)); } if (model.WithEmail == true) { var callbackUrl = Url.Link("LogPattern", new { Controller = "Account", Action = "ResetPassword", userId = user.Id, UserName = user.UserName, code = code }); EmailAccount emailAcc = HrUnitOfWork.Repository <EmailAccount>().FirstOrDefault(); emailAcc.EnableSsl = false; string Send = Db.Persistence.Services.EmailService.SendEmail(emailAcc, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>", user.Email, user.UserName, null, null); if (Send == "Error") { return(BadRequest()); } return(Ok(new ForgetDataViewModel() { UserName = user.UserName, UserId = user.Id, Code = null })); } else { return(Ok(new ForgetDataViewModel() { UserName = user.UserName, UserId = user.Id, Code = code })); } }
public List <int> GetEmpIdList(string ConnectionString, SendFormPageVM model, string Culture) { HrUnitOfWork unitofwork = new HrUnitOfWork(new HrContextFactory(ConnectionString)); List <int> EmpIdList = new List <int>(); //Get Employees in the department if (model.Departments != null) { var EmployeesListByDept = unitofwork.EmployeeRepository.GetActiveEmployees(Culture, 0, model.CompanyId) .Where(e => model.Departments.Contains((int)e.DepartmentId)) .Select(e => new { id = e.Id }).ToList(); foreach (var item in EmployeesListByDept) { EmpIdList.Add(item.id); } } //Get Employees in the job if (model.Jobs != null) { var EmployeesListByJob = unitofwork.EmployeeRepository.GetActiveEmployees(Culture, 0, model.CompanyId) .Where(e => model.Jobs.Contains((int)e.JobId)) .Select(e => new { id = e.Id }).ToList(); foreach (var item in EmployeesListByJob) { EmpIdList.Add(item.id); } } if (model.Employees != null) { EmpIdList.AddRange(model.Employees); } return(EmpIdList); }
public async Task <ActionResult> UserProfile(UserViewModel model, string Id, int EmpId, OptionsViewModel moreInfo, UserCompaniesVM grid1) { var Errors = new List <Error>(); var _hrUnitOfWork = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString)); var ServerValidationEnabled = System.Configuration.ConfigurationManager.AppSettings["ServerValidationEnabled"] == "true"; if (ModelState.IsValid) { if (ServerValidationEnabled) { var columns = Models.Utils.GetColumnViews(ModelState.Where(a => !a.Key.Contains('.'))); Errors = _hrUnitOfWork.SiteRepository.CheckForm(new CheckParm { CompanyId = User.Identity.GetDefaultCompany(), ObjectName = "UserProfile", TableName = "AspNetUsers", Columns = columns, Culture = User.Identity.GetLanguage() }); if (Errors.Count() > 0) { foreach (var e in Errors) { foreach (var errorMsg in e.errors) { ModelState.AddModelError(errorMsg.field, errorMsg.message); } } return(Json(Models.Utils.ParseFormErrors(ModelState))); } } var db = HttpContext.GetOwinContext().Get <UserContext>(); var _userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); //var db = new UserContext(); //var _userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(db)); ApplicationUser user = _userManager.FindById(Id); IdentityResult res; var loginId = User.Identity.GetUserId(); model.Messages = getMessage(model.Culture); //Update User if (user != null) { string OldCulture = user.Language; string OldTimeZone = user.TimeZone; int OldCompany = user.DefaultCompany.Value; AutoMapper(new Models.AutoMapperParm { Destination = user, Source = model, ObjectName = "UserProfile", Options = moreInfo }, _hrUnitOfWork); user.Language = model.Language == null ? "en-GB" : model.Language; user.Messages = getMessage(model.Culture); model.NewUser = false; user.LockoutEnabled = model.LockoutEnabled; if ((user.Id == loginId) && (user.TimeZone != OldTimeZone) && (OldCulture != model.Language) && (user.Language != null) && (user.TimeZone != null)) { ChangeAll(model.TimeZone, model.Language, model.DefaultCompany.Value); } else if ((user.Id == loginId) && (OldCulture != null) && (OldCulture != model.Language)) { ChangeCulture(model.Language, model.DefaultCompany.Value); } else if ((user.Id == loginId) && (OldTimeZone != null) && (OldTimeZone != model.TimeZone)) { ChangeTimeZone(model.TimeZone, model.DefaultCompany.Value); } else if ((user.Id == loginId) && (OldCompany != User.Identity.GetDefaultCompany())) { ChangeDefaultCompany(model.DefaultCompany.Value); } } else //New User { user = new ApplicationUser { UserName = model.UserName, Email = model.Email, LockoutEnabled = model.LockoutEnabled }; model.NewUser = true; } // database transactions //var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); var trans = db.Database.BeginTransaction(); var status = (model.NewUser == true ? PersonStatus.UserProfile : 0); if (!model.NewUser) { res = await _userManager.UpdateAsync(user); } else { if (model.Password == null) { user.ResetPassword = true; res = await _userManager.CreateAsync(user); } else { res = await _userManager.CreateAsync(user, model.Password); } } moreInfo.VisibleColumns.Remove("Id"); if (res.Errors.Count() > 0) { var err = res.Errors.FirstOrDefault().Split(' ')[0]; if (err == "Passwords") { ModelState.AddModelError("Password", MsgUtils.Instance.Trls("Passwordmustnotlest6")); } else if (err == "User") { ModelState.AddModelError("UserName", MsgUtils.Instance.Trls("Namemustcontaindigitorchar")); } else { ModelState.AddModelError("", MsgUtils.Instance.Trls(res.Errors.FirstOrDefault())); } trans.Rollback(); trans.Dispose(); return(Json(Models.Utils.ParseFormErrors(ModelState))); } if (model.NewUser) { AutoMapper(new Models.AutoMapperParm { Destination = user, Source = model, ObjectName = "UserProfile", Options = moreInfo }, _hrUnitOfWork); user.Messages = getMessage(model.Culture); user.Language = model.Language == null ? "en-GB" : model.Language; user.DefaultCompany = User.Identity.GetDefaultCompany(); user.EmpId = EmpId; model.EmpId = EmpId; model.DefaultCompany = user.DefaultCompany; model.Id = user.Id; } SaveGrid(grid1, ModelState.Where(a => a.Key.Contains("grid1")), user, _hrUnitOfWork, db); try { //if (model.NewUser) //{ // string Message; // SendNotifyLetterMethod(_hrUnitOfWork, user.UserName, EmpId, user.Id, out Message); //} db.SaveChanges(); } catch (Exception ex) { var message = _hrUnitOfWork.HandleDbExceptions(ex); if (message == "Date Already Exists") { message = "UserHaveOnlyRole"; } //scope.Dispose(); trans.Rollback(); trans.Dispose(); return(Json(MsgUtils.Instance.Trls(message))); } trans.Commit(); trans.Dispose(); if (status != PersonStatus.Done) { var person = _hrUnitOfWork.PeopleRepository.GetPerson(model.EmpId); person.Status = PersonStatus.Done; model.Status = PersonStatus.Done; _hrUnitOfWork.SaveChanges(); } return(Json("OK," + ((new JavaScriptSerializer()).Serialize(model)))); } return(Json(Models.Utils.ParseFormErrors(ModelState))); }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { //var user = await UserManager.FindByEmailAsync(model.Email); var user = dbc.Users.FirstOrDefault(u => u.UserName == model.Username && u.Email == model.Email); var val = Request.Cookies["culture"]; var culture = (HttpContext.Request.Cookies["culture"] != null) ? Request.Cookies["culture"].Value : "en-GB"; //|| !(await UserManager.IsEmailConfirmedAsync(user.Id)) if (user == null) { ModelState.AddModelError("Email", MsgUtils.Instance.Trls("incorrectuser", culture)); return(PartialView("ForgotPassword", model)); // Don't reveal that the user does not exist or is not confirmed } string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, UserName = user.UserName, code = code }, protocol: Request.Url.Scheme); EmailAccount emailAcc = HrUnitOfWork.Repository <EmailAccount>().FirstOrDefault(); emailAcc.EnableSsl = false; string Send = Db.Persistence.Services.EmailService.SendEmail(emailAcc, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>", user.Email, user.UserName, null, null); if (Send == "Error") { return(PartialView("Error")); } return(RedirectToAction("ForgotPasswordConfirmation", "Account")); } else { foreach (var item in ModelState) { if (ModelState["Username"].Errors.Count > 0) { var req0 = item.Value.Errors.SingleOrDefault(a => a.ErrorMessage == "The Username field is required."); item.Value.Errors.Remove(req0); ModelState.AddModelError("Username", MsgUtils.Instance.Trls("userNameRequired", model.Culture)); } else if (ModelState["Email"].Errors.Count > 0) { var req = item.Value.Errors.SingleOrDefault(a => a.ErrorMessage == "The Email field is required."); var req1 = item.Value.Errors.SingleOrDefault(a => a.ErrorMessage == "The Email field is not a valid e-mail address."); if (req != null) { item.Value.Errors.Remove(req); ModelState.AddModelError("Email", MsgUtils.Instance.Trls("emailRequired", model.Culture)); } else if (req1 != null) { item.Value.Errors.Remove(req1); ModelState.AddModelError("Email", MsgUtils.Instance.Trls("emailNotValid", model.Culture)); } } } return(PartialView(model)); } // If we got this far, something failed, redisplay form }
public static void ExtendContract(string Language) { HrUnitOfWork unitofwork = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString)); string ErrorMessage; ExtendContractMethod(unitofwork, Language, out ErrorMessage); //unitofwork.Save(); //// Get First Email Account //EmailAccount emailAcc = unitofwork.Repository<EmailAccount>().FirstOrDefault(); //// Get All employees The will Send Email to whose contract Finish and before No of days //var Employments = unitofwork.EmployeeRepository.SendMailEmployees(); //// Get an instance of Letter Controller which has the mailmerge Functin //LettersController LetterController = new LettersController(unitofwork); //// Instance of mailmergeviewmodel that will get result of function mailmerge //MailMergeViewmodel Temp = new MailMergeViewmodel(); //string Send = ""; //// Translation of subject and body of mail //string Subject = MsgUtils.Instance.Trls("ContractFinish", Language); //string Body = MsgUtils.Instance.Trls("YourContractFinish", Language); //foreach (var item in Employments) //{ // if (item.Email != null) // { // if (item.Renew) // the employees whose contract will Renewed // Temp = LetterController.MergeData("RenewContract", item.Id, item.EmpId, Language); // else // the employees whose contract will finished // Temp = LetterController.MergeData("ContractFinish", item.Id, item.EmpId, Language); // if (Temp.Exist) // if there is File or no error of mail merge // { // // The Attachement file that will send to employee // Attachment Attach = new Attachment(Temp.ServerFilePath); // //Send email Function // Send = Db.Persistence.Services.EmailService.SendEmail(emailAcc,item.Renew? MsgUtils.Instance.Trls("ContractRenew", Language):Subject,item.Renew ? MsgUtils.Instance.Trls("YourContractRenewed", Language):Body , item.Email, "", null, Attach); // try // { // if (Send == "Ok") // { // if (emailAcc.TodayCount <= emailAcc.Capacity) // if count of mails sent today less than the capacity of mailacount capacity // { // emailAcc.TodayCount = emailAcc.TodayCount + 1; // increase the mails sent today +1 // emailAcc.LastSentDate = DateTime.Now; // unitofwork.NotificationRepository.Attach(emailAcc); // unitofwork.NotificationRepository.Entry(emailAcc).State = System.Data.Entity.EntityState.Modified; // } // else // Change the email Account // emailAcc = unitofwork.NotificationRepository.GetEmailAccount(emailAcc.SendOrder); // } // // Create Notification if the email sent to employee or not to sent it later if not sent // NotifyLetter NL = new NotifyLetter() // { // CompanyId = item.CompanyId, // EmpId = item.EmpId, // NotifyDate = DateTime.Today, // NotifySource = item.Renew ? "RenewContract" : "ContractFinish", // SourceId = item.Id.ToString(), // Sent = Send == "Ok" ? true : false, // EventDate = item.EndDate // }; // unitofwork.NotificationRepository.AddNotifyLetter(NL); // unitofwork.Save(); // // Add the employee file to Documents // unitofwork.CompanyRepository.Add(new CompanyDocsViews() // { // CompanyId = item.CompanyId, // name = Temp.Path.Substring(Temp.Path.LastIndexOf("/") + 1), // Source = "NotifyLetter", // SourceId = NL.Id, // file_stream = System.IO.File.ReadAllBytes(Temp.ServerFilePath), // thumbs = null, // }); // unitofwork.Save(); // } // catch (Exception ex) // { // unitofwork.HandleDbExceptions(ex); // } // finally // { // Attach.Dispose(); // } // } // } //} }
/// <summary> /// shift business days + or - to specific no of days /// </summary> /// <param name="businessdate"></param> /// <param name="days"></param> /// <param name="sign"></param> /// <returns>new business date</returns> private static DateTime GetNotificationDate(HrUnitOfWork unitofwork, int company, Events e, string value) { DateTime businessdate = DateTime.Today; if (e == Events.IsDueIn) { return(businessdate); } int temp = 0; int sign = e == Events.WasDueThisAmountofTimeAgo ? -1 : 1; if (!string.IsNullOrEmpty(value)) { int.TryParse(value, out temp); } NotifyDays days = (NotifyDays)temp; if (days == 0 || e == Events.IsDueIn) { return(businessdate); } var setup = unitofwork.CompanyRepository.GetPersonSetup(company); if (holidays == null) { holidays = unitofwork.Repository <Model.Domain.Holiday>() .Where(a => a.CompanyId == company || !a.IsLocal) .Select(a => new Holidays { HoliDate = a.HoliDate, SDays = a.SDay, SMonth = a.SMonth, Standard = a.Standard }) .ToList(); } if (days <= NotifyDays._13CalendarDays) { int i = 1; while (i <= (int)days) { businessdate = businessdate.AddDays(i * sign); if (!IsHoliday(setup, businessdate)) { i++; } } } else if (days == NotifyDays._2Weeks) { businessdate = businessdate.AddDays(14 * sign); } else if (days == NotifyDays._3Weeks) { businessdate = businessdate.AddDays(21 * sign); } else if (days == NotifyDays._1Month) { businessdate = businessdate.AddMonths(sign); } else if (days == NotifyDays._2Months) { businessdate = businessdate.AddMonths(2 * sign); } else if (days == NotifyDays._3Months) { businessdate = businessdate.AddMonths(3 * sign); } else if (days == NotifyDays._4Months) { businessdate = businessdate.AddMonths(4 * sign); } return(businessdate); }
public async Task <ActionResult> SaveProfile(ProfileViewModel profile, OptionsViewModel moreInfo) { var _hrUnitOfWork = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString)); var _userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); var userbl = new UserBL(); if (ModelState.IsValid) { string userId = User.Identity.GetUserId(); ApplicationUser user = _userManager.FindById(userId); IdentityResult result; bool Changed = false; string message = "OK"; string OldCulture = user.Language; string OldTimeZone = user.TimeZone; int OldCompany = user.DefaultCompany.Value; AutoMapper(new AutoMapperParm() { ObjectName = "Profile", Source = profile, Destination = user, Options = moreInfo }, _hrUnitOfWork); user.Language = profile.Culture == null ? "en-GB" : profile.Culture; user.Messages = getMessage(profile.Culture); user.DefaultCompany = OldCompany; //if (user.SuperUser) //{ // user.SuperUser = profile.SuperUser; // int supersCount = _userManager.Users.Where(u => u.SuperUser).Count(); // if (!profile.SuperUser && supersCount <= 1) // { // ModelState.AddModelError("SuperUser", MsgUtils.Instance.Trls("CantRemoveSuperUser")); // return Json(Models.Utils.ParseFormErrors(ModelState)); // } //} result = await _userManager.UpdateAsync(user); if ((profile.TimeZone != OldTimeZone) && (OldCulture != user.Language) && (profile.Culture != null) && (profile.TimeZone != null)) { ChangeAll(profile.TimeZone, profile.Culture, 0); Changed = true; } else if ((profile.Culture != null) && (OldCulture != user.Language)) { ChangeCulture(profile.Culture, 0); Changed = true; } else if ((profile.TimeZone != null) && (OldTimeZone != profile.TimeZone)) { ChangeTimeZone(profile.TimeZone, 0); Changed = true; } if (result.Succeeded && profile.NewPassword != null && profile.OldPassword != null) { if (!userbl.DuplicatePassword(ModelState, profile.NewPassword, profile.OldPassword, user.Language)) { return(Json(Models.Utils.ParseFormErrors(ModelState))); } var CorrectoldPass = await _userManager.CheckPasswordAsync(user, profile.OldPassword); if (CorrectoldPass) { result = await _userManager.ChangePasswordAsync(userId, profile.OldPassword, profile.NewPassword); if (result.Errors.Count() > 0) { var ErrList = result.Errors.ToList(); foreach (var item in ErrList) { ModelState.AddModelError("ConfirmPassword", userbl.TranslateError(item, user.Language)); } return(Json(Models.Utils.ParseFormErrors(ModelState))); } } else { ModelState.AddModelError("OldPassword", MsgUtils.Instance.Trls("notOldPassword")); return(Json(Models.Utils.ParseFormErrors(ModelState))); } } else if (result.Succeeded && profile.NewPassword != null) { ModelState.AddModelError("OldPassword", MsgUtils.Instance.Trls("Required") + ";"); return(Json(Models.Utils.ParseFormErrors(ModelState))); } else if (result.Succeeded && profile.OldPassword != null) { ModelState.AddModelError("NewPassword", MsgUtils.Instance.Trls("Required") + ";"); return(Json(Models.Utils.ParseFormErrors(ModelState))); } //Validation if (result.Errors.Count() > 0) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } else { //if (user.EmpId != null) //{ // var person = _hrUnitOfWork.Repository<Person>().FirstOrDefault(a => a.Id == user.EmpId); // person.WorkEmail = user.Email; // person.WorkTel = user.PhoneNumber; // _hrUnitOfWork.PeopleRepository.Attach(person); // _hrUnitOfWork.PeopleRepository.Entry(person).State = System.Data.Entity.EntityState.Modified; //} _hrUnitOfWork.SaveChanges(user.Language); if (Changed) { message = "OK," + ((new JavaScriptSerializer()).Serialize(profile)); } return(Json(message)); } } userbl.CheckPasswordStrength(ModelState, User.Identity.GetLanguage()); return(Json(Models.Utils.ParseFormErrors(ModelState))); }
private void AutoMapper(Models.AutoMapperParm parm, HrUnitOfWork unitOfWork) { Models.AutoMapper mapper = new Models.AutoMapper(parm, unitOfWork, User.Identity); mapper.Map(); }
private void SaveGrid(UserCompaniesVM grid, IEnumerable <KeyValuePair <string, ModelState> > state, ApplicationUser user, HrUnitOfWork unitOfWork, UserContext db) { // Deleted if (grid.deleted != null) { foreach (var model in grid.deleted) { var companyrole = new UserCompanyRole { Id = model.Id }; db.UserCompanyRoles.Remove(companyrole); } } // updated records if (grid.updated != null) { foreach (var model in grid.updated) { var companyrole = new UserCompanyRole(); AutoMapper(new Models.AutoMapperParm { Destination = companyrole, Source = model, Transtype = TransType.Update }, unitOfWork); companyrole.UserId = user.Id; db.UserCompanyRoles.Attach(companyrole); db.Entry(companyrole).State = EntityState.Modified; } } // inserted records if (grid.inserted != null) { foreach (var model in grid.inserted) { var companyrole = new UserCompanyRole(); AutoMapper(new Models.AutoMapperParm { Destination = companyrole, Source = model, Transtype = TransType.Insert }, unitOfWork); companyrole.User = user; db.UserCompanyRoles.Add(companyrole); } } }
public EmployeeGetway() { _hrUnitOfWork = new HrUnitOfWork(new AssetDbContext()); }
public static void ReadNotifications(int CompanyId, int empId, string lang) { HrUnitOfWork unitofwork = new HrUnitOfWork(new HrContextFactory(System.Configuration.ConfigurationManager.ConnectionStrings["HrContext"].ConnectionString)); var conditions = unitofwork.NotificationRepository.ReadNotifications(CompanyId); EmailAccount emailaccount = null; bool modified = false; int counter = 0; holidays = null; if (emailaccount != null && modified) { emailaccount.LastSentDate = DateTime.Now; emailaccount.TodayCount = counter; unitofwork.NotificationRepository.Attach(emailaccount); unitofwork.NotificationRepository.Entry(emailaccount).State = System.Data.Entity.EntityState.Modified; } List <AppendMsgViewModel> SignalRAppend = new List <AppendMsgViewModel>(); foreach (var cond in conditions) { if (string.IsNullOrEmpty(cond.TableName) || string.IsNullOrEmpty(cond.ColumnName)) { continue; // can't get required data } if (string.IsNullOrEmpty(cond.Users) && string.IsNullOrEmpty(cond.CustEmail) && !cond.NotifyRef) { continue; // no one to sent } string[] arr = { "Currencies", "SchedualTasks" }; // prepare sql statement var sql = "SELECT " + cond.ColumnName + (Array.Exists(arr, f => f == cond.TableName) ? "" : ",Id") + (string.IsNullOrEmpty(cond.Fields) ? "" : "," + cond.Fields) + " FROM " + cond.TableName + " WHERE " + (cond.filter == null ? "" : (cond.filter.Replace("\"", "'") + " AND ")) + "CAST( " + cond.ColumnName + " as date )= '" + GetNotificationDate(unitofwork, CompanyId, cond.Event, cond.EventValue).ToString("yyyy-MM-dd") + "'"; // dynamic create datatable var table = GetData(sql); if (table.Rows.Count == 0) { continue; // condition doesn't match records } var employees = new List <int>(); if (cond.NotifyRef) { foreach (DataRow row in table.Rows) { if (row.Table.Columns.Contains("EmpId")) { if (row["EmpId"] != null && row["EmpId"].ToString().Length > 0) { employees.Add(int.Parse(row["EmpId"].ToString())); } } } } IList <UserView> users = GetUsers(cond.Users, employees.ToArray <int>()); if (users == null) // no users to send to { continue; } // create notification for each record foreach (DataRow row in table.Rows) { string m = MessageMerge(cond.Message, unitofwork, table, row, cond.TableName, lang); var notify = new Notification { CompanyId = CompanyId, ConditionId = cond.Id, CreationTime = DateTime.Now, EmpId = GetEmpId(row), RefEmpId = GetEmpId(row), Message = MessageMerge(cond.Message, unitofwork, table, row, cond.TableName, lang), Subject = cond.Subject, SourceId = GetId(row) }; foreach (var u in users.Where(a => a.WebNotify)) { WebMobLog log = new WebMobLog { MarkAsRead = false, Message = notify.Message, Notificat = notify, SentTime = DateTime.Now, SentToUser = u.Name, CompanyId = CompanyId, Subject = notify.Subject }; unitofwork.NotificationRepository.Add(log); } SignalRAppend.Add(new AppendMsgViewModel { User = users.Where(a => a.WebNotify).Select(a => a.Name).ToList(), Notify = notify }); var EmailUsers = users.Where(a => a.EmailNotify).ToList(); if (EmailUsers.Count > 0) { SendEmails(unitofwork.NotificationRepository, EmailUsers, notify, ref emailaccount, ref counter, ref modified); } if (cond.Sms) { SendSms(unitofwork.NotificationRepository, users.Where(a => a.SmsNotify).ToList(), notify); } } } unitofwork.SaveChanges(); foreach (var item in SignalRAppend) { Append(item.User, SignalR(item.Notify, item.Notify.EmpId)); } }