public ActionResult Create(FormCollection forms) { try { // TODO: Add insert logic here List<int> Roles = new List<int>(); Models.User user = new Models.User() { CreatedDate= DateTime.Now, Name = forms["Name"], Password = FormsAuthentication.HashPasswordForStoringInConfigFile(forms["Password"], "MD5"), Status= EntityStatuses.Actived.ToString(), UpdatedDate = DateTime.Now, Username = forms["Username"] }; foreach (string key in forms.AllKeys) { if (key.StartsWith("roleid") && forms[key] == "on") { string id = key.Split('_')[1]; Roles.Add(int.Parse(id)); } } UserService.Add(user, Roles); return RedirectToAction("List"); } catch { return View(); } }
public async Task<ActionResult> Post([FromBody]CreateUserRequest request) { if (!ModelState.IsValid) { return HttpBadRequest(); } else { var itemExists = await _context.Users.AnyAsync(i => i.EmailAddress == request.EmailAddress && i.IsDeleted != true); if (itemExists) { return HttpBadRequest(); } User item = new Models.User(); item.UserId = Guid.NewGuid().ToString().Replace("-", ""); item.CreatedOnUtc = DateTime.UtcNow; item.UpdatedOnUtc = DateTime.UtcNow; item.EmailAddress = request.EmailAddress; _context.Users.Add(item); await _context.SaveChangesAsync(); Context.Response.StatusCode = 201; return Ok(); } }
public ActionResult Login(string username,string password) { Models.User user = new Models.User(); AjaxModel ajaxModel = new AjaxModel(); user = db.Users.Where(u => u.Username == username || u.Phone == username).FirstOrDefault(); if (user == null) { ajaxModel.State = "nouser"; return Json(ajaxModel); } else { if (user.Password.Equals(Helper.Encryt.GetMD5(password))) { ajaxModel.State = "ok"; ajaxModel.Values = user; return Json(ajaxModel); } else { ajaxModel.State = "fail"; return Json(ajaxModel); } } }
public AccountService() { m_List = new List<ERPStore.Models.User>(); m_PasswordList = new Dictionary<int, string>(); var user = new Models.User() { Code = "Test", Corporate = null, CreationDate = DateTime.Now, DefaultAddress = AddressesDatas().First(), Email = "*****@*****.**", EmailVerificationStatus = ERPStore.Models.EmailVerificationStatus.UserConfirmed, FaxNumber = "0102030405", FirstName = "Test", Id = 1, IsResetPasswordRequiered = false, LastDeliveredAddress = AddressesDatas().ElementAt(2), LastName = "Test", Login = "******", PhoneNumber = "0102030405", Presentation = ERPStore.Models.UserPresentation.Mister, Roles = { "customer" }, MobileNumber = "0605040302", }; user.DeliveryAddressList.AddRange(AddressesDatas()); m_List.Add(user); m_PasswordList.Add(1, "pass"); }
public ActionResult Register(Models.User regUser) { if (ModelState.IsValid) { using (IDbConnection db = OpenDataBaseConnection()) { string hashedPassword = Crypto.CryptSHA512(regUser.Pass, regUser.Email); Models.User user = new Models.User() { Email = regUser.Email, FirstName = regUser.FirstName, LastName = regUser.LastName, Pass = hashedPassword, Gender = regUser.Gender, University = regUser.University, DateRegistered = DateTime.UtcNow, LastLogin = DateTime.UtcNow, PasswordSalt = regUser.Email, ProfilePicture = "" }; Insert(user); return RedirectToAction("Index", "Home"); } } return View(); }
public async System.Threading.Tasks.Task<List<Models.User>> GetUsers() { try { var results = await ParseUser.Query.FindAsync(); var users = new List<Models.User>(); foreach (var item in results.ToList()) { Models.User user = new Models.User(); user.Username = item.Username; user.Name = item.Get<string>("Name"); user.Email = item.Email; user.ObjectId = item.ObjectId; ParseFile file; item.TryGetValue<ParseFile>("ProfilePicture", out file); user.UserPicture = new CrossFeaturesXamarin.Models.File(); user.UserPicture.Name = file.Name; user.UserPicture.Url = file.Url.ToString(); users.Add(user); } return users; } catch (Exception) { return null; } }
public ActionResult Login(string username,string password) { AjaxModel ajaxModel = new AjaxModel(); Models.User user = new Models.User(); try { password = Helpers.Encryt.GetMD5(password); user = db.Users.Where(u => u.Number == username && u.Password == password).FirstOrDefault(); if (user != null) { ajaxModel.Statu = "ok"; ajaxModel.Msg = "登陆成功"; ajaxModel.Data = user; } else { ajaxModel.Statu = "err"; ajaxModel.Msg = "用户名或者密码错误!"; } } catch { ajaxModel.Statu = "err"; ajaxModel.Msg = "登陆异常"; } return Json(ajaxModel,JsonRequestBehavior.AllowGet); }
public ActionResult Create(FormCollection form) { try { if (form["Password"] != form["ConfirmPassword"]) ModelState.AddModelError("", "The supplied passwords do not match"); if (form["Password"].Length < 6) ModelState.AddModelError("Password", "Your password must be at least 6 characters"); Models.User user = new Models.User(); UpdateModel(user); if (!ModelState.IsValid) throw new InvalidOperationException("Input failed model validation"); user.Save(); foreach (string permission in form["permission"].Split(',')) user.AddPermission(permission); return RedirectToAction("Index"); } catch { ViewData["PermissionList"] = Models.Permission.SelectAll().Select(o => o.PermissionId); return View(); } }
private ActionResult OnLogin(bool isReadOnly) { Models.User u = new Models.User(); u.ReadOnly = isReadOnly; GlobalData.CurrentUser = u; return new RedirectResult("~/Employee"); }
//проверка авторизации на основе сессии public String CheckAuth() { try { if (Session["login"] == null | Session["password"] == null) return "0"; String login = Session["login"].ToString(); String password = Session["password"].ToString(); if (password != "" && login != "" && password != null && login != null) { String id_user; Models.User usr = new Models.User(); id_user = usr.doLogin(login, password); if (id_user != "") { Session["user_id"] = id_user; Session["login"] = login; Session["password"] = password; return "1"; } } return "0"; } catch { return "0"; } }
private IEnumerable<Models.User> MockGetUsers() { List<Models.User> users = new List<Models.User>(); Models.User user1 = new Models.User() { Id = 1, FirstName = "Shubh", LastName = "Dasgupta", DOB = "06/02/1986", Others = "NA" }; Models.User user2 = new Models.User() { Id = 2, FirstName = "Neeraj", LastName = "Mude", DOB = "06/02/1986", Others = "NA" }; Models.User user3 = new Models.User() { Id = 3, FirstName = "Abhijit", LastName = "J", DOB = "06/02/1986", Others = "NA" }; users.Add(user1); users.Add(user2); users.Add(user3); return users; }
// авторизация через веб-форму public String doAuth(String login, String password) { try { String id_user; if (login == null) return "0"; if (password == null) return "0"; Models.User usr = new Models.User(); if (password != "" && login != "") { id_user = usr.doLogin(login, password); if (id_user != "") { Session["user_id"] = id_user; Session["login"] = login; Session["password"] = password; return "1"; } } return "0"; } catch { return "0"; } }
public async Task<Models.User> Get(string login) { GitHubClient github = GitHubHelper.GetClient(); Octokit.User userBase = await github.User.Get(login); Models.User user = new Models.User(userBase); return user; }
public void AddFaction(Faction fan, User user) { using (LdxyDBEntities dbcontext = new LdxyDBEntities()) { fan.CreateTime = DateTime.Now; dbcontext.Factions.AddObject(fan); dbcontext.SaveChanges(); User us = new Models.User() { UserName = "******", Name = user.Name, Password = "******", RoleID = 1, CreateTime = DateTime.Now, Type = (int)UserType.帮派玩家, FanctionID = fan.FactionID, UserID = user.OUserID, State = 0, }; dbcontext.Users.AddObject(us); dbcontext.SaveChanges(); UserRole urole = new UserRole() { FanctionID = fan.FactionID, OUserID = us.OUserID, RoleID = (int)RoleEnum.帮主, }; dbcontext.UserRoles.AddObject(urole); dbcontext.SaveChanges(); } }
public ActionResult MakeAdmin(string userName) { _user = _user.Load(userName); _user.AddUserToRole(UserRole.Admin); _user.RemoveUserFromRole(UserRole.User); return RedirectToAction("List"); }
//mapper to convert from viewmodel to domain model public static Models.User MapUserAddEditToUser(UserAddEdit useraddedit) { var user = new Models.User(); user.Id = useraddedit.Id; user.Age = useraddedit.Age; user.FirstName = useraddedit.FirstName; user.LastName = useraddedit.LastName; return user; }
public Models.User AddNewUser(string providerKey, string email) { var u = new Models.User(); u.ProviderKey = providerKey; u.Email = email; _provider.Save(u); return u; }
/// <summary> /// 注销登录 /// </summary> public static void LoginOut() { User = null; var objCookie = new HttpCookie("mInfo"); var ts = new TimeSpan(-1, 0, 0, 0); objCookie.Expires = DateTime.Now.Add(ts); HttpContext.Current.Response.AppendCookie(objCookie); JsHelper.ParentRedirect(StaticResource.UserLoginUrl); }
public ActionResult Create(UserAccount accountToCreate) { if (ModelState.IsValid) { // If the accountToCreate object is valid // we'll need to save it in a database Catalogue.Models.CatalogueDBEntities userAccounts = new Models.CatalogueDBEntities(); userAccounts.Database.CreateIfNotExists(); if (userAccounts.Users.Count<Models.User>() > 0) foreach( Models.User user in userAccounts.Users) { if(string.Compare(accountToCreate.UserName.ToLower(), user.UserName.ToLower()) == 0) { ViewBag.Error = "Username already exists"; return View(accountToCreate); } } Models.User newUser = new Models.User(); newUser.UserName = accountToCreate.UserName; newUser.Email = accountToCreate.Email; newUser.UserID = userAccounts.Users.Count<Models.User>() + 1; SHA512 encryption = SHA512CryptoServiceProvider.Create(); byte[] data = new byte[accountToCreate.Password.Length]; byte[] result; for(int i = 0; i < accountToCreate.Password.Length; i++) data[i] = (byte)accountToCreate.Password[i]; result = encryption.ComputeHash(data); string newString = ""; for (int i = 0; i < result.Length; i++) newString += String.Format("{0:X2}", result[i]); newUser.Password = newString; userAccounts.Users.Add(newUser); userAccounts.SaveChanges(); // After saving we'll redirect the user back to Login's Index page return Redirect("/"); } // Invalid -- redisplay form with errors return View(accountToCreate); }
/// <summary> /// 用户登录 /// </summary> /// <param name="loginId">登录ID</param> /// <param name="password">登录密码</param> public static void LoginUser(string loginId, string password) { var userTemp = new Models.User { LoginResult = false }; var webUserDal = new WebUserDal(); var webUser = webUserDal.GetUserByLoginIdAndPassword(loginId, password); if (webUser != null) { System.Web.Security.FormsAuthentication.SetAuthCookie("Login", false); userTemp.Id = webUser.ID; userTemp.LoginId = webUser.LoginID; userTemp.Password = webUser.Password; userTemp.LoginResult = true; User = userTemp; //记录登录Cookie var objCookie = new HttpCookie("mInfo"); objCookie.Values.Add("i", RsaCryption.RsaEncrypt(userTemp.LoginId)); objCookie.Values.Add("p", RsaCryption.RsaEncrypt(userTemp.Password)); objCookie.Values.Add("tm", RsaCryption.RsaEncrypt(DateTime.Now.ToString(CultureInfo.InvariantCulture))); objCookie.Expires = DateTime.Now.AddMinutes(60); objCookie.Path = "/"; ////设置作用域 常用语跨域 //if (HttpContext.Current.Request.Url.Host.ToLower() != "localhost") //{ // objCookie.Domain = ValueConfig.DefaultHost; //} objCookie.HttpOnly = true; objCookie.Secure = false; HttpContext.Current.Response.Cookies.Set(objCookie); //检测用户主文件夹 var path = AppDomain.CurrentDomain.BaseDirectory + StaticResource.WebsFolder; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //检测用户文件夹 path += "\\" + User.LoginId; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } else { User = new Models.User { LoginResult = false }; } }
public ActionResult Enter(FormCollection collection) { ViewData["configRetry"] = Convert.ToInt32(ConfigurationManager.AppSettings.Get("LoginAttempts")); Models.User user = new Models.User(); Models.Login loginState = new Models.Login(); string username = collection["Username"]; string password = collection["Password"]; user = _userRepository.GetUserByID(username); loginState = _loginRepository.GetLoginByID(username); // if user or it's loginstate is null - user is not found. if (user == null || loginState == null) { ViewData["NotFound"] = "User not found"; } else { //if unlocked - log in if (!user.IsManuallyLocked) { //login attempt - if succeded - singout current logged in user //remove loginattempt tempdata //set auth cookie for new login. //set attempt cookie to an empty string //refirect to main page. if (user.Password == password) { FormsAuthentication.SignOut(); _loginRepository.SetSuccessLogin(loginState); TempData["loginAttempt"] = null; FormsAuthentication.SetAuthCookie(username, true); HttpContext.Response.Cookies["logintry_" + user.Username].Value = ""; return RedirectToRoute(new { controller = "Default", action = "Index", userId = username }); } } else //if unlocked - can't log in until unlocked by Admin { TempData["IsManuallyLocked"] = "you are locked by the admin !"; } } return View("index"); }
public ActionResult Delete(string id, FormCollection collection) { try { Models.User user = new Models.User(id); user.Delete(); return RedirectToAction("Index"); } catch { return View(new Models.User(id)); } }
public async Task<IActionResult> DeleteUser(int id) { User user = new Models.User(); user = await UserManager.FindByIdAsync(id.ToString()); List<IdentityUserRole<long>> roles = new List<IdentityUserRole<long>>(); roles = DB.UserRoles.Where(x => x.UserId == id).ToList(); foreach (var item in roles) { DB.UserRoles.Remove(item); } DB.SaveChanges(); await UserManager.DeleteAsync(user); return Content("ok"); }
Models.User BuildUser(int id, string first, string last) { var user = new Models.User { FirstName = first, LastName = last, Birth = DateTime.Now.Subtract(TimeSpan.FromDays(_random.Next(19, 40) * 365)), Email = $"{last}@domain.com", IsAdmin = id % 3 == 0, Validator = ValidateUser }; user.Validate(); return user; }
public async Task<IActionResult> Add(string Role, string Username, string Password) { try { User user = new Models.User(); user.UserName = Username; await UserManager.CreateAsync(user, Password); await UserManager.AddToRoleAsync(user, Role); return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult Details(string password, string confirmPassword) { if (password != confirmPassword) ModelState.AddModelError("", "The supplied passwords do not match"); if (password.Length < 6) ModelState.AddModelError("Password", "Your password must be at least 6 characters"); if (ModelState.IsValid) { Models.User user = new Models.User(User.Identity.Name); user.Password = password; user.Save(); } return View(); }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); if (User.Identity.IsAuthenticated) { CurrentUser = (from u in db.Users where u.UserName == User.Identity.Name select u).SingleOrDefault(); ViewBag.CurrentUser = CurrentUser; } else { ViewBag.CurrentUser = null; } ViewBag.SID = requestContext.HttpContext.Session["SID"].ToString(); }
public void LogActivity() { var userActivityService = new Gambit.Services.UserActivity(); var userService = new Gambit.Services.User(); var user = new Models.User() { }; var result = userService.Create(user); var userActivity = new Gambit.Models.UserActivity(); userActivityService.RecordUserActivity(userActivity); }
// GET: SetupSignUp public ActionResult SignUp() { if (TempData["status"] != null) { if (TempData["status"].ToString() == "success") ViewBag.SuccessMsg = "Your profile Successfully created."; else if (TempData["status"].ToString() == "fail") ViewBag.ErrorMsg = "Failed to Sign up try again!"; else if (TempData["status"].ToString() == "captchaFail") { ViewBag.ErrorMsg = "Entered Security Code is Not Correct!"; User user = new Models.User(); user = (User)TempData["ErrorModel"]; return View(user); } } return View(); }
public ActionResult Detail(string uid) { User model = null; if (uid == null) return HttpNotFound(); int decodedUid; if(Int32.TryParse(uid, out decodedUid)) { model = new Models.User { Uid = decodedUid, Name = "neko" }; } if (model == null) return HttpNotFound(); return View(model); }
public Tuple <int, int> CreateNewUser(Models.User user, int eventCode) { int last_inserted_id = 0; response_message = ""; try { MySqlConnection cn = new MySqlConnection(@"DataSource=localhost;Initial Catalog=luckydraw;User Id=root;Password=''"); cn.Open(); MySqlCommand cmd = cn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = String.Format("INSERT INTO user(Name, ICNumber, EmailAddress, ContactNumber, EventID, ProjectID, Unit, SalesConsultant, PrizeWon) VALUES (@name, @ic, @email, @contact, @eventID, @projectID, @unit, @salesconsultant, @prizewon); SELECT LAST_INSERT_ID() AS id;"); cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = user.Name.ToUpper(); cmd.Parameters.Add("@ic", MySqlDbType.VarChar).Value = user.ICNumber; cmd.Parameters.Add("@email", MySqlDbType.VarChar).Value = user.EmailAddress.ToLower(); cmd.Parameters.Add("@contact", MySqlDbType.VarChar).Value = user.ContactNumber; cmd.Parameters.Add("@eventID", MySqlDbType.Int32).Value = eventCode; cmd.Parameters.Add("@projectID", MySqlDbType.Int32).Value = user.ProjectID; cmd.Parameters.Add("@unit", MySqlDbType.VarChar).Value = user.Unit.ToUpper(); cmd.Parameters.Add("@salesconsultant", MySqlDbType.VarChar).Value = user.SalesConsultant.ToUpper(); cmd.Parameters.Add("@prizewon", MySqlDbType.Int16).Value = 0; MySqlDataReader rd = cmd.ExecuteReader(); while (rd.Read()) { last_inserted_id = Convert.ToInt32(rd["id"]); } rd.Close(); cmd.Dispose(); cn.Close(); } catch (Exception e) { response_message = e.Message; } try { MySqlConnection cn1 = new MySqlConnection(@"DataSource=localhost;Initial Catalog=luckydraw;User Id=root;Password=''"); cn1.Open(); MySqlCommand cmd1 = cn1.CreateCommand(); cmd1.CommandType = CommandType.Text; cmd1.CommandText = String.Format("UPDATE project SET NoOfProject= NoOfProject + 1 WHERE ProjectID = @projectID"); cmd1.Parameters.Add("@projectID", MySqlDbType.Int32).Value = user.ProjectID; MySqlDataReader rd1 = cmd1.ExecuteReader(); rd1.Close(); cmd1.Dispose(); cn1.Close(); } catch (Exception e) { response_message = e.Message; } return(CheckForLuckyDraw(user, last_inserted_id)); }
/// <summary> /// Pull the repository and compile for every set of given <paramref name="minutes"/> /// </summary> /// <param name="minutes">How many minutes the operation should repeat. Does not include running time</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param> /// <returns>A <see cref="Task"/> representing the running operation</returns> async Task TimerLoop(uint minutes, CancellationToken cancellationToken) { while (true) { try { await Task.Delay(TimeSpan.FromMinutes(minutes > Int32.MaxValue ? Int32.MaxValue : (int)minutes), cancellationToken).ConfigureAwait(false); logger.LogDebug("Beginning auto update..."); await eventConsumer.HandleEvent(EventType.InstanceAutoUpdateStart, new List <string>(), cancellationToken).ConfigureAwait(false); try { Models.User user = null; await databaseContextFactory.UseContext(async (db) => user = await db.Users.Where(x => x.CanonicalName == Api.Models.User.AdminName.ToUpperInvariant()).FirstAsync(cancellationToken).ConfigureAwait(false)).ConfigureAwait(false); var repositoryUpdateJob = new Job { Instance = new Models.Instance { Id = metadata.Id }, Description = "Scheduled repository update", CancelRightsType = RightsType.Repository, CancelRight = (ulong)RepositoryRights.CancelPendingChanges, StartedBy = user }; string deploySha = null; await jobManager.RegisterOperation(repositoryUpdateJob, async (paramJob, databaseContext, progressReporter, jobCancellationToken) => { var repositorySettingsTask = databaseContext.RepositorySettings.Where(x => x.InstanceId == metadata.Id).FirstAsync(jobCancellationToken); //assume 5 steps with synchronize const int ProgressSections = 7; const int ProgressStep = 100 / ProgressSections; const int NumSteps = 3; var doneSteps = 0; Action <int> NextProgressReporter() { var tmpDoneSteps = doneSteps; ++doneSteps; return(progress => progressReporter((progress + 100 * tmpDoneSteps) / NumSteps)); }; using (var repo = await RepositoryManager.LoadRepository(jobCancellationToken).ConfigureAwait(false)) { if (repo == null) { logger.LogTrace("Aborting repo update, no repository!"); return; } var startSha = repo.Head; if (!repo.Tracking) { logger.LogTrace("Aborting repo update, not tracking origin!"); deploySha = startSha; return; } var repositorySettings = await repositorySettingsTask.ConfigureAwait(false); //the main point of auto update is to pull the remote await repo.FetchOrigin(repositorySettings.AccessUser, repositorySettings.AccessToken, NextProgressReporter(), jobCancellationToken).ConfigureAwait(false); RevisionInformation currentRevInfo = null; bool hasDbChanges = false; Task <RevisionInformation> LoadRevInfo() => databaseContext.RevisionInformations .Where(x => x.CommitSha == startSha && x.Instance.Id == metadata.Id) .Include(x => x.ActiveTestMerges).ThenInclude(x => x.TestMerge) .FirstOrDefaultAsync(cancellationToken); async Task UpdateRevInfo(string currentHead, bool onOrigin) { if (currentRevInfo == null) { currentRevInfo = await LoadRevInfo().ConfigureAwait(false); } if (currentRevInfo == default) { logger.LogWarning(Repository.Repository.OriginTrackingErrorTemplate, currentHead); onOrigin = true; } var attachedInstance = new Models.Instance { Id = metadata.Id }; var oldRevInfo = currentRevInfo; currentRevInfo = new RevisionInformation { CommitSha = currentHead, OriginCommitSha = onOrigin ? currentHead : oldRevInfo.OriginCommitSha, Instance = attachedInstance }; if (!onOrigin) { currentRevInfo.ActiveTestMerges = new List <RevInfoTestMerge>(oldRevInfo.ActiveTestMerges); } databaseContext.Instances.Attach(attachedInstance); databaseContext.RevisionInformations.Add(currentRevInfo); hasDbChanges = true; } //take appropriate auto update actions bool shouldSyncTracked; if (repositorySettings.AutoUpdatesKeepTestMerges.Value) { logger.LogTrace("Preserving test merges..."); var currentRevInfoTask = LoadRevInfo(); var result = await repo.MergeOrigin(repositorySettings.CommitterName, repositorySettings.CommitterEmail, NextProgressReporter(), jobCancellationToken).ConfigureAwait(false); if (!result.HasValue) { throw new JobException("Merge conflict while preserving test merges!"); } currentRevInfo = await currentRevInfoTask.ConfigureAwait(false); var lastRevInfoWasOriginCommit = currentRevInfo == default || currentRevInfo.CommitSha == currentRevInfo.OriginCommitSha; var stillOnOrigin = result.Value && lastRevInfoWasOriginCommit; var currentHead = repo.Head; if (currentHead != startSha) { await UpdateRevInfo(currentHead, stillOnOrigin).ConfigureAwait(false); shouldSyncTracked = stillOnOrigin; } else { shouldSyncTracked = false; } } else { logger.LogTrace("Not preserving test merges..."); await repo.ResetToOrigin(NextProgressReporter(), jobCancellationToken).ConfigureAwait(false); var currentHead = repo.Head; currentRevInfo = await databaseContext.RevisionInformations .Where(x => x.CommitSha == currentHead && x.Instance.Id == metadata.Id) .FirstOrDefaultAsync(jobCancellationToken).ConfigureAwait(false); if (currentHead != startSha && currentRevInfo != default) { await UpdateRevInfo(currentHead, true).ConfigureAwait(false); } shouldSyncTracked = true; } //synch if necessary if (repositorySettings.AutoUpdatesSynchronize.Value && startSha != repo.Head) { var pushedOrigin = await repo.Sychronize(repositorySettings.AccessUser, repositorySettings.AccessToken, repositorySettings.CommitterName, repositorySettings.CommitterEmail, NextProgressReporter(), shouldSyncTracked, jobCancellationToken).ConfigureAwait(false); var currentHead = repo.Head; if (currentHead != currentRevInfo.CommitSha) { await UpdateRevInfo(currentHead, pushedOrigin).ConfigureAwait(false); } } if (hasDbChanges) { try { await databaseContext.Save(cancellationToken).ConfigureAwait(false); } catch { await repo.ResetToSha(startSha, progressReporter, default).ConfigureAwait(false); throw; } } progressReporter(5 * ProgressStep); deploySha = repo.Head; } }, cancellationToken).ConfigureAwait(false); await jobManager.WaitForJobCompletion(repositoryUpdateJob, user, cancellationToken, default).ConfigureAwait(false); if (deploySha == null) { logger.LogTrace("Aborting auto update, repository error!"); continue; } if (deploySha == LatestCompileJob()?.RevisionInformation.CommitSha) { logger.LogTrace("Aborting auto update, same revision as latest CompileJob"); continue; } //finally set up the job var compileProcessJob = new Job { StartedBy = user, Instance = repositoryUpdateJob.Instance, Description = "Scheduled code deployment", CancelRightsType = RightsType.DreamMaker, CancelRight = (ulong)DreamMakerRights.CancelCompile }; await jobManager.RegisterOperation(compileProcessJob, CompileProcess, cancellationToken).ConfigureAwait(false); await jobManager.WaitForJobCompletion(compileProcessJob, user, cancellationToken, default).ConfigureAwait(false); } catch (OperationCanceledException) { logger.LogDebug("Cancelled auto update job!"); throw; } catch (Exception e) { logger.LogWarning("Error in auto update loop! Exception: {0}", e); continue; } } catch (OperationCanceledException) { break; } } logger.LogTrace("Leaving auto update loop..."); }
public List <Models.User> CreateUserEntity() { Models.User sampleUser = new Models.User { Id = Guid.NewGuid().ToString(), CustomerId = _currentCustomer.Id, UserName = "******", FirstName = "Jeff", LastName = "Luckett", EmailAddress = "*****@*****.**", LastSignInDateTime = DateTime.Now.AddMinutes(-13), RegistrationStatus = "active", // inactive, pending approval RegistrationDateTime = DateTime.Now.AddDays(-25), ApprovedByAccount = "SysAdmin", Created = DateTime.Now, CreatedBy = "Rob.Wenc", Phones = new Phone[] { new Phone { PhoneType = "Cell", PhoneNumber = "(312) 555-1234", isPreferred = false }, new Phone { PhoneType = "Office", PhoneNumber = "(708) 555-4321", isPreferred = true } }, LocationIds = new UserToLocation[] { new UserToLocation { LocationId = _currentCustomer.Locations[0].LocationId, Roles = new UserRole[] { new UserRole { Role = "Admin" }, new UserRole { Role = "Yard" } } }, new UserToLocation { LocationId = _currentCustomer.Locations[1].LocationId, Roles = new UserRole[] { new UserRole { Role = "Admin" } } } } }; List <Models.User> sampleUsers = new List <Models.User>(); sampleUsers.Add(sampleUser); // User #2... sampleUser = new Models.User { Id = Guid.NewGuid().ToString(), CustomerId = _currentCustomer.Id, UserName = "******", FirstName = "Jeff", LastName = "Lechowicz", EmailAddress = "*****@*****.**", LastSignInDateTime = DateTime.Now.AddMinutes(-9), RegistrationStatus = "active", // inactive, pending approval RegistrationDateTime = DateTime.Now.AddDays(-5), ApprovedByAccount = "Jeff.Luckett", Created = DateTime.Now, CreatedBy = "Rob.Wenc", Phones = new Phone[] { new Phone { PhoneType = "Cell", PhoneNumber = "(312) 555-2222", isPreferred = true } }, LocationIds = new UserToLocation[] { new UserToLocation { LocationId = _currentCustomer.Locations[0].LocationId, Roles = new UserRole[] { new UserRole { Role = "Developer" } } } } }; sampleUsers.Add(sampleUser); return(sampleUsers); }
public ActionResult Index(Models.User user) { throw new NotImplementedException(); }
public ConversionWindow(Models.User user) { InitializeComponent(); DataContext = new ViewModels.ConversionViewModel(this, user); }
public ActionResult userRegister(RegisterViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var users = db.Users.ToList(); bool IsExistUserName = false; bool IsExistEmail = false; try { foreach (var item in users) { if (model.UserName == item.UserName) { IsExistUserName = true; } if (model.Email == item.Email) { IsExistEmail = true; } } if (IsExistUserName == false) { if (IsExistEmail == false) { User user = new Models.User(); user.UserName = model.UserName; user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "md5"); user.CreatedDate = DateTime.Now; user.Status = true; user.Email = model.Email; user.ConfirmedEmail = false; user.Ip = GetClientIp(); db.Users.InsertOnSubmit(user); db.SubmitChanges(); MailMessage m = new MailMessage( new MailAddress("*****@*****.**", "Web Registration"), new MailAddress(user.Email)); m.Subject = "Email Doğrulama"; m.Body = string.Format("Sevgili {0}<BR/>Kaydınız için Teşekkür Ederiz, Kaydınızı Tamamlamak için Lütfen Aşağıdaki Linki Tıklayınız: <a href=\"{1}\" title=\"Kullanıcı EPosta Onaylama\">{1}</a>", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.UserName, Email = user.Email }, Request.Url.Scheme)); m.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = "******", Password = "******" }; smtp.Credentials = credential; smtp.Host = "smtp.live.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.Send(m); } return(RedirectToAction("Confirm", "Account", new { Email = user.Email })); } else { return(RedirectToAction("ResetPassword", "Account", new { ExistedUser = true })); } } else { ModelState.AddModelError("", "Lütfen Farklı Bir Kullanıcı Adı Belirleyiniz"); return(View(model)); } } catch (Exception ex) { return(Content(GetErrorMessage(ex))); } }
public async Task <IActionResult> OnPostAsync() { if (User.Identity.IsAuthenticated) { if (ModelState.IsValid) { NewUser.EmailID = NewUser.EmailID.ToLower(); Models.User user = await userDbContext.Users.SingleOrDefaultAsync(m => m.EmailID == NewUser.EmailID); if (user == null) { Profile newProfile = new Profile() { LoginEmailID = NewUser.EmailID, FullName = NewUser.FullName, Designation = String.Empty, Department = String.Empty, College = String.Empty, EmailID = String.Empty, MobileNumber = String.Empty, GoogleScholarLink = String.Empty, UnderGraduateDegreeDetails = String.Empty, PostGraduateDegreeDetails = String.Empty, DoctoratesDegreeDetails = String.Empty, AreasOfInterest = String.Empty, Achievements = String.Empty, ShortBio = String.Empty, ProfilePic = String.Empty, ProfessionalExperience = String.Empty }; await profileDbContext.Profiles.AddAsync(newProfile); await userDbContext.Users.AddAsync(NewUser); await profileDbContext.SaveChangesAsync(); await userDbContext.SaveChangesAsync(); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); var claims = new List <Claim> { new Claim(ClaimTypes.Name, NewUser.FullName), new Claim(ClaimTypes.Email, NewUser.EmailID), }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(1) }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(RedirectToPage("/EditProfile")); } else { ModelState.AddModelError(String.Empty, "Email ID already Registered"); return(Page()); } } else { return(Page()); } } else { return(RedirectToPage("/Index")); } }
public JwtPacket Register([FromBody] Models.User user) { context.users.Add(user); context.SaveChanges(); return(CreateJwtPacket(user)); }
public static void SetCurrentUser( this System.Web.SessionState.HttpSessionState state, Models.User user) { state["CurrentUser"] = user == null ? null : (Guid?)user.Guid; }
/// <summary> /// The method to get user by id from database. /// </summary> /// <param name="login"> Login of requested user. </param> /// <returns> Variable of the User model type. </returns> public Models.User GetUser(string login) { Models.User result = Collection.Find(item => item.login == login).First(); return(result); }
public async Task <IActionResult> Register(RegisterViewModel register) { //var recaptcha = await _recaptcha.Validate(Request); //if (!recaptcha.success) //{ // ModelState.AddModelError("Recaptcha", "There was an error validating recatpcha. Please try again!"); // return View(!ModelState.IsValid ? register : new RegisterViewModel()); //} if (ModelState.IsValid) { VerifyEmailViewModel verifyEmailAddress = new VerifyEmailViewModel(); var result = await _repository.AddUserAsync(register, "Participant", _userManager, _signInManager); if (result == "added" || result.Contains("verify")) { Models.User user = null; switch (result) { case "verify username": user = await _userManager.FindByNameAsync(register.Username); break; case "verify email": user = await _userManager.FindByEmailAsync(register.Email); break; case "added": user = await _userManager.FindByEmailAsync(register.Email); break; } verifyEmailAddress.Email = register.Email; return(View("VerifyEmail", verifyEmailAddress)); } else { switch (result) { case "both exist": ModelState.AddModelError("Email", "Email Not Available"); ModelState.AddModelError("Username", "Username Not Available"); break; case "username exists": ModelState.AddModelError("Username", "Username Not Available"); break; case "email exists": ModelState.AddModelError("Email", "Email Not Available"); break; } } return(View()); } return(View()); }
/// Return value = number of records affected. public static int UpdateUnit(Models.User o) { if (o == null) { return(-1); } string sql = "UPDATE Users SET LoginName=@LoginName,DisplayName=@DisplayName,IsDisabled=@IsDisabled,UpdatedDt=@UpdatedDt,UpdatedBy=@UpdatedBy,Description=@Description" + (o.IsUpdateHash ? ",Hash=@Hash,Password=@Password" : "") + " WHERE UserId=@UserId"; List <SqlParameter> list = null; List <System.Data.SQLite.SQLiteParameter> list2 = null; try { if (DbHandler.IsMssqlConnected) { list = new List <SqlParameter>() { new SqlParameter("@UserId", SqlDbType.Int) { Value = o.UserId }, new SqlParameter("@LoginName", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.LoginName) }, new SqlParameter("@DisplayName", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.DisplayName) }, new SqlParameter("@IsDisabled", SqlDbType.Bit) { Value = o.IsDisabled }, new SqlParameter("@UpdatedDt", SqlDbType.DateTime) { Value = o.UpdatedDt }, new SqlParameter("@UpdatedBy", SqlDbType.Int) { Value = o.UpdatedBy }, new SqlParameter("@Description", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.Description) } }; if (o.IsUpdateHash) { list.Add(new SqlParameter("@Hash", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.Hash) }); list.Add(new SqlParameter("@Password", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.Password) }); } return(DbHandler.MSSQL.ExecuteNonQuery(sql, list.ToArray())); } else { list2 = new List <System.Data.SQLite.SQLiteParameter>() { new System.Data.SQLite.SQLiteParameter("@UserId", DbType.Int32) { Value = o.UserId }, new System.Data.SQLite.SQLiteParameter("@LoginName", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.LoginName) }, new System.Data.SQLite.SQLiteParameter("@DisplayName", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.DisplayName) }, new System.Data.SQLite.SQLiteParameter("@IsDisabled", DbType.Boolean) { Value = o.IsDisabled }, new System.Data.SQLite.SQLiteParameter("@UpdatedDt", DbType.DateTime) { Value = o.UpdatedDt }, new System.Data.SQLite.SQLiteParameter("@UpdatedBy", DbType.Int32) { Value = o.UpdatedBy }, new System.Data.SQLite.SQLiteParameter("@Description", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.Description) } }; if (o.IsUpdateHash) { list2.Add(new System.Data.SQLite.SQLiteParameter("@Hash", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.Hash) }); list2.Add(new System.Data.SQLite.SQLiteParameter("@Password", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.Password) }); } return(DbHandler.SQLite.ExecuteNonQuery(sql, list2.ToArray())); } } finally { if (list != null) { list.Clear(); list = null; } if (list2 != null) { list2.Clear(); list2 = null; } } }
public static int InsertUnit(Models.User o) { if (o == null) { return(-1); } string sql = "INSERT INTO Users (LoginName,DisplayName,Hash,Password,IsDisabled,CreatedDt,CreatedBy,UpdatedDt,UpdatedBy,Description) VALUES (@LoginName,@DisplayName,@Hash,@Password,@IsDisabled,@UpdatedDt,@UpdatedBy,@UpdatedDt,@UpdatedBy,@Description)"; return(DbHandler.IsMssqlConnected ? DbHandler.MSSQL.ExecuteNonQuery(sql, new SqlParameter("@LoginName", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.LoginName) }, new SqlParameter("@DisplayName", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.DisplayName) }, new SqlParameter("@Hash", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.Hash) }, new SqlParameter("@Password", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.Password) }, new SqlParameter("@IsDisabled", SqlDbType.Bit) { Value = o.IsDisabled }, new SqlParameter("@UpdatedDt", SqlDbType.DateTime) { Value = o.UpdatedDt }, new SqlParameter("@UpdatedBy", SqlDbType.Int) { Value = o.UpdatedBy }, new SqlParameter("@Description", SqlDbType.VarChar) { Value = DbHandler.GetObjectToDb(o.Description) }): DbHandler.SQLite.ExecuteNonQuery(sql, new System.Data.SQLite.SQLiteParameter("@LoginName", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.LoginName) }, new System.Data.SQLite.SQLiteParameter("@DisplayName", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.DisplayName) }, new System.Data.SQLite.SQLiteParameter("@Hash", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.Hash) }, new System.Data.SQLite.SQLiteParameter("@Password", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.Password) }, new System.Data.SQLite.SQLiteParameter("@IsDisabled", DbType.Boolean) { Value = o.IsDisabled }, new System.Data.SQLite.SQLiteParameter("@UpdatedDt", DbType.DateTime) { Value = o.UpdatedDt }, new System.Data.SQLite.SQLiteParameter("@UpdatedBy", DbType.Int32) { Value = o.UpdatedBy }, new System.Data.SQLite.SQLiteParameter("@Description", DbType.AnsiString) { Value = DbHandler.GetObjectToDb(o.Description) })); }
//private static readonly String apiBaseUrl = "http://*****:*****@trifork.com" }, { "Name", "Driving Notifier App" } } }, { "To", new JArray { new JObject { { "Email", user.Email }, { "Name", user.Email } } } }, { "Subject", "Reset Password: Driving Notifier App" }, { "TemplateLanguage", true }, { "HTMLPart", @"<!doctype html> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office'> <head> <title>Someone wants to add you!</title> <!--[if !mso]><!-- --> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <!--<![endif]--> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <style type='text/css'> #outlook a { padding: 0; } .ReadMsgBody { width: 100%; } .ExternalClass { width: 100%; } .ExternalClass * { line-height:100%; } body { margin: 0; padding: 0; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } table, td { border-collapse:collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; } img { border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; } p { display: block; margin: 13px 0; } </style> <!--[if !mso]><!--> <style type='text/css'> @media only screen and (max-width:480px) { @-ms-viewport { width:320px; } @viewport { width:320px; } } </style> <!--<![endif]--> <!--[if mso]> <xml> <o:OfficeDocumentSettings> <o:AllowPNG/> <o:PixelsPerInch>96</o:PixelsPerInch> </o:OfficeDocumentSettings> </xml> <![endif]--> <!--[if lte mso 11]> <style type='text/css'> .outlook-group-fix { width:100% !important; } </style> <![endif]--> <style type='text/css'> @media only screen and (min-width:480px) { .mj-column-per-100 { width:100%!important; } } </style> </head> <body style='background: #F4F4F4;'> <div class='mj-container' style='background-color:#F4F4F4;'><!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0' width='600' align='center' style='width:600px;'> <tr> <td style='line-height:0px;font-size:0px;mso-line-height-rule:exactly;'> <![endif]--><div style='margin:0px auto;max-width:600px;'><table role='presentation' cellpadding='0' cellspacing='0' style='font-size:0px;width:100%;' align='center' border='0'><tbody><tr><td style='text-align:center;vertical-align:top;direction:ltr;font-size:0px;padding:20px 0px;padding-bottom:0px;padding-top:0px;'><!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0'> <tr> <td style='vertical-align:top;width:600px;'> <![endif]--><div class='mj-column-per-100 outlook-group-fix' style='vertical-align:top;display:inline-block;direction:ltr;font-size:13px;text-align:left;width:100%;'><table role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'><tbody><tr><td style='word-wrap:break-word;font-size:0px;padding:10px 25px;padding-top:0px;padding-bottom:0px;padding-right:0px;padding-left:0px;' align='center'><table role='presentation' cellpadding='0' cellspacing='0' style='border-collapse:collapse;border-spacing:0px;' align='center' border='0'><tbody><tr><td style='width:577px;'><img alt=' title=' height='auto' src='http://90p1.mjt.lu/tplimg/90p1/b/6vm8/1hks.jpeg' style='border:none;border-radius:;display:block;font-size:13px;outline:none;text-decoration:none;width:100%;height:auto;' width='577'></td></tr></tbody></table></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--> <!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0' width='600' align='center' style='width:600px;'> <tr> <td style='line-height:0px;font-size:0px;mso-line-height-rule:exactly;'> <![endif]--><div style='margin:0px auto;max-width:600px;background:#ffffff;'><table role='presentation' cellpadding='0' cellspacing='0' style='font-size:0px;width:100%;background:#ffffff;' align='center' border='0'><tbody><tr><td style='text-align:center;vertical-align:top;direction:ltr;font-size:0px;padding:20px 0px 20px 0px;'><!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0'> <tr> <td style='vertical-align:top;width:600px;'> <![endif]--><div class='mj-column-per-100 outlook-group-fix' style='vertical-align:top;display:inline-block;direction:ltr;font-size:13px;text-align:left;width:100%;'><table role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'><tbody><tr><td style='word-wrap:break-word;font-size:0px;padding:0px 25px 0px 25px;padding-top:0px;padding-bottom:0px;' align='left'><div style='cursor:auto;color:#55575d;font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;'><h1 style='font-size: 20px; font-weight: bold;'> Driving Notifier App: Password Reset</h1></div></td></tr><tr><td style='word-wrap:break-word;font-size:0px;padding:0px 25px 0px 25px;padding-top:0px;padding-bottom:0px;' align='left'><div style='cursor:auto;color:#55575d;font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;'><p style='font-size: 13px; margin: 10px 0;'>Hello,</p><p style='font-size: 13px; margin: 10px 0;'>We have noticed that you want to reset your password for accessing the App. For doing so, you can use the following code and then update your password:</p></div></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--> <!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0' width='600' align='center' style='width:600px;'> <tr> <td style='line-height:0px;font-size:0px;mso-line-height-rule:exactly;'> <![endif]--><div style='margin:0px auto;max-width:600px;background:#ffffff;'><table role='presentation' cellpadding='0' cellspacing='0' style='font-size:0px;width:100%;background:#ffffff;' align='center' border='0'><tbody><tr><td style='text-align:center;vertical-align:top;direction:ltr;font-size:0px;padding:20px 0px;padding-bottom:0px;padding-top:0px;'><!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0'> <tr> <td style='vertical-align:top;width:600px;'> <![endif]--><div class='mj-column-per-100 outlook-group-fix' style='vertical-align:top;display:inline-block;direction:ltr;font-size:13px;text-align:left;width:100%;'><table role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'><tbody><tr><td style='word-wrap:break-word;font-size:0px;padding:10px 25px;padding-top:0px;padding-bottom:0px;' align='left'><div style='cursor:auto;color:#55575d;font-family:Arial, sans-serif;font-size:13px;line-height:24px;text-align:left;'><p style='font-size: 13px; text-align: center; margin: 10px 0;'><span style='font-family:Lucida Console,Helvetica,Arial,sans-serif'>PASSWORD CODE: " + code + @"</span></p></div></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--> <!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0' width='600' align='center' style='width:600px;'> <tr> <td style='line-height:0px;font-size:0px;mso-line-height-rule:exactly;'> <![endif]--><div style='margin:0px auto;max-width:600px;background:#ffffff;'><table role='presentation' cellpadding='0' cellspacing='0' style='font-size:0px;width:100%;background:#ffffff;' align='center' border='0'><tbody><tr><td style='text-align:center;vertical-align:top;direction:ltr;font-size:0px;padding:20px 0px;'><!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0'> <tr> <td style='vertical-align:top;width:600px;'> <![endif]--><div class='mj-column-per-100 outlook-group-fix' style='vertical-align:top;display:inline-block;direction:ltr;font-size:13px;text-align:left;width:100%;'><table role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'><tbody><tr><td style='word-wrap:break-word;font-size:0px;padding:10px 25px;padding-top:0px;padding-bottom:0px;' align='left'><div style='cursor:auto;color:#55575d;font-family:Arial, sans-serif;font-size:13px;line-height:22px;text-align:left;'><p style='font-size: 13px; margin: 10px 0;'> </p><p style='font-size: 13px; margin: 10px 0;'>You can generate a new code as many times as you need it, and later you can reset you password again through the Reset Password section in the main view of our App.</p><p style='font-size: 13px; margin: 10px 0;'>Best regards,</p><p style='font-size: 13px; margin: 10px 0;'>Driving Notifier App</p><p style='font-size: 13px; margin: 10px 0;'> </p></div></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--> <!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0' width='600' align='center' style='width:600px;'> <tr> <td style='line-height:0px;font-size:0px;mso-line-height-rule:exactly;'> <![endif]--><div style='margin:0px auto;max-width:600px;'><table role='presentation' cellpadding='0' cellspacing='0' style='font-size:0px;width:100%;' align='center' border='0'><tbody><tr><td style='text-align:center;vertical-align:top;direction:ltr;font-size:0px;padding:20px 0px 20px 0px;'><!--[if mso | IE]> <table role='presentation' border='0' cellpadding='0' cellspacing='0'> <tr> <td style='vertical-align:top;width:600px;'> <![endif]--><div class='mj-column-per-100 outlook-group-fix' style='vertical-align:top;display:inline-block;direction:ltr;font-size:13px;text-align:left;width:100%;'><table role='presentation' cellpadding='0' cellspacing='0' width='100%' border='0'><tbody><tr><td style='word-wrap:break-word;font-size:0px;padding:0px 20px 0px 20px;padding-top:0px;padding-bottom:0px;' align='center'><div style='cursor:auto;color:#55575d;font-family:Arial, sans-serif;font-size:11px;line-height:22px;text-align:center;'><p style='font-size: 13px; margin: 10px 0;'>This e-mail has been sent to [[EMAIL_TO]], <a href='https://www.youtube.com/watch?v=dQw4w9WgXcQ' style='color:inherit;text-decoration:none;' target='_blank'>click here to unsubscribe</a>.</p></div></td></tr><tr><td style='word-wrap:break-word;font-size:0px;padding:0px 20px 0px 20px;padding-top:0px;padding-bottom:0px;' align='center'><div style='cursor:auto;color:#55575d;font-family:Arial, sans-serif;font-size:11px;line-height:22px;text-align:center;'><p style='font-size: 13px; margin: 10px 0;'>DK</p></div></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--></td></tr></tbody></table></div><!--[if mso | IE]> </td></tr></table> <![endif]--></div> </body> </html>" } } }); MailjetResponse response = await client.PostAsync(request); if (response.IsSuccessStatusCode) { Console.WriteLine(string.Format("Total: {0}, Count: {1}\n", response.GetTotal(), response.GetCount())); Console.WriteLine(response.GetData()); } else { Console.WriteLine(string.Format("StatusCode: {0}\n", response.StatusCode)); Console.WriteLine(string.Format("ErrorInfo: {0}\n", response.GetErrorInfo())); Console.WriteLine(response.GetData()); Console.WriteLine(string.Format("ErrorMessage: {0}\n", response.GetErrorMessage())); } }
public ResponseModel <string> updateuserprofile(String userId, [FromBody] RegisterUserRequestModel newUserDetails) { try { //search for user with given Id Models.User user = dbcontext.tenants.FirstOrDefault(u => u.userId == userId); if (user == null) { user = dbcontext.managers.FirstOrDefault(u => u.userId == userId); if (user == null) { user = dbcontext.landlords.FirstOrDefault(u => u.userId == userId); } } //We will get inside the if statement if we find tenant if (user != null) { //change existing details with new provided details //this not modify fields which we do not want to modify if (newUserDetails.names != null && newUserDetails.names != "") { user.names = newUserDetails.names; } if (newUserDetails.username != null && newUserDetails.username != "") { user.username = newUserDetails.username; } if (newUserDetails.cellNumber != null && newUserDetails.cellNumber != "") { user.cellNumber = newUserDetails.cellNumber; } user.updatedAt = DateTime.Now; if (newUserDetails.profilePicture != null && newUserDetails.profilePicture != "") { user.profilePicture = newUserDetails.profilePicture; } if (newUserDetails.password != null && newUserDetails.password != "") { user.password = newUserDetails.password; } } //save our changes to database dbcontext.SaveChanges(); return(new ResponseModel <string> { data = "successfully updated user details", message = "successfully updated user details", status = true }); } catch (Exception ex) { return(new ResponseModel <string> { data = null, message = "Error updadting user" + ex.Message, status = false }); } }
public ViewResult Partial(Models.User model) { ViewBag.Valid = ModelState.IsValid; return(View(model)); }
public JsonResult Update([FromBody] Models.User data, [RequiredFromQuery] int status) { using (var context = new Data.ApplicationDbContext()) { String authUserId = User.GetClaim(OpenIdConnectConstants.Claims.Subject); Models.User authUser = context.Users.AsNoTracking().FirstOrDefault(u => u.Id.ToString() == authUserId); if (authUser == null) { return(Json(new { status_code = 2, status = "User '" + authUserId + "' does not exist" })); } if (!Helpers.PermissionChecker.CanModifyUser(authUser) && authUser.Id != data.Id) { return(Json(new { status_code = 1, status = "User '" + authUser.UserName + "' does not have permission to edit user" })); } Models.User dbUser = context.Users.FirstOrDefault(u => u.Id == data.Id); if (dbUser == null) { return(Json(new { status_code = 2, status = "User '" + data.Id + "' does not exist" })); } // Changes made to user object to be logged String changes = ""; // Id cannot be changed and LastLogin is handled elsewhere if (status == 0) { // Compares given user (data) to row stored in database (dbUser) List <Models.Log.Variance> variances = dbUser.Compare(data, false); if (variances.Count == 0) { return(Json(new { status_code = 0, status = "No changes made (given object same as database row)" })); } dbUser.Copy(data, false); // Logs each change in format: [(KEY=VALUE)][(KEY=VALUE)] // note: this format was chosen so values may contain commas or other symbols otherwise used to separate lists foreach (Models.Log.Variance var in variances) { changes += "[(" + var.Property + "=" + (var.New != null ? var.New.ToString() : "null") + ")]"; } } else if (status == 1) { dbUser.Password = data.Password; changes = "[(Password)]"; } else { return(Json(new { status_code = 4, status = "Unknown status code '" + status + "' when updating user info" })); } context.SaveChanges(); String description = ""; if (authUser.Id == dbUser.Id) { description = String.Format("{0} (id: {1}) changed his/her info", authUser.UserName, authUser.Id); } else { description = String.Format("{0} (id: {1}) changed {2}'s (id: {3}) info", authUser.UserName, authUser.Id, dbUser.UserName, dbUser.Id); } Helpers.LogHelper.LogAction(Models.Log.ActionType.ModifyUser, authUser.Id, dbUser.Id, description, changes); return(Json(new { status_code = 0 })); } }
public void Login(Models.User user) { //could this be UserId property instead of _session["UserId"] _session["UserId"] = user.Id; }
public void CreateAndSelectUser() { var id = Users.Max(x => x.Id); Users.Add(Selected = _userService.CreateUser(id + 1)); }
public JsonResult Create([FromBody] Models.User user, [RequiredFromQuery] int status) { if (status == 0) { using (var context = new Data.ApplicationDbContext()) { String authUserId = User.GetClaim(OpenIdConnectConstants.Claims.Subject); Models.User authUser = context.Users.AsNoTracking().FirstOrDefault(u => u.Id.ToString() == authUserId); if (authUser == null) { return(Json(new { status_code = 2, status = "User '" + authUserId + "' does not exist" })); } if (!Helpers.PermissionChecker.CanAddUser(authUser)) { return(Json(new { status_code = 1, status = "User '" + authUser.UserName + "' does not have permission to create new user" })); } if (context.Users.AsNoTracking().FirstOrDefault(u => user.UserName != null && u.UserName != null && user.UserName.ToLower().Equals(u.UserName.ToLower())) != null) { return(Json(new { status_code = 3, status = "User '" + user.UserName + "' already exists" })); } if (String.IsNullOrWhiteSpace(user.UserName) || String.IsNullOrWhiteSpace(user.Password)) { return(Json(new { status_code = 4, status = "Invalid user creation body" })); } user.Active = true; user.UserLastLogin = new DateTime(2000, 1, 1); context.Users.Add(user); context.SaveChanges(); Helpers.LogHelper.LogAction(Models.Log.ActionType.CreateUser, authUser.Id, user.Id, String.Format("{0} (id: {1}) created user {2} (id: {3})", authUser.UserName, authUser.Id, user.UserName, user.Id)); return(Json(new { status_code = 0, user.Id })); } } else if (status == 1) { using (var context = new Data.ApplicationDbContext()) { String authUserId = User.GetClaim(OpenIdConnectConstants.Claims.Subject); Models.User authUser = context.Users.AsNoTracking().FirstOrDefault(u => u.Id.ToString() == authUserId); if (authUser == null) { return(Json(new { status_code = 2, status = "User '" + authUserId + "' does not exist" })); } if (!Helpers.PermissionChecker.IsTechOrAdmin(authUser)) { return(Json(new { status_code = 1, status = "User '" + authUser.UserName + "' does not have permission to delete user" })); } Models.User deleteUser = context.Users.FirstOrDefault(u => u.Id == user.Id); if (deleteUser == null) { return(Json(new { status_code = 2, status = "User '" + user.Id + "' does not exist" })); } context.Users.Remove(deleteUser); context.SaveChanges(); Helpers.LogHelper.LogAction(Models.Log.ActionType.DeleteUser, authUser.Id, deleteUser.Id, String.Format("{0} (id: {1}) deleted user {2} (id: {3})", authUser.UserName, authUser.Id, deleteUser.UserName, deleteUser.Id)); } return(Json(new { status_code = 0 })); } else { return(Json(new { status_code = 4, status = "Invalid PUT status code '" + status + "'" })); } }
public ViewResult Multiple(Models.User model) { ViewBag.Valid = ModelState.IsValid; return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { String t = Request["User"].ToString(); //Console.WriteLine(t); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); if (t.Contains("Uczestnik")) { UserManager.AddToRole(user.Id, "User"); User u = new Models.User { Email = model.Email }; ExpoesContext expo = new ExpoesContext(); expo.Users.Add(u); expo.SaveChanges(); return(RedirectToAction("Create", "Users", new { id = u.ID })); } if (t.Contains("Wystawca")) { UserManager.AddToRole(user.Id, "Wystawca"); Company c = new Models.Company { Email = model.Email }; ExpoesContext expo = new ExpoesContext(); expo.Companies.Add(c); expo.SaveChanges(); return(RedirectToAction("Create", "Companies", new { id = c.Id })); } if (t.Contains("Organizator")) { UserManager.AddToRole(user.Id, "Organizator"); promoter p = new Models.promoter { Email = model.Email }; ExpoesContext expo = new ExpoesContext(); expo.Promoters.Add(p); expo.SaveChanges(); return(RedirectToAction("Create", "Promoters", new { id = p.Id })); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
private async void BtnAdd_Click(object sender, EventArgs e) { if (txtTitle.Text == "" || txtArticle.Text == "" || txtDescription.Text == "") { MessageBox.Show("Please add a title and description!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (Logo == null || Render == null) { MessageBox.Show("You must upload a logo and a render!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int logoWidth = Logo.Width; int logoHeight = Logo.Height; if (!(logoWidth == 256 && logoHeight == 256)) { MessageBox.Show("The logo's resolution must be 256x256px!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int renderWidth = Render.Width; int renderHeight = Render.Height; if (!(renderWidth == 1920 && renderHeight == 1080)) { MessageBox.Show("The render must be in Full HD (1920x1080px)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Models.User submitter = await $"{Properties.Settings.Default.APIUrl}/users/userid/{APIService.Username}".GetJsonAsync <Models.User>(); if (submitter == null) { MessageBox.Show("Your user ID is invalid!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var model = new NewsInputModel { Title = txtTitle.Text, Description = txtDescription.Text, Content = txtArticle.Text, DateAdded = DateTime.Now, UserID = submitter.Id }; string News = await $"{Properties.Settings.Default.APIUrl}/info/news".GetStringAsync(); string Logos = await $"{Properties.Settings.Default.APIUrl}/info/news/logos".GetStringAsync(); string RenderFileName = Path.GetFileName(RenderDialog.FileName); string LogoFileName = Path.GetFileName(LogoDialog.FileName); try { System.IO.File.Copy(RenderDialog.FileName, $@"{News}\{RenderFileName}"); System.IO.File.Copy(LogoDialog.FileName, $@"{Logos}\{LogoFileName}"); } catch { } model.Logo = $"/Assets/News/{LogoFileName}"; model.Image = $"/Assets/News/Logos/{RenderFileName}"; try { var returns = await _newsService.Insert <dynamic>(model); MessageBox.Show("News article added successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void MainForm_Load(object sender, System.EventArgs e) { // ************************************************** // DatabaseContext - Add New User // ************************************************** { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.User user = new Models.User { IsActive = true, Username = "******", }; databaseContext.Users.Add(user); databaseContext.SaveChanges(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); databaseContext = null; } } } // ************************************************** // /DatabaseContext - Add New User // ************************************************** // ************************************************** // UnitOfWork - Add New User // ************************************************** { Dal.UnitOfWork unitOfWork = null; try { unitOfWork = new Dal.UnitOfWork(); Models.User user = new Models.User { IsActive = true, Username = "******", }; unitOfWork.UserRepository.Insert(user); unitOfWork.Save(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } } } // ************************************************** // /UnitOfWork - Add New User // ************************************************** System.Guid id = new System.Guid ("a1a57f49-51fc-4c4b-8f06-19cd117d5c9e"); string username = "******"; // ************************************************** // DatabaseContext - Get The User From Database -> Update The User -> Save The User Changes To Database // ************************************************** { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); //Models.User user = // databaseContext.Users // .Where(current => current.Id == id) // .FirstOrDefault(); Models.User user = databaseContext.Users .Where(current => string.Compare(current.Username, username, true) == 0) .FirstOrDefault(); if (user != null) { user.IsActive = false; user.Username = "******"; databaseContext.SaveChanges(); } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); databaseContext = null; } } } // ************************************************** // /DatabaseContext - Get The User From Database -> Update The User -> Save The User Changes To Database // ************************************************** // ************************************************** // UnitOfWork - Get The User From Database -> Update The User -> Save The User Changes To Database // ************************************************** { Dal.UnitOfWork unitOfWork = null; try { unitOfWork = new Dal.UnitOfWork(); //Models.User user = // unitOfWork.UserRepository.GetById(id); Models.User user = unitOfWork.UserRepository.GetByUsername(username); if (user != null) { user.IsActive = false; user.Username = "******"; // نوشتن دستور ذیل الزامی نیست! ولی اگر بنویسیم مشکلی ندارد //unitOfWork.UserRepository.Update(user); unitOfWork.Save(); } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } } } // ************************************************** // /UnitOfWork - Get The User From Database -> Update The User -> Save The User Changes To Database // ************************************************** // ************************************************** // DatabaseContext - Just Update The User with Id -> Save The User Changes To Database // ************************************************** { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.User user = new Models.User(); user.Id = id; user.IsActive = false; user.Username = "******"; databaseContext.Entry(user).State = System.Data.Entity.EntityState.Modified; databaseContext.SaveChanges(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); databaseContext = null; } } } // ************************************************** // /DatabaseContext - Just Update The User with Id -> Save The User Changes To Database // ************************************************** // ************************************************** // UnitOfWork - Just Update The User with Id -> Save The User Changes To Database // ************************************************** { Dal.UnitOfWork unitOfWork = null; try { unitOfWork = new Dal.UnitOfWork(); Models.User user = new Models.User(); user.Id = id; user.IsActive = false; user.Username = "******"; unitOfWork.UserRepository.Update(user); unitOfWork.Save(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } } } // ************************************************** // /UnitOfWork - Just Update The User with Id -> Save The User Changes To Database // ************************************************** // ************************************************** // DatabaseContext - Get The User From Database -> Delete The User // ************************************************** { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); //Models.User user = // databaseContext.Users // .Where(current => current.Id == id) // .FirstOrDefault(); Models.User user = databaseContext.Users .Where(current => string.Compare(current.Username, username, true) == 0) .FirstOrDefault(); if (user != null) { databaseContext.Users.Remove(user); databaseContext.SaveChanges(); } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); databaseContext = null; } } } // ************************************************** // /DatabaseContext - Get The User From Database -> Delete The User // ************************************************** // ************************************************** // UnitOfWork - Get The User From Database -> Delete The User // ************************************************** { Dal.UnitOfWork unitOfWork = null; try { unitOfWork = new Dal.UnitOfWork(); //Models.User user = // unitOfWork.UserRepository.GetById(id); Models.User user = unitOfWork.UserRepository.GetByUsername(username); if (user != null) { unitOfWork.UserRepository.Delete(user); unitOfWork.Save(); } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } } } // ************************************************** // /UnitOfWork - Get The User From Database -> Delete The User // ************************************************** // ************************************************** // DatabaseContext - Just Delete The User with Id // ************************************************** { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); Models.User user = new Models.User(); user.Id = id; databaseContext.Entry(user).State = System.Data.Entity.EntityState.Deleted; databaseContext.SaveChanges(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); databaseContext = null; } } } // ************************************************** // /DatabaseContext - Just Delete The User with Id // ************************************************** // ************************************************** // UnitOfWork - Just Delete The User with Id // ************************************************** { Dal.UnitOfWork unitOfWork = null; try { unitOfWork = new Dal.UnitOfWork(); Models.User user = new Models.User(); user.Id = id; unitOfWork.UserRepository.Delete(user); unitOfWork.Save(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } } } // ************************************************** // /UnitOfWork - Just Delete The User with Id // ************************************************** // ************************************************** // DatabaseContext - Get Users For Filling DropDownList // ************************************************** { Models.DatabaseContext databaseContext = null; try { databaseContext = new Models.DatabaseContext(); //var users = // databaseContext.Users // .ToList() // ; //var users = // databaseContext.Users // .OrderBy(current => current.Username) // .ToList() // ; var users = databaseContext.Users .Where(current => current.IsActive) .OrderBy(current => current.Username) .ToList() ; //var users = // databaseContext.Users // .Where(current => current.IsActive) // .Where(current => current.IsDeleted == false) // .OrderBy(current => current.Username) // .ToList() // ; } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (databaseContext != null) { databaseContext.Dispose(); databaseContext = null; } } } // ************************************************** // /DatabaseContext - Get Users For Filling DropDownList // ************************************************** // ************************************************** // UnitOfWork - Get Users For Filling DropDownList // ************************************************** { Dal.UnitOfWork unitOfWork = null; try { unitOfWork = new Dal.UnitOfWork(); var users = unitOfWork.UserRepository.GetActiveUsers(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } } } // ************************************************** // /UnitOfWork - Get Users For Filling DropDownList // ************************************************** }
/// <inheritdoc/> public async Task SaveUserAsync(Models.User user) { await this.EnsureInitializedAsync(); await this.documentClient.UpsertDocumentAsync(this.usersCollection.SelfLink, user); }
public IActionResult Userspage() { string[] array = { "Moose Phillips", "Sarah", "Jerry", "Rene Ricky", "SBarbarah" }; Models.User peoplelist = new Models.User(array); return(View("users", peoplelist)); }
public async Task <IActionResult> CreateDynamicsAccount([FromBody] ViewModels.Account item) { _logger.LogInformation(LoggingEvents.HttpPost, "Begin method " + this.GetType().Name + "." + MethodBase.GetCurrentMethod().ReflectedType.Name); _logger.LogDebug(LoggingEvents.HttpPost, "Account parameters: " + JsonConvert.SerializeObject(item)); ViewModels.Account result = null; bool updateIfNull = true; Guid tryParseOutGuid; bool createContact = true; // get UserSettings from the session string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); _logger.LogDebug(LoggingEvents.HttpPost, "UserSettings: " + JsonConvert.SerializeObject(userSettings)); // get account Siteminder GUID string accountSiteminderGuid = userSettings.SiteMinderBusinessGuid; if (accountSiteminderGuid == null || accountSiteminderGuid.Length == 0) { _logger.LogError(LoggingEvents.Error, "No account Siteminder Guid exernal id"); throw new Exception("Error. No accountSiteminderGuid exernal id"); } // first check to see that a contact exists. string contactSiteminderGuid = userSettings.SiteMinderGuid; if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0) { _logger.LogError(LoggingEvents.Error, "No Contact Siteminder Guid exernal id"); throw new Exception("Error. No ContactSiteminderGuid exernal id"); } // get BCeID record for the current user Gov.Lclb.Cllb.Interfaces.BCeIDBusiness bceidBusiness = await _bceid.ProcessBusinessQuery(userSettings.SiteMinderGuid); var cleanNumber = BusinessNumberSanitizer.SanitizeNumber(bceidBusiness?.businessNumber); if (cleanNumber != null) { bceidBusiness.businessNumber = cleanNumber; } _logger.LogDebug(LoggingEvents.HttpGet, "BCeId business: " + JsonConvert.SerializeObject(bceidBusiness)); // get the contact record. MicrosoftDynamicsCRMcontact userContact = null; // see if the contact exists. try { userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid); if (userContact != null) { createContact = false; } } catch (OdataerrorException odee) { _logger.LogError(LoggingEvents.Error, "Error getting contact by Siteminder Guid."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error getting contact by Siteminder Guid"); } if (userContact == null) { // create the user contact record. userContact = new MicrosoftDynamicsCRMcontact(); // Adoxio_externalid is where we will store the guid from siteminder. string sanitizedContactSiteminderId = GuidUtility.SanitizeGuidString(contactSiteminderGuid); userContact.AdoxioExternalid = sanitizedContactSiteminderId; userContact.Fullname = userSettings.UserDisplayName; userContact.Nickname = userSettings.UserDisplayName; if (Guid.TryParse(userSettings.UserId, out tryParseOutGuid)) // BCeid id goes here { userContact.Employeeid = userSettings.UserId; } else // Store the BC service card id here { userContact.Externaluseridentifier = userSettings.UserId; } if (bceidBusiness != null) { // set contact according to item userContact.Firstname = bceidBusiness.individualFirstname; userContact.Middlename = bceidBusiness.individualMiddlename; userContact.Lastname = bceidBusiness.individualSurname; userContact.Emailaddress1 = bceidBusiness.contactEmail; userContact.Telephone1 = bceidBusiness.contactPhone; } else { userContact.Firstname = userSettings.UserDisplayName.GetFirstName(); userContact.Lastname = userSettings.UserDisplayName.GetLastName(); } userContact.Statuscode = 1; } // this may be an existing account, as this service is used during the account confirmation process. MicrosoftDynamicsCRMaccount account = await _dynamicsClient.GetAccountBySiteminderBusinessGuid(accountSiteminderGuid); _logger.LogDebug(LoggingEvents.HttpGet, "Account by siteminder business guid: " + JsonConvert.SerializeObject(account)); if (account == null) // do a deep create. create 3 objects at once. { _logger.LogDebug(LoggingEvents.HttpGet, "Account is null. Do a deep create of 3 objects at once."); // create a new account account = new MicrosoftDynamicsCRMaccount(); account.CopyValues(item, updateIfNull); // business type must be set only during creation, not in update (removed from copyValues() ) account.AdoxioBusinesstype = (int)Enum.Parse(typeof(ViewModels.AdoxioApplicantTypeCodes), item.businessType, true); // ensure that we create an account for the current user. // by convention we strip out any dashes present in the guid, and force it to uppercase. string sanitizedAccountSiteminderId = GuidUtility.SanitizeGuidString(accountSiteminderGuid); account.AdoxioExternalid = sanitizedAccountSiteminderId; account.Primarycontactid = userContact; account.AdoxioAccounttype = (int)AdoxioAccountTypeCodes.Applicant; if (bceidBusiness != null) { account.Emailaddress1 = bceidBusiness.contactEmail; account.Telephone1 = bceidBusiness.contactPhone; account.Address1City = bceidBusiness.addressCity; account.Address1Postalcode = bceidBusiness.addressPostal; account.Address1Line1 = bceidBusiness.addressLine1; account.Address1Line2 = bceidBusiness.addressLine2; account.Address1Postalcode = bceidBusiness.addressPostal; } // sets Business type with numerical value found in Adoxio_applicanttypecodes // using account.businessType which is set in bceid-confirmation.component.ts account.AdoxioBusinesstype = (int)Enum.Parse(typeof(AdoxioApplicantTypeCodes), item.businessType, true); var legalEntity = new MicrosoftDynamicsCRMadoxioLegalentity() { AdoxioAccount = account, AdoxioName = item.name, AdoxioIsindividual = 0, AdoxioIsapplicant = true, AdoxioLegalentitytype = account.AdoxioBusinesstype }; string legalEntityString = JsonConvert.SerializeObject(legalEntity); _logger.LogDebug("Legal Entity before creation in dynamics --> " + legalEntityString); try { legalEntity = await _dynamicsClient.Legalentities.CreateAsync(legalEntity); } catch (OdataerrorException odee) { string legalEntityId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(legalEntityId) && Guid.TryParse(legalEntityId, out Guid legalEntityGuid)) { legalEntity = await _dynamicsClient.GetLegalEntityById(legalEntityGuid); } else { _logger.LogError(LoggingEvents.Error, "Error creating legal entity."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating legal entitiy"); } } account.Accountid = legalEntity._adoxioAccountValue; // fetch the account and get the created contact. if (legalEntity.AdoxioAccount == null) { legalEntity.AdoxioAccount = await _dynamicsClient.GetAccountById(Guid.Parse(account.Accountid)); } if (legalEntity.AdoxioAccount.Primarycontactid == null) { legalEntity.AdoxioAccount.Primarycontactid = await _dynamicsClient.GetContactById(Guid.Parse(legalEntity.AdoxioAccount._primarycontactidValue)); } userContact.Contactid = legalEntity.AdoxioAccount._primarycontactidValue; legalEntityString = JsonConvert.SerializeObject(legalEntity); _logger.LogDebug("Legal Entity after creation in dynamics --> " + legalEntityString); var tiedHouse = new MicrosoftDynamicsCRMadoxioTiedhouseconnection() { }; tiedHouse.AccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); try { tiedHouse = await _dynamicsClient.Tiedhouseconnections.CreateAsync(tiedHouse); } catch (OdataerrorException odee) { string tiedHouseId = _dynamicsClient.GetCreatedRecord(odee, null); if (string.IsNullOrEmpty(tiedHouseId)) { _logger.LogError(LoggingEvents.Error, "Error creating Tied house connection."); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating Tied house connection."); } } catch (Exception e) { _logger.LogError(e.Message); } } else // it is a new user only. { if (createContact) { _logger.LogDebug(LoggingEvents.HttpGet, "Account is NOT null. Only a new user."); try { userContact = await _dynamicsClient.Contacts.CreateAsync(userContact); } catch (OdataerrorException odee) { string contactId = _dynamicsClient.GetCreatedRecord(odee, null); if (!string.IsNullOrEmpty(contactId) && Guid.TryParse(contactId, out Guid contactGuid)) { userContact = await _dynamicsClient.GetContactById(contactGuid); } else { _logger.LogError(LoggingEvents.Error, "Error creating contact"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error creating contact"); } } } } // always patch the userContact so it relates to the account. _logger.LogDebug(LoggingEvents.Save, "Patching the userContact so it relates to the account."); // parent customer id relationship will be created using the method here: //https://msdn.microsoft.com/en-us/library/mt607875.aspx MicrosoftDynamicsCRMcontact patchUserContact = new MicrosoftDynamicsCRMcontact(); patchUserContact.ParentCustomerIdAccountODataBind = _dynamicsClient.GetEntityURI("accounts", account.Accountid); try { await _dynamicsClient.Contacts.UpdateAsync(userContact.Contactid, patchUserContact); } catch (OdataerrorException odee) { _logger.LogError(LoggingEvents.Error, "Error binding contact to account"); _logger.LogError("Request:"); _logger.LogError(odee.Request.Content); _logger.LogError("Response:"); _logger.LogError(odee.Response.Content); throw new OdataerrorException("Error binding contact to account"); } // if we have not yet authenticated, then this is the new record for the user. if (userSettings.IsNewUserRegistration) { userSettings.AccountId = account.Accountid.ToString(); userSettings.ContactId = userContact.Contactid.ToString(); // we can now authenticate. if (userSettings.AuthenticatedUser == null) { Models.User user = new Models.User(); user.Active = true; user.AccountId = Guid.Parse(userSettings.AccountId); user.ContactId = Guid.Parse(userSettings.ContactId); user.UserType = userSettings.UserType; user.SmUserId = userSettings.UserId; userSettings.AuthenticatedUser = user; } userSettings.IsNewUserRegistration = false; string userSettingsString = JsonConvert.SerializeObject(userSettings); _logger.LogDebug("userSettingsString --> " + userSettingsString); // add the user to the session. _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString); _logger.LogDebug("user added to session. "); } else { _logger.LogError(LoggingEvents.Error, "Invalid user registration."); throw new Exception("Invalid user registration."); } //account.accountId = id; result = account.ToViewModel(); _logger.LogDebug(LoggingEvents.HttpPost, "result: " + JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); return(Json(result)); }
private void ToUser(UserResponse userResponse) { family.Clear(); friend.Clear(); var familyCounter = 1; var friendCounter = 1; var height1 = 30; var height2 = 20; if (userResponse.result != null) { foreach (UserDto dto in userResponse.result) { if (dto.user_email_id != null) { user = new Models.User() { FirstName = dto.user_first_name, LastName = dto.user_last_name, Email = dto.user_email_id, HavePic = DataParser.ToBool(dto.have_pic), PicUrl = dto.user_picture, MessageCard = dto.message_card, MessageDay = dto.message_day, MajorEvents = dto.user_major_events, MyHistory = dto.user_history, TimeSettings = ToTimeSettings(dto), user_birth_date = dto.user_birth_date }; } else { var firstName = ""; foreach (char a in dto.people_name) { if (a != ' ') { firstName += a; } else { break; } } Person toAdd = new Person() { Name = firstName, Relation = dto.relation_type, PicUrl = dto.ta_picture, Id = dto.ta_people_id, PhoneNumber = dto.ta_phone }; if (toAdd.PicUrl == null || toAdd.PicUrl == "") { toAdd.PicUrl = "aboutme.png"; } if (toAdd.Relation == "Family") { //family.Add(toAdd); if (familyCounter <= 5) { var myStack = new StackLayout(); myStack.HorizontalOptions = LayoutOptions.Center; myStack.WidthRequest = 40; myStack.HeightRequest = 40; var tap = new TapGestureRecognizer(); tap.Tapped += TapGestureRecognizer_Tapped_1; myStack.GestureRecognizers.Add(tap); var myFrame = new Frame(); myFrame.IsClippedToBounds = true; myFrame.Padding = 0; myFrame.WidthRequest = 40; myFrame.HeightRequest = 40; myFrame.HasShadow = false; myFrame.CornerRadius = 20; myFrame.BorderColor = Color.Black; var myImage = new Image(); myImage.Source = toAdd.PicUrl; myImage.Aspect = Aspect.AspectFill; myFrame.Content = myImage; myStack.Children.Add(myFrame); var name = new CustomizeFontLabel(); name.HorizontalTextAlignment = TextAlignment.Center; name.Text = toAdd.Name; name.TextColor = Color.Black; name.FontSize = 9; myStack.Children.Add(name); var phone = new CustomizeFontLabel(); phone.HorizontalTextAlignment = TextAlignment.Center; phone.Text = toAdd.PhoneNumber; phone.IsVisible = false; myStack.Children.Add(phone); familyMembersList.Children.Add(myStack); //height1 += 60; } familyCounter++; } if (toAdd.Relation == "Friends" || toAdd.Relation == "Friend") { //friend.Add(toAdd); if (friendCounter <= 5) { var myStack = new StackLayout(); myStack.HorizontalOptions = LayoutOptions.Center; myStack.WidthRequest = 40; myStack.HeightRequest = 40; var tap = new TapGestureRecognizer(); tap.Tapped += TapGestureRecognizer_Tapped_2; myStack.GestureRecognizers.Add(tap); var myFrame = new Frame(); myFrame.IsClippedToBounds = true; myFrame.Padding = 0; myFrame.WidthRequest = 40; myFrame.HeightRequest = 40; myFrame.HasShadow = false; myFrame.CornerRadius = 20; myFrame.BorderColor = Color.Black; var myImage = new Image(); myImage.Source = toAdd.PicUrl; myImage.Aspect = Aspect.AspectFill; myFrame.Content = myImage; myStack.Children.Add(myFrame); var name = new CustomizeFontLabel(); name.HorizontalTextAlignment = TextAlignment.Center; name.Text = toAdd.Name; name.TextColor = Color.Black; name.FontSize = 9; myStack.Children.Add(name); var phone = new CustomizeFontLabel(); phone.HorizontalTextAlignment = TextAlignment.Center; phone.Text = toAdd.PhoneNumber; phone.IsVisible = false; myStack.Children.Add(phone); friendMembersList.Children.Add(myStack); //height2 += 60; } friendCounter++; } } } //familyMembersList.ItemsSource = family; //friendMembersList.ItemsSource = friend; //familyMembersList.HeightRequest = height1; //friendMembersList.HeightRequest = height2; } }
public ActionResult Iogin(Models.User user) { return(View("Home", user)); }
static private void CopyToInstance(PerformContext performContext, DbAppContext dbContext, HETSAPI.Import.Dump_Truck oldObject, ref Models.DumpTruck instance, string systemId) { bool isNew = false; if (oldObject.Equip_Id <= 0) { return; } //Add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database Models.User modifiedBy = ImportUtility.AddUserFromString(dbContext, "", systemId); Models.User createdBy = ImportUtility.AddUserFromString(dbContext, "", systemId); if (instance == null) { isNew = true; instance = new Models.DumpTruck(); instance.Id = oldObject.Equip_Id; // instance.DumpTruckId = oldObject.Reg_Dump_Trk; if (oldObject.Single_Axle != null) { instance.IsSingleAxle = (oldObject.Single_Axle.Trim() == "Y") ? true : false; } if (oldObject.Tandem_Axle != null) { instance.IsTandemAxle = (oldObject.Tandem_Axle.Trim() == "Y") ? true : false; } if (oldObject.Tridem != null) { instance.IsTridem = (oldObject.Tridem.Trim() == "Y") ? true : false; } if (oldObject.PUP != null) { instance.HasPUP = (oldObject.PUP.Trim() == "Y") ? true : false; } //5 properties if (oldObject.Belly_Dump != null) { instance.HasBellyDump = (oldObject.Belly_Dump.Trim() == "Y") ? true : false; } if (oldObject.Rock_Box != null) { instance.HasRockBox = (oldObject.Rock_Box.Trim() == "Y") ? true : false; } if (oldObject.Hilift_Gate != null) { instance.HasHiliftGate = (oldObject.Hilift_Gate.Trim() == "Y") ? true : false; } if (oldObject.Water_Truck != null) { instance.IsWaterTruck = (oldObject.Water_Truck.Trim() == "Y") ? true : false; } if (oldObject.Seal_Coat_Hitch != null) { instance.HasSealcoatHitch = (oldObject.Seal_Coat_Hitch.Trim() == "Y") ? true : false; } //5 properties // instance.ArchiveDate = oldObject. if (oldObject.Rear_Axle_Spacing != null) { instance.RearAxleSpacing = oldObject.Rear_Axle_Spacing; } if (oldObject.Front_Tire_Size != null) { instance.FrontTireSize = oldObject.Front_Tire_Size; } if (oldObject.Front_Tire_UOM != null) { instance.FrontTireUOM = oldObject.Front_Tire_UOM; } if (oldObject.Front_Axle_Capacity != null) { instance.FrontAxleCapacity = oldObject.Front_Axle_Capacity; } if (oldObject.Rare_Axle_Capacity != null) { instance.RearAxleCapacity = oldObject.Rare_Axle_Capacity; } //3 properties if (oldObject.Legal_Load != null) { instance.LegalLoad = oldObject.Legal_Load; } if (oldObject.Legal_Capacity != null) { instance.LegalCapacity = oldObject.Legal_Capacity; } if (oldObject.Legal_PUP_Tare_Weight != null) { instance.LegalPUPTareWeight = oldObject.Legal_PUP_Tare_Weight; } //6 properties if (oldObject.Licenced_GVW != null) { instance.LicencedGVW = oldObject.Licenced_GVW; } if (oldObject.Licenced_GVW_UOM != null) { instance.LicencedGVWUOM = oldObject.Licenced_GVW_UOM; } if (oldObject.Licenced_Tare_Weight != null) { instance.LicencedTareWeight = oldObject.Licenced_Tare_Weight; } if (oldObject.Licenced_PUP_Tare_Weight != null) { instance.LicencedPUPTareWeight = oldObject.Licenced_PUP_Tare_Weight; } if (oldObject.Licenced_Load != null) { instance.LicencedLoad = oldObject.Licenced_Load; } if (oldObject.Licenced_Capacity != null) { instance.LicencedCapacity = oldObject.Licenced_Capacity; } // 8 properties if (oldObject.Box_Length != null) { instance.BoxLength = oldObject.Box_Length; } if (oldObject.Box_Width != null) { instance.BoxWidth = oldObject.Box_Width; } if (oldObject.Box_Height != null) { instance.BoxHeight = oldObject.Box_Height; } if (oldObject.Box_Capacity != null) { instance.BoxCapacity = oldObject.Box_Capacity; } if (oldObject.Trailer_Box_Length != null) { instance.TrailerBoxLength = oldObject.Trailer_Box_Length; } if (oldObject.Trailer_Box_Width != null) { instance.TrailerBoxWidth = oldObject.Trailer_Box_Width; } if (oldObject.Trailer_Box_Height != null) { instance.TrailerBoxHeight = oldObject.Trailer_Box_Height; } if (oldObject.Trailer_Box_Capacity != null) { instance.TrailerBoxCapacity = oldObject.Trailer_Box_Capacity; } instance.CreateTimestamp = DateTime.UtcNow; instance.CreateUserid = createdBy.SmUserId; dbContext.DumpTrucks.Add(instance); } else { instance = dbContext.DumpTrucks .First(x => x.Id == oldObject.Equip_Id); instance.LastUpdateUserid = modifiedBy.SmUserId; instance.LastUpdateTimestamp = DateTime.UtcNow; dbContext.DumpTrucks.Update(instance); } }