protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, string channelId, CancellationToken cancellationToken) { var urlHash = info.Url.GetMD5().ToString("N"); var prefix = ChannelIdPrefix + urlHash; if (!channelId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { return null; } var channels = await GetChannels(info, true, cancellationToken).ConfigureAwait(false); var m3uchannels = channels.Cast<M3UChannel>(); var channel = m3uchannels.FirstOrDefault(c => string.Equals(c.Id, channelId, StringComparison.OrdinalIgnoreCase)); if (channel != null) { var path = channel.Path; MediaProtocol protocol = MediaProtocol.File; if (path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { protocol = MediaProtocol.Http; } else if (path.StartsWith("rtmp", StringComparison.OrdinalIgnoreCase)) { protocol = MediaProtocol.Rtmp; } else if (path.StartsWith("rtsp", StringComparison.OrdinalIgnoreCase)) { protocol = MediaProtocol.Rtsp; } var mediaSource = new MediaSourceInfo { Path = channel.Path, Protocol = protocol, MediaStreams = new List<MediaStream> { new MediaStream { Type = MediaStreamType.Video, // Set the index to -1 because we don't know the exact index of the video stream within the container Index = -1, IsInterlaced = true }, new MediaStream { Type = MediaStreamType.Audio, // Set the index to -1 because we don't know the exact index of the audio stream within the container Index = -1 } }, RequiresOpening = false, RequiresClosing = false, ReadAtNativeFramerate = true }; return new List<MediaSourceInfo> { mediaSource }; } return new List<MediaSourceInfo>(); }
internal async Task RemoveAllRenameAnnotationsAsync(IEnumerable<DocumentId> documentWithRenameAnnotations, AnnotationTable<RenameAnnotation> annotationSet, CancellationToken cancellationToken) { foreach (var documentId in documentWithRenameAnnotations) { if (_renamedSpansTracker.IsDocumentChanged(documentId)) { var document = _newSolution.GetDocument(documentId); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // For the computeReplacementToken and computeReplacementNode functions, use // the "updated" node to maintain any annotation removals from descendants. var newRoot = root.ReplaceSyntax( nodes: annotationSet.GetAnnotatedNodes(root), computeReplacementNode: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()), tokens: annotationSet.GetAnnotatedTokens(root), computeReplacementToken: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()), trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), computeReplacementTrivia: null); _intermediateSolutionContainingOnlyModifiedDocuments = _intermediateSolutionContainingOnlyModifiedDocuments.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity); } } _newSolution = _intermediateSolutionContainingOnlyModifiedDocuments; }
public async Task<bool> PeekAsync(CancellationToken cancellationToken) { //If we already have a byte read but not consumed, do nothing. if (_hasPeekByte) { return true; } //If transport closed we can't peek. if (!IsOpen) { return false; } //Try to read one byte. If succeeds we will need to store it for the next read. try { var bytes = await ReadAsync(_peekBuffer, 0, 1, cancellationToken); if (bytes == 0) { return false; } } catch (IOException) { return false; } _hasPeekByte = true; return true; }
public async Task Start(CancellationToken token) { while (!token.IsCancellationRequested) { Settings.Default.Reload(); var imageInfo = GetLatestImageInfo(); if (imageInfo != null) { var image = AssembleImageFrom(imageInfo); var imageFile = SaveImage(image); Wallpaper.Set(imageFile, Wallpaper.Style.Fit); } if (Settings.Default.Interval > 0) { _internalTokenSource = new CancellationTokenSource(); using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_internalTokenSource.Token, token)) { try { await Task.Delay(TimeSpan.FromMinutes(Settings.Default.Interval), linkedCts.Token); } catch { // ignore exception raised by token cancellation } } } } }
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken) { var users = _userManager.Users .DistinctBy(ChannelDownloadScheduledTask.GetUserDistinctValue) .Select(i => i.Id.ToString("N")) .ToList(); var numComplete = 0; foreach (var user in users) { double percentPerUser = 1; percentPerUser /= users.Count; var startingPercent = numComplete * percentPerUser * 100; var innerProgress = new ActionableProgress<double>(); innerProgress.RegisterAction(p => progress.Report(startingPercent + (percentPerUser * p))); await DownloadContent(user, cancellationToken, innerProgress).ConfigureAwait(false); numComplete++; double percent = numComplete; percent /= users.Count; progress.Report(percent * 100); } progress.Report(100); }
private async Task VerifyFixInternalAsync(string language, ImmutableArray<DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex, bool allowNewCompilerDiagnostics, int maxNumberOfIterations, Func<ImmutableArray<DiagnosticAnalyzer>, CodeFixProvider, int?, CancellationToken, Document, int, Task<Document>> getFixedDocument, CancellationToken cancellationToken) { var document = this.CreateDocument(oldSource, language); var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false); document = await getFixedDocument(analyzers, codeFixProvider, codeFixIndex, cancellationToken, document, maxNumberOfIterations).ConfigureAwait(false); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false)); // check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false)); string message = string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)).ToFullString()); Assert.True(false, message); } // after applying all of the code fixes, compare the resulting string to the inputted one var actual = await GetStringFromDocumentAsync(document, cancellationToken).ConfigureAwait(false); Assert.Equal(newSource, actual); }
public override Task ExecuteBindingAsync(Controllers.HttpActionContext actionContext, CancellationToken cancellationToken) { return _traceWriter.TraceBeginEndAsync( actionContext.ControllerContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info, _innerBinding.GetType().Name, ExecuteBindingAsyncMethodName, beginTrace: null, execute: () => _innerBinding.ExecuteBindingAsync(actionContext, cancellationToken), endTrace: (tr) => { if (!actionContext.ModelState.IsValid) { tr.Message = Error.Format(SRResources.TraceModelStateInvalidMessage, FormattingUtilities.ModelStateToString( actionContext.ModelState)); } else { if (actionContext.ActionDescriptor.GetParameters().Count > 0) { tr.Message = Error.Format(SRResources.TraceValidModelState, FormattingUtilities.ActionArgumentsToString( actionContext.ActionArguments)); } } }, errorTrace: null); }
private static async Task<Document> MakeMock(Document document, SyntaxNode invokationSyntax, CancellationToken cancellationToken) { var testSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel); var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray(); var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields); var memberAccessExpressions = invokationSyntax.DescendantNodes() .OfType<ExpressionSyntax>() .Where(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax) .Select(expr => { var memberAccess = expr as MemberAccessExpressionSyntax; var invokationExpression = expr as InvocationExpressionSyntax; var expression = invokationExpression == null ? memberAccess : invokationExpression.Expression; return expression; }); var invokedMethodsOfMocks = memberAccessExpressions.SelectMany(expressionSyntax => MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts)) .DistinctBy(x => string.Join(",", x.FieldsToSetup.SelectMany(y => y.Field.Select(z => z))) + "," + x.MethodOrPropertySymbol) .ToArray(); if (invokedMethodsOfMocks.Length == 0) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); ChangesMaker.ApplyChanges(invokationSyntax, editor, invokedMethodsOfMocks); return editor.GetChangedDocument(); }
public override async Task OnAuthorizationAsync( HttpActionContext actionContext, CancellationToken cancellationToken ) { if ( actionContext.ControllerContext.ControllerDescriptor.ControllerType == typeof( UserController ) || string.Equals( actionContext.ActionDescriptor.ActionName, "Test", StringComparison.OrdinalIgnoreCase ) ) return; var request = actionContext.Request; string loginToken = null; if ( loginToken == null ) { var authorization = request.Headers.Authorization; if ( authorization != null && authorization.Scheme == "Hello" ) loginToken = authorization.Parameter; } if ( loginToken == null ) { var cookie = request.Headers.GetCookies( "loginToken" ).SelectMany( c => c.Cookies ); if ( cookie.Any() ) loginToken = cookie.First().Value; } var userId = Host.UserService.GetUserID( loginToken ); if ( userId == null ) actionContext.Response = request.CreateErrorResponse( HttpStatusCode.Unauthorized, "Unauthorized" ); else actionContext.Request.Properties["UserID"] = userId; }
private static bool IsExtensionMethodParameterContext(CSharpSyntaxContext context, CancellationToken cancellationToken) { // TODO(cyrusn): lambda/anon methods can have out/ref parameters if (!context.SyntaxTree.IsParameterModifierContext(context.Position, context.LeftToken, cancellationToken, allowableIndex: 0)) { return false; } var token = context.LeftToken; var method = token.GetAncestor<MethodDeclarationSyntax>(); var typeDecl = method.GetAncestorOrThis<TypeDeclarationSyntax>(); if (method == null || typeDecl == null) { return false; } if (typeDecl.Kind() != SyntaxKind.ClassDeclaration) { return false; } if (!method.Modifiers.Any(t => t.Kind() == SyntaxKind.StaticKeyword)) { return false; } if (!typeDecl.Modifiers.Any(t => t.Kind() == SyntaxKind.StaticKeyword)) { return false; } return true; }
public async Task<IEnumerable<CodeAction>> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindNode(textSpan); var switchStatementNode = node as SwitchStatementSyntax; if (switchStatementNode == null) return null; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var memberEx = switchStatementNode.Expression as MemberAccessExpressionSyntax; if (memberEx == null) return null; var symbolInfo = semanticModel.GetTypeInfo(memberEx.Name); var enumTypeInfo = symbolInfo.Type; if (enumTypeInfo.TypeKind != TypeKind.Enum) return null; var enumName = enumTypeInfo.Name; var nameSpace = enumTypeInfo.ContainingNamespace.Name; var enumType = Type.GetType(nameSpace + "." + enumName); if (enumType == null) return null; return new[] { CodeAction.Create("Explode Switch", c => ExplodeSwitch(document, root, semanticModel, switchStatementNode, c)) }; }
//probe==StartBounder public bool GeneratePasswords(int[] probe, int[] startBoundary, int[] endBoundary, int depth, int range, CancellationToken ct, CancellationTokenSource tokenSource, Action<string> sendPassword) { bool result = false; char[] probeChar = CharForThread(probe, _options); string probeString = String.Join("", probeChar); if (depth==0) { Console.WriteLine(probeString); if (VerifyMd5Hash(probeString)) { Password = probeString; sendPassword(Password); return true; } return false; } if (ct.IsCancellationRequested) { Console.WriteLine("Task is canceled"); } if (probe.SequenceEqual(endBoundary)) return false; for (int i = 0; i < range; i++) { probe[depth - 1] = i; result = GeneratePasswords(probe, startBoundary, endBoundary, depth - 1, range, ct, tokenSource, sendPassword); if (result) break; } return result; }
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsInstanceExpressionOrStatement(context) || IsExtensionMethodParameterContext(context, cancellationToken) || IsConstructorInitializerContext(context); }
protected override bool TryInitializeState( Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken, out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType) { var baseClassNode = node as TypeSyntax; if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax && baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode) { if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration)) { abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol; cancellationToken.ThrowIfCancellationRequested(); if (abstractClassType.IsAbstractClass()) { var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax; classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol; return classType != null && abstractClassType != null; } } } classType = null; abstractClassType = null; return false; }
public async Task<Token> TokenAsync(string code, CancellationToken cancellationToken = default(CancellationToken)) { var token = await _requestExecuter.Execute<Token>(() => _requestGenerator.AccessToken(_options.ClientId, _options.ClientSecret, _options.RedirectUri, code), cancellationToken: cancellationToken).ConfigureAwait(false); _options.AccessToken = token.access_token; return token; }
public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken) { if (TvdbSeriesProvider.IsValidSeries(item.ProviderIds)) { var language = item.GetPreferredMetadataLanguage(); var seriesDataPath = await TvdbSeriesProvider.Current.EnsureSeriesInfo(item.ProviderIds, language, cancellationToken).ConfigureAwait(false); var path = Path.Combine(seriesDataPath, "banners.xml"); try { var seriesOffset = TvdbSeriesProvider.GetSeriesOffset(item.ProviderIds); if (seriesOffset != null && seriesOffset.Value != 0) return TvdbSeasonImageProvider.GetImages(path, language, seriesOffset.Value + 1, cancellationToken); return GetImages(path, language, cancellationToken); } catch (FileNotFoundException) { // No tvdb data yet. Don't blow up } catch (DirectoryNotFoundException) { // No tvdb data yet. Don't blow up } } return new RemoteImageInfo[] { }; }
public override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { if (symbol.TypeKind != TypeKind.Enum) { return; } var flagsAttribute = WellKnownTypes.FlagsAttribute(compilation); if (flagsAttribute == null) { return; } var zeroValuedFields = GetZeroValuedFields(symbol).ToImmutableArray(); bool hasFlagsAttribute = symbol.GetAttributes().Any(a => a.AttributeClass == flagsAttribute); if (hasFlagsAttribute) { CheckFlags(symbol, zeroValuedFields, addDiagnostic); } else { CheckNonFlags(symbol, zeroValuedFields, addDiagnostic); } }
private async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Create an editor to do all the transformations. This allows us to fix all // the diagnostics in a clean manner. If we used the normal batch fix provider // then it might fail to apply all the individual text changes as many of the // changes produced by the diff might end up overlapping others. var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var options = document.Project.Solution.Workspace.Options; // Attempt to use an out-var declaration if that's the style the user prefers. // Note: if using 'var' would cause a problem, we will use the actual type // of hte local. This is necessary in some cases (for example, when the // type of the out-var-decl affects overload resolution or generic instantiation). var useVarWhenDeclaringLocals = options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals); var useImplicitTypeForIntrinsicTypes = options.GetOption(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes).Value; foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); await AddEditsAsync(document, editor, diagnostic, useVarWhenDeclaringLocals, useImplicitTypeForIntrinsicTypes, cancellationToken).ConfigureAwait(false); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); }
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext || context.IsNonAttributeExpressionContext; }
public static async Task<RemoteHostClient> CreateAsync( Workspace workspace, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.ServiceHubRemoteHostClient_CreateAsync, cancellationToken)) { var primary = new HubClient("ManagedLanguage.IDE.RemoteHostClient"); var remoteHostStream = await primary.RequestServiceAsync(WellKnownRemoteHostServices.RemoteHostService, cancellationToken).ConfigureAwait(false); var instance = new ServiceHubRemoteHostClient(workspace, primary, remoteHostStream); // make sure connection is done right var current = $"VS ({Process.GetCurrentProcess().Id})"; var host = await instance._rpc.InvokeAsync<string>(WellKnownRemoteHostServices.RemoteHostService_Connect, current).ConfigureAwait(false); // TODO: change this to non fatal watson and make VS to use inproc implementation Contract.ThrowIfFalse(host == current.ToString()); instance.Connected(); // Create a workspace host to hear about workspace changes. We'll // remote those changes over to the remote side when they happen. RegisterWorkspaceHost(workspace, instance); // return instance return instance; } }
public void Execute(CancellationToken cancellationToken) { using (var connection = _context.Storage.GetConnection()) using (var fetchedJob = connection.FetchNextJob(_context.Queues, cancellationToken)) { try { ProcessJob(fetchedJob.JobId, connection, _context.PerformanceProcess, cancellationToken); // Checkpoint #4. The job was performed, and it is in the one // of the explicit states (Succeeded, Scheduled and so on). // It should not be re-queued, but we still need to remove its // processing information. fetchedJob.RemoveFromQueue(); // Success point. No things must be done after previous command // was succeeded. } catch (JobAbortedException) { fetchedJob.RemoveFromQueue(); } catch (Exception) { fetchedJob.Requeue(); throw; } } }
/// <summary> /// <para>Generates the authorize URI as an asynchronous operation.</para> /// <para>Then call <see cref="CoreTweet.OAuth.GetTokensAsync"/> after get the pin code.</para> /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> /// <param name="oauthCallback"> /// <para>For OAuth 1.0a compliance this parameter is required.</para> /// <para>The value you specify here will be used as the URL a user is redirected to should they approve your application's access to their account.</para> /// <para>Set this to oob for out-of-band pin mode.</para> /// <para>This is also how you specify custom callbacks for use in desktop/mobile applications.</para> /// <para>Always send an oauth_callback on this step, regardless of a pre-registered callback.</para> /// </param> /// <param name="options">The connection options for the request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <para>The task object representing the asynchronous operation.</para> /// <para>The Result property on the task object returns the authorize URI.</para> /// </returns> public static Task<OAuthSession> AuthorizeAsync(string consumerKey, string consumerSecret, string oauthCallback = "oob", ConnectionOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { var reqUrl = GetRequestTokenUrl(options); var prm = new Dictionary<string, object>(); if(!string.IsNullOrEmpty(oauthCallback)) prm.Add("oauth_callback", oauthCallback); var header = Tokens.Create(consumerKey, consumerSecret, null, null) .CreateAuthorizationHeader(MethodType.Get, reqUrl, prm); return Request.HttpGetAsync(reqUrl, prm, header, options, cancellationToken) .ResponseCallback(cancellationToken) .ContinueWith( t => InternalUtils.ReadResponse(t, s => { var dic = s.Split('&') .Where(z => z.Contains("=")) .Select(z => z.Split('=')) .ToDictionary(z => z[0], z => z[1]); return new OAuthSession() { RequestToken = dic["oauth_token"], RequestTokenSecret = dic["oauth_token_secret"], ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, ConnectionOptions = options }; }, cancellationToken), cancellationToken ).Unwrap(); }
/// <inheritdoc/> public async Task<Uri> UploadMessageAsync(Stream content, DateTime expirationUtc, string contentType, string contentEncoding, IProgress<int> bytesCopiedProgress, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(content, "content"); Requires.Range(expirationUtc > DateTime.UtcNow, "expirationUtc"); string blobName = Utilities.CreateRandomWebSafeName(DesktopUtilities.BlobNameLength); if (expirationUtc < DateTime.MaxValue) { DateTime roundedUp = expirationUtc - expirationUtc.TimeOfDay + TimeSpan.FromDays(1); blobName = roundedUp.ToString("yyyy.MM.dd") + "/" + blobName; } var blob = this.container.GetBlockBlobReference(blobName); // Set metadata with the precise expiration time, although for efficiency we also put the blob into a directory // for efficient deletion based on approximate expiration date. if (expirationUtc < DateTime.MaxValue) { blob.Metadata["DeleteAfter"] = expirationUtc.ToString(CultureInfo.InvariantCulture); } blob.Properties.ContentType = contentType; blob.Properties.ContentEncoding = contentEncoding; await blob.UploadFromStreamAsync(content.ReadStreamWithProgress(bytesCopiedProgress), cancellationToken); return blob.Uri; }
public static async Task<FidoU2FHidMessage> ReadFidoU2FHidMessageAsync([NotNull] this IHidDevice device, CancellationToken cancellationToken) { if (device == null) throw new ArgumentNullException(nameof(device)); var initReport = await device.GetInputReportAsync(cancellationToken); var init = InitializationPacket.ReadFrom(initReport.Data); var dataSizeReceived = init.Data.Count; var continuations = new List<ContinuationPacket>(); byte index = 0; while (dataSizeReceived < init.PayloadLength) { var continuationReport = await device.GetInputReportAsync(cancellationToken); var continuation = ContinuationPacket.ReadFrom(continuationReport.Data, init.PayloadLength - dataSizeReceived); if (continuation.PaketSequence != index) { throw new InvalidSequenceNumberException(continuationReport.Data, $"The sequence number isn't the expected one, expected {index} but read {continuation.PaketSequence}"); } continuations.Add(continuation); dataSizeReceived += continuation.Data.Count; index += 1; } return BuildMessage(init, continuations); }
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsNonAttributeExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || context.IsGenericTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string identifier = GetUserIdentifier(request); if (String.IsNullOrEmpty(identifier)) return CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client."); string cacheKey = GetCacheKey(identifier); long requestCount = 0; using (IRedisClient client = _clientsManager.GetClient()) { requestCount = client.IncrementValueBy(cacheKey, 1); if (requestCount == 1) client.ExpireEntryIn(cacheKey, _period); } Task<HttpResponseMessage> response = null; long maxRequests = _maxRequestsForUserIdentifier(identifier); if (requestCount > maxRequests) response = CreateResponse(request, HttpStatusCode.Conflict, _message); else response = base.SendAsync(request, cancellationToken); return response.ContinueWith(task => { long remaining = maxRequests - requestCount; if (remaining < 0) remaining = 0; HttpResponseMessage httpResponse = task.Result; httpResponse.Headers.Add("RateLimit-Limit", maxRequests.ToString()); httpResponse.Headers.Add("RateLimit-Remaining", remaining.ToString()); return httpResponse; }); }
public async Task<BuildResponse> GetResponseAsync(BuildRequest req, CancellationToken cancellationToken) { NamedPipeClientStream pipeStream; if (TryAutoConnectToServer(cancellationToken, out pipeStream)) { // We have a good connection BuildResponse response = await DoCompilationAsync(pipeStream, req, cancellationToken).ConfigureAwait(false); if (response != null) { return response; } else { CompilerServerLogger.Log("Compilation failed, constructing new compiler server"); // The compilation failed. There are a couple possible reasons for this, // including that we are using a 32-bit compiler server and we are out of // memory. This is the last attempt -- we will create a new server manually // and try to compile. There is no mutex because anyone else using // this server is accidental only. int newProcessId = CreateNewServerProcess(); if (newProcessId != 0 && TryConnectToProcess(newProcessId, TimeOutMsNewProcess, cancellationToken, out pipeStream)) { return await DoCompilationAsync(pipeStream, req, cancellationToken).ConfigureAwait(false); } } } return null; }
/// <summary> /// 模拟登录 /// </summary> /// <param name="passport"></param> /// <param name="password"></param> /// <param name="cancelToken"></param> /// <returns></returns> public async Task<OAuthAccessToken> LoginAsync(string passport, string password, CancellationToken cancelToken) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; }; var request = WebRequest.Create(Settings.AuthorizeUrl) as HttpWebRequest; request.Referer = GetAuthorizeUrl(); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = new CookieContainer(); var postBody = GetSimulateLoginPostBody(passport, password); var postData = System.Text.Encoding.UTF8.GetBytes(postBody); cancelToken.ThrowIfCancellationRequested(); var result = ""; using (var requestStream = await request.GetRequestStreamAsync()) { await requestStream.WriteAsync(postData, 0, postData.Length, cancelToken); } using (var response = await request.GetResponseAsync()) { using (var sr = new System.IO.StreamReader(response.GetResponseStream())) { cancelToken.ThrowIfCancellationRequested(); result = await sr.ReadToEndAsync(); return ConvertToAccessTokenByRegex(result); } } }
public Task Run(IProgress<double> progress, CancellationToken cancellationToken) { var items = _libraryManager.RootFolder.RecursiveChildren.ToList(); var boxsets = items.OfType<BoxSet>().ToList(); var numComplete = 0; foreach (var boxset in boxsets) { foreach (var child in boxset.Children.Concat(boxset.GetLinkedChildren()).OfType<ISupportsBoxSetGrouping>()) { var boxsetIdList = child.BoxSetIdList.ToList(); if (!boxsetIdList.Contains(boxset.Id)) { boxsetIdList.Add(boxset.Id); } child.BoxSetIdList = boxsetIdList; } numComplete++; double percent = numComplete; percent /= boxsets.Count; progress.Report(percent * 100); } progress.Report(100); return Task.FromResult(true); }
public static CodeGenerationUnit FromCodeGenerationUnitSyntax(CodeGenerationUnitSyntax syntax, CancellationToken cancellationToken) { if (syntax == null) { throw new ArgumentNullException(nameof(syntax)); } var builder = new CodeGenerationUnitBuilder(); builder.Process(syntax, cancellationToken); var model=new CodeGenerationUnit( syntax, builder._codeUsings, builder._taskDeclarations, builder._taskDefinitions, builder._includes, builder._symbols, builder._diagnostics.ToUnique()); foreach(var taskDefinition in builder._taskDefinitions) { taskDefinition.FinalConstruct(model); } foreach (var taskDeclaration in builder._taskDeclarations.Where(td=>!td.IsIncluded)) { taskDeclaration.FinalConstruct(model); } return model; }