public void AddNewUser(User user) { user.StartGame = true; user.Ordinal = ordinal; this.listuser.Add(user); ordinal++; }
public void addUser(string[] info) { int byteCount; bool validUserDate = true; bool valid = false; User temp = new User(info); if(temp.DateOfBirth == null) { validUserDate = false; } if(validUserDate) { valid = worker.AddUser(temp); } if (valid == true) { string success = "SUCCESS,"; byte[] message = encoding.GetBytes(success); byteCount = clientSocket.Send(message); clientSocket.Close(); } else { string failed = "FAILED, Bad registration"; byte[] message = encoding.GetBytes(failed); byteCount = clientSocket.Send(message); clientSocket.Close(); } }
public Message(User aUser, String aContent) { //TODO: incremented id _sender = aUser; _content = aContent; _likes = 0; _dislike = 0; _isDeleted = false; }
/// <summary>Add new client(list/log/new thread)</summary> public void AddClient( User client ) { if ( this.listBox_ClientList.InvokeRequired ) { ClientDelegate addClient = new ClientDelegate( AddClient ); this.listBox_ClientList.Invoke( addClient , client ); } else { this.ClientList.Add( client ); this.listBox_ClientList.Items.Add( client.userName ); } }
public ActionResult Login(User model, string returnUrl) { bool userValid = model.Name != null && model.Name.Equals(this._configuration.UserId, StringComparison.InvariantCultureIgnoreCase) && model.Password != null && model.Password.Equals(this._configuration.Password, StringComparison.InvariantCulture); if(userValid) { FormsAuthentication.SetAuthCookie(model.Name, false); if(Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } ModelState.AddModelError("", "The user name or password provided is incorrect."); // If we got this far, something failed, redisplay form return View(); }
public void testAddFileOwnershipFunctionality() { User user = new User("username", "password"); Search.database.registerUser(user); CaesFile file = new CaesFile("testfile.txt", "Test"); Search.database.AddFile(file); Search.database.AddOwnership(user.Username, file.Path); var owned = Search.database.GetListOfOwnedFiles(user).First(); Assert.AreEqual(file.Path, owned); }
public bool AddFriend(User user, User friend) { bool success = true; bool alreadyFriends = false; List<String> value = getFriendsList(user.Username); foreach(var name in value) { string[] tokens = name.Split(' '); if (tokens[0].Equals(friend.Username)) alreadyFriends = true; } if (!alreadyFriends) { try { using (SqlConnection connection = new SqlConnection(conString)) { connection.Open(); SqlCommand command = new SqlCommand("INSERT INTO Friends (Username, FriendUsername, FriendIP, UserIP) VALUES " + "(@Username, @FriendUsername, @FriendIP, @UserIP)", connection); command.Parameters.Add("@Username", SqlDbType.NVarChar, 50); command.Parameters["@Username"].Value = user.Username; command.Parameters.Add("@FriendUsername", SqlDbType.NVarChar, 50); command.Parameters["@FriendUsername"].Value = friend.Username; command.Parameters.Add("@FriendIP", SqlDbType.NVarChar, 50); command.Parameters["@FriendIP"].Value = friend.IP; command.Parameters.Add("@UserIP", SqlDbType.NVarChar, 50); command.Parameters["@UserIP"].Value = user.IP; command.ExecuteNonQuery(); connection.Close(); } } catch (Exception e) { } } else { success = false; } return success; }
public UserModel Create(User user) { return new UserModel() { Id = user.Id, Name = user.Name, DeviceId = user.DeviceId, Basic = user.Basic, Premium = user.Premium, Energy = user.Energy, Registered = user.AccountRegistered, KilledBosses = user.KilledBosses, Token = user.Token, TokenExpiration = user.TokenExpireTime }; }
public void RemoveClient( User user ) { if ( this.listBox_ClientList.InvokeRequired ) { ClientDelegate removeClient = new ClientDelegate( RemoveClient ); this.listBox_ClientList.Invoke( removeClient , user ); } else { int index = this.ClientList.IndexOf( user ); if ( index >= 0 && index <= this.listBox_ClientList.Items.Count ) { this.listBox_ClientList.Items.RemoveAt( index ); this.ClientList.Remove( user ); } } }
public bool AddUser(User user) { try { using (SqlConnection connection = new SqlConnection(conString)) { connection.Open(); SqlCommand command = new SqlCommand("INSERT INTO Users (Username, Password, Name, Email, Address, Phone, DateOfBirth, IP) VALUES " + "(@Username, @Password, @Name, @Email, @Address, @Phone, @DateOfBirth, @IP)", connection); command.Parameters.Add("@Username", SqlDbType.NVarChar, 50); command.Parameters["@Username"].Value = user.Username; command.Parameters.Add("@Password", SqlDbType.NVarChar, 50); command.Parameters["@Password"].Value = user.Password; command.Parameters.Add("@Name", SqlDbType.NVarChar, 50); command.Parameters["@Name"].Value = user.Name; command.Parameters.Add("@Email", SqlDbType.NVarChar, 50); command.Parameters["@Email"].Value = user.Email; command.Parameters.Add("@Address", SqlDbType.NVarChar, 50); command.Parameters["@Address"].Value = user.Address; command.Parameters.Add("@Phone", SqlDbType.NVarChar, 50); command.Parameters["@Phone"].Value = user.Phone; command.Parameters.Add("@DateOfBirth", SqlDbType.DateTime); command.Parameters["@DateOfBirth"].Value = user.DateOfBirth; command.Parameters.Add("@IP", SqlDbType.NVarChar, 50); command.Parameters["@IP"].Value = user.IP; command.ExecuteNonQuery(); connection.Close(); return true; } } catch (Exception e) { return false; } }
public void testIsRegisteredInDatabase() { LINQDatabase mockDatabase = mocks.Stub<LINQDatabase>(); User zarakavaUse = new User(); zarakavaUse.setName("Zarakava"); zarakavaUse.setPass("Testing"); using (mocks.Record()) { mockDatabase.getUser("Zarakava"); LastCall.Return(zarakavaUse); mockDatabase.getUser("NULLMAN"); LastCall.Return(null); } UserRegistration.setDatabase(mockDatabase); Assert.IsTrue(UserRegistration.isRegistered("Zarakava")); Assert.IsFalse(UserRegistration.isRegistered("NULLMAN")); }
private static void OnTimedEvent(Object source, ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime); string[] localNames = usernames.ToArray(); string[] localIPS = ips.ToArray(); users.Clear(); for (int i = 0; i < localNames.Length; i++) { User temp = new User(); temp.Username = localNames[i]; temp.IP = localIPS[i]; users.Add(temp); } foreach (var user in users) { SendActiveList(user); } users.Clear(); }
public void testFileOwnershipUnknownUser() { User u1 = new User("testuser1", "p"); User u2 = new User("testuser2", "p"); CaesFile f1 = new CaesFile("text.txt", "Text"); CaesFile f2 = new CaesFile("other.txt", "Other"); Search.database.AddFile(f1); Search.database.AddFile(f2); List<String> owned = Search.database.GetListOfOwnedFiles(u1); List<String> owned2 = Search.database.GetListOfOwnedFiles(u2); Assert.AreEqual(new List<String>(), owned); Assert.AreEqual(new List<String>(), owned2); }
public void testFileOwnershipTwoUsersOneFileEach() { User u1 = new User("testuser1", "p"); User u2 = new User("testuser2", "p"); Search.database.registerUser(u1); Search.database.registerUser(u2); CaesFile f1 = new CaesFile("text.txt", "Text"); CaesFile f2 = new CaesFile("other.txt", "Other"); Search.database.AddFile(f1); Search.database.AddFile(f2); Search.database.AddOwnership(u1.Username, f1.Path); Search.database.AddOwnership(u2.Username, f2.Path); List<String> owned = Search.database.GetListOfOwnedFiles(u1); List<String> owned2 = Search.database.GetListOfOwnedFiles(u2); List<String> expected = new List<String>(); expected.Add(f1.Path); List<String> expected2 = new List<String>(); expected2.Add(f2.Path); Assert.AreEqual(expected, owned); Assert.AreEqual(expected2, owned2); }
public void testCheckFileOwnershipFunctionality() { User user = new User("username", "password"); Search.database.registerUser(user); CaesFile file = new CaesFile("testfile.txt", "Test"); Search.database.AddFile(file); Search.database.AddOwnership(user.Username, file.Path); var isOwned = Search.database.CheckIfOwnsFile(user.Username, file.Path); var shouldNotBeOwned = Search.database.CheckIfOwnsFile(user.Username, "uadf.txt"); Assert.IsTrue(isOwned); Assert.IsFalse(shouldNotBeOwned); }
private void sendToClient(User user, String message) { try { user.bw.Write(message); user.bw.Flush(); //清空缓冲区,使数据写上传送,而不是等缓冲区满再发送 AddItemToListBox(String.Format("向[{0}]发送:{1}", user.userName, message)); } catch { AddItemToListBox(String.Format("向[{0}]发送信息失败", user.userName)); } }
private void sendToAllClient(User user, String message) { String command = message.Split(',')[0].ToLower(); if (command == "login") { for (int i = 0; i < userList.Count; i++) { if (userList[i].userName != user.userName) { sendToClient(userList[i], message); //将登录信息发给所有人 sendToClient(user,"login,"+userList[i].userName); //将已登录人信息发给刚登陆的人 } } } else if (command == "logout") { for (int i = 0; i < userList.Count; i++) { if (userList[i].userName != user.userName) { sendToClient(userList[i], message); } } } }
/// <summary> /// Adds a user to the database. /// </summary> /// <param name="email">The email of the user</param> /// <param name="password">The encrypted password of the user</param> /// <returns>The id of the added user. -1 if a user with the given email already exists</returns> public int AddUser(String email, String password) { using (PieFactoryEntities context = new PieFactoryEntities()) { User user = new User(); user.email = email; user.password = password; //Add a root folder named "root" Folder folder = new Folder(); folder.name = "root"; user.Folder = folder; context.Users.AddObject(user); context.SaveChanges(); return user.id; } }
public void TestRegisterAndGetUser() { User user = new User("山田", "saikyou"); Search.database.registerUser(user); var actual = Search.database.getUser("山田"); Assert.AreEqual(user, actual); Assert.AreEqual(user.Username, actual.Username); Assert.AreEqual(user.PasswordHash, actual.PasswordHash); }
public bool setToAccept(User user, User friend) { bool success = true; try { using (SqlConnection connection = new SqlConnection(conString)) { connection.Open(); SqlCommand command = new SqlCommand("UPDATE Friends SET Accepted = 1 WHERE Username = @FriendUsername AND FriendUsername = @Username", connection); command.Parameters.Add("@Username", SqlDbType.NVarChar, 50); command.Parameters["@Username"].Value = user.Username; command.Parameters.Add("@FriendUsername", SqlDbType.NVarChar, 50); command.Parameters["@FriendUsername"].Value = friend.Username; command.ExecuteNonQuery(); connection.Close(); } } catch (Exception e) { } success = AddFriend(user, friend); try { using (SqlConnection connection = new SqlConnection(conString)) { connection.Open(); SqlCommand command = new SqlCommand("UPDATE Friends SET Accepted = 1 WHERE Username = @Username AND FriendUsername = @FriendUsername", connection); command.Parameters.Add("@Username", SqlDbType.NVarChar, 50); command.Parameters["@Username"].Value = user.Username; command.Parameters.Add("@FriendUsername", SqlDbType.NVarChar, 50); command.Parameters["@FriendUsername"].Value = friend.Username; command.ExecuteNonQuery(); connection.Close(); } } catch (Exception e) { } return success; }
public User Parse(UserModel userModel) { try { var user = new User() { Id = userModel.Id, Name = userModel.Name, Basic = userModel.Basic, Premium = userModel.Premium, DeviceId = userModel.DeviceId, KilledBosses = userModel.KilledBosses, Energy = userModel.Energy, AccountRegistered = userModel.Registered, Token = userModel.Token, TokenExpireTime = userModel.TokenExpiration, }; return user; } catch { return null; } }
public Mail(User toUsername, User fromUsername, String message) : this(toUsername.Username, fromUsername.Username, message) { }
private static void SendActiveList(User destinationUser) { userSemaphore.WaitOne(); Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string message; string[] localNames = usernames.ToArray(); string[] localIPS = ips.ToArray(); foreach (var user in users) { message = ""; for(int i = 0; i < localNames.Length; i++) { message += localNames[i]; message += " "; message += localIPS[i]; message += ','; } IPAddress send_to_address = IPAddress.Parse(destinationUser.IP); IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 12001); byte[] data = Encoding.ASCII.GetBytes(message); try { sending_socket.SendTo(data, sending_end_point); } catch (Exception e) { } } userSemaphore.Release(); }
public void TestInvalidToUser() { var from = new User("fromUser", "fromUserpwd"); var to = new User("toUser", "toUserpwd"); Search.database.registerUser(from); String message = "hello toUser"; Search.database.SendMail(to, from, message); }
public void TestMultipleMessagesWithSameToFrom() { var from = new User("fromUser", "fromUserpwd"); var to = new User("toUser", "toUserpwd"); Search.database.registerUser(from); Search.database.registerUser(to); String message = "hello toUser"; String message2 = "hello toUser second"; Search.database.SendMail(to, from, message); Search.database.SendMail(to, from, message2); var rec = Search.database.CheckMail(to.Username); Mail m1 = new Mail(to, from, message); Mail m2 = new Mail(to, from, message2); var expected = new List<Mail>(); expected.Add(m1); expected.Add(m2); Assert.AreEqual(expected.First().Message, rec.First().Message); expected.Remove(expected.First()); rec.Remove(rec.First()); Assert.AreEqual(expected.First().Message, rec.First().Message); }
private void listenClientConnect() { TcpClient newClient = null; while (true) //循环监听 { try { newClient = myListener.AcceptTcpClient(); //有客户端接入,新建一个与客户端通信的套接字 } catch { break; } User user = new User(newClient); Thread threadReceive = new Thread(ReceiveData); //开启与客户端通信的线程 threadReceive.Start(user); userList.Add(user); AddItemToListBox(String.Format("[{0}]进入", newClient.Client.RemoteEndPoint)); AddItemToListBox(String.Format("当前连接用户数:{0}", userList.Count)); } }
public void TestSendReceiveMailMessage() { var from = new User("fromUser", "fromUserpwd"); var to = new User("toUser", "toUserpwd"); Search.database.registerUser(from); Search.database.registerUser(to); String message = "hello toUser"; Search.database.SendMail(to, from, message); var rec = Search.database.CheckMail(to).First(); Assert.AreEqual(message, rec.Message); Assert.AreEqual(to.Username, rec.To); Assert.AreEqual(from.Username, rec.From); }
/// <summary> /// 用户退出,更新状态 /// </summary> /// <param name="user"></param> private void RemoveUser(User user) { userList.Remove(user); user.Close(); AddItemToListBox(String.Format("当前连接用户数:{0}", userList.Count)); }
public void FriendRequest() { string request = ""; int byteCount; byte[] incoming = new byte[1500]; byteCount = clientSocket.Receive(incoming); request = encoding.GetString(incoming); string[] package = request.Split(','); if(package[0] == "ADD") { User user = new User(); user.Username = package[1]; user.IP = package[2]; User friend = new User(); friend.Username = package[3]; friend.IP = package[4]; bool areFriends = checkIfFriends(user.Username, friend.Username); if(areFriends) { string info = "Already added by friend. Accept invite when prompted."; byte[] message = encoding.GetBytes(info); byteCount = clientSocket.Send(message); clientSocket.Close(); } else { worker.AddFriend(user, friend); string info = "Friend added."; byte[] message = encoding.GetBytes(info); byteCount = clientSocket.Send(message); clientSocket.Close(); } } if(package[0] == "ACCEPT") { User user = new User(); //user username, user ip, friend username, friend ip user.Username = package[1]; user.IP = package[2]; User friend = new User(); friend.Username = package[3]; friend.IP = package[4]; bool success = worker.setToAccept(user, friend); if (success) { string info = "Friend request accepted."; byte[] message = encoding.GetBytes(info); byteCount = clientSocket.Send(message); clientSocket.Close(); } else { string info = "Friend accept invalid"; byte[] message = encoding.GetBytes(info); byteCount = clientSocket.Send(message); clientSocket.Close(); } } if(package[0] == "REJECT") { User user = new User(); user.Username = package[1]; User friend = new User(); friend.Username = package[2]; worker.reject(user, friend); string info = "Friend request rejected."; byte[] message = encoding.GetBytes(info); byteCount = clientSocket.Send(message); clientSocket.Close(); } }
public void receive() { while (!(client.Client.Poll(0, SelectMode.SelectRead) && client.Client.Available == 0)) { byte[] bytesFrom = new byte[(int)client.ReceiveBufferSize]; try { sslStream.Read(bytesFrom, 0, (int)client.ReceiveBufferSize); } catch (Exception e) { Console.WriteLine("Exception occured while trying to get data from client. Disconnecting..."); Console.WriteLine(e.StackTrace); Stop(); } String response = Encoding.ASCII.GetString(bytesFrom); String[] response_parts = response.Split('|'); if (response_parts.Length > 0) { User currentUser = null; switch (response_parts[0]) { case "0": //login if (response_parts.Length == 4) { int admin, id; _global.CheckLogin(response_parts[1], response_parts[2], out admin, out id); if (id > -1) { this.username = response_parts[1]; this.iduser = id; if (_global.GetUsers().First(item => item.id == response_parts[1]).isDoctor) { sendString("0|1|1|"); // Doctor } else { sendString("0|1|0|"); //Patient } } else { sendString("0|0|0|"); } } break; case "1": //meetsessies ophalen currentUser = _global.GetUsers().First(item => item.id == response_parts[1]); sendString("1|" + JsonConverter.GetUserSessions(currentUser)); break; case "2": //Livedata opvragen currentUser = _global.GetUsers().First(item => item.id == response_parts[1]); JsonConverter.GetLastMeasurement(currentUser.tests.Last()); break; case "3": //Nieuwe meetsessie aanmaken if (response_parts.Length == 6 && iduser != -1) { _global.AddSession(response_parts[1], int.Parse(response_parts[2]), response_parts[3]); } break; case "4": // Nieuwe patient User user = new User(response_parts[1], response_parts[2], Int32.Parse(response_parts[3]), Boolean.Parse(response_parts[4]), Int32.Parse(response_parts[5])); _global.NewUser(user); break; case "5": //data pushen naar meetsessie currentUser = _global.GetUsers().First(item => item.id == response_parts[1]); currentUser.tests.Last().AddMeasurement(JsonConvert.DeserializeObject<Measurement>(response_parts[2])); break; case "6": //chatberichten ontvangen van gebruikers //controleren of het bericht wel tekens bevat if (response_parts[3] != null) { String message = response_parts[3].TrimEnd('\0'); String receiver = response_parts[2]; String sender = response_parts[1]; string case6str = "7|" + sender + "|" + receiver + "|" + message; Console.WriteLine(case6str); sendString(case6str); foreach (var client in Program.Clients) { if (client.username == receiver) client.sendString("7|" + sender + "|" + receiver + "|" + message); } } break; case "8": //alle online Patients sturen naar Doctorclient if (response_parts[1] != null) { if (response_parts[1] == "doctor" || true) //TODO: doctor check { string strToSend = "8|"; List<string> activePatients = _global.GetActivePatients(); if (!(activePatients.Count > 0)) { strToSend += "-1"; } else { foreach (string patient in _global.GetActivePatients()) { strToSend += (patient + '\t'); } } sendString(strToSend.TrimEnd('\t')); } } break; default: break; } } } Stop(); }