public override void Execute(MonitorWorkItem workItem, ITaskExecutionContext context) { Uri[] uriArray = PingUrlsStep.ParseUrls(workItem.Configuration.PingUrls.Urls, context.Log); if (uriArray.Length == 0) { return; } try { Parallel.ForEach <Uri>(uriArray, new ParallelOptions() { MaxDegreeOfParallelism = 4 }, (Uri url) => { Stopwatch stopwatch = Stopwatch.StartNew(); try { System.Threading.Tasks.Task <HttpResponseMessage> task = this.HttpGet(url, workItem.Configuration.PingUrls.MaximumWaitTimeSeconds); task.Wait(); task.Result.EnsureSuccessStatusCode(); } catch (Exception exception) { throw new PingUrlsStep.PingException(url, stopwatch, exception); } }); } catch (AggregateException aggregateException) { PingUrlsStep.PingException[] pingExceptionArray = PingUrlsStep.AssertExceptions(aggregateException); for (int i = 0; i < (int)pingExceptionArray.Length; i++) { this.AddException(pingExceptionArray[i], workItem); } } }
public string AcquireLeaseOnBlob( string blob, TimeSpan?maxWaitDefault = null, TimeSpan?delayDefault = null) { TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(120); TimeSpan delay = delayDefault ?? TimeSpan.FromMilliseconds(500); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // This will throw an exception with HTTP code 409 when we cannot acquire the lease // But we should block until we can get this lease, with a timeout (maxWaitSeconds) while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds) { try { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); System.Threading.Tasks.Task <string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null); task.Wait(); return(task.Result); } catch (Exception e) { Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}"); Thread.Sleep(delay); } } throw new Exception($"Unable to acquire lease on {blob}"); }
public string GetServerList(string url) { try { HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(1, 1, 1); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppContext.Token); System.Threading.Tasks.Task <HttpResponseMessage> responseTask = httpClient.GetAsync(url); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; System.Threading.Tasks.Task <String> strContentTask = response.Content.ReadAsStringAsync(); strContentTask.Wait(); string strContent = strContentTask.Result; return(strContent); } catch (Exception ex) { MessageBox.Show("Somethink Wrong Error: " + ex.Message); return(""); } }
public CloudJob GetJob(string jobId, DetailLevel detailLevel) { using (System.Threading.Tasks.Task <CloudJob> getJobTask = this.GetJobAsync(jobId, detailLevel)) { getJobTask.Wait(); return(getJobTask.Result); } }
public virtual int Count() { System.Threading.Tasks.Task <int> count = repository.Count(); count.Wait(); return(count.Result); }
public string AcquireLeaseOnBlob(string blob) { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); System.Threading.Tasks.Task <string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null); task.Wait(); return(task.Result); }
// // Once full OM support is added, we can remove all protocol based job operations // /// <summary> /// TODO: This is a hack because Job.Refresh breaks using the job due to its ParentWorkItem name being invalidated in the property router /// </summary> public ICloudJob GetJob(string workItemName, string jobName, DetailLevel detailLevel) { using (System.Threading.Tasks.Task <ICloudJob> getJobTask = this.GetJobAsync(workItemName, jobName, detailLevel)) { getJobTask.Wait(); return(getJobTask.Result); } }
public static bool TryExecute <T>(this System.Threading.Tasks.Task <T> task, out T result, int limitWait = 1000) { if (task.Wait(limitWait)) { result = task.Result; return(task.IsCompleted); } result = default(T); return(false); }
private string GetToken() { Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext cntx = new AuthenticationContext(_config.AadEndpoint); string clientId = _config.BatchApplicationId; string clientKey = _config.BatchApplicationKey; System.Threading.Tasks.Task <AuthenticationResult> result = cntx.AcquireTokenAsync(_config.BatchServiceUrl, new ClientCredential(clientId, clientKey)); result.Wait(); return(result.Result.AccessToken); }
public string UploadAttachments() { System.Threading.Tasks.Task <byte[]> task = this.Request.Content.ReadAsByteArrayAsync(); task.Wait(); byte[] byteArray = task.Result; Manager.Instance.UploadAttachments(byteArray); return("success."); }
private string GetToken() { AuthenticationContext cntx = new AuthenticationContext(Settings[SETTING_BATCH_AUTHORITY_URI]); string clientId = Settings[SETTING_BATCH_APPLICATION_ID]; string clientKey = Settings[SETTING_BATCH_APPLICATION_KEY]; System.Threading.Tasks.Task <AuthenticationResult> r = cntx.AcquireTokenAsync(Settings[SETTING_BATCH_RESOURCE_URL], new ClientCredential(clientId, clientKey)); r.Wait(); return(r.Result.AccessToken); }
public void CreateBlobIfNotExists(string path) { System.Threading.Tasks.Task <bool> task = _blobContainer.GetBlockBlobReference(path).ExistsAsync(); task.Wait(); if (!task.Result) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } }
public static string GenerateRSAKeyPair() { try { RSAKeys rsa = new RSAKeys(); AsymmetricCipherKeyPair keypair = null; using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024)) { RSAParameters rsaKeyInfo = rsaProvider.ExportParameters(true); keypair = DotNetUtilities.GetRsaKeyPair(rsaKeyInfo); } var _privateKey = rsa.ImportPrivateKey(keypair); var _publicKey = rsa.ImportPublicKey(keypair); Keys keys = new Keys(); keys.privateKey = rsa.ExportPrivateKey(_privateKey); keys.publicKey = rsa.ExportPublicKey(_publicKey); //call Arca and get response then //Decrypt here ArcaRequest arca = new ArcaRequest(); //ArcaResult readTask = null; System.Threading.Tasks.Task <ArcaResult> readTask = null; arca.svaCode = "TESTCode"; arca.rsaPublicKey = keys.publicKey; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(""); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("key", "testKeyValue"); var response = client.PostAsJsonAsync("", arca); response.Wait(); if (response.Result.IsSuccessStatusCode) { readTask = response.Result.Content.ReadAsAsync <ArcaResult>(); readTask.Wait(); } return(rsa.RsaDecryptWithPrivate(readTask.Result.key, keypair)); } catch (Exception ex) { return(null); } }
public MainViewModel(INavigator<ViewModelBase> navigator, IRootTaskManagerViewModelFactory taskManagerViewModelFactory, IAuthenticator authenticator) { Navigator = navigator; Authenticator = authenticator; UpdateCurrentViewModelCommand = new UpdateCurrentViewModelCommand(navigator, taskManagerViewModelFactory); LogoutCommand = new LogoutCommand(this); System.Threading.Tasks.Task<bool> t = System.Threading.Tasks.Task.Run(() => Authenticator.TryToAuthenticateAsync()); t.Wait(); bool isAuthenticated = t.Result; if (isAuthenticated) { UpdateCurrentViewModelCommand.Execute(ViewType.IssuesTasks); } else { UpdateCurrentViewModelCommand.Execute(ViewType.Login); } }
private static T GetWeixinReturnObject <T>(string url) { HttpWebRequest httpWebRequest = (HttpWebRequest)(HttpWebRequest.Create(url)); System.Threading.Tasks.Task <WebResponse> getResponseTask = httpWebRequest.GetResponseAsync(); getResponseTask.Wait(); using (HttpWebResponse httpWebResponse = getResponseTask.Result as HttpWebResponse) { Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); string responseString = streamReader.ReadToEnd(); httpWebRequest.Abort(); T objectFromJsonstr = JsonConvert.DeserializeObject <T>(responseString); return(objectFromJsonstr); } }
public string AcquireLeaseOnBlob( string blob, TimeSpan?maxWaitDefault = null, TimeSpan?delayDefault = null) { TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(1800); TimeSpan delay = delayDefault ?? TimeSpan.FromMilliseconds(500); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // This will throw an exception with HTTP code 409 when we cannot acquire the lease // But we should block until we can get this lease, with a timeout (maxWaitSeconds) while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds) { try { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); System.Threading.Tasks.Task <string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null); task.Wait(); string leaseID = task.Result; // Create a cancelabble task that will auto-renew the lease until the lease is released _cancellationTokenSource = new CancellationTokenSource(); _leaseRenewalTask = Task.Run(() => { AutoRenewLease(this, blob, leaseID); }, _cancellationTokenSource.Token); return(leaseID); } catch (Exception e) { Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}"); Thread.Sleep(delay); } } ResetLeaseRenewalTaskState(); throw new Exception($"Unable to acquire lease on {blob}"); }
public string GetToken(string url, string user, string pass) { try { JObject oLogin = JObject.FromObject(new { username = user, password = pass }); HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(1, 1, 1); var content = new StringContent(oLogin.ToString(), Encoding.UTF8, "application/json"); System.Threading.Tasks.Task <HttpResponseMessage> responseTask = httpClient.PostAsync("https://playground.tesonet.lt/v1/tokens", content); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; System.Threading.Tasks.Task <String> strContentTask = response.Content.ReadAsStringAsync(); strContentTask.Wait(); string strContent = strContentTask.Result; JObject tobj = JObject.Parse(strContent); if (!String.IsNullOrWhiteSpace((string)tobj["message"])) { MessageBox.Show((string)tobj["message"], "Warning"); return(""); } return((string)tobj["token"]); } catch (Exception ex) { MessageBox.Show("Somethink Wrong Error: " + ex.Message); return(""); } }
public static string GetOpenId(string code) { string appId = WxPayAPI.WxPayConfig.APPID; string secret = WxPayAPI.WxPayConfig.APPSECRET; string getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code"; HttpWebRequest httpWebRequest = (HttpWebRequest)(HttpWebRequest.Create(getOpenIdUrl)); System.Threading.Tasks.Task <WebResponse> getResponseTask = httpWebRequest.GetResponseAsync(); getResponseTask.Wait(); using (HttpWebResponse httpWebResponse = getResponseTask.Result as HttpWebResponse) { Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); string responseString = streamReader.ReadToEnd(); httpWebRequest.Abort(); LoginByWeixin.Json_access_token json_access_token = JsonConvert.DeserializeObject <LoginByWeixin.Json_access_token>(responseString); return(json_access_token.Openid); } }
protected static T Read <T>(System.Threading.Tasks.Task <HttpResponseMessage> t, bool performRead) where T : class { t.Wait(); if (t.Result.IsSuccessStatusCode) { if (performRead) { try { var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter(), new XmlMediaTypeFormatter() }; using (var tr = t.Result.Content.ReadAsAsync <T>(formatters)) { tr.Wait(); return(tr.Result); } } catch// (Exception ex) { throw; } } } else { var info = ProcessError(t); if (info.HasValue) { throw new Exception(info.ToString()); } } return(null); }
static T Wait <T>(System.Threading.Tasks.Task <T> task) { task.Wait(); return(task.Result); }
public bool IsLatestSpecifiedVersion(string version) { System.Threading.Tasks.Task <bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync(); task.Wait(); return(task.Result); }
public static T RunSynchronously <T>(System.Threading.Tasks.Task <T> task) { task.Wait(); return(task.Result); }