public WriteHandler(AsyncUserDefinedFunction parent, AsyncClient client, Key key, string binName) { this.parent = parent; this.client = client; this.key = key; this.binName = binName; }
public async Task <string> Register(AsyncClient Client, string FirstName, string LastName, string Username, string Password, string SecondPassword, string Gender) { Message m = new Message { Resource = "user", Method = "register", Fields = new Fields { User = new User { FirstName = FirstName, LastName = LastName, Username = Username, Gender = Gender }, Password = Password } }; if (SecondPassword == Password) { return(await Client.SendAsync(JsonConvert.SerializeObject(m))); } return("Password did not match"); }
public async Task RunDataScenarioAsync(int clientCount) { var clients = new List <AsyncClient>(); var tasks = new List <Task>(); for (int i = 0; i < clientCount; i++) { var client = new AsyncClient(); clients.Add(client); tasks.Add(client.Start(_address)); } await Task.Delay(10000).ConfigureAwait(false); var sendTasks = new List <Task>(); for (int i = 0; i < clients.Count; i++) { sendTasks.Add(DataTask(clients[i])); } await Task.WhenAll(sendTasks).ConfigureAwait(false); await Console.Out.WriteLineAsync("Finished SendTasks").ConfigureAwait(false); for (int i = 0; i < clients.Count; i++) { clients[i].ShutDown(); } await Task.WhenAll(tasks).ConfigureAwait(false); await Console.Out.WriteLineAsync("Finished DataScenario").ConfigureAwait(false); }
private void btnStart_Click(object sender, EventArgs e) { btnStart.Enabled = false; _Client = new AsyncClient(txtIP.Text, Convert.ToInt32(txtPort.Text)); try { _Client.Connected += new EventHandler <AsyncClientEventArgs>(Client_OnConnected); _Client.DataReceived += new EventHandler <AsyncClientEventArgs>(Client_OnDataReceived); _Client.DataSended += new EventHandler <AsyncClientEventArgs>(Client_OnDataSended); _Client.Closing += new EventHandler <AsyncClientEventArgs>(Client_OnClosing); _Client.Closed += new EventHandler <AsyncClientEventArgs>(Client_OnClosed); _Client.Exception += new EventHandler <AsyncClientEventArgs>(Client_OnException); _Client.ConnectTimeout = 3000; _Client.Connect(); } catch (Exception ex) { WriteLog("無法連接至伺服器!!!"); if (ex.GetType().Equals(typeof(System.Net.Sockets.SocketException))) { System.Net.Sockets.SocketException se = (System.Net.Sockets.SocketException)ex; WriteLog("{0} - {1}", se.SocketErrorCode, se.Message); } btnStart.Enabled = true; } }
public CDNs(string channel) { using (var asyncClient = new AsyncClient("us.patch.battle.net", 1119)) { asyncClient.Send($"/{channel}/cdns"); using (var reader = new StreamReader(asyncClient.Stream)) { // Skip header // ReSharper disable once RedundantAssignment var line = reader.ReadLine(); while ((line = reader.ReadLine()) != null) { var lineTokens = line.Split('|'); Records[lineTokens[0]] = new Record() { Name = lineTokens[0], Path = lineTokens[1], Hosts = lineTokens[2].Split(' ').Where(h => !h.Contains("edgecast")).ToArray() }; } } } }
public WriteHandler(TestAsyncPutGet parent, AsyncClient client, Key key, Bin bin) { this.parent = parent; this.client = client; this.key = key; this.bin = bin; }
public Versions(string channel) { using (var asyncClient = new AsyncClient("us.patch.battle.net", 1119)) { asyncClient.Send($"/{channel}/versions"); using (var reader = new StreamReader(asyncClient.Stream)) { // Skip header // ReSharper disable once RedundantAssignment var line = reader.ReadLine(); while ((line = reader.ReadLine()) != null) { var lineTokens = line.Split('|'); Records[lineTokens[0]] = new Record { Region = lineTokens[0], BuildConfig = BuildHash(lineTokens[1]), CDNConfig = BuildHash(lineTokens[2]), KeyRing = BuildHash(lineTokens[3]), BuildID = int.Parse(lineTokens[4]), VersionsName = lineTokens[5], ProductConfig = BuildHash(lineTokens[6]), Channel = channel }; } } } }
public async Task <string> GetProjectInfo(AsyncClient Client, int id) { try { var Message = new Message { Resource = "project", Method = "getinfo", Fields = new Fields { Projects = new List <Model.Project> { new Project { Id = id } } } }; return(await Client.SendAsync(JsonConvert.SerializeObject(Message))); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task <string> InviteUser(AsyncClient Client, string username, int projectId) { try { Message message = new Message { Method = "invite", Resource = "project", Fields = new Fields { PendingInvitation = new PendingInvitation { ProjectId = projectId, Username = username } } }; string test = JsonConvert.SerializeObject(message); return(await Client.SendAsync(JsonConvert.SerializeObject(message))); } catch (Exception e) { Console.WriteLine(e); throw; } }
public MainWindowViewModel() { _parser = new ParserApsTensileV1(); asyncClient = new AsyncClient(hostName, portNumber); asyncClient.MessageReceived += AsyncClient_MessageReceived; asyncClient.Connect(); }
public async Task <string> KickUser(AsyncClient AsyncClient, string KickUsername, int projectId) { try { Message message = new Message { Method = "deleteuser", Resource = "project", Fields = new Fields { User = new User { Username = KickUsername }, Projects = new List <Project> { new Project { Id = projectId } } } }; return(await AsyncClient.SendAsync(JsonConvert.SerializeObject(message))); } catch (Exception e) { Console.WriteLine(e); throw; } }
public KassaPaymentService(ApplicationContext db, IOptions <AppSettings> appSettings) { _db = db; _client = new Client( appSettings.Value.KassaShopId, appSettings.Value.KassaSecret).MakeAsync(); }
private void Connect() { if (client != null) { return; } clientLock.Wait(); try { if (client == null) { client = new AsyncClient(config.ClientPolicy, config.Hosts); try { RegisterUDF(); } catch (Exception) { client.Close(); client = null; throw; } } } finally { clientLock.Release(); } }
private void InitNet() { try { InitAsyncTimer(); ip = ConfigHelper.GetInstace().IP; port = ConfigHelper.GetInstace().Port; if (this.asyncClient != null) { this.asyncClient.Dispose(); this.asyncClient.onConnected -= new AsyncClient.Connected(client_onConnected); this.asyncClient.onDisConnect -= new AsyncClient.DisConnect(client_onDisConnect); this.asyncClient.onDataByteIn -= new AsyncClient.DataByteIn(client_onDataByteIn); } asyncClient = new AsyncClient(); asyncClient.onConnected += new AsyncClient.Connected(client_onConnected); asyncClient.Connect(ip, port); asyncClient.onDataByteIn += new AsyncClient.DataByteIn(client_onDataByteIn); asyncClient.onDisConnect += new AsyncClient.DisConnect(client_onDisConnect); } catch (Exception ex) { Console.WriteLine("cannot connect to server:" + ex.Message); } }
private void BtnRegistration_Click(object sender, RoutedEventArgs e) { try { AsyncClient.SetTypeInfo(TypeOfInfo.User); AsyncClient.StartClient(); User user = new User { Id = 1, UserName = this.Username.Text, Password = Model.Validation.GetHashString(Password.Password) }; mainMenuxaml.UserNameMain.Content = user.UserName; win.flagautoriz = true; AsyncClient.SetUser(user); AsyncClient.SetTypeInfo(TypeOfInfo.User); AsyncClient.StartClient(); AsyncClient.SetTypeInfo(TypeOfInfo.Users); AsyncClient.StartClient(); win.Close(); mainMenuxaml.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Open a file from its data ID. /// </summary> /// <param name="fileDataID"></param> /// <returns></returns> public override BLTE OpenFile(uint fileDataID) { foreach (var rootEntry in _rootEntries.Values.Flatten(item => item.Item2 == fileDataID)) { List <Tuple <uint, byte[]> > encodingEntries; if (!_encodingEntries.TryGetValue(rootEntry.Item1, out encodingEntries)) { continue; } foreach (var encodingEntry in encodingEntries) { Tuple <int, int, int> indexEntry; if (!_indexEntries.TryGetValue(encodingEntry.Item2, out indexEntry)) { continue; } using (var asyncClient = new AsyncClient(ServerInfo.Hosts[0])) { var archiveHash = ContentConfig.Archives[indexEntry.Item1]; asyncClient.RequestHeaders.Add("Range", $"bytes={indexEntry.Item2}-{indexEntry.Item3}"); asyncClient.Send($"/{ServerInfo.Path}/data/{archiveHash[0]:x2}/{archiveHash[1]:x2}/{archiveHash.ToHexString()}"); if (!asyncClient.Failed) { return(new BLTE(asyncClient.Stream, 0, indexEntry.Item3)); } } } } return(null); }
private void RunPutGet(AsyncClient client, Arguments args, Key key, Bin bin) { console.Info("Put: namespace={0} set={1} key={2} value={3}", key.ns, key.setName, key.userKey, bin.value); client.Put(args.writePolicy, new WriteHandler(this, client, args.writePolicy, key, bin), key, bin); }
public static async Task <User> createUser(string externalId, String email, UserGender gender, String dob, String ipAddress) { IPAddress address; if (!IPAddress.TryParse(ipAddress, out address)) { Console.Write("UserFactory - Create User - Invalid IP - " + ipAddress); return(null); } var myUser = new User { external_id = externalId, email = email, dob = dob, gender = gender.ToString("g"), ip = ipAddress }; SMRequest createUserRequest = new SMRequest(); createUserRequest.user = myUser; SMResponse m = await AsyncClient.post(APIRoutes.createUserRoute(), createUserRequest); if (m == null) { return(null); } return(m.user); }
/// <summary> /// После выполнения клиент не будет пытаться подключиться /// </summary> public void DisposeAsyncClient() { _isManualDispose = true; _asyncClient.Dispose(); _asyncClient = null; _isManualDispose = false; }
public async Task InitializeMembershipTable(bool tryInitTableVersion) { await Task.Run(async() => { _clientPolicy = new AsyncClientPolicy() { user = _options.Username, password = _options.Password }; _client = new AsyncClient(_clientPolicy, _options.Host, _options.Port); if (_options.CleanupOnInit) { _client.Truncate(null, _options.Namespace, _options.SetName, null); } await PutTableVersionEntry(new TableVersion(0, "")); try { var task = _client.CreateIndex(null, _options.Namespace, _options.SetName, _options.SetName + "_clusterIdx", "clusterid", IndexType.STRING); task.Wait(); } catch (Exception) { // todo: evaluate if error comes from multiple index creation or other source } }); }
//public void StarService(CompressionType eCompression, int iMaxClient, int iPort, int iSocketBuffer) public void StarService(IPEndPoint pEndPoint, CompressionType eCompression, int iSocketBuffer) { //IPEndPoint pServerPoint = new IPEndPoint(0, iPort); //pSocketServer = new SocketServer(this, eCompression, iSocketBuffer, 1, 1); //pSocketServer.AddListener(pServerPoint, iMaxClient); //pSocketServer.ServiceStart(); switch (this._eNetService) { case NetServiceType.HOST: pSocketServer = new SocketServer(this, eCompression, iSocketBuffer, this.iCheckInterval, this.iCheckTimeOut); pSocketServer.AddListener(pEndPoint, this.iMaxClient); pSocketServer.ServiceStart(); break; case NetServiceType.CLIENT: pSocketClient = new AsyncClient(this, eCompression, iSocketBuffer, this.iCheckInterval, this.iCheckTimeOut); pSocketClient.AddConnector(pEndPoint); pSocketClient.ServiceStart(); break; } }
public void TearDown() { AsyncClient?.Dispose(); #if SYNC_CLIENT SyncClient?.Dispose(); #endif }
private void sendRequestBtn_Click(object sender, RoutedEventArgs e) { Alarmus.RequestMessage request = new Alarmus.RequestMessage(troubleDataBox.Text, troubleTypeBox.SelectedItem.ToString()); AsyncClient.SendMessage(request); sendRequestBtn.IsEnabled = false; /* * Самый простой способ подождать сеть. * Ждем, пока асинхронный клиент получит ответ от сервера */ Thread.Sleep(500); //Проверяем ответ от сервера switch (AsyncClient.GetServerResponse()) { case Alarmus.ServerResponse.SR_REQUEST_SUCCESS: MessageBox.Show("Заявка успешно отправлена"); break; case Alarmus.ServerResponse.SR_REQUEST_FAILED: MessageBox.Show("Заявка не была отправлена. Попробуйте позже"); break; case Alarmus.ServerResponse.SR_NULL: MessageBox.Show("Заявка не была отправлена. Возможны неполадки с сетью"); Alarmus.Log.Warning("Ответ на заявку не успел дойти. Возможны неполадки с сетью или сервер был отсоединен"); break; } sendRequestBtn.IsEnabled = true; }
public static async Task <Order> createOrderById(String offerId, String ipAddress, String Id) { IPAddress address; if (!IPAddress.TryParse(ipAddress, out address)) { Console.WriteLine("UserFactory - Create User - Invalid IP - " + ipAddress); return(null); } Order myOrder = new Order { quantity = 1, recaptcha_challenge_field = "", recaptcha_response_field = "", ip = ipAddress, email = "" }; SMRequest newOrderRequest = new SMRequest(); newOrderRequest.order = myOrder; SMResponse m = await AsyncClient.post(APIRoutes.createNewOrderForOfferWithIdRoute(offerId, Id), newOrderRequest); return(m.order); }
internal WebServiceClient( int accountId, string licenseKey, IEnumerable <string>?locales, string host, int timeout, HttpMessageHandler?httpMessageHandler, // This is a hack so that we can keep this internal while adding // httpMessageHandler to the public constructor. We can remove // this when we drop .NET 4.5 support and get rid of ISyncClient. bool fakeParam = false #if !NETSTANDARD1_4 , ISyncClient?syncWebRequest = null #endif , HttpClient?httpClient = null ) { var auth = EncodedAuth(accountId, licenseKey); _host = host; _locales = locales == null ? new List <string> { "en" } : new List <string>(locales); #if !NETSTANDARD1_4 _syncClient = syncWebRequest ?? new SyncClient(auth, timeout, UserAgent); #endif _asyncClient = new AsyncClient(auth, timeout, UserAgent, httpMessageHandler, httpClient); }
private void exitBtn_Click(object sender, RoutedEventArgs e) { AsyncClient.Disconnect(); AutorizationPage view = new AutorizationPage(); NavigationService.Navigate(view); }
public async Task RunKeepAliveScenarioAsync(int clientCount) { await Console.Out.WriteLineAsync($"Client creation count is {clientCount}.").ConfigureAwait(false); var clients = new List <AsyncClient>(); var tasks = new List <Task>(); for (int i = 0; i < clientCount; i++) { var client = new AsyncClient(); clients.Add(client); tasks.Add(client.Start(_address)); } await Console.Out.WriteLineAsync($"Successfully Added Clients. Count: {clients.Count}.").ConfigureAwait(false); if (clients.Count > 0) { await Task.Delay(1000 * 60).ConfigureAwait(false); } for (int i = 0; i < clients.Count; i++) { clients[i].ShutDown(); } await Task.WhenAll(tasks).ConfigureAwait(false); await Console.Out.WriteLineAsync("Finished KeepAliveScenario").ConfigureAwait(false); }
private void AsyncAutorization(Alarmus.AutorizationMessage msg) { AsyncClient.SetToNullServerResponse(); AsyncClient.SendMessage(msg); /* Серебрянная пуля. * Поток будет ждать, пока данные полностью дойдут * Если избегать этого, то, недождавшись ответа от сервера, сработает ветка SR_NULL * И это происходит достаточно часто. */ Thread.Sleep(500); if (AsyncClient.GetServerResponse() == Alarmus.ServerResponse.SR_AUTORIZATION_SUCCESS) { /* * Вызываем диспетчер, который будет вызывать методы связанные с UI в thread safe режиме */ Dispatcher.Invoke(new System.Action(() => setButtonEnable(true))); Dispatcher.Invoke(new System.Action(() => changeView())); return; } else if (AsyncClient.GetServerResponse() == Alarmus.ServerResponse.SR_AUTORIZATION_FAILED) { MessageBox.Show("Невозможно авторизироваться. Проверьте логин и пароль"); } else if (AsyncClient.GetServerResponse() == Alarmus.ServerResponse.SR_NULL) { MessageBox.Show("Невозможно авторизироваться. Попробуйте позже"); Alarmus.Log.Warning("Этого не должно было произойти..."); } Dispatcher.Invoke(new System.Action(() => setButtonEnable(true))); }
private void InitClient() { try { InitAsyncTimer(); string zoneIP = ConfigHelper.GetInstace().ZoneIP; int zonePort = ConfigHelper.GetInstace().ZonePort; if (this.asyncClient != null) { this.asyncClient.Dispose(); this.asyncClient.onConnected -= new AsyncClient.Connected(client_onConnected); this.asyncClient.onDisConnect -= new AsyncClient.DisConnect(client_onDisConnect); this.asyncClient.onDataByteIn -= new AsyncClient.DataByteIn(client_onDataByteIn); } asyncClient = new AsyncClient(); asyncClient.onConnected += new AsyncClient.Connected(client_onConnected); asyncClient.Connect(zoneIP, zonePort); asyncClient.onDataByteIn += new AsyncClient.DataByteIn(client_onDataByteIn); asyncClient.onDisConnect += new AsyncClient.DisConnect(client_onDisConnect); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private AsyncClient RegenerateClient(string host, int port, List <string> secondaryHosts) { AsyncClient existing = null; var clientKey = GetClientKey(host, port, secondaryHosts); _lock.EnterWriteLock(); try { AsyncClient client = null; if (_cachedClientDictionary.TryGetValue(clientKey, out existing) == false) { client = GetNewClient(host, port, secondaryHosts); _cachedClientDictionary[clientKey] = client; return(client); } if (existing.Connected == false) { existing.Dispose(); _cachedClientDictionary.Remove(clientKey); client = GetNewClient(host, port, secondaryHosts); _cachedClientDictionary[clientKey] = client; return(client); } } finally { _lock.ExitWriteLock(); } return(existing); }
protected AsyncClientFixture() { HttpClient = new StubHttpClient(); JsonNetSerializer = new JsonNetSerializer(); AsyncClient = new AsyncClient(HttpClient, JsonNetSerializer) { OnBeforeSend = request => { if (request.Content != null) RequestContent = request.Content.ReadAsStringAsync().Result; } }; }
public Task Initialize(bool newKey = false) { string apiKey; if (newKey || String.IsNullOrWhiteSpace(Properties.Settings.Default.ApiKey)) { apiKey = EditAPIKey(); if (String.IsNullOrWhiteSpace(apiKey)) { // No key entered: exit now. Application.Exit(); } } else { apiKey = Properties.Settings.Default.ApiKey; } _client = new AsyncClient(apiKey, 15); return ValidateAPIKey(); }
/// <summary> /// The call no return. /// </summary> /// <param name="className">The class name.</param> /// <param name="criteria">The criteria.</param> /// <param name="innerCall">The inner call.</param> /// <returns> /// The <see cref="bool" />. /// </returns> internal bool CallNoReturn(string className, object criteria, Func<IAsyncClient, CancellationToken, Task<HttpResponseMessage>> innerCall) { var source = new CancellationTokenSource(); CancellationToken token = source.Token; using (var client = new AsyncClient()) { client.Init(this.securityKeys.Credentials); using (Task<HttpResponseMessage> task = innerCall(client, token)) { if (task.Wait(30000, token) == false) { if (token.CanBeCanceled) { source.Cancel(); } return false; } return task.Result.IsSuccessStatusCode; } } }
static void Main(string[] args) { AsyncClient client = new AsyncClient(1024, 1024 * 4, new Loger()); client.OnReceived+= ReceiveCommond; client.OnConnected += Connected; client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),9989)); Console.ReadLine(); short i =0; while (i<5) { Task.Delay(1).Wait(); i++; var data = Encoding.UTF8.GetBytes("测试数据"+i); Session.SendAsync(new SendCommond() { CommondId = i, Buffer = data }); } Console.ReadLine(); }
/// <summary> /// The call. /// </summary> /// <param name="innerCall">The inner call.</param> /// <param name="userId">The user Id.</param> /// <param name="request">The request.</param> /// <param name="transactionType">The transaction Type.</param> /// <returns> /// The <see cref="XDocument" />. /// </returns> private AsyncCallResult<XDocument> Call(Func<IAsyncClient, CancellationToken, Task<HttpResponseMessage>> innerCall, string userId = "", string request = "", TransactionTypes transactionType = TransactionTypes.UnKnown) { var source = new CancellationTokenSource(); CancellationToken token = source.Token; string response = "Connection Timeout"; using (var client = new AsyncClient()) { client.Init(this.securityKeys.Credentials); using (Task<HttpResponseMessage> task = innerCall(client, token)) { try { if (task.Wait(20000, token) == false) { if (token.CanBeCanceled) { source.Cancel(); } this.LogToDb(userId, request, response, transactionType); return new AsyncCallResult<XDocument>(AsyncCallFailureReason.TimeOut); } } catch (Exception ex) { response = "Connection failure ,error :- " + ex; this.LogToDb(userId, request, response, transactionType); return new AsyncCallResult<XDocument>(AsyncCallFailureReason.FailedConnection); } Task<Stream> content = task.Result.Content.ReadAsStreamAsync(); if (content.Wait(20000, token) == false) { if (token.CanBeCanceled) { source.Cancel(); } this.LogToDb(userId, request, response, transactionType); return new AsyncCallResult<XDocument>(AsyncCallFailureReason.TimeOut); } using (var streamReader = new StreamReader(content.Result)) { XDocument doc = XDocument.Load(streamReader, LoadOptions.SetLineInfo); response = doc.ToString(); if (task.Result.IsSuccessStatusCode == false) { this.LogToDb(userId, request, response, transactionType); return new AsyncCallResult<XDocument>(AsyncCallFailureReason.FailedStatusCode, doc); } this.LogToDb(userId, request, response, transactionType); return new AsyncCallResult<XDocument>(AsyncCallFailureReason.None, doc); } } } }