/// <summary> /// Flow to perform on successful pick of an account from the WAM popup /// </summary> /// <param name="pi">Details of the WAM provider choosen</param> /// <param name="info">Details of the WAM authenticated account</param> /// <param name="result">WebTokenRequestResult instance containing token info.</param> private async void WAM_Success(WebAccountManager.WebAccountProviderInfo pi, WebAccountManager.WebAccountInfo info, WebTokenRequestResult result) { try { this.ShowBusyStatus(Account.TextAuthenticating, true); // Create an account with the API _cts = new CancellationTokenSource(); using (var api = new ClientApi()) { var response = await api.AuthenticateAsync(info, _cts.Token); // Authenticate the user into the app await this.Platform.AuthManager.SetUserAsync(response); } this.ClearStatus(); this.Platform.Navigation.Home(this.ViewParameter); } catch (Exception ex) { await this.HandleExceptionAsync(ex, "Failed to perform work during WAM success"); } finally { this.Dispose(); } }
/// <summary> /// Refreshes the search results /// </summary> /// <param name="ct">Cancellation token.</param> /// <returns>Awaitable task.</returns> protected override async Task OnRefreshAsync(bool forceRefresh, CancellationToken ct) { if (!string.IsNullOrWhiteSpace(this.SearchText)) { if (forceRefresh || this.Results == null || _parameterChanged) { _parameterChanged = false; // Show the busy status this.Title = string.Format(Search.TextSearching, this.SearchText); this.ShowBusyStatus(this.Title, true); // Call the API to perform the search this.Platform.Analytics.Event("Search", this.SearchText); using (var api = new ClientApi()) { this.Results = new ModelList <ItemModel>(await api.SearchItems(this.SearchText, ct)); } // Update the page title this.Title = string.Format(Search.TextSearchResultsCount, this.Results.Count, this.SearchText); } } else { // No results, clear page this.Results = null; this.Title = Search.ButtonTextSearch; } }
public CustomMainForm() { InitializeComponent(); label_GameHash.Click += label_GameHash_Click; ClientApi.BeforeQuickSave += (sender, e) => { if (e.Slot != 0) { return; // only take effect on slot 0 } var basePath = Path.Combine(PathManager.GetSaveStatePath(Global.Game), "Test"); if (!Directory.Exists(basePath)) { Directory.CreateDirectory(basePath); } ClientApi.SaveState(Path.Combine(basePath, e.Name)); e.Handled = true; }; ClientApi.BeforeQuickLoad += (sender, e) => { if (e.Slot != 0) { return; // only take effect on slot 0 } var basePath = Path.Combine(PathManager.GetSaveStatePath(Global.Game), "Test"); ClientApi.LoadState(Path.Combine(basePath, e.Name)); e.Handled = true; }; }
private void CallClientApi(ClientApi api, string desc, Action <AndroidJavaObject> call, Action <bool> callback) { Logger.d("Requesting API call: " + desc); RunWhenConnectionStable(() => { // we got a stable connection state to the games service // (either connected or disconnected, but not in progress). if (mGameHelperManager.IsConnected()) { // we are connected, so make the API call Logger.d("Connected! Calling API: " + desc); call.Invoke(api == ClientApi.Games ? mGameHelperManager.GetGamesClient() : mGameHelperManager.GetAppStateClient()); if (callback != null) { PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(true); }); } } else { // we are not connected, so fail the API call Logger.w("Not connected! Failed to call API :" + desc); if (callback != null) { PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(false); }); } } }); }
private bool TrySendingMessage(DataPackageEnvelope nextMessage) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown try { StaticFileLogger.Current.LogEvent(GetType().Name + ".TrySendingMessage()", $"Sending message #{nextMessage.Sequence} of type: " + nextMessage.Packages[0].ColType, "", EventLogEntryType.Information); ClientApi val = new ClientApi(Configuration); CommunicationLog communicationLog = new CommunicationLog(); communicationLog.Request = Configuration.ApiClient.Serialize((object)nextMessage); DataPackageReceipt val2 = val.Push(nextMessage); if (val2.ServerTime.HasValue) { ServerTime = val2.ServerTime.Value; } OnResponseReceived(val2); communicationLog.Response = val2.ToJson(); if (_debugDumpTraffic) { StaticFileLogger.Current.LogEvent(GetType().Name + ".TrySendingMessage()", $" Data sent was: {communicationLog.ToString()}", "", EventLogEntryType.Information); } LatestLog = communicationLog; return(true); } catch (Exception ex) { StaticFileLogger.Current.LogEvent(GetType().Name + ".TrySendingMessage()", $" Error sending message to server. Message was : {ex.Message}. Exception is: {ex.ToString()}", "", EventLogEntryType.Error); return(false); } }
public Ecco2Tool(CustomMainForm f, GameRegion r) : base(f, r) { _top = _bottom = 112; _left = _right = 160; ClientApi.SetGameExtraPadding(_left, _top, _right, _bottom); switch (r) { case GameRegion.J: _3DTypeProvider = new J3DProvider(); _2DTypeProvider = new J2DProvider(); break; case GameRegion.U: _3DTypeProvider = new U3DProvider(); _2DTypeProvider = new U2DProvider(); break; case GameRegion.E: _3DTypeProvider = new E3DProvider(); _2DTypeProvider = new E2DProvider(); break; default: break; } }
/// <summary> /// Preenche a lista de funcionarios /// </summary> public async Task PreencheListBox() { try { switch (selecao) { case 0: funcionarios = await ClientApi.GetEmployeesAsync(true).ConfigureAwait(true); break; case 1: funcionarios = await ClientApi.GetEmployeesAsync(false).ConfigureAwait(true); break; case 2: funcionarios = await ClientApi.GetEmployeesAsync().ConfigureAwait(true); break; } } catch (HttpRequestException e) { Console.WriteLine(e.Message); } dgFuncionarios.ItemsSource = funcionarios; }
private async void button1_Click(object sender, EventArgs e) { UsuarioRQ objRq = new UsuarioRQ(); objRq.usuario = txtUsuario.Text; objRq.clave = txtClave.Text; ClientApi api = new ClientApi("usuario/validateCredentials"); try { Persona p = await api.SendPost <Persona>(objRq); MessageBox.Show("Bienvenid(a) " + p.nombres); this.Visible = false; FrmMain x = new FrmMain(); x.ShowDialog(); this.Close(); } catch (JException ex) { MessageBox.Show(ex.ToString()); } }
public static int GetPort() { try { var process = ClientApi.GetProcessByName("League of Legends"); if (process != null) { LOLHandle = process.MainWindowHandle; var x = NativeMethods.GetAllTcpConnections(); foreach (var a in x) { if (process.Id == a.owningPid) { return(a.LocalPort); } } } else { LOLHandle = IntPtr.Zero; } } catch (Exception x) { Logger.Log("getport error: " + x.Message); } return(0); }
/// <summary> /// Submits the form to the account forgotten service. /// </summary> /// <returns>Awaitable task is returned.</returns> private async Task SubmitAsync() { try { this.IsSubmitEnabled = false; this.ShowBusyStatus(Account.TextValidatingUsername, true); using (var api = new ClientApi()) { var response = await api.ForgotPasswordAsync(this, CancellationToken.None); this.ClearStatus(); await this.ShowMessageBoxAsync(CancellationToken.None, response.Message, this.Title); if (response?.IsValid == true) { this.Platform.Navigation.GoBack(); } } } catch (Exception ex) { await this.HandleExceptionAsync(ex, "Error during account forgot password."); } finally { this.CheckIfValid(); } }
protected override async Task OnRefreshAsync(bool forceRefresh, CancellationToken ct) { if (string.IsNullOrEmpty(this.ID)) { throw new UserFriendlyException("No item was requested to be displayed."); } if (forceRefresh || this.Item == null) { this.ShowInterstitialAd(); try { if (this.Item == null) { this.Title = Resources.TextLoading; } this.ShowBusyStatus(Resources.TextLoading, this.Item == null); using (var api = new ClientApi()) { this.Item = await api.GetItemByID(this.ID, ct); } } finally { await this.RefreshUIAsync(); } } if (this.Item == null) { this.Title = Resources.TextNotApplicable; throw new ArgumentException("No item to display."); } }
private async Task <bool> RegistrarPaciente() { if (cboSexo.SelectedIndex >= 0 && cboTipoDocumento.SelectedIndex >= 0) { try { ClientApi api = new ClientApi("paciente"); PacienteRegisterRQ paciente = new PacienteRegisterRQ(); paciente.Nombres = txtNombres.Text; paciente.Apellidos = txtApellidos.Text; paciente.Sexo = cboSexo.SelectedItem.ToString(); paciente.NumeroDocumento = txtNumDoc.Text; paciente.TipoDocumento = new PacienteRegisterRQ.TipoDocumentoRQ() { Codigo = ((TipoDocumento)cboTipoDocumento.SelectedItem).Codigo }; paciente.FechaNacimiento = dateTimePicker1.Value.ToString("yyyy-MM-dd"); await api.SendPost <long>(paciente); return(true); } catch (JException ex) { MessageBox.Show(ex.ToString()); } } return(false); }
private async Task LoadStockAsync() { try { IsLoading = true; var symbols = await ClientApi.GetSymbols(); if (symbols != null) { Collection.Clear(); foreach (var symbol in symbols) { string typeName; if (Security.TypeDictionary.TryGetValue(symbol.Type.ToUpper(), out typeName)) { symbol.Type = typeName; } Collection.Add(symbol); } } Content = $"Last Loaded: {DateTime.Now.ToString()}"; } catch (Exception ex) { GetService <IMessageBoxService>()?.ShowMessage("An error occurred getting symbols data"); //Log.Error(ex); } finally { IsLoading = false; } }
private void loadstate_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(savestateName.Text)) { return; } ClientApi.LoadState(savestateName.Text);
public void BRIdenticalComment() { // create the post to add comments to var requestPost = WithAuth(SetClientAndGiveRequest("posts")) .AddParameter("title", "Test Businessrule" + DateTime.Now.ToString("f")) .AddParameter("content", "In this test two identical comments will be posted. It is expected the first comment is allowed and the second is rejected by the businessrule") .AddParameter("status", "publish") .AddParameter("discussion", "comments_open"); var responsePost = ClientApi.Post(requestPost); var responseBodyJsonP = JObject.Parse(responsePost.Content); var createdId = responseBodyJsonP.SelectToken("id"); Console.WriteLine("Created post id: " + createdId); checkStatusCode(responsePost, HttpStatusCode.Created); // create the first comment var requestComment1 = WithAuth(SetClientAndGiveRequest("comments")) .AddParameter("post", createdId) .AddParameter("content", "Test business rule identical comment"); var responseComment1 = ClientApi.Post(requestComment1); var responseBodyJsonC1 = JObject.Parse(responseComment1.Content); checkStatusCode(responseComment1, HttpStatusCode.Created); // create the second comment var requestComment2 = WithAuth(SetClientAndGiveRequest("comments")) .AddParameter("post", createdId) .AddParameter("content", "Test business rule identical comment"); var responseComment2 = ClientApi.Post(requestComment2); var responseBodyJsonC2 = JObject.Parse(responseComment2.Content); Console.WriteLine(responseComment2); checkStatusCode(responseComment2, HttpStatusCode.Conflict); }
private static void ComposeObjects() { var api = new ClientApi(); var archiveVm = new ArchiveViewModel(); var commentsVm = new CommentsViewModel(); var newEmployeeVm = new EmployeeViewModel(); var employeesVm = new EmployeesViewModel(newEmployeeVm); var loginVm = new LoginViewModel(api); var forgetPasswodVm = new ForgetPasswordViewModel(); var myTasksVm = new MyTasksViewModel(); var newTaskVm = new NewTaskViewModel(); var profileVm = new ProfileViewModel(); var trackingTasksVm = new TrackingTasksViewModel(newTaskVm); var reportsVm = new ReportsViewModel(); var mainWindowVm = new MainWindowViewModel(archiveVm, commentsVm, employeesVm, loginVm, forgetPasswodVm, myTasksVm, profileVm, reportsVm, trackingTasksVm); Current.MainWindow = new MainWindow(mainWindowVm); }
void IWidget.Init(ClientApi clientApi, string gameToken, string refreshToken) { ClientApi = clientApi; Model = new WidgetModel(); Model.ApplyTokens(gameToken, refreshToken); View.ApplyModel(Model); }
protected override async Task <object> Run_Internal(IObserver observer, string asset, IScanRepository repository, object args) { ReportResponse ret = null; if (!String.IsNullOrEmpty(asset) && args is IDictionary <string, object> dic) { string owaspIp = dic[nameof(owaspIp)]?.ToString(); string owaspPort = dic[nameof(owaspPort)]?.ToString(); if (!String.IsNullOrEmpty(owaspIp) && !String.IsNullOrEmpty(owaspPort)) { ClientApi api = new ClientApi(owaspIp, Convert.ToInt32(owaspPort), null); var scanId = ((ApiResponseElement)api.spider.scan(asset, "5", "true", "", "false")).Value; await Progress(observer, "Spider", () => Convert.ToInt32(((ApiResponseElement)api.spider.status(scanId)).Value)); var response = api.ascan.scan(asset, "", "", "", "", "", ""); await Progress(observer, "Active Scan", () => Convert.ToInt32(((ApiResponseElement)api.ascan.status(scanId)).Value)); byte[] report = api.core.jsonreport(); string json = Encoding.UTF8.GetString(report); ret = JsonConvert.DeserializeObject <ReportResponse>(json); } } return(ret); }
private async Task LoadTiposDocumento() { ClientApi api = new ClientApi("tipo-documento"); List <TipoDocumento> tipoDocumentos = await api.SendGet <List <TipoDocumento> >(); tipoDocumentos.ForEach(x => cboTipoDocumento.Items.Add(x)); }
static async Task ShowMyAccount() { //klient podaje numer konta //pobiera z bazy klasy Payment dane zgodne z numerem konta //jeśli się uda pobrać drukuje numer oraz kwotę na koncie ClientApi api = new ClientApi(); Console.WriteLine(); Console.Write("Pokazywanie zawartości konta konta."); Console.WriteLine("Podaj Numer Twojego konta:"); string number = Console.ReadLine(); //numer Id w bazie Account i Payment są identyczne!! (bool isSucces, string content) = await api.GetPaymentData(number, _tokenSource.Token);//pociągnięcie danych if (isSucces) { Payment payment = JsonConvert.DeserializeObject <Payment>(content); Console.WriteLine(); Console.WriteLine(string.Format( "Na koncie nr: {0}\n obecnie znajduje się następująca kwota środków w złotych: {1}", payment.AccountNumber, payment.AccountBalance )); } else { Console.WriteLine(content); } }
private void HalfMinuteTimerCallback(object state) { //Logger.Log("half tim: " + GameState.Started); if (GameState.Started == true) { try { //TimerTick = DateTime.Now.Ticks; if (goB < 1) { if (Player.GetLevel() >= 6) { SkillUp(4); } Random rand = new Random(); int choice = rand.Next(1, 4); SkillUp(choice); //Server.SetInfoText("skillup: " + choice); } //TODO } catch (Exception ex) { Logger.Log("err: " + ex.Message); } } ClientApi.TimerChange(HalfMinuteTimer, RandomTimeGenerator(30000)); }
public void WrongIpAdress() { var request = new RestRequest("v1?apiKey=at_08HkDwTYC8ygW3NSKRF9iIFSYqL4F&ipAddress=0", Method.GET); var response = ClientApi.GetInstance().Client.Execute(request); Assert.AreEqual(HttpStatusCode.UnprocessableEntity, response.StatusCode); }
public JwtResponse GetJwt(ClientApi clientApi, string username) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.NameId, clientApi.Name), new Claim(JwtRegisteredClaimNames.UniqueName, clientApi.ClientId), new Claim(JwtRegisteredClaimNames.Sid, clientApi.ClientSecret), new Claim("Username", username.ToBase64Encode()), }; var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], //Owner Api => Application Name or URL API audience: clientApi.ClientId, //Client Token => Client Name or URL Website claims, notBefore: DateTime.Now, expires: DateTime.Now.AddHours(int.Parse(_config["Jwt:ExpiresInHours"])), signingCredentials: credentials); var encodeToken = new JwtSecurityTokenHandler().WriteToken(token); var jwtResponse = new JwtResponse { Token = encodeToken, ValidFrom = token.ValidFrom.ToLocalTime(), ValidTo = token.ValidTo.ToLocalTime() }; return(jwtResponse); }
public async Task <Guid?> PutAsync(ClientApi model) { Guid?id = null; var where = new Dictionary <string, object> { { nameof(model.ClientId), model.ClientId } }; var param = new ExistWithKeyModel { KeyName = nameof(model.Id), KeyValue = model.Id, FieldName = nameof(model.ClientId), FieldValue = model.ClientId, WhereData = where }; if (!await _repository.IsExistDataWithKeyAsync(param)) { await _repository.UpdateAsync(model); id = model.Id; } return(id); }
public void WrongCredentials() { var request = new RestRequest("v1?apiKey=ay_08HkDwTYC8ygW3NSKRF9iIFSYqL4F&ipAddress=8.8.8.8", Method.GET); var response = ClientApi.GetInstance().Client.Execute(request); Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); }
private void B_Connection_Click(object sender, EventArgs e) { if (this.name != null) { return; } NameDialog dlg = new NameDialog(); var dlgRes = dlg.ShowDialog(); if (dlgRes == DialogResult.OK) { name = dlg.Nickname; clientApi = new ClientApi(new EventHandler(FreePlayersListChanged), new EventHandler(InviteOccur), new EventHandler(SuccessOccur), AuthProcessing, RegProcessing); clientApi.SendReg(name, dlg.Password); } if (dlgRes == DialogResult.Yes) { name = dlg.Nickname; clientApi = new ClientApi(new EventHandler(FreePlayersListChanged), new EventHandler(InviteOccur), new EventHandler(SuccessOccur), AuthProcessing, RegProcessing); clientApi.SendAuth(name, dlg.Password); } dlg.Dispose(); }
private async Task <HttpResponseMessage> Atualizar(Scheduling item) { var client = new ClientApi(); var content = JsonConvert.SerializeObject(item); return(await client.Put($"schedulings/{item.Id}", content)); }
private async void FrmFactoresRiesgoPaciente_Load(object sender, EventArgs e) { ShowPacienteData(); ClientApi api = new ClientApi("factor-riesgo"); List <FactorRiesgo> factorRiesgos = await api.SendGet <List <FactorRiesgo> >(); factorRiesgos.ForEach(x => { string presenta = "-"; string comentario = ""; Nullable <DateTime> fechaRegistro = null; var factorFound = paciente.Historial?.FactoresRiesgo? .Where(f => f.FactorRiesgo.Codigo == x.Codigo) .FirstOrDefault(); if (factorFound != null) { presenta = "SI"; comentario = factorFound.Comentario; fechaRegistro = factorFound.FechaRegistro; } dgvFactorRiesgoPaciente.Rows.Add(x.Codigo, x.Nombre, presenta, comentario, fechaRegistro); }); }
public void Init(string basicAccessToken, string basicRefreshToken, ClientApi clientApi) { Model = new WidgetModel(); Model.SetBasicTokens(basicAccessToken, basicRefreshToken); MarketApi = clientApi; MobileInputFieldHandler.InputSelected += OnMobileInputFieldSelected; }
private static async Task <string> CheckTitleNumber(string titleNo, ClientApi clientApi) { var res = (await clientApi.GetTitle(titleNo))?.TitleNo; Console.WriteLine((res == null)?$"{titleNo} not found in {clientApi.BaseAddress}":$"{res} found in {clientApi.BaseAddress}"); return(res); }
static void Main(string[] args) { ClientApi api = new ClientApi("128.230.199.93", "username", "password"); ResultSet set = api.DoSQL("SELECT * FROM table0"); foreach(var row in set){ int row_index = set.GetInt("row_index"); String address = set.GetString("postal_address"); } }
public HttpSessions(ClientApi api) { this.api = api; }
public SessionManagement(ClientApi api) { this.api = api; }
public Break(ClientApi api) { this.api = api; }
public void InstantiateClientApi() { zap = new ClientApi("localhost", 7070); }
public static void Init(ClientInitializer initializer) { var user = new User(initializer.Nick, initializer.NickColor); if (Interlocked.CompareExchange(ref model, new ClientModel(user), null) != null) throw new InvalidOperationException("model already inited"); Api = new ClientApi(); Client = new AsyncClient(initializer.Nick); Peer = new AsyncPeer(); Plugins = new ClientPluginManager(initializer.PluginsPath); Plugins.LoadPlugins(initializer.ExcludedPlugins); }
public Search(ClientApi api) { this.api = api; }
public Authentication(ClientApi api) { this.api = api; }
public Users(ClientApi api) { this.api = api; }
public ForcedUser(ClientApi api) { this.api = api; }
private void CallClientApi(ClientApi api, string desc, Action<AndroidJavaObject> call, Action<bool> callback) { Logger.d("Requesting API call: " + desc); RunWhenConnectionStable(() => { // we got a stable connection state to the games service // (either connected or disconnected, but not in progress). if (mGameHelperManager.IsConnected()) { // we are connected, so make the API call Logger.d("Connected! Calling API: " + desc); call.Invoke(api == ClientApi.Games ? mGameHelperManager.GetGamesClient() : mGameHelperManager.GetAppStateClient()); if (callback != null) { PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(true); }); } } else { // we are not connected, so fail the API call Logger.w("Not connected! Failed to call API :" + desc); if (callback != null) { PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(false); }); } } }); }
public Reveal(ClientApi api) { this.api = api; }
public Params(ClientApi api) { this.api = api; }
public ResultSet(int result_id, ClientApi api_ref) { api_ref.registerCallback(new PutDatasetDelegate(putDataSetCallback)); }
public Ascan(ClientApi api) { this.api = api; }
public AjaxSpider(ClientApi api) { this.api = api; }
public Selenium(ClientApi api) { this.api = api; }
public Autoupdate(ClientApi api) { this.api = api; }
public Acsrf(ClientApi api) { this.api = api; }
public Script(ClientApi api) { this.api = api; }
public Context(ClientApi api) { this.api = api; }