protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Method == HttpMethod.Get && request.RequestUri.Segments.Last() == "authtoken") { string querystring = request.RequestUri.Query.Substring(1); string[] queryParams = querystring.Split(new[] { '&' }); var queryStringParams = request.RequestUri.ParseQueryString(); if (queryStringParams.Count > 0) { string code = queryParams.Where(p => p.StartsWith("code")).First().Split(new[] { '=' })[1]; return Task.Factory.StartNew( () => { string accessToken = this.GetFacebookAccessToken(code, request); string username = GetFacebookUsername(accessToken); var ticket = new FormsAuthenticationTicket(username, false, 60); string s = FormsAuthentication.Encrypt(ticket); var response = new HttpResponseMessage(); response.Headers.Add("Set-Cookie", string.Format("ticket={0}; path=/", s)); var responseContentBuilder = new StringBuilder(); responseContentBuilder.AppendLine("<html>"); responseContentBuilder.AppendLine(" <head>"); responseContentBuilder.AppendLine(" <title>Login Callback</title>"); responseContentBuilder.AppendLine(" </head>"); responseContentBuilder.AppendLine(" <body>"); responseContentBuilder.AppendLine(" <script type=\"text/javascript\">"); responseContentBuilder.AppendLine( " if(window.opener){"); if (queryStringParams["callback"] != null) { responseContentBuilder.AppendLine(queryStringParams["callback"] + "();"); } responseContentBuilder.AppendLine(" window.close()';"); responseContentBuilder.AppendLine(" }"); responseContentBuilder.AppendLine(" </script>"); responseContentBuilder.AppendLine(" </body>"); responseContentBuilder.AppendLine("</html>"); response.Content = new StringContent(responseContentBuilder.ToString()); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true }; return response; }); } return Task.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.InternalServerError)); } return base.SendAsync(request, cancellationToken); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var authHeader = request.Headers.Authorization; if (authHeader == null) return base.SendAsync(request, cancellationToken); if (authHeader.Scheme != "Basic") return base.SendAsync(request, cancellationToken); if (String.IsNullOrEmpty(authHeader.Parameter)) return base.SendAsync(request, cancellationToken); var encodedUserPass = authHeader.Parameter.Trim(); var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass)); var parts = userPass.Split(":".ToCharArray()); var email = parts[0]; var password = parts[1]; var mem = new UserMembershipProvider(); if (!mem.ValidateUserEncoded(email, password)) return base.SendAsync(request, cancellationToken); var i = new RadarIdentity(email, "Basic"); //var identity = new GenericIdentity(username, "Basic"); //string[] roles = RadarRoleProvider.GetRolesForUser(email); var p = new RadarPrincipal(i); //var principal = new GenericPrincipal(i, roles); Thread.CurrentPrincipal = p; if (HttpContext.Current != null) HttpContext.Current.User = p; return base.SendAsync(request, cancellationToken); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // if request is local, just serve it without https object httpContextBaseObject; if (request.Properties.TryGetValue("MS_HttpContext", out httpContextBaseObject)) { var httpContextBase = httpContextBaseObject as HttpContextBase; if (httpContextBase != null && httpContextBase.Request.IsLocal) { return base.SendAsync(request, cancellationToken); } } // if request is remote, enforce https if (request.RequestUri.Scheme != Uri.UriSchemeHttps) { return Task<HttpResponseMessage>.Factory.StartNew( () => { var response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("HTTPS Required") }; return response; }); } return base.SendAsync(request, cancellationToken); }
//// this is Castle.Core.Logging.ILogger, not log4net.Core.ILogger //public ILogger Logger { get; set; } /// <summary> /// Executes the authorization filter. /// </summary> /// <param name="actionContext">The action context.</param> /// <param name="cancellationToken">The cancellation token associated with the filter.</param> /// <param name="continuation">The continuation.</param> /// <returns> /// The authorization filter to synchronize. /// </returns> public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { HttpRequestMessage request = actionContext.Request; try { if (IsAjaxRequest(request)) { ValidateRequestHeader(request); } else { AntiForgery.Validate(); } } catch (Exception) { //LogManager.GetCurrentClassLogger().Warn("Anti-XSRF Validation Failed", ex); actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, RequestMessage = actionContext.ControllerContext.Request }; return FromResult(actionContext.Response); } return continuation(); }
/// <summary>Asynchronously iterates through an enumerable of tasks.</summary> /// <param name="factory">The target factory.</param> /// <param name="source">The enumerable containing the tasks to be iterated through.</param> /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <param name="scheduler">The scheduler to which tasks will be scheduled.</param> /// <returns>A Task that represents the complete asynchronous operation.</returns> public static Task Iterate( this TaskFactory factory, IEnumerable<object> source, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Iterate(factory, source, null, cancellationToken, creationOptions, scheduler); }
/// <summary> /// Takes an OAuth code and turns it into an API token. /// </summary> /// <param name="code">A code returned from the OAuth page (https://quizlet.com/authorize/)</param> /// <param name="success">A delegate to be called when the authentication succeeds.</param> /// <param name="failure">What to do when the authentication fails.</param> /// <param name="token">A CancellationToken, which is currently useless.</param> public void Authenticate(string code, Action success, Action<Exception> failure, CancellationToken token) { var fields = "grant_type=authorization_code&code=" + code + "&redirect_uri=https://q.asztal.net/"; var req = new HttpsRequest("POST", "/oauth/token"); req.BasicAuthorization(ClientID, SecretKey); req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; req.PostData = Encoding.UTF8.GetBytes(fields); FetchJSON(req, json => { try { if (json is JsonDictionary) { var ctx = new JsonContext(); var accessToken = ctx.FromJson<string>((json as JsonDictionary).Items["access_token"]); var userName = ctx.FromJson<string>((json as JsonDictionary).Items["user_id"]); var tokenExpiry = DateTime.Now.AddSeconds(ctx.FromJson<double>((json as JsonDictionary).Items["expires_in"])); Credentials = new Credentials(accessToken, userName, tokenExpiry); success(); } else { failure(new FormatException("Quizlet server returned an invalid response.")); } } catch (KeyNotFoundException) { failure(new FormatException("Quizlet server returned an invalid response.")); } catch (JsonConvertException) { failure(new FormatException("Quizlet server returned an invalid response.")); } }, failure, token); }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError); response.Content = new StringContent(Content); response.RequestMessage = Request; return Task.FromResult(response); }
/// <summary>Asynchronously iterates through an enumerable of tasks.</summary> /// <param name="factory">The target factory.</param> /// <param name="source">The enumerable containing the tasks to be iterated through.</param> /// <param name="cancellationToken">The cancellation token used to cancel the iteration.</param> /// <returns>A Task that represents the complete asynchronous operation.</returns> public static Task Iterate( this TaskFactory factory, IEnumerable<object> source, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return Iterate(factory, source, null, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); }
private static Int32 Sum(CancellationToken cancelToken, Int32 n) { Int32 sum = 0; for (; n > 0; n--){ cancelToken.ThrowIfCancellationRequested(); checked{ sum += n; } } return sum; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers.Add("Cookie", this.cookie); request.Headers.Add("X-Unity-Version", GameInfo.instance.UV); request.Headers.Add("charset", "UTF-8"); request.Headers.Add("UserAgent", GameInfo.instance.UA); request.Headers.Add("Connection", "Keep-Alive"); return base.SendAsync(request, cancellationToken); }
// http://blogs.msdn.com/b/lucian/archive/2012/12/08/await-httpclient-getstringasync-and-cancellation.aspx public static async Task<int> DownloadAndCountBytesAsync(string url, CancellationToken token = new CancellationToken()) { await Task.Delay(TimeSpan.FromSeconds(3), token).ConfigureAwait(false); var client = new HttpClient(); using (var response = await client.GetAsync(url, token).ConfigureAwait(false)) { var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); return data.Length; } }
private static void EnsureOperationCanceledExceptionThrown(Action action, CancellationToken token, string message) { OperationCanceledException operationCanceledEx = Assert.Throws<OperationCanceledException>(action); if (operationCanceledEx.CancellationToken != token) { Assert.True(false, string.Format("ManualResetEventCancellationTests: Failed. " + message)); } }
/// <summary> /// Registers a callback for the <paramref name="cancellationToken"/> that blocks calls to <see cref="CancellationTokenSource.Cancel()"/> until <see cref="Dispose"/> has been called. /// </summary> /// <param name="cancellationToken">Used to signal cancellation requests.</param> public CancellationGuard(CancellationToken cancellationToken) { _registration = cancellationToken.Register( #if NET40 || NET45 _tcs.Task.Wait #else () => _event.WaitOne() #endif ); }
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { var mockResponseMessage = new HttpResponseMessage() { //Mock content contains json of two face results Content = new StringContent("[\n {\n \"faceRectangle\": {\n \"left\": 68,\n \"top\": 97,\n \"width\": 64,\n \"height\": 97\n },\n \"scores\": {\n \"anger\": 0.00300731952,\n \"contempt\": 5.14648448E-08,\n \"disgust\": 9.180124E-06,\n \"fear\": 0.0001912825,\n \"happiness\": 0.9875571,\n \"neutral\": 0.0009861537,\n \"sadness\": 1.889955E-05,\n \"surprise\": 0.008229999\n }\n },\n{\n \"faceRectangle\": {\n \"left\": 68,\n \"top\": 97,\n \"width\": 64,\n \"height\": 97\n },\n \"scores\": {\n \"anger\": 0.00300731952,\n \"contempt\": 5.14648448E-08,\n \"disgust\": 9.180124E-06,\n \"fear\": 0.0001912825,\n \"happiness\": 0.9875571,\n \"neutral\": 0.0009861537,\n \"sadness\": 1.889955E-05,\n \"surprise\": 0.008229999\n }\n }\n]"), StatusCode = HttpStatusCode.OK }; return Task.FromResult(mockResponseMessage); }
private static void EnsureOperationCanceledExceptionThrown(Action action, CancellationToken token, string message) { OperationCanceledException operationCanceledEx = Assert.Throws<OperationCanceledException>(action); // Failure Case: OperationCanceledException not thrown. if (operationCanceledEx.CancellationToken != token) { Assert.True(false, string.Format("SemaphoreSlimCancellationTests: Failed. " + message)); } }
public void doStuff(string exampleString) { cancelSource = new CancellationTokenSource(); cancelToken = cancelSource.Token; var decRep = new Progress<decimal>((decCount) => { if (PctChangedEvent != null) PctChangedEvent(decCount); }); Task.Run(() => { doStuffTask(exampleString, decRep, cancelToken); }); }
/// <summary> /// Downloads a file as a string. /// </summary> /// <param name="address">File URL</param> /// <param name="cancellationToken">Optional cancellation token</param> public static Task<string> DownloadAsStringAsync(string address, CancellationToken cancellationToken = new CancellationToken()) { return Task.Factory.StartNew( delegate { using (var webClient = new WebClient()) { return webClient.DownloadString(address); } }, cancellationToken); }
public static void MultiplyParallel(CancellationToken cancellationToken, Matrix src1, Matrix src2, Matrix dst) { if (src1._size != src2._size || src1._size != dst._size) throw new ArgumentOutOfRangeException("src1"); int N = src1._size; matrix_mult_parallel( cancellationToken, N, N, N, src1._dataPtr, 0, 0, N, src2._dataPtr, 0, 0, N, dst._dataPtr, 0, 0, N); }
protected override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken) { if (OnSend != null) return OnSend (request); if (OnSendFull != null) return OnSendFull (request, cancellationToken); Assert.Fail ("Send"); return null; }
public async override Task<HttpResponseMessage> ExecuteAsync( HttpControllerContext controllerContext, CancellationToken cancellationToken) { using (Session = Store.OpenAsyncSession()) { var result = await base.ExecuteAsync(controllerContext, cancellationToken); await Session.SaveChangesAsync(); return result; } }
private static int Sum(CancellationToken ct, int n) { int sum = 0; for (; n > 0; n--) { ct.ThrowIfCancellationRequested(); checked { sum += n; } } return sum; }
public static void MultiplyStrassens(CancellationToken cancellationToken, Matrix src1, Matrix src2, Matrix dst) { if (src1._size != src2._size || src1._size != dst._size) throw new ArgumentOutOfRangeException("src1"); int N = src1._size; strassen_mult_serial( cancellationToken, N, src1._dataPtr, 0, 0, N, src2._dataPtr, 0, 0, N, dst._dataPtr, 0, 0, N, 64); }
public CodeActionEdit GetEdit(CancellationToken cancellationToken) { var tree = (SyntaxTree)document.GetSyntaxTree(); var newRoot = tree.GetRoot().ReplaceNodes( oldNodes, (e, a) => { var n = newNodeFunc(e, a); if (addFormatAnnotation) n = CodeAnnotations.Formatting.AddAnnotationTo(n); return n; }); return new CodeActionEdit(document.UpdateSyntaxRoot(newRoot)); }
static void Run1(CancellationToken ct) { ct.ThrowIfCancellationRequested(); Console.WriteLine("我是任务1"); Thread.Sleep(2000); ct.ThrowIfCancellationRequested(); Console.WriteLine("我是任务1的第二部分信息"); }
private static Int32 Sum(CancellationToken ct, Int32 n){ Int32 sum = 0; for (; n > 0; n--) { // The following line throws OperationCanceledException when Cancel // is called on the CancellationTokenSource referred to by the token ct.ThrowIfCancellationRequested(); checked { sum += n; }// if n is large, this will throw System.OverflowException } return sum; }
/// <summary> /// Continuously read strings from the socketclient and yield them as <code>Message</code> instances. /// Stops when <code>eof</code> is hit. Messages are delimited by <code>eom</code>. /// </summary> /// <param name="client"></param> /// <param name="cancellationToken"></param> /// <param name="eom"></param> /// <param name="eof"></param> /// <returns></returns> public static IEnumerable<Message> ReadStrings(this ITcpSocketClient client, CancellationToken cancellationToken, string eom = "<EOM>", string eof = "<EOF>") { var from = String.Format("{0}:{1}", client.RemoteAddress, client.RemotePort); var currData = ""; int bytesRec = 0; bool gotEof = false; while (bytesRec != -1 && !cancellationToken.IsCancellationRequested && !gotEof) { var buffer = new byte[1024]; bytesRec = client.ReadStream.Read(buffer, 0, buffer.Length); currData += Encoding.UTF8.GetString(buffer, 0, bytesRec); // Hit an EOM - we have a full message in currData; if (currData.IndexOf(eom, StringComparison.Ordinal) > -1) { var msg = new Message { Text = currData.Substring(0, currData.IndexOf(eom)), DetailText = String.Format("<Received from {0} at {1}>", from, DateTime.Now.ToString("HH:mm:ss")) }; yield return msg; currData = currData.Substring(currData.IndexOf(eom) + eom.Length); } // Hit an EOF - client is gracefully disconnecting if (currData.IndexOf(eof, StringComparison.Ordinal) > -1) { var msg = new Message { DetailText = String.Format("<{0} disconnected at {1}>", from, DateTime.Now.ToString("HH:mm:ss")) }; yield return msg; gotEof = true; } } // if we get here, either the stream broke, the cancellation token was cancelled, or the eof message was received // time to drop the client. try { client.DisconnectAsync().Wait(); client.Dispose(); } catch { } }
public DelayTask(CancellationToken cancellationToken, int millisecondsDelay) { if (cancellationToken.CanBeCanceled) { cancellationToken.Register(Complete, false); } if (millisecondsDelay != Timeout.Infinite) { m_timer = new Timer(_ => Complete(), null, millisecondsDelay, Timeout.Infinite); } m_cancellationToken = cancellationToken; }
public void doStuffTask(string exampleString, IProgress<decimal> decRep, CancellationToken token) { int twenty = 20; string whatever = ""; for (int i = 0; i < twenty; i++) { if (!token.IsCancellationRequested) { whatever += exampleString; decRep.Report((Math.Ceiling((decimal)(i + 1) * 100 / twenty))); } } } // public void doStuffTask
public static Task ExecuteWithDelay(this TimeSpan delay, Action methodToExecute, CancellationToken cancellationToken) { return Task.Run(() => { while (true) { var isCancelled = cancellationToken.WaitHandle.WaitOne(delay); if (isCancelled) break; methodToExecute.Invoke(); } }, cancellationToken); }
/// <summary> /// Registers a callback for the <paramref name="cancellationToken"/> that blocks calls to <see cref="CancellationTokenSource.Cancel()"/> until <see cref="Dispose"/> has been called. /// </summary> /// <param name="cancellationToken">Used to signal cancellation requests.</param> /// <param name="timeout">A timespan after which the cancellation will be considered completed even if <see cref="Dispose"/> has not been called yet.</param> public CancellationGuard(CancellationToken cancellationToken, TimeSpan timeout) { _registration = cancellationToken.Register( #if NET40 || NET45 () => _tcs.Task.Wait(timeout) #else () => { _event.WaitOne(timeout, exitContext: true); _event.Close(); } #endif ); }
public async Task T03_Cancellation() { var ct = new CancellationToken(true); await Assert.ThrowsAsync <OperationCanceledException>(async() => await SocketConnector.ConnectAsync(IPEndPoint, Logger, -1, ct)); }
public async Task <IActionResult> ExecuteAsync(SaveOfferApplication parameter, CancellationToken cancellationToken = new CancellationToken()) { var offer = this.saveOfferToOfferMapper.Map(parameter); offer = await this._offerRepository.UpdateApplications(offer, cancellationToken); var offerViewModel = this.offerToOfferMapper.Map(offer); return(new CreatedAtRouteResult( OffersControllerRoute.GetOffer, new { offerId = offerViewModel.OfferId }, offerViewModel)); }
public Task <int> SaveChangesAsync(CancellationToken cancellationToken) { CheckDisposed(); return(Context.SaveChangesAsync(cancellationToken)); }
private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken) { ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty; List<CodeFixProvider> projectFixers; Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers); var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers); // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if (hasAnySharedFixer && document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive) { workspaceFixers = workspaceFixers.WhereAsArray(IsInteractiveCodeFixProvider); hasAnySharedFixer = workspaceFixers.Any(); } Lazy<ISuppressionFixProvider>? lazySuppressionProvider = null; var hasSuppressionFixer = considerSuppressionFixes && _suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) && lazySuppressionProvider.Value != null; if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer) { return false; } var allFixers = ImmutableArray<CodeFixProvider>.Empty; if (hasAnySharedFixer) { allFixers = workspaceFixers; } if (hasAnyProjectFixer) { allFixers = allFixers.AddRange(projectFixers); } var dx = await diagnostic.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false); if (hasSuppressionFixer && lazySuppressionProvider?.Value.CanBeSuppressedOrUnsuppressed(dx) == true) { return true; } var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, dx, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (action, applicableDiagnostics) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics)); } }, verifyArguments: false, cancellationToken: cancellationToken); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); // we do have fixer. now let's see whether it actually can fix it foreach (var fixer in allFixers) { await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask).ConfigureAwait(false); foreach (var fix in fixes) { if (!fix.Action.PerformFinalApplicabilityCheck) { return true; } // Have to see if this fix is still applicable. Jump to the foreground thread // to make that check. var applicable = await Task.Factory.StartNew(() => fix.Action.IsApplicable(document.Project.Solution.Workspace), cancellationToken).ConfigureAwait(false); // TODO: check if this is needed // cancellationToken, TaskCreationOptions.None, this.ForegroundTaskScheduler).ConfigureAwait(false); if (applicable) { return true; } } } return false; }
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) { return _getProjectDiagnosticsAsync(project, false, _diagnosticIds, cancellationToken); }
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.TargetToken.IsUsingKeywordInUsingDirective() || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken) || context.SyntaxTree.IsLambdaDeclarationContext(position, otherModifier: SyntaxKind.AsyncKeyword, cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); }
/// <summary> /// Get all globally unsubscribed email addresses. /// </summary> /// <param name="startDate">The start date.</param> /// <param name="endDate">The end date.</param> /// <param name="limit">The limit.</param> /// <param name="offset">The offset.</param> /// <param name="onBehalfOf">The user to impersonate</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// An array of <see cref="GlobalSuppression"/>. /// </returns> public Task <GlobalSuppression[]> GetAllAsync(DateTime?startDate = null, DateTime?endDate = null, int limit = 50, int offset = 0, string onBehalfOf = null, CancellationToken cancellationToken = default(CancellationToken)) { return(_client .GetAsync("suppression/unsubscribes") .OnBehalfOf(onBehalfOf) .WithArgument("start_time", startDate?.ToUnixTime()) .WithArgument("end_time", endDate?.ToUnixTime()) .WithArgument("limit", limit) .WithArgument("offset", offset) .WithCancellationToken(cancellationToken) .AsSendGridObject <GlobalSuppression[]>()); }
internal StreamCopyOperation(Stream source, Stream destination, long?bytesRemaining, int bufferSize, CancellationToken cancel) : this(source, destination, bytesRemaining, new byte[bufferSize], cancel) { }
internal StreamCopyOperation(Stream source, Stream destination, long?bytesRemaining, CancellationToken cancel) : this(source, destination, bytesRemaining, DefaultBufferSize, cancel) { }
public static async Task Execute(ISession session, CancellationToken cancellationToken) { if (!CheckSnipeConditions(session)) { return; } inProgress = true; double originalLatitude = session.Client.CurrentLatitude; double originalLongitude = session.Client.CurrentLongitude; session.KnownLatitudeBeforeSnipe = originalLatitude; session.KnownLongitudeBeforeSnipe = originalLongitude; //Logger.Write($"DEBUG : Location before snipe : {originalLatitude},{originalLongitude}"); var pth = Path.Combine(Directory.GetCurrentDirectory(), "SnipeMS.json"); try { if (OutOffBallBlock > DateTime.Now || ( File.Exists(pth) && autoSnipePokemons.Count == 0 && manualSnipePokemons.Count == 0 && pokedexSnipePokemons.Count == 0)) { return; } if (autoSnipePokemons.Count > 0 && !(await CheckPokeballsToSnipe( session.LogicSettings.MinPokeballsToSnipe + 1, session, cancellationToken).ConfigureAwait(false))) { session.EventDispatcher.Send(new WarnEvent() { Message = session.Translation.GetTranslation(TranslationString.AutoSnipeDisabled, session.LogicSettings.SnipePauseOnOutOfBallTime) }); OutOffBallBlock = DateTime.Now.AddMinutes(session.LogicSettings.SnipePauseOnOutOfBallTime); return; } List <MSniperInfo2> mSniperLocation2 = new List <MSniperInfo2>(); if (File.Exists(pth)) { var sr = new StreamReader(pth, Encoding.UTF8); var jsn = sr.ReadToEnd(); sr.Close(); mSniperLocation2 = JsonConvert.DeserializeObject <List <MSniperInfo2> >(jsn); File.Delete(pth); if (mSniperLocation2 == null) { mSniperLocation2 = new List <MSniperInfo2>(); } } using (await locker.LockAsync().ConfigureAwait(false)) { if (pokedexSnipePokemons.Count > 0) { mSniperLocation2.Add(pokedexSnipePokemons.OrderByDescending(x => x.PokemonId).FirstOrDefault()); pokedexSnipePokemons.Clear(); } if (manualSnipePokemons.Count > 0) { mSniperLocation2.AddRange(manualSnipePokemons); manualSnipePokemons.Clear(); } else { autoSnipePokemons.RemoveAll(x => x.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now); // || ( x.ExpiredTime >0 && x.ExpiredTime < DateTime.Now.ToUnixTime())); autoSnipePokemons.OrderBy(x => x.Priority) .ThenByDescending(x => PokemonGradeHelper.GetPokemonGrade((PokemonId)x.PokemonId)) .ThenByDescending(x => x.Iv) .ThenByDescending(x => x.PokemonId) .ThenByDescending(x => x.AddedTime); var batch = autoSnipePokemons.Take(session.LogicSettings.AutoSnipeBatchSize); if (batch != null && batch.Count() > 0) { mSniperLocation2.AddRange(batch); autoSnipePokemons.RemoveAll(x => batch.Contains(x)); } } } foreach (var location in mSniperLocation2) { if (session.Stats.CatchThresholdExceeds(session) || isBlocking) { break; } using (await locker.LockAsync().ConfigureAwait(false)) { if (location.EncounterId > 0 && expiredCache.Get(location.EncounterId.ToString()) != null) { continue; } if (pokedexSnipePokemons.Count > 0 || manualSnipePokemons.Count > 0) { break; //should return item back to snipe list } } session.EventDispatcher.Send(new SnipePokemonStarted(location)); if (location.EncounterId > 0 && session.Cache[location.EncounterId.ToString()] != null) { continue; } if (!(await CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, cancellationToken).ConfigureAwait(false))) { session.EventDispatcher.Send(new WarnEvent() { Message = session.Translation.GetTranslation(TranslationString.AutoSnipeDisabled) }); OutOffBallBlock = DateTime.Now.AddMinutes(session.LogicSettings.SnipePauseOnOutOfBallTime); break; } if (location.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now) { continue; } //If bot already catch the same pokemon, and very close this location. string uniqueCacheKey = $"{session.Settings.Username}{Math.Round(location.Latitude, 6)}{location.PokemonId}{Math.Round(location.Longitude, 6)}"; if (session.Cache.Get(uniqueCacheKey) != null) { continue; } session.Cache.Add(location.EncounterId.ToString(), true, DateTime.Now.AddMinutes(15)); cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); session.EventDispatcher.Send(new SnipeScanEvent { Bounds = new Location(location.Latitude, location.Longitude), PokemonId = (PokemonId)location.PokemonId, Source = "InternalSnipe", Iv = location.Iv }); session.Stats.IsSnipping = true; var result = (location.IsVerified()) ? await CatchFromService(session, cancellationToken, location).ConfigureAwait(false) : await CatchWithSnipe(session, location, cancellationToken).ConfigureAwait(false); await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(originalLatitude, originalLongitude), 0).ConfigureAwait(false); if (result) { snipeFailedCount = 0; } else { snipeFailedCount++; if (snipeFailedCount >= 3) { break; //maybe softban, stop snipe wait until verify it not been } } //await Task.Delay(1000, cancellationToken).ConfigureAwait(false); session.Stats.LastSnipeTime = DateTime.Now; session.Stats.SnipeCount++; waitNextPokestop = true; } } catch (ActiveSwitchByPokemonException ex) { throw ex; } catch (ActiveSwitchAccountManualException ex) { throw ex; } catch (ActiveSwitchByRuleException ex) { throw ex; } catch (CaptchaException cex) { throw cex; } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException is CaptchaException) { throw ex.InnerException; } File.Delete(pth); var ee = new ErrorEvent { Message = ex.Message }; if (ex.InnerException != null) { ee.Message = ex.InnerException.Message; } session.EventDispatcher.Send(ee); } finally { inProgress = false; session.Stats.IsSnipping = false; //Logger.Write($"DEBUG : Back to home location: {originalLatitude},{originalLongitude}"); await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(originalLatitude, originalLongitude), 0).ConfigureAwait(false); } }
public static async Task <bool> CatchFromService(ISession session, CancellationToken cancellationToken, MSniperInfo2 encounterId) { cancellationToken.ThrowIfCancellationRequested(); double originalLat = session.Client.CurrentLatitude; double originalLng = session.Client.CurrentLongitude; EncounterResponse encounter; try { // Speed set to 0 for random speed. await LocationUtils.UpdatePlayerLocationWithAltitude( session, new GeoCoordinate(encounterId.Latitude, encounterId.Longitude, session.Client.CurrentAltitude), 0 ).ConfigureAwait(false); await session.Client.Misc.RandomAPICall().ConfigureAwait(false); encounter = await session.Client.Encounter.EncounterPokemon(encounterId.EncounterId, encounterId.SpawnPointId).ConfigureAwait(false); if (encounter != null && encounter.Status != EncounterResponse.Types.Status.EncounterSuccess) { Logger.Debug($"{encounter}"); } //pokemon has expired, send event to remove it. if (encounter != null && (encounter.Status == EncounterResponse.Types.Status.EncounterClosed || encounter.Status == EncounterResponse.Types.Status.EncounterNotFound)) { session.EventDispatcher.Send(new SnipePokemonUpdateEvent(encounterId.EncounterId.ToString(), false, null)); } } catch (CaptchaException ex) { throw ex; } catch (Exception) { return(false); } finally { session.Client.Player.SetCoordinates(originalLat, originalLng, session.Client.CurrentAltitude); //only reset d } if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull) { Logger.Write("Pokemon bag full, snipe cancel"); await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); return(false); } if (encounter.Status == EncounterResponse.Types.Status.EncounterClosed) { Logger.Write("This pokemon has been expired"); return(true); } PokemonData encounteredPokemon; // Catch if it's a WildPokemon (MSniping not allowed for Incense pokemons) if (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess) { encounteredPokemon = encounter.WildPokemon?.PokemonData; } else { Logger.Write($"Pokemon despawned or wrong link format!", LogLevel.Service, ConsoleColor.Gray); return(false); //return await CatchWithSnipe(session, encounterId, cancellationToken).ConfigureAwait(false);// No success to work with } var pokemon = new MapPokemon { EncounterId = encounterId.EncounterId, Latitude = encounterId.Latitude, Longitude = encounterId.Longitude, PokemonId = encounteredPokemon.PokemonId, SpawnPointId = encounterId.SpawnPointId }; return(await CatchPokemonTask.Execute( session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : true ).ConfigureAwait(false)); }
public static async Task <bool> SnipeUnverifiedPokemon(ISession session, IEnumerable <PokemonId> pokemonIds, double latitude, double longitude, CancellationToken cancellationToken) { var currentLatitude = session.Client.CurrentLatitude; var currentLongitude = session.Client.CurrentLongitude; var catchedPokemon = false; session.EventDispatcher.Send(new SnipeModeEvent { Active = true }); List <MapPokemon> catchablePokemon; int retry = 3; bool isCaptchaShow = false; try { do { retry--; await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude, 10d), 0).ConfigureAwait(false); // Set speed to 0 for random speed. latitude += 0.00000001; longitude += 0.00000001; session.EventDispatcher.Send(new UpdatePositionEvent { Longitude = longitude, Latitude = latitude }); var mapObjects = await session.Client.Map.GetMapObjects(true, false).ConfigureAwait(false); catchablePokemon = mapObjects.MapCells.SelectMany(q => q.CatchablePokemons) .Where(q => pokemonIds.Contains(q.PokemonId)) .OrderByDescending(pokemon => PokemonInfo.CalculateMaxCp(pokemon.PokemonId)) .ToList(); } while (catchablePokemon.Count == 0 && retry > 0); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { throw ex; } catch (Exception e) { Logger.Write($"Error: {e.Message}", LogLevel.Error); throw e; } finally { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. } if (catchablePokemon.Count == 0) { session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.NoPokemonToSnipe), }); session.EventDispatcher.Send(new SnipeFailedEvent { Latitude = latitude, Longitude = longitude, PokemonId = pokemonIds.FirstOrDefault() }); return(false); } isCaptchaShow = false; foreach (var pokemon in catchablePokemon) { EncounterResponse encounter; try { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed. encounter = await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).ConfigureAwait(false); } catch (HasherException ex) { throw ex; } catch (CaptchaException ex) { isCaptchaShow = true; throw ex; } finally { if (!isCaptchaShow) { await LocationUtils.UpdatePlayerLocationWithAltitude(session, // Set speed to 0 for random speed. new GeoCoordinate(currentLatitude, currentLongitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); } } switch (encounter.Status) { case EncounterResponse.Types.Status.EncounterSuccess: session.EventDispatcher.Send(new UpdatePositionEvent { Latitude = currentLatitude, Longitude = currentLongitude }); catchedPokemon = await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, currentFortData : null, sessionAllowTransfer : true).ConfigureAwait(false); break; case EncounterResponse.Types.Status.PokemonInventoryFull: if (session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } else { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) }); } return(false); default: session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation( TranslationString.EncounterProblem, encounter.Status) }); break; } if (!Equals(catchablePokemon.ElementAtOrDefault(catchablePokemon.Count - 1), pokemon)) { await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken).ConfigureAwait(false); } } if (catchedPokemon) { session.Stats.SnipeCount++; } session.EventDispatcher.Send(new SnipeModeEvent { Active = false }); return(true); //await Task.Delay(session.LogicSettings.DelayBetweenPlayerActions, cancellationToken).ConfigureAwait(false); }
private async Task WriteConfigFileToDiskAsync(FirstStartConfiguration firstStartConfiguration, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(firstStartConfiguration.ConnectionString)) { FirstStartConfig.ConnectionString = Config.GetConnectionString(ConstStrings.SqlServerConnection); FirstStartConfig.Database = "SqlServer"; } string settingsFileLocation = Path.Combine(Env.ContentRootPath, "appsettings.json"); if (!System.IO.File.Exists(settingsFileLocation)) { FileStream fileStream = System.IO.File.Create(settingsFileLocation); byte[] bytes = ASCIIEncoding.ASCII.GetBytes("{}"); await fileStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken); fileStream.Close(); await fileStream.DisposeAsync(); } string fileContents = await System.IO.File.ReadAllTextAsync(settingsFileLocation, cancellationToken); JObject jsonFile = JsonConvert.DeserializeObject<JObject>(fileContents); jsonFile[ConstStrings.IsFirstStart] = false; jsonFile[ConstStrings.InitializeFakeData] = firstStartConfiguration.InitializeFakeData; jsonFile[ConstStrings.AdminUserName] = firstStartConfiguration.AdminUserName; jsonFile[ConstStrings.AdminEmail] = firstStartConfiguration.AdminEmail; jsonFile[ConstStrings.AdminPassword] = firstStartConfiguration.AdminPassword; jsonFile[ConstStrings.DataProvider] = firstStartConfiguration.Database; jsonFile["ConnectionStrings"][$"{firstStartConfiguration.Database}Connection"] = firstStartConfiguration.ConnectionString; await System.IO.File.WriteAllTextAsync(settingsFileLocation, JsonConvert.SerializeObject(jsonFile, Formatting.Indented), cancellationToken); }
public async Task <MakeOrderResponseModel> Handle(MakeOrderRequestModel request, CancellationToken cancellationToken) { var result = new MakeOrderResponseModel { IsSuccess = true, OrderId = Guid.NewGuid() }; //business logic here return(result); }
/// <summary> /// Check if a recipient address is in the global suppressions group. /// </summary> /// <param name="email">email address to check</param> /// <param name="onBehalfOf">The user to impersonate</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if the email address is in the global suppression group; otherwise, <c>false</c>. /// </returns> public async Task <bool> IsUnsubscribedAsync(string email, string onBehalfOf = null, CancellationToken cancellationToken = default(CancellationToken)) { var responseContent = await _client .GetAsync($"{_endpoint}/{email}") .OnBehalfOf(onBehalfOf) .WithCancellationToken(cancellationToken) .AsString(null) .ConfigureAwait(false); // If the email address is on the global suppression list, the response will look like this: // { // "recipient_email": "{email}" // } // If the email address is not on the global suppression list, the response will be empty // // Therefore, we check for the presence of the 'recipient_email' to indicate if the email // address is on the global suppression list or not. var dynamicObject = JObject.Parse(responseContent); var propertyDictionary = (IDictionary <string, JToken>)dynamicObject; return(propertyDictionary.ContainsKey("recipient_email")); }
public Task <IPercolateResponse> PercolateAsync <T>(IPercolateRequest <T> request, CancellationToken cancellationToken = default(CancellationToken)) where T : class => this.Dispatcher.DispatchAsync <IPercolateRequest <T>, PercolateRequestParameters, PercolateResponse, IPercolateResponse>( request, cancellationToken, this.LowLevelDispatch.PercolateDispatchAsync <PercolateResponse> );
public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan textSpan, bool includeSuppressionFixes, CancellationToken cancellationToken) { var result = await _inner.GetFixesAsync(document, textSpan, includeSuppressionFixes, cancellationToken).ConfigureAwait(false); return result.Select(x => new CodeFixCollection(x)).ToImmutableArray(); }
public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan textSpan, bool considerSuppressionFixes, CancellationToken cancellationToken) { var result = await _inner.GetFirstDiagnosticWithFixAsync(document, textSpan, considerSuppressionFixes, cancellationToken).ConfigureAwait(false); return new FirstDiagnosticResult(result); }
public static ControlMainThreadAwaitable SwitchToMainThreadAsync(this Control control, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { #pragma warning disable VSTHRD004 // Await SwitchToMainThreadAsync return new ControlMainThreadAwaitable(ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken), disposable: null); #pragma warning restore VSTHRD004 // Await SwitchToMainThreadAsync } if (control.IsDisposed) { #pragma warning disable VSTHRD004 // Await SwitchToMainThreadAsync return new ControlMainThreadAwaitable(ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(_preCancelledToken), disposable: null); #pragma warning restore VSTHRD004 // Await SwitchToMainThreadAsync } var disposedCancellationToken = ControlIsDisposedCancellationFactory.Instance.GetOrCreateCancellationToken(control); CancellationTokenSource? cancellationTokenSource = null; if (cancellationToken.CanBeCanceled) { cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(disposedCancellationToken, cancellationToken); disposedCancellationToken = cancellationTokenSource.Token; } #pragma warning disable VSTHRD004 // Await SwitchToMainThreadAsync var mainThreadAwaiter = ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(disposedCancellationToken); #pragma warning restore VSTHRD004 // Await SwitchToMainThreadAsync return new ControlMainThreadAwaitable(mainThreadAwaiter, cancellationTokenSource); }
public Task StopAsync(CancellationToken cancellationToken) { _startup?.Stop(); TinyFoxService.Stop(); return(Task.CompletedTask); }
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) { return _getDocumentDiagnosticsAsync(document, _diagnosticIds, cancellationToken); }
private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(document); var solution = document.Project.Solution; var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null)); return await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false); }
private async Task Loop(CancellationToken cancellationToken) { var teams = new Teams { Blue = ImmutableList.Create(MatchTesting.TestVenonatForOverlay), Red = ImmutableList.Create(MatchTesting.TestVenonatForOverlay), }; await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken); await ResetBalances(); //ensure everyone has money to bet before the betting period const int matchId = -1; // TODO IBettingShop<User> bettingShop = new DefaultBettingShop<User>( async user => await _pokeyenBank.GetAvailableMoney(user)); bettingShop.BetPlaced += (_, args) => TaskToVoidSafely(_logger, () => _overlayConnection.Send(new MatchPokeyenBetUpdateEvent { MatchId = matchId, DefaultAction = "", NewBet = new Bet { Amount = args.Amount, Team = args.Side, BetBonus = 0 }, NewBetUser = args.User, Odds = bettingShop.GetOdds() }, cancellationToken)); _bettingPeriod = new BettingPeriod<User>(_pokeyenBank, bettingShop); _bettingPeriod.Start(); IMatchCycle match = new CoinflipMatchCycle(_loggerFactory.CreateLogger<CoinflipMatchCycle>()); Task setupTask = match.SetUp(new MatchInfo(teams.Blue, teams.Red), cancellationToken); await _overlayConnection.Send(new MatchCreatedEvent(), cancellationToken); await _overlayConnection.Send(new MatchBettingEvent(), cancellationToken); await _overlayConnection.Send(new MatchModesChosenEvent(), cancellationToken); // TODO await _overlayConnection.Send(new MatchSettingUpEvent { MatchId = 1234, Teams = teams, BettingDuration = _matchmodeConfig.DefaultBettingDuration.TotalSeconds, RevealDuration = 0, Gimmick = "speed", Switching = SwitchingPolicy.Never, BattleStyle = BattleStyle.Singles, InputOptions = new InputOptions { Moves = new MovesInputOptions { Policy = MoveSelectingPolicy.Always, Permitted = ImmutableList.Create("a", "b", "c", "d") }, Switches = new SwitchesInputOptions { Policy = SwitchingPolicy.Never, Permitted = ImmutableList<string>.Empty, RandomChance = 0 }, Targets = new TargetsInputOptions { Policy = TargetingPolicy.Disabled, Permitted = ImmutableList<string>.Empty, AllyHitChance = 0 }, }, BetBonus = 35, BetBonusType = "bet", }, cancellationToken); Duration bettingBeforeWarning = _matchmodeConfig.DefaultBettingDuration - _matchmodeConfig.WarningDuration; await Task.Delay(bettingBeforeWarning.ToTimeSpan(), cancellationToken); await _overlayConnection.Send(new MatchWarningEvent(), cancellationToken); await Task.Delay(_matchmodeConfig.WarningDuration.ToTimeSpan(), cancellationToken); await setupTask; _bettingPeriod.Close(); Task<MatchResult> performTask = match.Perform(cancellationToken); await _overlayConnection.Send(new MatchPerformingEvent { Teams = teams }, cancellationToken); MatchResult result = await performTask; await _overlayConnection.Send(new MatchOverEvent { MatchResult = result }, cancellationToken); // TODO log matches Dictionary<User, long> changes = await _bettingPeriod.Resolve(matchId, result, cancellationToken); await _overlayConnection.Send( new MatchResultsEvent { PokeyenResults = new PokeyenResults { Transactions = changes.ToImmutableDictionary(kvp => kvp.Key.Id, kvp => new Transaction { Change = kvp.Value, NewBalance = kvp.Key.Pokeyen }) } }, cancellationToken); await Task.Delay(_matchmodeConfig.ResultDuration.ToTimeSpan(), cancellationToken); await _overlayConnection.Send(new ResultsFinishedEvent(), cancellationToken); }
private async Task <Document> InsertAwaitKeyword(Document document, InvocationExpressionSyntax declaration, CancellationToken cancellationToken) { // Get comments (comments and stuff) var firstToken = declaration.GetFirstToken(); var leadingTrivia = firstToken.LeadingTrivia; // Remove comments var newDeclaration = declaration.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty)); // Create 'await' expression before the problem AwaitExpressionSyntax awaiter = SyntaxFactory.AwaitExpression(newDeclaration); // Replace the node with the new node - and insert trivia on the new node var rootNode = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = rootNode.ReplaceNode(declaration, awaiter.WithLeadingTrivia(leadingTrivia)); return(document.WithSyntaxRoot(newRoot)); }
private async Task AppendFixesAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics, IList<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap); var projectFixersMap = GetProjectFixers(document.Project); var hasAnyProjectFixer = projectFixersMap.Any(); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return; } var allFixers = new List<CodeFixProvider>(); // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive bool isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive; // ReSharper disable once PossibleMultipleEnumeration foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); ImmutableArray<CodeFixProvider> workspaceFixers; if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers)) { if (isInteractive) { allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider)); } else { allFixers.AddRange(workspaceFixers); } } List<CodeFixProvider> projectFixers; if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers)) { Debug.Assert(!isInteractive); allFixers.AddRange(projectFixers); } } var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); foreach (var fixer in allFixers.Distinct()) { cancellationToken.ThrowIfCancellationRequested(); await AppendFixesOrSuppressionsAsync( // ReSharper disable once PossibleMultipleEnumeration document, span, diagnostics, result, fixer, hasFix: d => GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id), getFixes: dxs => GetCodeFixesAsync(document, span, fixer, dxs, cancellationToken), cancellationToken: cancellationToken).ConfigureAwait(false); } }
public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken) { if (document == null || !document.IsOpen()) { return default; } using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject()) { var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics.Object) { cancellationToken.ThrowIfCancellationRequested(); if (!range.IntersectsWith(diagnostic.TextSpan)) { continue; } // REVIEW: 2 possible designs. // 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or // 2. kick off a task that finds all fixes for the given range here but return once we find the first one. // at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes. // // first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then // I will try the second approach which will be more complex but quicker var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false); if (hasFix) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic); } } return new FirstDiagnosticResult(!fullResult, false, default); } }
internal StreamCopyOperation(Stream source, Stream destination, long?bytesRemaining, byte[] buffer, CancellationToken cancel) { Contract.Assert(source != null); Contract.Assert(destination != null); Contract.Assert(!bytesRemaining.HasValue || bytesRemaining.Value >= 0); Contract.Assert(buffer != null); _source = source; _destination = destination; _bytesRemaining = bytesRemaining; _cancel = cancel; _buffer = buffer; _tcs = new TaskCompletionSource <object>(); _readCallback = new AsyncCallback(ReadCallback); _writeCallback = new AsyncCallback(WriteCallback); }
private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(project); if (includeAllDocumentDiagnostics) { // Get all diagnostics for the entire project, including document diagnostics. var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); } else { // Get all no-location diagnostics for the project, doesn't include document diagnostics. var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null)); return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); } }
public async Task GenerateReport(IReportServiceContext reportServiceContext, ZipArchive archive, bool isFis, CancellationToken cancellationToken) { Task <IMessage> ilrFileTask = _ilrProviderService.GetIlrFile(reportServiceContext, cancellationToken); Task <FM81Global> fm81Task = _fm81TrailBlazerProviderService.GetFM81Data(reportServiceContext, cancellationToken); Task <List <string> > validLearnersTask = _validLearnersService.GetLearnersAsync(reportServiceContext, cancellationToken); await Task.WhenAll(ilrFileTask, fm81Task, validLearnersTask); if (cancellationToken.IsCancellationRequested) { return; } List <ILearner> learners = ilrFileTask.Result?.Learners?.Where(x => validLearnersTask.Result.Contains(x.LearnRefNumber)).ToList(); if (learners == null) { _logger.LogWarning("Failed to get learners for Trailblazer Employer Incentives Report"); return; } var fm81Data = fm81Task.Result; var trailblazerEmployerIncentivesModels = new List <TrailblazerEmployerIncentivesModel>(); var fm81EmployerIdentifierList = fm81Data?.Learners?.Select(l => l.LearningDeliveries?.Select(x => string.Join(",", x.LearningDeliveryValues.EmpIdSmallBusDate, x.LearningDeliveryValues.EmpIdFirstYoungAppDate, x.LearningDeliveryValues.EmpIdSecondYoungAppDate, x.LearningDeliveryValues.EmpIdAchDate))).FirstOrDefault(); if (fm81EmployerIdentifierList != null) { var fm81EmployerIdentifierUniqueList = fm81EmployerIdentifierList.First().Split(',').ToArray() .Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList(); foreach (string empIdentifier in fm81EmployerIdentifierUniqueList) { var learnerFm81Data = fm81Data?.Learners?.SelectMany(x => x.LearningDeliveries).ToList(); trailblazerEmployerIncentivesModels.Add( _trailblazerEmployerIncentivesModelBuilder.BuildTrailblazerEmployerIncentivesModel( Convert.ToInt32(empIdentifier), null, learnerFm81Data)); } } trailblazerEmployerIncentivesModels.Sort(new TrailblazerEmployerIncentivesModelComparer()); var csv = GetReportCsv(trailblazerEmployerIncentivesModels); var jobId = reportServiceContext.JobId; var ukPrn = reportServiceContext.Ukprn.ToString(); var externalFileName = GetExternalFilename(ukPrn, jobId, reportServiceContext.SubmissionDateTimeUtc); var fileName = GetFilename(ukPrn, jobId, reportServiceContext.SubmissionDateTimeUtc); await _streamableKeyValuePersistenceService.SaveAsync($"{externalFileName}.csv", csv, cancellationToken); await WriteZipEntry(archive, $"{fileName}.csv", csv); }
public async Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information // (if it is up-to-date) or synchronously do the work at the spot. // // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed. // sometimes way more than it is needed. (compilation) Dictionary<TextSpan, List<DiagnosticData>>? aggregatedDiagnostics = null; foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken: cancellationToken).ConfigureAwait(false)) { if (diagnostic.IsSuppressed) { continue; } cancellationToken.ThrowIfCancellationRequested(); aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>(); aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic); } if (aggregatedDiagnostics == null) { return ImmutableArray<CodeFixCollection>.Empty; } var result = new List<CodeFixCollection>(); foreach (var spanAndDiagnostic in aggregatedDiagnostics) { await AppendFixesAsync( document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } if (result.Count > 0) { // sort the result to the order defined by the fixers var priorityMap = _fixerPriorityMap[document.Project.Language].Value; result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1); } // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive if (document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeSuppressionFixes) { foreach (var spanAndDiagnostic in aggregatedDiagnostics) { await AppendSuppressionsAsync( document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } } return result.ToImmutableArray(); }