public async Task <bool> TryRegister(string pass, string login) { await allDbContext.Clients.LoadAsync(); if (await allDbContext.Clients.FirstOrDefaultAsync(x => x.Password == pass) != null) { ErrorMessage = "Такой пароль уже есть"; return(false); } _client = new Client { Login = login, Email = Email, Name = _name, Password = pass }; allDbContext.Clients.Add(_client); try { await allDbContext.SaveChangesAsync(); Registered?.Invoke(); } catch (Exception ex) { ErrorMessage = ex.Message; return(false); } return(true); }
public Slot Register(Item item) { if (IsRegistered(item)) { this.Log($"Cannot register {item}: Already registered"); return(GetSlot(item)); } if (!CanRemoveSlot() && IsFull) { this.Log($"Cannot register {item}: No free slot available"); return(null); } this.Log($"Registering {item}"); var slot = new Slot(item); if (!IsFull) { Slots.Add(slot); Registered?.Invoke(this, new RegisteredEventArgs(item)); return(slot); } Unregister(FirstRemovableSlot.Item); Slots.Add(slot); Registered?.Invoke(this, new RegisteredEventArgs(item)); return(slot); }
/// <summary> /// Triggers the <see cref="Registered"/> event /// </summary> protected void TriggerRegisteredEvent(IPeer peer, IAccountData account) { if (Registered != null) { Registered.Invoke(peer, account); } }
private void OnEnable() { foreach (IManagedObject managedObject in GetComponents <IManagedObject>()) { Registered?.Invoke(managedObject); } }
public static void Register(Guid guid, PObject model) { if (!guid.Equals(model.Guid)) { return; } dict[guid] = model; Registered?.Invoke(typeof(GlobalModels), guid); }
private void Add(T instance) { if (Filter != null && !Filter(instance)) { return; } _space.Add(instance); _newInstances.Add(instance); Registered?.Invoke(instance); }
public void Register(ICallout callout) { Argument.IsNotNull(() => callout); Log.Debug($"Registering callout '{callout}'"); _callouts.Add(callout); SubscribeToCallout(callout); Registered?.Invoke(this, new CalloutEventArgs(callout)); }
/// <summary> /// Unregisters an element with the name scope. /// </summary> /// <param name="name">The name.</param> public void Unregister(string name) { Contract.Requires <ArgumentNullException>(name != null); object element; if (_inner.TryGetValue(name, out element)) { _inner.Remove(name); Registered?.Invoke(this, new NameScopeEventArgs(name, element)); } }
private void RegisterButton_Click(object sender, EventArgs e) { registerButton.Click -= RegisterButton_Click; if (passwordField.Text != confirmField.Text) { redLabel.Visibility = ViewStates.Visible; registerButton.Click += RegisterButton_Click; return; } progressBar.Visibility = ViewStates.Visible; Registered.Invoke(this, null); }
private void Interpret(ICompositionMessage <T> message) { T instance = message.Instance; if (Filter != null && !Filter(message.Instance)) { return; } _tracker.Add(instance); _newInstances.Add(instance); Registered?.Invoke(instance); }
public void Register(EntityComponent entity) { if (!entity) { return; } this.Log($"Registry registering entity {entity}"); Entities.Add(entity); Registered?.Invoke(this, new EntityEventArgs(entity)); }
/// <summary> /// Sends a registration request to given connection /// </summary> public void Register(Dictionary <string, string> data, SuccessCallback callback, IClientSocket connection) { if (_isLogginIn) { callback.Invoke(false, "Log in is already in progress"); return; } if (IsLoggedIn) { callback.Invoke(false, "Already logged in"); return; } if (!connection.IsConnected) { callback.Invoke(false, "Not connected to server"); return; } // We first need to get an aes key // so that we can encrypt our login data Msf.Security.GetAesKey(aesKey => { if (aesKey == null) { callback.Invoke(false, "Failed to register due to security issues"); return; } var encryptedData = Msf.Security.EncryptAES(data.ToBytes(), aesKey); connection.SendMessage((short)MsfOpCodes.RegisterAccount, encryptedData, (status, response) => { if (status != ResponseStatus.Success) { callback.Invoke(false, response.AsString("Unknown error")); return; } callback.Invoke(true, null); if (Registered != null) { Registered.Invoke(); } }); }, connection); }
public bool CreateNewAccount(UserDTO user) { try { User newOne = mapper.Map <User>(user); userRepository.CreateOrUpdate(newOne); unitOfWork.Save(); Registered?.Invoke(); return(true); } catch { return(false); } }
public Task RegisterAsync(IBus bus, Peer self, IEnumerable <Subscription> subscriptions) { _self = self; var selfDescriptor = new PeerDescriptor(self.Id, self.EndPoint, false, self.IsUp, self.IsResponding, SystemDateTime.UtcNow, subscriptions.ToArray()) { HasDebuggerAttached = Debugger.IsAttached }; _peerRepository.AddOrUpdatePeer(selfDescriptor); _pingStopwatch.Restart(); bus.Publish(new PeerStarted(selfDescriptor)); Registered?.Invoke(); return(Task.CompletedTask); }
// -------------------------------------------------------------------------------------------------------------------------- public static void Register <T>(T instance, bool overwriteExisting = false) { if (instance == null) { throw new ArgumentNullException("instance"); } Type t = typeof(T); if (overwriteExisting) { Items[t] = instance; } else { Items.Add(t, instance); } Registered?.Invoke(null, new GopherRegisteredEventArgs(instance)); }
public void Register(Structure structure) { var group = Instantiate(_groupTemplate, transform); group.Target = structure.transform; foreach (var(resource, value) in structure.Consumption) { var missing = Instantiate(_missingTemplate, group.transform); missing.Bind(resource, value); } structure.Died += () => { Destroy(group.gameObject); _groups.Remove(structure); }; _groups[structure] = (RectTransform)group.transform; Registered?.Invoke(structure); }
/// <summary> /// Registers an element with the name scope. /// </summary> /// <param name="name">The element name.</param> /// <param name="element">The element.</param> public void Register(string name, object element) { Contract.Requires <ArgumentNullException>(name != null); Contract.Requires <ArgumentNullException>(element != null); object existing; if (_inner.TryGetValue(name, out existing)) { if (existing != element) { throw new ArgumentException($"Control with the name '{name}' already registered."); } } else { _inner.Add(name, element); Registered?.Invoke(this, new NameScopeEventArgs(name, element)); } }
/// <inheritdoc /> /// <summary> /// Registers the specified character spawn. /// </summary> /// <param name="characterSpawn">The character spawn.</param> public void Register(ICharacterSpawn characterSpawn) { if (Members.ContainsKey(characterSpawn.Id)) { return; } ChannelRegisteringEventArgs channelRegisteringEventArgs = new ChannelRegisteringEventArgs(characterSpawn); Registering?.Invoke(this, channelRegisteringEventArgs); if (channelRegisteringEventArgs.Cancel) { return; } Members.Add(characterSpawn.Id, characterSpawn); ChannelRegisteredEventArgs channelRegisteredEventArgs = new ChannelRegisteredEventArgs(characterSpawn); Registered?.Invoke(this, channelRegisteredEventArgs); }
public void AttemptRegistration() { if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password)) { VisualTools.ShowError("Please Enter both your Username and Password"); } else { Task.Run(() => SessionModel.Current.API.GetUserToken(Username, Password)).ContinueOnUIThread(Dispatcher, task => { if (string.IsNullOrWhiteSpace(task.Result)) { VisualTools.ShowError("The Username/Password was incorrect"); } else { SessionModel.Current.DeviceRegistered(task.Result); Registered?.Invoke(this, null); } }); } }
public void Register(string accessToken, string deviceToken) { LogHelper.Call(nameof(TwilioVoiceHelper), nameof(Register), $"AccessToken: {accessToken}, DeviceToken: {deviceToken}"); if (accessToken == null || deviceToken == null) { return; } TwilioVoice.RegisterWithAccessToken(accessToken, deviceToken, error => { if (error == null) { LogHelper.Info("Successfully registered for VoIP push notifications"); _registeredAccessToken = accessToken; _registeredDeviceToken = deviceToken; Registered?.Invoke(this, EventArgs.Empty); } else { LogHelper.Info($"An error occurred while registering: {error.LocalizedDescription}"); RegisteredWithError?.Invoke(this, error); } }); }
private void OnRegistered(Type e) { Registered?.Invoke(this, e); }
///<summary>Fires the Registered event.</summary> public override void HandleBasicConsumeOk(string consumerTag) { base.HandleBasicConsumeOk(consumerTag); Registered?.Invoke(this, new ConsumerEventArgs(consumerTag)); }
/// <summary> /// Handles account registration request /// </summary> /// <param name="message"></param> protected virtual void HandleRegister(IIncommingMessage message) { var encryptedData = message.AsBytes(); var securityExt = message.Peer.GetExtension <PeerSecurityExtension>(); var aesKey = securityExt.AesKey; if (aesKey == null) { // There's no aesKey that client and master agreed upon message.Respond("Insecure request".ToBytes(), ResponseStatus.Unauthorized); return; } var decrypted = Msf.Security.DecryptAES(encryptedData, aesKey); var data = new Dictionary <string, string>().FromBytes(decrypted); if (!data.ContainsKey("username") || !data.ContainsKey("password") || !data.ContainsKey("email")) { message.Respond("Invalid registration request".ToBytes(), ResponseStatus.Error); return; } var username = data["username"]; var password = data["password"]; var email = data["email"].ToLower(); var usernameLower = username.ToLower(); var extension = message.Peer.GetExtension <IUserExtension>(); if (extension != null && !extension.AccountData.IsGuest) { // Fail, if user is already logged in, and not with a guest account message.Respond("Invalid registration request".ToBytes(), ResponseStatus.Error); return; } if (!IsUsernameValid(usernameLower)) { message.Respond("Invalid Username".ToBytes(), ResponseStatus.Error); return; } if (Config.ForbiddenUsernames.Contains(usernameLower)) { // Check if uses forbidden username message.Respond("Forbidden word used in username".ToBytes(), ResponseStatus.Error); return; } if (Config.ForbiddenWordsInUsernames.FirstOrDefault(usernameLower.Contains) != null) { // Check if there's a forbidden word in username message.Respond("Forbidden word used in username".ToBytes(), ResponseStatus.Error); return; } if ((username.Length < Config.UsernameMinChars) || (username.Length > Config.UsernameMaxChars)) { // Check if username length is good message.Respond("Invalid usernanme length".ToBytes(), ResponseStatus.Error); return; } if (!ValidateEmail(email)) { // Check if email is valid message.Respond("Invalid Email".ToBytes(), ResponseStatus.Error); return; } var db = Msf.Server.DbAccessors.GetAccessor <IAuthDatabase>(); var account = db.CreateAccountObject(); account.Username = username; account.Email = email; account.Password = Msf.Security.CreateHash(password); try { db.InsertNewAccount(account); if (Registered != null) { Registered.Invoke(message.Peer, account); } message.Respond(ResponseStatus.Success); } catch (Exception e) { Logs.Error(e); message.Respond("Username or E-mail is already registered".ToBytes(), ResponseStatus.Error); } }
public void OnRegistered() { Registered?.Invoke(this, new EventArgs()); }
public void Register() { Registered?.Invoke(this, EventArgs.Empty); }
private static void OnRegistered(object sender, EventArgs e) { Registered?.Invoke(sender, e); }
/// <summary> /// 处理客户端的方法 /// </summary> public static void ProcessTcpClient() { using (NetworkStream ns = client.GetStream()) { string receiveError = ""; while (client.Connected) { JObject json; try { json = NetworkStreamProcessing.GetJObjectFromBase64Bytes(NetworkStreamProcessing.ReadDataFromNetworkStream(ns)); } catch (Exception e) { receiveError = e.Message; break; } if ((string)json["application"] != "LNC") { client.Close(); } try { if ((bool)json["error"] == true) { #region error string action = (string)json["action"]; string errorMessage = (string)json["errorMessage"]; string errorType = (string)json["errorType"]; new Thread(() => { System.Windows.Forms.MessageBox.Show($"详细信息如下:\n\n执行的动作: {action}\n\n错误类型:{errorType}\n\n错误信息:\n{errorMessage}", "错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); lastError = (string)json["action"]; }) { IsBackground = true }.Start(); #endregion } else { switch ((string)json["action"]) { #region login case "login": User = User.GetUserFromJObject((JObject)json["user"]); break; #endregion #region changeUserInfo case "changeUserInfo": User tmp04 = User.GetUserFromJObject((JObject)json["user"]); if (tmp04.Id == User.Id) { User.ChangeInformation(tmp04); } else { LoginedUser[tmp04.Id].ChangeInformation(tmp04); } Program.mainForm.Invoke(new Action(() => { UserInformationChanged?.Invoke(null, tmp04); })); break; #endregion #region chat case "chat": Chat tmp = Chat.GetChatFromJObject(JObject.Parse(json["chat"].ToString())); try { tmp.User = LoginedUser[tmp.UserId]; } catch { break; } if (tmp.ToUserId == -1) { _chatMessages.Add(tmp); } else { LoginedUser[tmp.UserId].Messages.Add(tmp); } Program.mainForm.Invoke(new Action(() => { ReceiveChat?.Invoke(null, tmp); })); break; #endregion #region getAllUser case "getAllUser": List <User> tmp1 = new List <User>(); foreach (JToken t in JArray.Parse(json["users"].ToString())) { User u = User.GetUserFromJObject(JObject.Parse(t.ToString())); LoginedUser.Add(u.Id, u); tmp1.Add(u); } Program.mainForm.Invoke(new Action(() => { ReceiveOnlineUser?.Invoke(null, tmp1.ToArray()); })); break; #endregion #region login2 case "login2": User user = User.GetUserFromJObject(JObject.Parse(json["user"].ToString())); LoginedUser.Add(user.Id, user); Program.mainForm.Invoke(new Action(() => { UserLogin?.Invoke(null, user); })); break; #endregion #region logout case "logout": User user2 = User.GetUserFromJObject(JObject.Parse(json["user"].ToString())); var tmp3 = LoginedUser[user2.Id]; LoginedUser.Remove(user2.Id); Program.mainForm.Invoke(new Action(() => { UserLogout?.Invoke(null, tmp3); })); break; #endregion #region file case "file": string filename = (string)json["filename"]; int hash = (int)json["hash"]; int toUser = (int)json["toUser"]; int fromUser = (int)json["fromUser"]; int port = (int)json["port"]; new Thread(() => { TcpClient tmp0 = new TcpClient(); tmp0.Connect(new IPEndPoint(serverIP, port)); //Thread.Sleep(1000); JObject json1 = JObject.Parse("{\"type\":\"\"}"); if (fromUser == User.Id) { json["type"] = "send"; } else { json["type"] = "receive"; } NetworkStreamProcessing.WriteBase64BytesEncodedJObjectToNetworkStream(tmp0.GetStream(), json); JObject json2 = NetworkStreamProcessing.GetJObjectFromBase64Bytes(NetworkStreamProcessing.ReadDataFromNetworkStream(tmp0.GetStream())); if ((int)json2["hash"] != hash) { return; } NetworkStream ns0 = tmp0.GetStream(); if (fromUser == User.Id) { FileStream fs; try { fs = new FileStream(SendFilePool[hash], FileMode.Open); } catch { if (tmp0.Connected) { tmp0.Close(); } return; } while (fs.Position < fs.Length) { byte[] buffer = new byte[8192]; try { int s = fs.Read(buffer, 0, 8192); ns0.Write(buffer, 0, s); } catch { if (tmp0.Connected) { tmp0.Close(); } fs.Dispose(); return; } } try { fs.Close(); } catch { } } else { if (!Directory.Exists("ReceiveFiles")) { Directory.CreateDirectory("ReceiveFiles"); } FileStream fs; try { fs = new FileStream(@"ReceiveFiles\" + filename, FileMode.CreateNew); } catch { if (tmp0.Connected) { tmp0.Close(); } return; } while (tmp0.Connected) { try { byte[] buffer = NetworkStreamProcessing.ReadDataFromNetworkStream(ns0); if (buffer.Length == 0) { tmp0.Close(); } fs.Write(buffer, 0, buffer.Length); } catch { if (tmp0.Connected) { tmp0.Close(); } fs.Dispose(); } } try { fs.Close(); } catch { } if (tmp0.Connected) { tmp0.Close(); } if (File.ReadAllBytes(@"ReceiveFiles\" + filename).GetHashCode() != hash) { System.Windows.Forms.MessageBox.Show($"\"{filename}\" 文件已损坏!"); } } }) { IsBackground = true }.Start(); break; #endregion #region register case "register": if ((string)json["status"] == "success") { Registered?.Invoke(null, EventArgs.Empty); } break; #endregion #region getNotVerifiedUsers case "getNotVerifiedUsers": List <User> tmp01 = new List <User>(); foreach (JObject t in JArray.Parse(json["users"].ToString())) { tmp01.Add(User.GetUserFromJObject(t)); } User[] tmp03 = tmp01.ToArray(); new Thread(() => { VerifyUserForm tmp02 = new VerifyUserForm(null, tmp03); tmp02.AcceptUser += (a, b) => { b.ChangeInformationAndPushToServer(b.Name, b.Age, b.Birth, b.Telephone, b.Pay, b.Unit, b.Number, 1, b.Banned, Client.Stream); }; tmp02.DenyUser += (a, b) => { b.ChangeInformationAndPushToServer(b.Name, b.Age, b.Birth, b.Telephone, b.Pay, b.Unit, b.Number, -1, b.Banned, Client.Stream); }; tmp02.InformationOpened += (a, b) => { new Thread(() => { try { new PersonalInfomation(b, User).ShowDialog(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }).Start(); }; tmp02.ShowDialog(); }) { IsBackground = true }.Start(); break; #endregion #region getAllUserFromDatabase case "getAllUserFromDatabase": List <User> tmp001 = new List <User>(); foreach (JObject t in JArray.Parse(json["users"].ToString())) { tmp001.Add(User.GetUserFromJObject(t)); } User[] tmp003 = tmp001.ToArray(); new Thread(() => { ChangeAllUsersInformationForm cauif = null; (cauif = new ChangeAllUsersInformationForm(User, tmp003, (a) => { try { new PersonalInfomation(a, User).ShowDialog(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } cauif.Refresh(); })).ShowDialog(); }) { IsBackground = true }.Start(); break; #endregion } } } catch { } } if (receiveError != "") { System.Windows.Forms.MessageBox.Show($"与服务器断开连接!\n\n详细信息:{receiveError}"); } else { System.Windows.Forms.MessageBox.Show($"与服务器断开连接!"); } Disconnected?.Invoke(null, EventArgs.Empty); } }
protected virtual void OnRegistered(PrinterEventArgs e) { Registered?.Invoke(this, e); }
private void Listener_OnRegistered(object sender, EventArgs e) { Registered?.Invoke(this, e); }
///<summary>Fires the Registered event.</summary> public override async Task HandleBasicConsumeOk(string consumerTag) { await base.HandleBasicConsumeOk(consumerTag).ConfigureAwait(false); await(Registered?.Invoke(this, new ConsumerEventArgs(new[] { consumerTag })) ?? Task.CompletedTask).ConfigureAwait(false); }