private void btnLogOut_Click(object sender, RoutedEventArgs e) { Login lg = new Login(); lg.Show(); this.Close(); }
public bool doAuth(string username, string password) { if(string.IsNullOrEmpty(getCurrentAuthToken())) { var login = new Login(username, password); string authToken; try { authToken = login.Parse(makeCall(login)).token; } catch(CallException e) { Debug.LogError("error getting login auth token:" + e.Message); return false; } context.addNamedMapping<string>(NamedInjections.API_TOKEN, authToken); } if(allLanguagesSupported == null) { getLanguageList(); if(allLanguagesSupported == null) return false; } return true; }
public static void GrantDbPermissions(Database db, string username) { var server = db.Parent; Login login; if (!(server.Logins.Contains(username))) { login = new Login(server, username); login.LoginType = LoginType.WindowsUser; login.DefaultDatabase = db.Name; login.Create(); } else { login = server.Logins[username]; } User newUser; if (!(db.Users.Contains(username))) { newUser = new User(db, username); newUser.Login = username; newUser.UserType = UserType.SqlLogin; newUser.Create(); } else { newUser = db.Users[username]; } AddUserToRoles(newUser, "db_datareader", "db_datawriter", "db_ddladmin"); }
public frmPutniNalozi(Login piLoginInstance) { InitializeComponent(); // set login component passed when instancing this.piLogin = piLoginInstance; }
private System.Collections.IEnumerator doLogin(LoginServerCall lsc) { Debug.Log("starting login" + calls.Count); string url = serverUrl+"login/"+lsc.getId()+"/" + lsc.getDeviceType()+"/MSW"+"/" +lsc.getVersion(); Debug.Log(url); WWW www = new WWW(url); yield return www; Debug.Log("after yield"); try { if (www.error == null) { online = true; //no error occured Debug.Log (www.text); Response response = Response.DeserializeObject(www.text); //login.debug(); security = response.security; login = response.login; content = response.content; lsc.processCallback(response); } else { Debug.Log("ERROR: " + www.error); setOffline(); calls.Add(lsc); } www.Dispose(); www = null; } catch (Exception e) { Debug.Log("got an exception " + e.Message); } processing = false; Debug.Log("ending login"+ calls.Count); }
public SecurityUserDetails(User user, Login p) { parent = p; InitializeComponent(); _user = user; populateFormFromUser(user); }
public ActionResult Login( Login model, string returnUrl ) { if ( !ModelState.IsValid ) { return View( model ); } else { return RedirectToLocal( "Error" ); } }
public async void LoginButtonClick(object sender, EventArgs e) { LoginPage.loginFail.IsVisible = false; if (String.IsNullOrEmpty(LoginPage.username.Text) || String.IsNullOrEmpty(LoginPage.password.Text)) { await DisplayAlert("Validation Error", "Username and Password are required", "Re-try"); } else { //code here for check valid username and password from server new System.Threading.Thread (new System.Threading.ThreadStart (() => { Device.BeginInvokeOnMainThread (() => { LoginPage.loginButton.IsEnabled = false; LoginPage.activityIndicator.IsRunning = true; }); })).Start(); Login loginData = new Login (); loginData.lastConnectWebscoketUrl = LoginPage.websocketUrl.Text; loginData.username = LoginPage.username.Text; loginData.password = sha256_hash(LoginPage.password.Text); loginData.flagForLogin = ""; loginData.node_command = "check_login"; //no await App.Database.Save_Login_Item (loginData.username, LoginPage.password.Text, "pass", loginData.lastConnectWebscoketUrl); string jsonCommandLogin = JsonConvert.SerializeObject(loginData, Formatting.Indented); System.Diagnostics.Debug.WriteLine ("jsonCommandLogin" , jsonCommandLogin); WebsocketManager.websocketMaster.Send (jsonCommandLogin); //WebsocketManager.websocketMaster.Send("{\"cmd_login\":[{\"username\":\"admin\",\"flagForLogin\":\"pass\",\"lastConnectWebscoketUrl\":\"ws://echo.websocket.org\"}]}"); // no ipm1.showMenuTabPage (); } }
public LoginResponse Post(Login request) { AuthService authService = ResolveService<AuthService>(); authService.Post(new Auth { provider = AuthService.CredentialsProvider, UserName = request.UserName, Password = request.Password }) ; IAuthSession session = this.GetSession(); //UserManager um = new UserManager(base.RequestContext, AuthRepoProxy); //AuthorizationResponse aur = um.GetAuthorization( // new GetAuthorization{UserId=int.Parse(session.UserAuthId)}); AuthorizationResponse aur= new AuthorizationResponse{Roles= GetFakeRoles()}; session.Permissions= aur.Permissions.ConvertAll(f=>f.Name); session.Roles= aur.Roles.ConvertAll(f=>f.Name); //(from r in aur.Roles select r.Name).ToList(); authService.SaveSession(session); return new LoginResponse(){ DisplayName= session.DisplayName.IsNullOrEmpty()? session.UserName: session.DisplayName, Roles= aur.Roles, Permissions= aur.Permissions }; }
public ActionResult Index(Login login) { // UserStore and UserManager manages data retreival. UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); IdentityUser identityUser = manager.Find(login.UserName, login.Password); if (ModelState.IsValid) { if (identityUser != null) { IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager .SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, login.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role); // SignIn() accepts ClaimsIdentity and issues logged in cookie. authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); return RedirectToAction("SecureArea", "Home"); } } return View(); }
public async Task ProcessPackage(User user, Login package) { var users = (await mServer.BD.Find<UserInfo>(u => u.Name == package.Name)).ToArray(); var result = new Login(); if (!users.Any()) { result.ID = Guid.Empty; await mServer.ClientListener.Send(user, result); return; } var foundUser = users.Single(); if (!BCrypt.Net.BCrypt.Verify(package.Password, foundUser.PasswordHash)) { result.ID = Guid.Empty; await mServer.ClientListener.Send(user, result); return; } if (mServer.Lobby.Values.Any(u => u.Name == package.Name)) { result.ID = Guid.Empty; await mServer.ClientListener.Send(user, result); return; } user.ID = foundUser.ID; user.Name = foundUser.Name; if (foundUser.RoomID != Guid.Empty && mServer.Rooms.ContainsKey(foundUser.RoomID)) user.Room = mServer.Rooms[foundUser.RoomID]; result.ID = foundUser.ID; await mServer.ClientListener.Send(user, result); }
private void button2_Click(object sender, EventArgs e) { string id = textBox1.Text.Trim(); string password = textBox2.Text.Trim(); string againPw = textBox3.Text.Trim(); if (id != "" && password != "" && againPw != "") { if (SqlAdmin.exitById(id)) { MessageBox.Show("该用户名已经存在。"); return; } else if (password != againPw) { MessageBox.Show("请确保两段密码相同."); } else { Admin admin = new Admin(id,password); SqlAdmin.addAdmin(admin); MessageBox.Show("注册成功."); Login loginView = new Login(); loginView.Show(); this.Dispose(); } } else { MessageBox.Show("该输入所有数据."); } }
/* * Overload when called from user listing */ public frmDodjelaPrava(Login piLoginInstance, iUser korisnik) { InitializeComponent(); this.piLogin = piLoginInstance; this.korisnik = korisnik; }
public ActionResult Index(Login login) { if (ModelState.IsValid) { try { if (ServiceLocator.GetMembershipService().Authenticate(login.Username, login.Password)) { FormsAuthentication.SetAuthCookie(login.Username, false); return this.RedirectToRoute("Investors-Current-Unitholders-Members"); } else { this.ModelState.AddModelError("Email", "Invalid username or password, please try again"); } } catch (Exception exception) { this.ModelState.AddModelError("Email", "There was a problem logging you in. Please try again." + exception.Message); } } if (login.LoginLocation == LoginLocation.Home) { return this.RedirectToRoute("Home"); } else { return this.RedirectToRoute("Investors-Current-Unitholders"); } }
public static Login GetLoginByID(int id) { Login login = new Login(); SqlLoginProvider sqlLoginProvider = new SqlLoginProvider(); login = sqlLoginProvider.GetLoginByID(id); return login; }
public ActionResult Login(Login pLogin) { if (ModelState.IsValid) { //Tecnico tecnico = TecnicoRepository.CheckUser(pLogin); Tecnico tecnico = new Tecnico() { Nome = "Admin", Senha = "Admin" }; if (tecnico.Nome != "") { Session["Nome"] = tecnico.Nome; return RedirectToAction("Index"); } else { return RedirectToAction("Login").ComMensagemDeErro("Nome ou senha inválidos!"); } } else { return View(); } }
protected void Page_Load(object sender, EventArgs e) { Login l = new Login(); l.logado = false; Session.Abandon(); Response.Redirect("/Home.aspx"); }
private void Loaded_Method() { Login login = new Login(); LoginViewModel lvm = new LoginViewModel(); login.DataContext = lvm; login.ShowDialog(); try { LoginAccount = lvm.Account; AccountName = lvm.Account.AccountName; MainModel.MainAccount = lvm.Account; AccountPhoto AccountPhotoView = new AccountPhoto(MainFrame); AccountPhotoModelView AccountPhotoModelView = new AccountPhotoModelView(MainModel.MainAccount, MainFrame); AccountPhotoView.DataContext = AccountPhotoModelView; MainFrame.NavigationService.Navigate(AccountPhotoView, UriKind.Relative); SearhcEnable = true; MainFrame.NavigationService.RemoveBackEntry(); while (MainFrame.CanGoBack) { MainFrame.RemoveBackEntry(); } } catch (NullReferenceException) { AccountName = "Нажмите чтобы войти"; SearhcEnable = false; MainModel.MainAccount = null; while (MainFrame.CanGoBack) { MainFrame.RemoveBackEntry(); } } }
public ActionResult Login(Login login) { if (login.Name == "Admin" && login.Password == "Admin") { var account = new Account() { Email = "*****@*****.**", Login = "******", Password = "******", Role = Role.Admin }; var authorize = new ExampleAuthorizeService(); authorize.SignIn(account, false); } else if (login.Name == "User" && login.Password == "User") { var account = new Account() { Email = "*****@*****.**", Login = "******", Password = "******", Role = Role.User }; var authorize = new ExampleAuthorizeService(); authorize.SignIn(account, false); } else { return View(); } return RedirectToAction("AllIndex"); }
public ActionResult Index(Login user) { if (ModelState.IsValid) { var login = from user2 in db.Users where user2.UserName == user.Username && user2.Password == user.Password select user2; if (login.Count() == 1) { FormsAuthentication.SetAuthCookie(user.Username, false); if (this.Request.RawUrl.Contains("ReturnUrl=")) { return Redirect("/"+this.Request.RawUrl.Substring(26)); } return RedirectToAction("Index","Home"); } else { ModelState.AddModelError("", "Invalid Username or Password"); } } return View(); }
public void LoginTest() { var mth = new Login() { UserName = "******", Password = "******" }; var a = ApiClient.Execute(mth).Result; }
protected void Button1_Click(object sender, EventArgs e) { string username = TextBox1.Text; string password = TextBox2.Text; Login lBAL = new Login(); int recordStatus = 0; try { recordStatus = lBAL.LoginUser(username, password); if (recordStatus < 0) { Server.Transfer("DeleteRecords.aspx"); } else { lblError.Text = "Incorrect Password or Username"; } } catch (Exception ex) { lblError.Text = "Incorrect Password or Username"; } }
public dynamic UserLogin(Login Login) { try { if (Login.UserName != null && Login.Password != null) { var loginModel = _NotificationService.Login(Login.UserName, Login.Password); if (loginModel != null) { return loginModel; } else { return false; } } else { return false; } } catch (Exception ex) { return false; } }
public static Tecnico CheckUser(Login pLogin) { try { StringBuilder sql = new StringBuilder(); Tecnico tecnico = new Tecnico(); sql.Append("SELECT * "); sql.Append("FROM Tecnico "); sql.Append("WHERE Nome='" + pLogin.Nome + "' and Senha='" + pLogin.Senha + "'"); SqlDataReader dr = SqlConn.Get(sql.ToString()); while (dr.Read()) { tecnico.IdTecnico = (int)dr["IdTecnico"]; tecnico.Nome = (string)dr["Nome"]; tecnico.Senha = (string)dr["Senha"]; } return tecnico; } catch (Exception) { return null; } }
/// <summary> /// converts the string to "Login" object /// </summary> /// <param name="str">the string. format : [username]_[password]</param> /// <returns>the Login object</returns> public static Login Parse(string str) { Login r = new Login(); r.username = str.Split('_')[0]; r.password = str.Split('_')[1]; return r; }
//private WebBrowser showwebpage; public Main() { InitializeComponent(); //showwebpage = htmlTextBox1.Browser; Welcome welcomedlg = new Welcome(); if (welcomedlg.ShowDialog() == DialogResult.OK) { Login logindlg = new Login(); if (logindlg.ShowDialog() == DialogResult.OK) { ///////添加登录日志 } else { this.Close(); //Application.Exit(); Environment.Exit(0); } } InfoSource info = new InfoSource(); info.GetAllInfo(); InitTreeView(); InitTagsTree(); //InitRssSource(); //更新状态信息 UpdateManager.UpdateEvent += new UpdateManager.UpdateStatuHandler(UpdateManager_UpdateEvent); UseUpdateConfig(); }
void Start() { Login.SetGameMachineApp(this); login = gameObject.AddComponent<Login>() as Login; login.SetLoginUi(this); login.DoLogin(); }
public static Login GetLoginByLoginName(string loginName) { Login login = new Login(); SqlLoginProvider sqlLoginProvider = new SqlLoginProvider(); login = sqlLoginProvider.GetLoginByLoginName(loginName); return login; }
static void Main(string[] args) { ILogger logger = new NLogger(); // Create the threads. ServerThread server = new ServerThread(logger); ListenThread listen = new ListenThread(logger, server, 4530); DatabaseThread database = new DatabaseThread(logger); // Create the login handler. Login login = new Login(logger, server, database); // Start things up. server.Run(); listen.Run(); database.Run(); // We could potentially make this a service so there's no infinite // looping. while (true) { if (server.Fatal || listen.Fatal) { // TODO: Potentially attempt to restart? break; } Thread.Sleep(100); } }
public ActionResult Index(Login user) { if (ModelState.IsValid) { //var login = from user2 in db.Users // where user2.UserName == user.Username && user2.Password == user.Password // select user2; //if (login.Count() == 1) if(user.Username == "sing1205" && user.Password=="123456") { FormsAuthentication.SetAuthCookie(user.Username, false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "Invalid Username or Password"); } } return View(); }
public LoginViewModel(Login loginView) { view = loginView; user = new tblUser(); UserList = service.GetAllUsers().ToList(); }
public bool LoginUser(UserContext uContext) { return(Login.LoginUser(uContext)); }
public Landing_admin_gui(Login l) { InitializeComponent(); this.l = l; }
/// <summary> /// Method to send the request to the server using the WebClient object /// and parse the response for feed exception. /// </summary> /// <param name="webServicePage">The name of the web service page.</param> /// <param name="uploadValues">The NameValueCollection of values to POST with the request.</param> /// <param name="loginObject">Object containing the login credentials.</param> public static void ProcessRequest(string webServicePage, NameValueCollection uploadValues, ref Login loginObject) { // // validate the login object. // Base.ValidateLoginObject(loginObject); // // create the request uri from the web service page input // Uri requestUri = new Uri(BASE_URL + webServicePage); // // create the WebClient object // WebClient webClient = new WebClient(); webClient.Headers.Add("encryptedTicket", loginObject.EncryptedTicket); // // upload the values // byte[] responseBytes = webClient.UploadValues(requestUri, uploadValues); // // get back the encryptedTicket response header for the ticket returned // with the response if it has been updated because of sliding expiration. // this header might not always be there, so check if it exists first. // if (webClient.ResponseHeaders["encryptedTicket"] != null) { loginObject.EncryptedTicket = webClient.ResponseHeaders["encryptedTicket"]; } // // get the response // UTF8Encoding encoding = new UTF8Encoding(); string response = encoding.GetString(responseBytes); // // declare the namespace manager object. // XmlNamespaceManager namespaceMgr; // // get the feed node, this will also parse the response for feed exceptions // XmlNode feedNode = Base.GetFeedNode(response, out namespaceMgr); }
public override int GetHashCode() => ID.GetHashCode() ^ Login.GetHashCode();
private void ShowLoginWindow() { Login loginWindow = new Login(); loginWindow.Show(); }
public void setup() { dn = new Login(); }
void Callback_Login(Login message) { Debug.Log(message.loginName + " " + Time.time); }
public async Task Process(Login login) { var ret = await Task.Run(() => server.LoginChecker.DoLogin(login, RemoteEndpointIP, login.Dlc, challengeToken)); if (ret.LoginResponse.ResultCode == LoginResponse.Code.Ok) { var user = ret.User; //Trace.TraceInformation("{0} login: {1}", this, response.ResultCode.Description()); await this.SendCommand(user); // send self to self first connectedUser = server.ConnectedUsers.GetOrAdd(user.Name, (n) => new ConnectedUser(server, user)); connectedUser.User = user; connectedUser.Connections.TryAdd(this, true); // close other connections foreach (var otherConnection in connectedUser.Connections.Keys.Where(x => x != null && x != this).ToList()) { otherConnection.RequestClose(); bool oth; connectedUser.Connections.TryRemove(otherConnection, out oth); } server.SessionTokens[ret.LoginResponse.SessionToken] = user.AccountID; await SendCommand(ret.LoginResponse); // login accepted connectedUser.ResetHasSeen(); foreach (var b in server.Battles.Values.Where(x => x != null)) { await SendCommand(new BattleAdded() { Header = b.GetHeader() }); } // mutually syncs users based on visibility rules await server.TwoWaySyncUsers(Name, server.ConnectedUsers.Keys); server.OfflineMessageHandler.SendMissedMessagesAsync(this, SayPlace.User, Name, user.AccountID); var defChans = await server.ChannelManager.GetDefaultChannels(user.AccountID); defChans.AddRange(server.Channels.Where(x => x.Value.Users.ContainsKey(user.Name)).Select(x => x.Key)); // add currently connected channels to list too foreach (var chan in defChans.ToList().Distinct()) { await connectedUser.Process(new JoinChannel() { ChannelName = chan, Password = null }); } foreach (var bat in server.Battles.Values.Where(x => x != null && x.IsInGame)) { var s = bat.spring; if (s.LobbyStartContext.Players.Any(x => !x.IsSpectator && x.Name == Name) && !s.Context.ActualPlayers.Any(x => x.Name == Name && x.LoseTime != null)) { await SendCommand(new RejoinOption() { BattleID = bat.BattleID }); await bat.ProcessPlayerJoin(connectedUser, bat.Password); } } await SendCommand(new FriendList() { Friends = connectedUser.FriendEntries.ToList() }); await SendCommand(new IgnoreList() { Ignores = connectedUser.Ignores.ToList() }); await server.MatchMaker.OnLoginAccepted(connectedUser); await server.PlanetWarsMatchMaker.OnLoginAccepted(connectedUser); await SendCommand(server.NewsListManager.GetCurrentNewsList()); await SendCommand(server.LadderListManager.GetCurrentLadderList()); await SendCommand(server.ForumListManager.GetCurrentForumList(user.AccountID)); using (var db = new ZkDataContext()) { var acc = db.Accounts.Find(user.AccountID); if (acc != null) { await server.PublishUserProfileUpdate(acc); } } } else { await SendCommand(ret.LoginResponse); if (ret.LoginResponse.ResultCode == LoginResponse.Code.Banned) { await Task.Delay(500); // this is needed because socket writes are async and might not be queued yet await transport.Flush(); transport.RequestClose(); } } }
public WatchlistDisplayModel GetRentalWatchlist(WatchlistDisplayModel model, Login login) { var data = db.RentalWatchList.Where(x => x.PersonId == login.Id && x.IsActive) .Select(x => new WatctlistItem <RentListingModel> { View = new RentListingViewModel { IsOwner = db.OwnerProperty.FirstOrDefault(y => y.PropertyId == x.RentalListing.PropertyId).OwnerId == login.Id, IsApplied = db.RentalApplication.Any(y => y.RentalListingId == x.RentalListing.Id && y.PersonId == login.Id), }, Model = new RentListingModel { Id = x.RentalListing.Id, WatchListId = x.Id, MovingCost = x.RentalListing.MovingCost, TargetRent = x.RentalListing.TargetRent, AvailableDate = x.RentalListing.AvailableDate, Furnishing = x.RentalListing.Furnishing, OccupantCount = x.RentalListing.OccupantCount, PetsAllowed = x.RentalListing.PetsAllowed, Title = x.RentalListing.Title, Description = x.RentalListing.Description, PropertyId = x.RentalListing.PropertyId, IdealTenant = x.RentalListing.IdealTenant, IsActive = x.RentalListing.IsActive, RentalStatusId = x.RentalListing.RentalStatusId, MediaFiles = x.RentalListing.RentalListingMedia.Select(y => new MediaModel { Id = y.Id, NewFileName = y.NewFileName, OldFileName = y.OldFileName }).ToList() }, Address = new AddressViewModel { Street = x.RentalListing.Property.Address.Street, Suburb = x.RentalListing.Property.Address.Suburb, AddressId = x.RentalListing.Property.Address.AddressId, CountryId = x.RentalListing.Property.Address.AddressId, Number = x.RentalListing.Property.Address.Number, Region = x.RentalListing.Property.Address.Region, City = x.RentalListing.Property.Address.City, PostCode = x.RentalListing.Property.Address.PostCode, Latitude = x.RentalListing.Property.Address.Lat, Longitude = x.RentalListing.Property.Address.Lng }, Property = new PropertyViewModel { Bedroom = x.RentalListing.Property.Bedroom, Bathroom = x.RentalListing.Property.Bathroom, FloorArea = x.RentalListing.Property.FloorArea, LandArea = x.RentalListing.Property.LandSqm, ParkingSpace = x.RentalListing.Property.ParkingSpace, CreatedDate = x.RentalListing.Property.CreatedOn, PropertyType = x.RentalListing.Property.PropertyType.Name, RentalPaymentType = x.RentalListing.Property.TargetRentType.Name }, }); var allItems = data.OrderBy(x => x.Model.Title).ToPagedList(model.Page, 2); allItems.ToList().ForEach(x => x.Model.MediaFiles.ToList().ForEach(y => y.InjectMediaModelViewProperties())); if (string.IsNullOrWhiteSpace(model.SortOrder)) { model.SortOrder = "Latest Listing"; } switch (model.SortOrder) { case "Title": data = data.OrderBy(x => x.Model.Title); break; case "Title_Desc": data = data.OrderByDescending(x => x.Model.Title); break; case "Highest Rent": data = data.OrderByDescending(x => x.Model.TargetRent); break; case "Lowest Rent": data = data.OrderBy(x => x.Model.TargetRent); break; case "Latest Avaible": data = data.OrderByDescending(x => x.Model.AvailableDate); break; case "Earliest Avaible": data = data.OrderBy(x => x.Model.AvailableDate); break; case "Latest Listing": data = data.OrderByDescending(x => x.Property.CreatedDate); break; case "Earliest Listing": data = data.OrderBy(x => x.Property.CreatedDate); break; default: data = data.OrderByDescending(x => x.Property.CreatedDate); break; } if (!String.IsNullOrWhiteSpace(model.SearchString)) { SearchUtil searchTool = new SearchUtil(); int searchType = searchTool.CheckDisplayType(model.SearchString); string formatString = searchTool.ConvertString(model.SearchString); data = data.Where(x => x.Model.Title.ToLower().Contains(formatString) || x.Address.City.ToLower().Contains(formatString) || x.Address.Number.ToLower().Contains(formatString) || x.Address.PostCode.ToLower().Contains(formatString) || x.Address.Region.ToLower().Contains(formatString) || x.Address.Street.ToLower().Contains(formatString) || x.Address.Suburb.ToLower().Contains(formatString) || x.Model.AvailableDate.ToString().Contains(formatString) || x.Model.Description.ToLower().Contains(formatString) ); } ; var items = data.ToPagedList(model.Page, 10); items.ToList().ForEach(x => x.Model.MediaFiles.ToList().ForEach(y => y.InjectMediaModelViewProperties())); if (String.IsNullOrWhiteSpace(model.SearchString)) { model.Page = 1; } var sortOrders = new List <SortOrderModel>(); var rvr = new RouteValueDictionary(new { SearchString = model.SearchString }); sortOrders.Add(new SortOrderModel { SortOrder = "Title", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Title") }); sortOrders.Add(new SortOrderModel { SortOrder = "Title_Desc", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Title_Desc") }); sortOrders.Add(new SortOrderModel { SortOrder = "Highest Rent", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Highest Rent") }); sortOrders.Add(new SortOrderModel { SortOrder = "Lowest Rent", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Lowest Rent") }); sortOrders.Add(new SortOrderModel { SortOrder = "Latest Available", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Latest Available") }); sortOrders.Add(new SortOrderModel { SortOrder = "Earliest Available", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Earliest Available") }); sortOrders.Add(new SortOrderModel { SortOrder = "Latest Listing", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Latest Listing") }); sortOrders.Add(new SortOrderModel { SortOrder = "Earliest Listing", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Earliest Listing") }); model.SortOrders = sortOrders; model.PagedInput = new PagedInput { ActionName = "Index", ControllerName = "Watchlist", PagedLinkValues = new RouteValueDictionary(new { SortOrder = model.SortOrder, SearchString = model.SearchString }) }; model.PageCount = items.Count == 0 ? allItems.PageCount : items.PageCount; model.SearchCount = items.Count; model.Items = items.Count == 0 ? allItems : items; return(model); }
public async Task <LoginCheckerResponse> DoLogin(Login login, string ip) { await semaphore.WaitAsync(); try { var userID = login.UserID; var lobbyVersion = login.LobbyVersion; using (var db = new ZkDataContext()) { if (!VerifyIp(ip)) { return(new LoginCheckerResponse(LoginResponse.Code.BannedTooManyConnectionAttempts)); } SteamWebApi.PlayerInfo info = null; if (!string.IsNullOrEmpty(login.SteamAuthToken)) { info = await server.SteamWebApi.VerifyAndGetAccountInformation(login.SteamAuthToken); if (info == null) { LogIpFailure(ip); return(new LoginCheckerResponse(LoginResponse.Code.InvalidSteamToken)); } } Account accBySteamID = null; Account accByLogin = null; if (info != null) { accBySteamID = db.Accounts.Include(x => x.Clan).Include(x => x.Faction).FirstOrDefault(x => x.SteamID == info.steamid); } if (!string.IsNullOrEmpty(login.Name)) { accByLogin = db.Accounts.Include(x => x.Clan).Include(x => x.Faction).FirstOrDefault(x => x.Name == login.Name); } if (accBySteamID == null) { if (accByLogin == null) { LogIpFailure(ip); if (!string.IsNullOrEmpty(login.Name)) { return(new LoginCheckerResponse(LoginResponse.Code.InvalidName)); } else { return(new LoginCheckerResponse(LoginResponse.Code.SteamNotLinkedAndLoginMissing)); } } if (string.IsNullOrEmpty(login.PasswordHash) || !accByLogin.VerifyPassword(login.PasswordHash)) { LogIpFailure(ip); return(new LoginCheckerResponse(LoginResponse.Code.InvalidPassword)); } } var acc = accBySteamID ?? accByLogin; var ret = new LoginCheckerResponse(LoginResponse.Code.Ok); ret.LoginResponse.Name = acc.Name; var user = ret.User; acc.Country = ResolveCountry(ip); if ((acc.Country == null) || string.IsNullOrEmpty(acc.Country)) { acc.Country = "unknown"; } acc.LobbyVersion = lobbyVersion; acc.LastLogin = DateTime.UtcNow; if (info != null) { if (db.Accounts.Any(x => x.SteamID == info.steamid && x.Name != acc.Name)) { LogIpFailure(ip); return(new LoginCheckerResponse(LoginResponse.Code.SteamLinkedToDifferentAccount)); } acc.SteamID = info.steamid; acc.SteamName = info.personaname; } user.LobbyVersion = login.LobbyVersion; user.IpAddress = ip; UpdateUserFromAccount(user, acc); LogIP(db, acc, ip); LogUserID(db, acc, userID); db.SaveChanges(); ret.LoginResponse.SessionToken = Guid.NewGuid().ToString(); // create session token var banPenalty = Punishment.GetActivePunishment(acc.AccountID, ip, userID, x => x.BanLobby); if (banPenalty != null) { return (BlockLogin( $"Banned until {banPenalty.BanExpires} (match to {banPenalty.AccountByAccountID.Name}), reason: {banPenalty.Reason}", acc, ip, userID)); } if (!acc.HasVpnException && GlobalConst.VpnCheckEnabled) { if (HasVpn(ip, acc, db)) { return(BlockLogin("Connection using proxy or VPN is not allowed! (You can ask for exception)", acc, ip, userID)); } } return(ret); } } finally { semaphore.Release(); } }
public IActionResult Login(Login user) { // Run the login dynamic method return login(user); }
public LoginViewModel(Login openLogin) { login = openLogin; currentUser = new User(); }
public void Post(Login login) { }
public void SetupLogin() { var salt = Tete.Api.Helpers.Crypto.NewSalt(); User existingUser = new User() { Id = existingUserId, UserName = existingUserName, Salt = salt }; User newUser = new User() { Id = newUserId, UserName = newUserName, Salt = salt }; User guestUser = new User() { Id = guestUserId, UserName = "", Salt = salt }; Login existingUserLogin = new Login() { UserId = existingUser.Id, PasswordHash = Tete.Api.Helpers.Crypto.Hash(testPassword, salt) }; Login newUserLogin = new Login() { UserId = newUser.Id, PasswordHash = Tete.Api.Helpers.Crypto.Hash(testPassword, salt) }; var accessRoles = new List <AccessRole>() { new AccessRole(existingUser.Id, "Admin") { CreatedBy = existingUser.Id } }; IQueryable <User> users = new List <User> { existingUser, guestUser }.AsQueryable(); IQueryable <Login> logins = new List <Login> { existingUserLogin, newUserLogin }.AsQueryable(); IQueryable <AccessRole> userAccessRoles = accessRoles.AsQueryable(); Session existingUserSession = new Session() { UserId = existingUser.Id, Token = existingUserToken }; Session newUserSession = new Session() { UserId = newUser.Id, Token = newUserToken }; Session guestSession = new Session() { UserId = guestUser.Id, Token = guestToken }; Session orphanSession = new Session() { UserId = Guid.NewGuid(), Token = orphanToken }; IQueryable <Session> sessions = new List <Session> { existingUserSession, newUserSession, guestSession, orphanSession }.AsQueryable(); IQueryable <Tete.Models.Localization.UserLanguage> userLanguages = new List <Tete.Models.Localization.UserLanguage> { new Tete.Models.Localization.UserLanguage() { } }.AsQueryable(); IQueryable <Tete.Models.Users.Profile> userProfiles = new List <Tete.Models.Users.Profile> { new Tete.Models.Users.Profile(existingUser.Id) { About = about, PrivateAbout = privateAbout } }.AsQueryable(); var mockUsers = MockContext.MockDBSet <User>(users); var mockLogins = MockContext.MockDBSet <Login>(logins); var mockSessions = MockContext.MockDBSet <Session>(sessions); var mockUserLanguages = MockContext.MockDBSet <Tete.Models.Localization.UserLanguage>(userLanguages); var mockUserProfiles = MockContext.MockDBSet <Tete.Models.Users.Profile>(userProfiles); var mockUserAccessRoles = MockContext.MockDBSet <AccessRole>(userAccessRoles); mockContext.Setup(c => c.Users).Returns(mockUsers.Object); mockContext.Setup(c => c.Logins).Returns(mockLogins.Object); mockContext.Setup(c => c.Sessions).Returns(mockSessions.Object); mockContext.Setup(c => c.UserLanguages).Returns(mockUserLanguages.Object); mockContext.Setup(c => c.UserProfiles).Returns(mockUserProfiles.Object); mockContext.Setup(c => c.AccessRoles).Returns(mockUserAccessRoles.Object); }
public static void SetLoginPage(Frame F) { LoginPage = new Login(F); }
public async Task <IActionResult> Post([FromServices] TokenOptions tokenOptions, [FromBody] Login login) { if (login == null || string.IsNullOrEmpty(login.Username) || string.IsNullOrEmpty(login.Password)) { return(Unauthorized()); } if (login.Username.Equals("usr") && login.Password.Equals("pwd")) { var gi = new GenericIdentity(login.Username); var ci = new ClaimsIdentity(gi, new[] { new Claim(JwtRegisteredClaimNames.Jti, tokenOptions.GenerateJti()), new Claim(JwtRegisteredClaimNames.UniqueName, login.Username), new Claim("Jwt", "User"), new Claim("Jwt", "Admin") }); var tokenCreation = DateTime.Now; var tokenExpiration = tokenCreation.Add(TimeSpan.FromMinutes(60)); var handler = new JwtSecurityTokenHandler(); var security = new SecurityTokenDescriptor { Issuer = tokenOptions.Issuer, Audience = tokenOptions.Audience, SigningCredentials = tokenOptions.Credentials, Subject = ci, NotBefore = tokenCreation, Expires = tokenExpiration }; var securityToken = handler.CreateToken(security); var answer = JsonConvert.SerializeObject( new { access_token = handler.WriteToken(securityToken), expires = tokenExpiration, creation = tokenCreation, data = new { username = login.Username } } ); return(await Task.FromResult(Json(answer))); } return(Unauthorized()); }
public HomeController(Login loginService) { _loginService = loginService; }
//For Test //public int PageOffset { get; set; } public Client(ISettings settings) { if (settings.UsePogoDevHashServer || settings.UseCustomAPI) { if (string.IsNullOrEmpty(settings.AuthAPIKey)) { throw new AuthConfigException("You have selected Pogodev API but not provide proper API Key"); } Cryptor = new Cipher(); ApiEndPoint = Constants.ApiEndPoint; Hasher = new PokefarmerHasher(settings, settings.AuthAPIKey, settings.DisplayVerboseLog, ApiEndPoint); // These 4 constants below need to change if we update the hashing server API version that is used. Unknown25 = Constants.Unknown25; // WARNING! IF YOU CHANGE THE APPVERSION BELOW ALSO UPDATE THE API_VERSION AT THE TOP OF THE FILE! AppVersion = Constants.AppVersion; CurrentApiEmulationVersion = new Version(Constants.API_VERSION); UnknownPlat8Field = Constants.UnknownPlat8Field; } /* * else * if (settings.UseLegacyAPI) * { * Hasher = new LegacyHashser(); * Cryptor = new LegacyCrypt(); * * Unknown25 = -816976800928766045;// - 816976800928766045;// - 1553869577012279119; * AppVersion = 4500; * CurrentApiEmulationVersion = new Version("0.45.0"); * } */ else { throw new AuthConfigException("No API method was selected in auth.json"); } Settings = settings; Proxy = InitProxy(); PokemonHttpClient = new PokemonHttpClient(); Login = new Login(this); Player = new Player(this); Download = new Download(this); Inventory = new Inventory(this); Map = new Map(this); Fort = new Fort(this); Encounter = new Encounter(this); Misc = new Misc(this); KillswitchTask = new KillSwitchTask(this); Player.SetCoordinates(Settings.DefaultLatitude, Settings.DefaultLongitude, Settings.DefaultAltitude); Platform = settings.DevicePlatform.Equals("ios", StringComparison.Ordinal) ? Platform.Ios : Platform.Android; // We can no longer emulate Android so for now just overwrite settings with randomly generated iOS device info. if (Platform == Platform.Android) { Signature.Types.DeviceInfo iosInfo = DeviceInfoHelper.GetRandomIosDevice(); settings.DeviceId = iosInfo.DeviceId; settings.DeviceBrand = iosInfo.DeviceBrand; settings.DeviceModel = iosInfo.DeviceModel; settings.DeviceModelBoot = iosInfo.DeviceModelBoot; settings.HardwareManufacturer = iosInfo.HardwareManufacturer; settings.HardwareModel = iosInfo.HardwareModel; settings.FirmwareBrand = iosInfo.FirmwareBrand; settings.FirmwareType = iosInfo.FirmwareType; // Clear out the android fields. settings.AndroidBoardName = ""; settings.AndroidBootloader = ""; settings.DeviceModelIdentifier = ""; settings.FirmwareTags = ""; settings.FirmwareFingerprint = ""; // Now set the client platform to ios Platform = Platform.Ios; } }
public HttpResponseMessage Login(HttpRequestMessage request, int operationResult, Login login) { Result res = new Result(); res.result = "用户不存在"; var resp = request.CreateResponse(HttpStatusCode.InternalServerError, res); switch (operationResult) { case 1: IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { "userId", login.UserId }, { "password", login.InPassword }, { "time", DateTime.Now } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, "UTF-8"); DataConnection pclsCache = new DataConnection(); int a = userInfoMethod.MstUserChangeToken(pclsCache, login.UserId, token); res.result = "登录成功|" + token; resp = request.CreateResponse(HttpStatusCode.OK, res); break; case 0: res.result = "用户不存在"; resp = request.CreateResponse(HttpStatusCode.InternalServerError, res); break; case -1: res.result = "密码错误"; resp = request.CreateResponse(HttpStatusCode.BadRequest, res); break; case -2: res.result = "数据库连接失败"; resp = request.CreateResponse(HttpStatusCode.NotFound, res); break; default: break; } return(resp); }
public void CadastraPropostaPF() { #region Abrir o Chrome //inicializando o chrome IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("http://main.safety8.local/#/login?cnpj=72.408.271%2F0001-91"); driver.Manage().Window.Maximize(); System.Threading.Thread.Sleep(3000); #endregion #region Login var cnpj = driver.FindElement(By.Id("cnpj")); cnpj.SendKeys("72408271000191"); System.Threading.Thread.Sleep(8000); { var elemento = driver.FindElement(By.CssSelector(".logo-login-q")); Actions builder = new Actions(driver); builder.MoveToElement(elemento).ClickAndHold().Perform(); } { var elemento = driver.FindElement(By.CssSelector(".efeitoOverlay")); Actions builder = new Actions(driver); builder.MoveToElement(elemento).Release().Perform(); } driver.FindElement(By.CssSelector(".container-fluid")).Click(); driver.FindElement(By.CssSelector(".ng-scope > .animated")).Click(); { var dropdown = driver.FindElement(By.CssSelector(".ng-scope > .animated")); dropdown.FindElement(By.XPath("/html/body/div[5]/div[2]/div[2]/div/div/div/div/div/div[2]/div[2]/select/option[3]")).Click(); //driver.Quit(); } Login login = new Login(); driver.FindElement(By.CssSelector(".ng-scope > .animated")).Click(); driver.FindElement(By.Id("usuario")).Click(); driver.FindElement(By.Id("usuario")).SendKeys(login.RetornaUsuario()); driver.FindElement(By.Id("senha")).SendKeys(login.RetornaSenha()); driver.FindElement(By.CssSelector(".button-login-q")).Click(); #endregion #region Cadastro de Proposta PF //Realizar a busca System.Threading.Thread.Sleep(3000);//Aguardando a pagina carregar driver.FindElement(By.XPath("/html/body/div[5]/div[2]/div[3]/div[4]/div[1]/vs-portal-consultas-directive/div/div/div/div[3]/div")).Click(); driver.FindElement(By.XPath("/html/body/div[5]/div[2]/div[3]/div[4]/div[1]/vs-portal-consultas-directive/div/div/div/div[3]/div/input")).SendKeys("fausto silva"); //Clicar no busca driver.FindElement(By.CssSelector("div:nth-child(5) > div.container-fluid > div:nth-child(3) > div.index-conteudo.ng-scope.animated.fadeIn.conteudo-geral > div:nth-child(1) > vs-portal-consultas-directive > div > div > div > div:nth-child(3) > div > span > button")).Click(); //Clicar no cliente System.Threading.Thread.Sleep(8000);//Aguardando a pagina carregar IWebElement cliente = driver.FindElement(By.PartialLinkText("FAUSTO SILVA")); cliente.Click(); //Clicar em seguros System.Threading.Thread.Sleep(8000);//Aguardando a pagina carregar driver.FindElement(By.XPath("/html/body/div[5]/div[1]/nav/div[3]/div/vs-menu-responsivo/div/div[2]/div/div/ul/li[2]/a")).Click(); //Clicar em incluir System.Threading.Thread.Sleep(8000);//Aguardando a pagina carregar driver.FindElement(By.XPath("/html/body/div[5]/div[2]/div[3]/div[4]/div/vs-relacao3/div/div/div/div/div/div/div[1]/button")).Click(); //seleciona seguradora System.Threading.Thread.Sleep(2000);//Aguardando a pagina carregar driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_cia_codigo")).Click(); driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_cia_codigo")).SendKeys("porto"); driver.FindElement(By.CssSelector("strong")).Click(); //Seleciona o Produto driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_ramo_codigo")).Click(); driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_ramo_codigo")).SendKeys("automoveis"); System.Threading.Thread.Sleep(2000);//Aguardando a pagina carregar driver.FindElement(By.LinkText("AUTOMOVEIS")).Click(); //Seleciona a Origem driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_docori_codigo")).Click(); driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_docori_codigo")).SendKeys("geral"); System.Threading.Thread.Sleep(2000);//Aguardando a pagina carregar driver.FindElement(By.LinkText("GERAL")).Click(); //Seleciona o ponto de vendas driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_pto_codigo")).Click(); driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_pto_codigo")).Clear(); //Deixa o campo vazio driver.FindElement(By.Name("frmAutoFormdocumentosundefined_edt_pto_codigo")).SendKeys("matriz"); System.Threading.Thread.Sleep(2000); //Aguardando a pagina carregar driver.FindElement(By.LinkText("MATRIZ")).Click(); //Gravar driver.FindElement(By.CssSelector("div:nth-child(2) > .botoes-bottom-verde")).Click(); #endregion MetodosNavega.SairPlus(driver); driver.Quit(); }
public async Task <IActionResult> Logins([FromBody] Login model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByNameAsync(model.Username); if (user == null) { user = await _userManager.FindByEmailAsync(model.Username);//.Include(b => b.User); if (user == null) { return(BadRequest("Invalid Username: user doesn't Exist")); } } var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true); if (!result.Succeeded) { return(BadRequest($"Incorrect Password for {model.Username}")); } await _signInManager.SignInAsync(user, true, "Bearer"); var userClaims = await _userManager.GetClaimsAsync(user); userClaims.Add(new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)); userClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("wertyuiopasdfghjklzxcvbnm123456")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var com = _companyRepository.Query().LastOrDefault(); var name = "Acyst Tech"; var image = "logo.png"; var company = "Acyst Technology Company"; if (user.EmployeeId != null) { var emp = _employeeRepository.Query().FirstOrDefault(e => e.EmployeeId == user.EmployeeId); if (emp != null) { name = emp.FullName; } image = emp.Image; } if (com != null) { company = com.Name; } userClaims.Add(new Claim("Id", user.Id)); userClaims.Add(new Claim("FullName", name)); userClaims.Add(new Claim("Company", company)); userClaims.Add(new Claim("Image", image)); userClaims.Add(new Claim("Mobile", user.PhoneNumber)); userClaims.Add(new Claim("Email", user.Email)); userClaims.Add(new Claim("UserType", user.UserType)); userClaims.Add(new Claim("LoginTime", DateTime.Now.ToString())); var token = new JwtSecurityToken( issuer: _configuration.GetSection("AppSettings")["Url"], audience: "http://localhost:53720", claims: userClaims, expires: DateTime.Now.AddHours(12), signingCredentials: creds); user.Login = DateTime.UtcNow; user.IsLoggedIn = true; await _userManager.UpdateAsync(user); var auth = new JwtSecurityTokenHandler().WriteToken(token); await _userManager.SetAuthenticationTokenAsync(user, "Server", user.UserName, auth); var tok = await _userManager.CreateSecurityTokenAsync(user); //await _signInManager.CanSignInAsync(user); return(Ok(new { Access_Token = auth, Expires_In_Hours = 12, Date = DateTime.UtcNow })); }
// POST: api/Login public async Task <bool> Post(Login login) { return(await _logic.LoginAsync(login)); }
private Login Authenticate(LoginModel model) { Login user = _login.ValidateLogin(model.UserName, model.Password); return(user); }
private void MySession_FormClosed(object sender, FormClosedEventArgs e) { Form fmrLogin = new Login(); fmrLogin.Show(); }
/// <summary> /// Shows all operators with their data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void llbPass_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { MessageBox.Show(Login.View(), "USER INFO", MessageBoxButtons.OK); }
public Bot(Configuration.BotInfo config, Log log, string apiKey, UserHandlerCreator handlerCreator, Login _login, bool debug = false) { this.main = _login; logOnDetails = new SteamUser.LogOnDetails { Username = _login.Username, Password = _login.Password }; ChatResponse = ""; TradePollingInterval = 50; Admins = new ulong[1]; Admins[0] = 123456789; this.apiKey = apiKey; try { LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), "Debug", true); } catch (ArgumentException) { Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'"); LogLevel = Log.LogLevel.Info; } this.log = log; CreateHandler = handlerCreator; BotControlClass = "SteamBot.SimpleUserHandler"; // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; log.Debug("Initializing Steam account..."); main.Invoke((Action)(() => { main.label_status.Text = "Initializing Steam account..."; })); SteamClient = new SteamClient(); SteamTrade = SteamClient.GetHandler <SteamTrading>(); SteamUser = SteamClient.GetHandler <SteamUser>(); SteamFriends = SteamClient.GetHandler <SteamFriends>(); log.Info("Connecting..."); main.Invoke((Action)(() => { main.label_status.Text = "Connecting to Steam..."; })); SteamClient.Connect(); Thread CallbackThread = new Thread(() => // Callback Handling { while (true) { CallbackMsg msg = SteamClient.WaitForCallback(true); HandleSteamMessage(msg); } }); CallbackThread.Start(); CallbackThread.Join(); log.Success("Done loading account!"); main.Invoke((Action)(() => { main.label_status.Text = "Done loading account!"; })); }
private void pgRoomStatus_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (App.mainWindow.Visibility == Visibility.Visible) { if (Auth.GetLoginStatus() && Auth.GetLoggedInUserTypeIsCustomer() == false) { // Disable buttons btnRoomDetail.IsEnabled = false; btnSearch.IsEnabled = true; // Load Hotel info SqlCommand cmd = new SqlCommand(); cmd.Connection = dbQLKS.dbConnection; cmd.CommandType = CommandType.Text; cmd.CommandText = @"select * from KhachSan as KS, NhanVien as NV where NV.maNV = '" + Auth.GetLoggedInUserId() + "' AND NV.MaKS = KS.maKS"; SqlDataReader dr; dbQLKS.dbConnection.Open(); dr = cmd.ExecuteReader(); if (dr.Read()) { lblHotelName.Content = dr["tenKS"].ToString(); lblHotelAddress.Content = dr["soNha"] + ", " + dr["duong"] + ", " + dr["quan"] + ", " + dr["thanhPho"]; MaKS = dr["maKS"].ToString(); // Load RoomType list cmd.CommandText = "SELECT * FROM LoaiPhong WHERE maKS = '" + MaKS + "'"; List <RoomTypeRow> RoomtTypeList = new List <RoomTypeRow>(); dr.Close(); dr = cmd.ExecuteReader(); while (dr.Read()) { RoomTypeRow roomTypeRow = new RoomTypeRow(); roomTypeRow.MaLoaiPhong = dr["maLoaiPhong"].ToString(); roomTypeRow.TenLoaiPhong = dr["tenLoaiPhong"].ToString(); RoomtTypeList.Add(roomTypeRow); } dgRoomStatus.ItemsSource = RoomtTypeList; } else { MessageBox.Show("You are not beloing to any Hotel"); Auth.Logout(); App.mainWindow.Hide(); Login x = new Login(); x.Show(); } dbQLKS.dbConnection.Close(); } else { App.mainWindow.Hide(); Login x = new Login(); x.Show(); } } }
private WatchlistDisplayModel GetMarketJobWatchlist(WatchlistDisplayModel model, Login login) { var data = db.JobWatchList.Where(x => x.PersonId == login.Id && x.IsActive) .Select(x => new WatctlistItem <JobMarketModel> { Market = new MarketJobViewModel { IsApplyByUser = db.JobQuote.Any(y => y.JobRequestId == x.TenantJobRequest.Id && y.ProviderId == login.Id && y.Status.ToLower() == "opening"), IsOwnedByUser = db.TenantJobRequest.FirstOrDefault(y => y.Id == x.TenantJobRequest.Id).OwnerId == login.Id, }, Model = new JobMarketModel { WatchListId = x.Id, Id = x.TenantJobRequest.Id, Title = x.TenantJobRequest.Title, MaxBudget = x.TenantJobRequest.MaxBudget, JobDescription = x.TenantJobRequest.JobDescription, PostedDate = x.TenantJobRequest.CreatedOn, MediaFiles = x.TenantJobRequest.TenantJobRequestMedia.Select(y => new MediaModel { Id = y.Id, NewFileName = y.NewFileName, OldFileName = y.OldFileName }).ToList() }, Address = new AddressViewModel { AddressId = x.TenantJobRequest.Property.Address.AddressId, CountryId = x.TenantJobRequest.Property.Address.AddressId, Number = x.TenantJobRequest.Property.Address.Number, Street = x.TenantJobRequest.Property.Address.Street, Suburb = x.TenantJobRequest.Property.Address.Suburb, Region = x.TenantJobRequest.Property.Address.Region, City = x.TenantJobRequest.Property.Address.City, PostCode = x.TenantJobRequest.Property.Address.PostCode, Longitude = x.TenantJobRequest.Property.Address.Lng, Latitude = x.TenantJobRequest.Property.Address.Lat } }); var allItems = data.OrderBy(x => x.Model.Title).ToPagedList(model.Page, 2); allItems.ToList().ForEach(x => x.Model.MediaFiles.ToList().ForEach(y => y.InjectMediaModelViewProperties())); if (string.IsNullOrWhiteSpace(model.SortOrder)) { model.SortOrder = "Title"; } switch (model.SortOrder) { case "Title": data = data.OrderBy(x => x.Model.Title); break; case "Title_Desc": data = data.OrderByDescending(x => x.Model.Title); break; case "MaxBudget": data = data.OrderBy(x => x.Model.MaxBudget); break; case "MaxBudget_Desc": data = data.OrderByDescending(x => x.Model.MaxBudget); break; case "Date_Desc": data = data.OrderByDescending(x => x.Model.PostedDate); break; case "Date": data = data.OrderBy(x => x.Model.PostedDate); break; default: data = data.OrderByDescending(x => x.Model.Title); break; } if (!String.IsNullOrWhiteSpace(model.SearchString)) { SearchUtil searchTool = new SearchUtil(); int searchType = searchTool.CheckDisplayType(model.SearchString); string formatString = searchTool.ConvertString(model.SearchString); data = data.Where(x => x.Model.Title.ToLower().Contains(formatString) ); } ; var items = data.ToPagedList(model.Page, 9); items.ToList().ForEach(x => x.Model.MediaFiles.ToList().ForEach(y => y.InjectMediaModelViewProperties())); if (String.IsNullOrWhiteSpace(model.SearchString)) { model.Page = 1; } var sortOrders = new List <SortOrderModel>(); var rvr = new RouteValueDictionary(new { ItemType = "MarketJob", SearchString = model.SearchString }); sortOrders.Add(new SortOrderModel { SortOrder = "Title", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Title") }); sortOrders.Add(new SortOrderModel { SortOrder = "Title_Desc", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Title_Desc") }); sortOrders.Add(new SortOrderModel { SortOrder = "MaxBudget", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "MaxBudget") }); sortOrders.Add(new SortOrderModel { SortOrder = "MaxBudget_Desc", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "MaxBudget_Desc") }); sortOrders.Add(new SortOrderModel { SortOrder = "Date_Desc", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Date_Desc") }); sortOrders.Add(new SortOrderModel { SortOrder = "Date", ActionName = "Index", RouteValues = rvr.AddRouteValue("SortOrder", "Date") }); model.SortOrders = sortOrders; model.PagedInput = new PagedInput { ActionName = "Index", ControllerName = "Watchlist", PagedLinkValues = new RouteValueDictionary(new { ItemType = "MarketJob", SortOrder = model.SortOrder, SearchString = model.SearchString }) }; model.PageCount = items.Count == 0 ? allItems.PageCount : items.PageCount; model.SearchCount = items.Count; model.Items = items.Count == 0 ? allItems : items; return(model); }
public async Task <ApiResult> Login(Login request) { return(await _mediator.Send(request)); }