Пример #1
1
        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;
            });
        }
Пример #2
1
        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);
        }
		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;
		}
Пример #4
1
        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 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)) };
		}
Пример #6
1
 protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
 {
     return
         IsInstanceExpressionOrStatement(context) ||
         IsExtensionMethodParameterContext(context, cancellationToken) ||
         IsConstructorInitializerContext(context);
 }
Пример #7
1
        /// <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<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;
            }
        }
 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);
 }
Пример #10
1
        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);
 }
Пример #12
1
        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;
        }
Пример #13
1
        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);
        }
Пример #14
1
        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>();
        }
Пример #15
1
    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;
    }
Пример #16
1
 /// <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();
 }
Пример #17
1
        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;
                }
            }
        }
        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);
        }
Пример #19
1
        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();
        }
Пример #20
1
        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;
        }
 protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
 {
     return
         context.IsStatementContext ||
         context.IsGlobalStatementContext ||
         context.IsNonAttributeExpressionContext;
 }
        //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;
        }
Пример #23
1
        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);
            }
        }
Пример #24
1
        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;
        }
Пример #25
1
        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 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;
        }
Пример #28
0
        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);
        }
Пример #29
0
        /// <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);
                }
            }
        }
Пример #30
0
        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;
        }
Пример #31
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutLifecyclePolicy operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutLifecyclePolicy operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/PutLifecyclePolicy">REST API Reference for PutLifecyclePolicy Operation</seealso>
        public virtual Task <PutLifecyclePolicyResponse> PutLifecyclePolicyAsync(PutLifecyclePolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new PutLifecyclePolicyRequestMarshaller();
            var unmarshaller = PutLifecyclePolicyResponseUnmarshaller.Instance;

            return(InvokeAsync <PutLifecyclePolicyRequest, PutLifecyclePolicyResponse>(request, marshaller,
                                                                                       unmarshaller, cancellationToken));
        }
Пример #32
0
        /// <summary>
        /// Initiates the asynchronous execution of the StartLifecyclePolicyPreview operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the StartLifecyclePolicyPreview operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/StartLifecyclePolicyPreview">REST API Reference for StartLifecyclePolicyPreview Operation</seealso>
        public virtual Task <StartLifecyclePolicyPreviewResponse> StartLifecyclePolicyPreviewAsync(StartLifecyclePolicyPreviewRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new StartLifecyclePolicyPreviewRequestMarshaller();
            var unmarshaller = StartLifecyclePolicyPreviewResponseUnmarshaller.Instance;

            return(InvokeAsync <StartLifecyclePolicyPreviewRequest, StartLifecyclePolicyPreviewResponse>(request, marshaller,
                                                                                                         unmarshaller, cancellationToken));
        }
Пример #33
0
        /// <summary>
        /// Sends a command to an Amazon QLDB ledger.
        ///
        ///  <note>
        /// <para>
        /// Instead of interacting directly with this API, we recommend that you use the Amazon
        /// QLDB Driver or the QLDB Shell to execute data transactions on a ledger.
        /// </para>
        ///  <ul> <li>
        /// <para>
        /// If you are working with an AWS SDK, use the QLDB Driver. The driver provides a high-level
        /// abstraction layer above this <code>qldbsession</code> data plane and manages <code>SendCommand</code>
        /// API calls for you. For information and a list of supported programming languages,
        /// see <a href="https://docs.aws.amazon.com/qldb/latest/developerguide/getting-started-driver.html">Getting
        /// started with the driver</a> in the <i>Amazon QLDB Developer Guide</i>.
        /// </para>
        ///  </li> <li>
        /// <para>
        /// If you are working with the AWS Command Line Interface (AWS CLI), use the QLDB Shell.
        /// The shell is a command line interface that uses the QLDB Driver to interact with a
        /// ledger. For information, see <a href="https://docs.aws.amazon.com/qldb/latest/developerguide/data-shell.html">Accessing
        /// Amazon QLDB using the QLDB Shell</a>.
        /// </para>
        ///  </li> </ul> </note>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the SendCommand service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the SendCommand service method, as returned by QLDBSession.</returns>
        /// <exception cref="Amazon.QLDBSession.Model.BadRequestException">
        /// Returned if the request is malformed or contains an error such as an invalid parameter
        /// value or a missing required parameter.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.InvalidSessionException">
        /// Returned if the session doesn't exist anymore because it timed out or expired.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.LimitExceededException">
        /// Returned if a resource limit such as number of active sessions is exceeded.
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.OccConflictException">
        /// Returned when a transaction cannot be written to the journal due to a failure in the
        /// verification phase of <i>optimistic concurrency control</i> (OCC).
        /// </exception>
        /// <exception cref="Amazon.QLDBSession.Model.RateExceededException">
        /// Returned when the rate of requests exceeds the allowed throughput.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/qldb-session-2019-07-11/SendCommand">REST API Reference for SendCommand Operation</seealso>
        public virtual Task <SendCommandResponse> SendCommandAsync(SendCommandRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SendCommandRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SendCommandResponseUnmarshaller.Instance;

            return(InvokeAsync <SendCommandResponse>(request, options, cancellationToken));
        }
        /// <summary>
        /// Returns the projected utilization metrics of Amazon EC2 instance recommendations.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetEC2RecommendationProjectedMetrics service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the GetEC2RecommendationProjectedMetrics service method, as returned by ComputeOptimizer.</returns>
        /// <exception cref="Amazon.ComputeOptimizer.Model.AccessDeniedException">
        /// You do not have sufficient access to perform this action.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.InternalServerException">
        /// An internal error has occurred. Try your call again.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.InvalidParameterValueException">
        /// An invalid or out-of-range value was supplied for the input parameter.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.MissingAuthenticationTokenException">
        /// The request must contain either a valid (registered) AWS access key ID or X.509 certificate.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.OptInRequiredException">
        /// The account is not opted in to AWS Compute Optimizer.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.ResourceNotFoundException">
        /// A resource that is required for the action doesn't exist.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.ServiceUnavailableException">
        /// The request has failed due to a temporary failure of the server.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.ThrottlingException">
        /// The request was denied due to request throttling.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/compute-optimizer-2019-11-01/GetEC2RecommendationProjectedMetrics">REST API Reference for GetEC2RecommendationProjectedMetrics Operation</seealso>
        public virtual Task <GetEC2RecommendationProjectedMetricsResponse> GetEC2RecommendationProjectedMetricsAsync(GetEC2RecommendationProjectedMetricsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = GetEC2RecommendationProjectedMetricsRequestMarshaller.Instance;
            options.ResponseUnmarshaller = GetEC2RecommendationProjectedMetricsResponseUnmarshaller.Instance;

            return(InvokeAsync <GetEC2RecommendationProjectedMetricsResponse>(request, options, cancellationToken));
        }
        /// <summary>
        /// Starts the asynchronous detection of text in a document. Amazon Textract can detect
        /// lines of text and the words that make up a line of text.
        ///
        ///
        /// <para>
        ///  <code>StartDocumentTextDetection</code> can analyze text in documents that are in
        /// JPEG, PNG, and PDF format. The documents are stored in an Amazon S3 bucket. Use <a>DocumentLocation</a>
        /// to specify the bucket name and file name of the document.
        /// </para>
        ///
        /// <para>
        ///  <code>StartTextDetection</code> returns a job identifier (<code>JobId</code>) that
        /// you use to get the results of the operation. When text detection is finished, Amazon
        /// Textract publishes a completion status to the Amazon Simple Notification Service (Amazon
        /// SNS) topic that you specify in <code>NotificationChannel</code>. To get the results
        /// of the text detection operation, first check that the status value published to the
        /// Amazon SNS topic is <code>SUCCEEDED</code>. If so, call <a>GetDocumentTextDetection</a>,
        /// and pass the job identifier (<code>JobId</code>) from the initial call to <code>StartDocumentTextDetection</code>.
        /// </para>
        ///
        /// <para>
        /// For more information, see <a href="https://docs.aws.amazon.com/textract/latest/dg/how-it-works-detecting.html">Document
        /// Text Detection</a>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the StartDocumentTextDetection service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the StartDocumentTextDetection service method, as returned by Textract.</returns>
        /// <exception cref="Amazon.Textract.Model.AccessDeniedException">
        /// You aren't authorized to perform the action.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.BadDocumentException">
        /// Amazon Textract isn't able to read the document.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.DocumentTooLargeException">
        /// The document can't be processed because it's too large. The maximum document size
        /// for synchronous operations 5 MB. The maximum document size for asynchronous operations
        /// is 500 MB for PDF files.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.IdempotentParameterMismatchException">
        /// A <code>ClientRequestToken</code> input parameter was reused with an operation, but
        /// at least one of the other input parameters is different from the previous call to
        /// the operation.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.InternalServerErrorException">
        /// Amazon Textract experienced a service issue. Try your call again.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.InvalidParameterException">
        /// An input parameter violated a constraint. For example, in synchronous operations,
        /// an <code>InvalidParameterException</code> exception occurs when neither of the <code>S3Object</code>
        /// or <code>Bytes</code> values are supplied in the <code>Document</code> request parameter.
        /// Validate your parameter before calling the API operation again.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.InvalidS3ObjectException">
        /// Amazon Textract is unable to access the S3 object that's specified in the request.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.LimitExceededException">
        /// An Amazon Textract service limit was exceeded. For example, if you start too many
        /// asynchronous jobs concurrently, calls to start operations (<code>StartDocumentTextDetection</code>,
        /// for example) raise a LimitExceededException exception (HTTP status code: 400) until
        /// the number of concurrently running jobs is below the Amazon Textract service limit.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.ProvisionedThroughputExceededException">
        /// The number of requests exceeded your throughput limit. If you want to increase this
        /// limit, contact Amazon Textract.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.ThrottlingException">
        /// Amazon Textract is temporarily unable to process the request. Try your call again.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.UnsupportedDocumentException">
        /// The format of the input document isn't supported. Documents for synchronous operations
        /// can be in PNG or JPEG format. Documents for asynchronous operations can also be in
        /// PDF format.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/textract-2018-06-27/StartDocumentTextDetection">REST API Reference for StartDocumentTextDetection Operation</seealso>
        public virtual Task <StartDocumentTextDetectionResponse> StartDocumentTextDetectionAsync(StartDocumentTextDetectionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = StartDocumentTextDetectionRequestMarshaller.Instance;
            options.ResponseUnmarshaller = StartDocumentTextDetectionResponseUnmarshaller.Instance;

            return(InvokeAsync <StartDocumentTextDetectionResponse>(request, options, cancellationToken));
        }
Пример #36
0
 private async Task <DialogTurnResult> PromptForQuestion(WaterfallStepContext stepContext, System.Threading.CancellationToken cancellationToken)
 {
     return(await stepContext.PromptAsync(
                FAQPROMPT,
                new PromptOptions
     {
         Prompt = MessageFactory.Text("聞きたいことを記入してください。"),
     },
                cancellationToken : cancellationToken).ConfigureAwait(false));
 }
        /// <summary>
        /// After you deploy a model into production using Amazon SageMaker hosting services,
        /// your client applications use this API to get inferences from the model hosted at the
        /// specified endpoint.
        ///
        ///
        /// <para>
        /// For an overview of Amazon SageMaker, see <a href="http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works.html">How
        /// It Works</a>.
        /// </para>
        ///
        /// <para>
        /// Amazon SageMaker strips all POST headers except those supported by the API. Amazon
        /// SageMaker might add additional headers. You should not rely on the behavior of headers
        /// outside those enumerated in the request syntax.
        /// </para>
        ///
        /// <para>
        /// Cals to <code>InvokeEndpoint</code> are authenticated by using AWS Signature Version
        /// 4. For information, see <a href="http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html">Authenticating
        /// Requests (AWS Signature Version 4)</a> in the <i>Amazon S3 API Reference</i>.
        /// </para>
        ///  <note>
        /// <para>
        /// Endpoints are scoped to an individual account, and are not public. The URL does not
        /// contain the account ID, but Amazon SageMaker determines the account ID from the authentication
        /// token that is supplied by the caller.
        /// </para>
        ///  </note>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the InvokeEndpoint service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the InvokeEndpoint service method, as returned by SageMakerRuntime.</returns>
        /// <exception cref="Amazon.SageMakerRuntime.Model.InternalFailureException">
        /// An internal failure occurred.
        /// </exception>
        /// <exception cref="Amazon.SageMakerRuntime.Model.ModelErrorException">
        /// Model (owned by the customer in the container) returned an error 500.
        /// </exception>
        /// <exception cref="Amazon.SageMakerRuntime.Model.ServiceUnavailableException">
        /// The service is unavailable. Try your call again.
        /// </exception>
        /// <exception cref="Amazon.SageMakerRuntime.Model.ValidationErrorException">
        /// Inspect your request and try again.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/runtime.sagemaker-2017-05-13/InvokeEndpoint">REST API Reference for InvokeEndpoint Operation</seealso>
        public virtual Task <InvokeEndpointResponse> InvokeEndpointAsync(InvokeEndpointRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = InvokeEndpointRequestMarshaller.Instance;
            options.ResponseUnmarshaller = InvokeEndpointResponseUnmarshaller.Instance;

            return(InvokeAsync <InvokeEndpointResponse>(request, options, cancellationToken));
        }
Пример #38
0
        /// <summary>
        /// Initiates the asynchronous execution of the CreateTags operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateTags operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/CreateTags">REST API Reference for CreateTags Operation</seealso>
        public virtual Task <CreateTagsResponse> CreateTagsAsync(CreateTagsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new CreateTagsRequestMarshaller();
            var unmarshaller = CreateTagsResponseUnmarshaller.Instance;

            return(InvokeAsync <CreateTagsRequest, CreateTagsResponse>(request, marshaller,
                                                                       unmarshaller, cancellationToken));
        }
Пример #39
0
        /// <summary>
        /// Describes the specified WorkSpaces.
        ///
        ///
        /// <para>
        /// You can filter the results using bundle ID, directory ID, or owner, but you can specify
        /// only one filter at a time.
        /// </para>
        /// </summary>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the DescribeWorkspaces service method, as returned by WorkSpaces.</returns>
        /// <exception cref="Amazon.WorkSpaces.Model.InvalidParameterValuesException">
        /// One or more parameter values are not valid.
        /// </exception>
        /// <exception cref="Amazon.WorkSpaces.Model.ResourceUnavailableException">
        /// The specified resource is not available.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/DescribeWorkspaces">REST API Reference for DescribeWorkspaces Operation</seealso>
        public virtual Task <DescribeWorkspacesResponse> DescribeWorkspacesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var request = new DescribeWorkspacesRequest();

            return(DescribeWorkspacesAsync(request, cancellationToken));
        }
Пример #40
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeWorkspacesConnectionStatus operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeWorkspacesConnectionStatus operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/DescribeWorkspacesConnectionStatus">REST API Reference for DescribeWorkspacesConnectionStatus Operation</seealso>
        public virtual Task <DescribeWorkspacesConnectionStatusResponse> DescribeWorkspacesConnectionStatusAsync(DescribeWorkspacesConnectionStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new DescribeWorkspacesConnectionStatusRequestMarshaller();
            var unmarshaller = DescribeWorkspacesConnectionStatusResponseUnmarshaller.Instance;

            return(InvokeAsync <DescribeWorkspacesConnectionStatusRequest, DescribeWorkspacesConnectionStatusResponse>(request, marshaller,
                                                                                                                       unmarshaller, cancellationToken));
        }
Пример #41
0
        /// <summary>
        /// Initiates the asynchronous execution of the ModifyWorkspaceProperties operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the ModifyWorkspaceProperties operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/ModifyWorkspaceProperties">REST API Reference for ModifyWorkspaceProperties Operation</seealso>
        public virtual Task <ModifyWorkspacePropertiesResponse> ModifyWorkspacePropertiesAsync(ModifyWorkspacePropertiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new ModifyWorkspacePropertiesRequestMarshaller();
            var unmarshaller = ModifyWorkspacePropertiesResponseUnmarshaller.Instance;

            return(InvokeAsync <ModifyWorkspacePropertiesRequest, ModifyWorkspacePropertiesResponse>(request, marshaller,
                                                                                                     unmarshaller, cancellationToken));
        }
Пример #42
0
        /// <summary>
        /// Initiates the asynchronous execution of the RebuildWorkspaces operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the RebuildWorkspaces operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/RebuildWorkspaces">REST API Reference for RebuildWorkspaces Operation</seealso>
        public virtual Task <RebuildWorkspacesResponse> RebuildWorkspacesAsync(RebuildWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new RebuildWorkspacesRequestMarshaller();
            var unmarshaller = RebuildWorkspacesResponseUnmarshaller.Instance;

            return(InvokeAsync <RebuildWorkspacesRequest, RebuildWorkspacesResponse>(request, marshaller,
                                                                                     unmarshaller, cancellationToken));
        }
Пример #43
0
        /// <summary>
        /// Initiates the asynchronous execution of the ListImages operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the ListImages operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/ListImages">REST API Reference for ListImages Operation</seealso>
        public virtual Task <ListImagesResponse> ListImagesAsync(ListImagesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new ListImagesRequestMarshaller();
            var unmarshaller = ListImagesResponseUnmarshaller.Instance;

            return(InvokeAsync <ListImagesRequest, ListImagesResponse>(request, marshaller,
                                                                       unmarshaller, cancellationToken));
        }
        /// <summary>
        /// Describes information over a provided set of accelerators belonging to an account.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the DescribeAccelerators service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the DescribeAccelerators service method, as returned by ElasticInference.</returns>
        /// <exception cref="Amazon.ElasticInference.Model.BadRequestException">
        /// Raised when a malformed input has been provided to the API.
        /// </exception>
        /// <exception cref="Amazon.ElasticInference.Model.InternalServerException">
        /// Raised when an unexpected error occurred during request processing.
        /// </exception>
        /// <exception cref="Amazon.ElasticInference.Model.ResourceNotFoundException">
        /// Raised when the requested resource cannot be found.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/elastic-inference-2017-07-25/DescribeAccelerators">REST API Reference for DescribeAccelerators Operation</seealso>
        public virtual Task <DescribeAcceleratorsResponse> DescribeAcceleratorsAsync(DescribeAcceleratorsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = DescribeAcceleratorsRequestMarshaller.Instance;
            options.ResponseUnmarshaller = DescribeAcceleratorsResponseUnmarshaller.Instance;

            return(InvokeAsync <DescribeAcceleratorsResponse>(request, options, cancellationToken));
        }
Пример #45
0
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateSubscriber operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UpdateSubscriber operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public virtual Task <UpdateSubscriberResponse> UpdateSubscriberAsync(UpdateSubscriberRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = UpdateSubscriberRequestMarshaller.Instance;
            options.ResponseUnmarshaller = UpdateSubscriberResponseUnmarshaller.Instance;

            return(InvokeAsync <UpdateSubscriberResponse>(request, options, cancellationToken));
        }
Пример #46
0
        /// <summary>
        /// Initiates the asynchronous execution of the CreateNotification operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateNotification operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public virtual Task <CreateNotificationResponse> CreateNotificationAsync(CreateNotificationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = CreateNotificationRequestMarshaller.Instance;
            options.ResponseUnmarshaller = CreateNotificationResponseUnmarshaller.Instance;

            return(InvokeAsync <CreateNotificationResponse>(request, options, cancellationToken));
        }
        /// <summary>
        /// Updates the state, variable values, and timer settings of one or more detectors (instances)
        /// of a specified detector model.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the BatchUpdateDetector service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the BatchUpdateDetector service method, as returned by IoTEventsData.</returns>
        /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException">
        /// An internal failure occured.
        /// </exception>
        /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException">
        /// The request was invalid.
        /// </exception>
        /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException">
        /// The service is currently unavailable.
        /// </exception>
        /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException">
        /// The request could not be completed due to throttling.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/BatchUpdateDetector">REST API Reference for BatchUpdateDetector Operation</seealso>
        public virtual Task <BatchUpdateDetectorResponse> BatchUpdateDetectorAsync(BatchUpdateDetectorRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = BatchUpdateDetectorRequestMarshaller.Instance;
            options.ResponseUnmarshaller = BatchUpdateDetectorResponseUnmarshaller.Instance;

            return(InvokeAsync <BatchUpdateDetectorResponse>(request, options, cancellationToken));
        }
Пример #48
0
 public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory <byte> buffer, System.Threading.CancellationToken cancellationToken = default)
 {
     throw null;
 }
Пример #49
0
        /// <summary>
        /// Acquire license units
        /// </summary>
        /// <remarks>
        /// Client Credentials Flow required permissions: Administration or
        /// Administration.Write.
        ///
        /// Requires authentication.
        /// </remarks>
        /// <param name='dto'>
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <LicenseResult> > AcquireWithHttpMessagesAsync(ConsumptionLicenseDto dto, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (dto == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "dto");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("dto", dto);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Acquire", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Licensing/Acquire").ToString();
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (dto != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(dto, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 409 && (int)_statusCode != 503)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <LicenseResult>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <LicenseResult>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Пример #50
0
 public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken)
 {
     throw null;
 }
        /// <summary>
        /// Gets the results for an Amazon Textract asynchronous operation that analyzes text
        /// in a document.
        ///
        ///
        /// <para>
        /// You start asynchronous text analysis by calling <a>StartDocumentAnalysis</a>, which
        /// returns a job identifier (<code>JobId</code>). When the text analysis operation finishes,
        /// Amazon Textract publishes a completion status to the Amazon Simple Notification Service
        /// (Amazon SNS) topic that's registered in the initial call to <code>StartDocumentAnalysis</code>.
        /// To get the results of the text-detection operation, first check that the status value
        /// published to the Amazon SNS topic is <code>SUCCEEDED</code>. If so, call <code>GetDocumentAnalysis</code>,
        /// and pass the job identifier (<code>JobId</code>) from the initial call to <code>StartDocumentAnalysis</code>.
        /// </para>
        ///
        /// <para>
        ///  <code>GetDocumentAnalysis</code> returns an array of <a>Block</a> objects. The following
        /// types of information are returned:
        /// </para>
        ///  <ul> <li>
        /// <para>
        /// Form data (key-value pairs). The related information is returned in two <a>Block</a>
        /// objects, each of type <code>KEY_VALUE_SET</code>: a KEY <code>Block</code> object
        /// and a VALUE <code>Block</code> object. For example, <i>Name: Ana Silva Carolina</i>
        /// contains a key and value. <i>Name:</i> is the key. <i>Ana Silva Carolina</i> is the
        /// value.
        /// </para>
        ///  </li> <li>
        /// <para>
        /// Table and table cell data. A TABLE <code>Block</code> object contains information
        /// about a detected table. A CELL <code>Block</code> object is returned for each cell
        /// in a table.
        /// </para>
        ///  </li> <li>
        /// <para>
        /// Lines and words of text. A LINE <code>Block</code> object contains one or more WORD
        /// <code>Block</code> objects. All lines and words that are detected in the document
        /// are returned (including text that doesn't have a relationship with the value of the
        /// <code>StartDocumentAnalysis</code> <code>FeatureTypes</code> input parameter).
        /// </para>
        ///  </li> </ul>
        /// <para>
        /// Selection elements such as check boxes and option buttons (radio buttons) can be detected
        /// in form data and in tables. A SELECTION_ELEMENT <code>Block</code> object contains
        /// information about a selection element, including the selection status.
        /// </para>
        ///
        /// <para>
        /// Use the <code>MaxResults</code> parameter to limit the number of blocks that are returned.
        /// If there are more results than specified in <code>MaxResults</code>, the value of
        /// <code>NextToken</code> in the operation response contains a pagination token for getting
        /// the next set of results. To get the next page of results, call <code>GetDocumentAnalysis</code>,
        /// and populate the <code>NextToken</code> request parameter with the token value that's
        /// returned from the previous call to <code>GetDocumentAnalysis</code>.
        /// </para>
        ///
        /// <para>
        /// For more information, see <a href="https://docs.aws.amazon.com/textract/latest/dg/how-it-works-analyzing.html">Document
        /// Text Analysis</a>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the GetDocumentAnalysis service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the GetDocumentAnalysis service method, as returned by Textract.</returns>
        /// <exception cref="Amazon.Textract.Model.AccessDeniedException">
        /// You aren't authorized to perform the action.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.InternalServerErrorException">
        /// Amazon Textract experienced a service issue. Try your call again.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.InvalidJobIdException">
        /// An invalid job identifier was passed to <a>GetDocumentAnalysis</a> or to <a>GetDocumentAnalysis</a>.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.InvalidParameterException">
        /// An input parameter violated a constraint. For example, in synchronous operations,
        /// an <code>InvalidParameterException</code> exception occurs when neither of the <code>S3Object</code>
        /// or <code>Bytes</code> values are supplied in the <code>Document</code> request parameter.
        /// Validate your parameter before calling the API operation again.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.ProvisionedThroughputExceededException">
        /// The number of requests exceeded your throughput limit. If you want to increase this
        /// limit, contact Amazon Textract.
        /// </exception>
        /// <exception cref="Amazon.Textract.Model.ThrottlingException">
        /// Amazon Textract is temporarily unable to process the request. Try your call again.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/textract-2018-06-27/GetDocumentAnalysis">REST API Reference for GetDocumentAnalysis Operation</seealso>
        public virtual Task <GetDocumentAnalysisResponse> GetDocumentAnalysisAsync(GetDocumentAnalysisRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = GetDocumentAnalysisRequestMarshaller.Instance;
            options.ResponseUnmarshaller = GetDocumentAnalysisResponseUnmarshaller.Instance;

            return(InvokeAsync <GetDocumentAnalysisResponse>(request, options, cancellationToken));
        }
Пример #52
0
 public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken)
 {
     throw null;
 }
        /// <summary>
        /// Exports optimization recommendations for Amazon EC2 instances.
        ///
        ///
        /// <para>
        /// Recommendations are exported in a comma-separated values (.csv) file, and its metadata
        /// in a JavaScript Object Notation (.json) file, to an existing Amazon Simple Storage
        /// Service (Amazon S3) bucket that you specify. For more information, see <a href="https://docs.aws.amazon.com/compute-optimizer/latest/ug/exporting-recommendations.html">Exporting
        /// Recommendations</a> in the <i>Compute Optimizer User Guide</i>.
        /// </para>
        ///
        /// <para>
        /// You can have only one Amazon EC2 instance export job in progress per AWS Region.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the ExportEC2InstanceRecommendations service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the ExportEC2InstanceRecommendations service method, as returned by ComputeOptimizer.</returns>
        /// <exception cref="Amazon.ComputeOptimizer.Model.AccessDeniedException">
        /// You do not have sufficient access to perform this action.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.InternalServerException">
        /// An internal error has occurred. Try your call again.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.InvalidParameterValueException">
        /// An invalid or out-of-range value was supplied for the input parameter.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.LimitExceededException">
        /// The request exceeds a limit of the service.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.MissingAuthenticationTokenException">
        /// The request must contain either a valid (registered) AWS access key ID or X.509 certificate.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.OptInRequiredException">
        /// The account is not opted in to AWS Compute Optimizer.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.ServiceUnavailableException">
        /// The request has failed due to a temporary failure of the server.
        /// </exception>
        /// <exception cref="Amazon.ComputeOptimizer.Model.ThrottlingException">
        /// The request was denied due to request throttling.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/compute-optimizer-2019-11-01/ExportEC2InstanceRecommendations">REST API Reference for ExportEC2InstanceRecommendations Operation</seealso>
        public virtual Task <ExportEC2InstanceRecommendationsResponse> ExportEC2InstanceRecommendationsAsync(ExportEC2InstanceRecommendationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = ExportEC2InstanceRecommendationsRequestMarshaller.Instance;
            options.ResponseUnmarshaller = ExportEC2InstanceRecommendationsResponseUnmarshaller.Instance;

            return(InvokeAsync <ExportEC2InstanceRecommendationsResponse>(request, options, cancellationToken));
        }
Пример #54
0
        /// <summary>
        /// Initiates the asynchronous execution of the RegisterScalableTarget operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the RegisterScalableTarget operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/RegisterScalableTarget">REST API Reference for RegisterScalableTarget Operation</seealso>
        public virtual Task <RegisterScalableTargetResponse> RegisterScalableTargetAsync(RegisterScalableTargetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = RegisterScalableTargetRequestMarshaller.Instance;
            var unmarshaller = RegisterScalableTargetResponseUnmarshaller.Instance;

            return(InvokeAsync <RegisterScalableTargetRequest, RegisterScalableTargetResponse>(request, marshaller,
                                                                                               unmarshaller, cancellationToken));
        }
Пример #55
0
        /// <summary>
        /// Initiates the asynchronous execution of the UploadLayerPart operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the UploadLayerPart operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/UploadLayerPart">REST API Reference for UploadLayerPart Operation</seealso>
        public virtual Task <UploadLayerPartResponse> UploadLayerPartAsync(UploadLayerPartRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new UploadLayerPartRequestMarshaller();
            var unmarshaller = UploadLayerPartResponseUnmarshaller.Instance;

            return(InvokeAsync <UploadLayerPartRequest, UploadLayerPartResponse>(request, marshaller,
                                                                                 unmarshaller, cancellationToken));
        }
Пример #56
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutScheduledAction operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutScheduledAction operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/PutScheduledAction">REST API Reference for PutScheduledAction Operation</seealso>
        public virtual Task <PutScheduledActionResponse> PutScheduledActionAsync(PutScheduledActionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = PutScheduledActionRequestMarshaller.Instance;
            var unmarshaller = PutScheduledActionResponseUnmarshaller.Instance;

            return(InvokeAsync <PutScheduledActionRequest, PutScheduledActionResponse>(request, marshaller,
                                                                                       unmarshaller, cancellationToken));
        }
Пример #57
0
        /// <summary>
        /// Initiates the asynchronous execution of the SetRepositoryPolicy operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the SetRepositoryPolicy operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/SetRepositoryPolicy">REST API Reference for SetRepositoryPolicy Operation</seealso>
        public virtual Task <SetRepositoryPolicyResponse> SetRepositoryPolicyAsync(SetRepositoryPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new SetRepositoryPolicyRequestMarshaller();
            var unmarshaller = SetRepositoryPolicyResponseUnmarshaller.Instance;

            return(InvokeAsync <SetRepositoryPolicyRequest, SetRepositoryPolicyResponse>(request, marshaller,
                                                                                         unmarshaller, cancellationToken));
        }
Пример #58
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeScheduledActions operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeScheduledActions operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/application-autoscaling-2016-02-06/DescribeScheduledActions">REST API Reference for DescribeScheduledActions Operation</seealso>
        public virtual Task <DescribeScheduledActionsResponse> DescribeScheduledActionsAsync(DescribeScheduledActionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = DescribeScheduledActionsRequestMarshaller.Instance;
            var unmarshaller = DescribeScheduledActionsResponseUnmarshaller.Instance;

            return(InvokeAsync <DescribeScheduledActionsRequest, DescribeScheduledActionsResponse>(request, marshaller,
                                                                                                   unmarshaller, cancellationToken));
        }
Пример #59
0
        /// <summary>
        /// Initiates the asynchronous execution of the InitiateLayerUpload operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the InitiateLayerUpload operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/InitiateLayerUpload">REST API Reference for InitiateLayerUpload Operation</seealso>
        public virtual Task <InitiateLayerUploadResponse> InitiateLayerUploadAsync(InitiateLayerUploadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new InitiateLayerUploadRequestMarshaller();
            var unmarshaller = InitiateLayerUploadResponseUnmarshaller.Instance;

            return(InvokeAsync <InitiateLayerUploadRequest, InitiateLayerUploadResponse>(request, marshaller,
                                                                                         unmarshaller, cancellationToken));
        }
Пример #60
0
        /// <summary>
        /// Initiates the asynchronous execution of the TerminateWorkspaces operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the TerminateWorkspaces operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/TerminateWorkspaces">REST API Reference for TerminateWorkspaces Operation</seealso>
        public virtual Task <TerminateWorkspacesResponse> TerminateWorkspacesAsync(TerminateWorkspacesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new TerminateWorkspacesRequestMarshaller();
            var unmarshaller = TerminateWorkspacesResponseUnmarshaller.Instance;

            return(InvokeAsync <TerminateWorkspacesRequest, TerminateWorkspacesResponse>(request, marshaller,
                                                                                         unmarshaller, cancellationToken));
        }