Ejemplo n.º 1
0
        internal static async Task <HttpContent> CreateIndividualRequest(IClientServiceRequest request)
        {
            HttpRequestMessage requestMessage = request.CreateRequest(false);
            string             requestContent = await CreateRequestContentString(requestMessage).ConfigureAwait(false);

            var content = new StringContent(requestContent);

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/http");
            return(content);
        }
Ejemplo n.º 2
0
        public override IRequest CreateRequest(IClientServiceRequest serviceRequest)
        {
            IRequest request = Request.CreateRequest(this, serviceRequest);

            if (!string.IsNullOrEmpty(base.ApiKey))
            {
                request = request.WithKey(base.ApiKey);
            }
            return(request.WithAuthentication(base.Authenticator));
        }
        //private List<BaseClientService> ServiceObjects = new List<BaseClientService>();

        public void Queue <TResponse>(IClientServiceRequest request, BatchRequest.OnResponse <TResponse> callback) where TResponse : class
        {
            SetCurrentBatchRequest(request);

            try
            {
                _currentBatchRequest.Queue(request, callback);
            }
            catch (InvalidOperationException ex)
            {
                throw;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Queues an individaul request
        /// </summary>
        /// <typeparam name="TResponse">The Response type</typeparam>
        /// <param name="request">The individual request </param>
        /// <param name="callback">A callback which will be called on request completion</param>
        public void Queue <TResponse>(IClientServiceRequest request, MultiRequest.OnResponse <TResponse> callback)
            where TResponse : class
        {
            _services.Add(request.Service);

            var innerRequest = new MultiRequest.InnerRequest <TResponse>
            {
                ClientRequest      = request,
                ResponseType       = typeof(TResponse),
                OnResponseCallback = callback
            };

            this._allRequests.Add(innerRequest);
        }
Ejemplo n.º 5
0
        /// <summary>Queues an individual request.</summary>
        /// <typeparam name="TResponse">The response's type.</typeparam>
        /// <param name="request">The individual request.</param>
        /// <param name="callback">A callback which will be called after a response was parsed.</param>
        public void Queue <TResponse>(IClientServiceRequest request, OnResponse <TResponse> callback)
            where TResponse : class
        {
            if (Count > QueueLimit)
            {
                throw new InvalidOperationException("A batch request cannot contain more than 1000 single requests");
            }

            allRequests.Add(new InnerRequest <TResponse>
            {
                ClientRequest      = request,
                ResponseType       = typeof(TResponse),
                OnResponseCallback = callback,
            });
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Given an API method, create the appropriate Request for it.
        /// </summary>
        public static IRequest CreateRequest(IClientService service, IClientServiceRequest request)
        {
            switch (request.HttpMethod)
            {
            case GET:
            case PUT:
            case POST:
            case DELETE:
            case PATCH:
                return(new Request {
                    Service = service, ServiceRequest = request, BaseURI = new Uri(service.BaseUri)
                });

            default:
                throw new NotSupportedException(
                          string.Format(
                              "The HttpMethod[{0}] of Method[{1}] in Service[{2}] was not supported", request.HttpMethod,
                              request.MethodName, service.Name));
            }
        }
        public void Queue <TResponse>(IClientServiceRequest request, BatchRequest.OnResponse <TResponse> callback) where TResponse : class
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            var currentBatch = _batches.Last();

            if (currentBatch.Count == BatchSizeLimit)
            {
                currentBatch = new BatchRequest(_service);
                _batches.Add(currentBatch);
            }

            currentBatch.Queue(request, callback);
        }
        public async static Task <Stream> ExecuteAsStreamWithRetryAsync <TResponse>(
            this IClientServiceRequest <TResponse> request,
            ExponentialBackOff backOff,
            CancellationToken cancellationToken)
        {
            int retries = 0;

            while (true)
            {
                try
                {
                    return(await request
                           .ExecuteAsStreamOrThrowAsync(cancellationToken)
                           .ConfigureAwait(false));;
                }
                catch (GoogleApiException e) when(e.Error != null && e.Error.Code == 429)
                {
                    // Too many requests.
                    if (retries < backOff.MaxNumOfRetries)
                    {
                        CommonTraceSources.Default.TraceWarning(
                            "Too many requests - backing of and retrying...", retries);

                        retries++;
                        await Task
                        .Delay(backOff.GetNextBackOff(retries))
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        // Retried too often already.
                        CommonTraceSources.Default.TraceWarning("Giving up after {0} retries", retries);
                        throw;
                    }
                }
            }
        }
 public RequestExecutionUnexpectedException(IClientServiceRequest request, Exception innerException) : base(GetDefaultMessage(), innerException)
 {
     this.Request = request;
 }
 public void Queue(IClientServiceRequest request)
 {
     Queue <object>(request, (content, error, index, message) => { });
 }
Ejemplo n.º 11
0
 public MethodValidator(IClientServiceRequest method, ParameterCollection parameters)
 {
     CurrentMethod = method;
     Parameters    = parameters;
 }
 public static async Task <TResponse> ExecuteWithRetryAsync <TResponse>(this IClientServiceRequest <TResponse> request)
 => await ExecuteWithRetryAsync(() => request.ExecuteAsync());
Ejemplo n.º 13
0
        private async Task searchAsync(IClientServiceRequest request, String searchInfo, bool isNextPage)
        {
            if (SearchTask != null && !SearchTask.IsCompleted)
            {
                try
                {
                    TokenSource.Cancel();
                    await SearchTask;
                }
                catch (OperationCanceledException)
                {

                }
                finally
                {
                    TokenSource = new CancellationTokenSource();
                }
            }

            try
            {
                SearchTask = search(request, searchInfo, isNextPage, TokenSource.Token);
                await SearchTask;
            }
            catch (OperationCanceledException)
            {

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Youtube Search Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 14
0
 public abstract IRequest CreateRequest(IClientServiceRequest request);
Ejemplo n.º 15
0
 public YoutubeSearchQuery(IClientServiceRequest request, String queryName = "")
 {
     Request = request;         
     QueryName = queryName;            
 }
Ejemplo n.º 16
0
        private async Task search(IClientServiceRequest request, String searchInfo, bool isNextPage, CancellationToken token)
        {
            SearchListResponse searchResponse = null;
            PlaylistItemListResponse playlistItemResponse = null;
            PlaylistListResponse playlistResponse = null;

            SearchResource.ListRequest searchRequest = request as SearchResource.ListRequest;
            PlaylistItemsResource.ListRequest playlistItemsRequest = request as PlaylistItemsResource.ListRequest;
            PlaylistsResource.ListRequest playlistRequest = request as PlaylistsResource.ListRequest;

            List<YoutubeItem> items = new List<YoutubeItem>();  
            int relevance;

            if (isNextPage)
            {
                if (NextPageToken == null)
                {
                    // Final page
                    return;
                }

                if (searchRequest != null)
                {
                    searchRequest.PageToken = NextPageToken;
                }
                else if (playlistItemsRequest != null) 
                {
                    playlistItemsRequest.PageToken = NextPageToken;
                }
                else if (playlistRequest != null)
                {
                    playlistRequest.PageToken = NextPageToken;
                }

                relevance = MediaState.UIMediaCollection.Count;
            }
            else
            {
                MediaState.clearUIState(searchInfo, DateTime.Now, MediaStateType.SearchResult);

                CurrentQuery = request;
                relevance = 0;
            }                       
          
            // Call the search.list method to retrieve results matching the specified query term.
            if (searchRequest != null)
            {
                searchResponse = await searchRequest.ExecuteAsync(token);

                NextPageToken = searchResponse.NextPageToken;
                
                foreach (SearchResult searchResult in searchResponse.Items)
                {
                    YoutubeItem newItem = null;

                    switch (searchResult.Id.Kind)
                    {
                        case "youtube#video":
                            newItem = new YoutubeVideoItem(searchResult, relevance);
                            break;

                        case "youtube#channel":
                            newItem = new YoutubeChannelItem(searchResult, relevance);
                            break;

                        case "youtube#playlist":
                            newItem = new YoutubePlaylistItem(searchResult, relevance);
                            break;
                        default:
                            break;
                    }

                    if (newItem == null || MediaState.UIMediaCollection.Contains(newItem)) continue;

                    items.Add(newItem);

                    relevance++;
                }
               
            }

            if (playlistItemsRequest != null)
            {
                playlistItemResponse = await playlistItemsRequest.ExecuteAsync(token);
                NextPageToken = playlistItemResponse.NextPageToken;

                foreach (PlaylistItem playlistItem in playlistItemResponse.Items)
                {
                    YoutubeVideoItem newItem = new YoutubeVideoItem(playlistItem, relevance);

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistRequest != null)
            {
                playlistResponse = await playlistRequest.ExecuteAsync(token);
                NextPageToken = playlistResponse.NextPageToken;

                foreach (Playlist playlist in playlistResponse.Items)
                {
                    YoutubePlaylistItem newItem = new YoutubePlaylistItem(playlist, relevance);

                    if (!items.Contains(newItem))
                    {
                        items.Add(newItem);
                    }

                    relevance++;
                }

            }
                                              
            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.                        
            MediaState.addUIState(items);
        }
Ejemplo n.º 17
0
        //EBVMInstanceStatus is the condition in here
        private int PerformActionOnInstances(
            Tuple <string, EBVMInstanceAction, EBVMInstanceStatus>[] _Operations,
            Action _OnCompleted,
            Action _OnFailure,
            Action <string> _ErrorMessageAction = null)
        {
            int ProgressStackIx = Interlocked.Increment(ref CurrentActionIndex);

            var ProgressStack = new Stack <object>();

            if (_Operations != null && _Operations.Length > 0)
            {
                lock (ProgressStacks_Lock)
                {
                    ProgressStacks.Add(ProgressStackIx, ProgressStack);
                }

                var Service = GetService(); //Will be disposed in async methods
                var Request = new BatchRequest(Service);

                foreach (var _Operation in _Operations)
                {
                    var FoundInstance = FindInstanceByUniqueName(_Operation.Item1, _ErrorMessageAction);
                    if (FoundInstance != null)
                    {
                        if (GetStatusFromString(FoundInstance.Status) == _Operation.Item3)
                        {
                            IClientServiceRequest RequestAction = null;
                            if (_Operation.Item2 == EBVMInstanceAction.Start)
                            {
                                RequestAction = Service.Instances.Start(ProjectID, ZoneName, FoundInstance.Name);
                            }
                            else if (_Operation.Item2 == EBVMInstanceAction.Stop)
                            {
                                RequestAction = Service.Instances.Stop(ProjectID, ZoneName, FoundInstance.Name);
                            }

                            if (RequestAction != null)
                            {
                                Request.Queue <Instance>(RequestAction,
                                                         (Content, Error, i, Message) =>
                                {
                                    lock (ProgressStacks_Lock)
                                    {
                                        if (ProgressStacks.TryGetValue(ProgressStackIx, out Stack <object> FoundStack) && FoundStack.Count > 0)
                                        {
                                            if (Error != null)
                                            {
                                                _ErrorMessageAction?.Invoke("BVMServiceGC->PerformActionOnInstances->Error: " + Error.Message);
                                                FoundStack.Clear();
                                                _OnFailure?.Invoke();
                                            }
                                            else
                                            {
                                                FoundStack.Pop();
                                                if (FoundStack.Count == 0)
                                                {
                                                    ProgressStacks.Remove(ProgressStackIx);
                                                    _OnCompleted?.Invoke();
                                                }
                                            }
                                        }
                                    }
                                });
                                ProgressStack.Push(new object());
                            }
                        }
                    }
                }
                if (ProgressStack.Count > 0)
                {
                    BTaskWrapper.Run(() =>
                    {
                        Thread.CurrentThread.IsBackground = true;

                        try
                        {
                            using (var CreatedTask = Request.ExecuteAsync())
                            {
                                CreatedTask.Wait();
                            }
                        }
                        catch (Exception e)
                        {
                            _ErrorMessageAction?.Invoke("BVMServiceGC->PerformActionOnInstances->Exception: " + e.Message);
                            _OnFailure?.Invoke();
                        }
                        Service?.Dispose();
                    });
                }
                else
                {
                    lock (ProgressStacks_Lock)
                    {
                        ProgressStacks.Remove(ProgressStackIx);
                    }
                    Service?.Dispose();
                }
            }
            return(ProgressStack.Count);
        }
Ejemplo n.º 18
0
        private async Task search(IClientServiceRequest request, String searchInfo, bool isNextPage, CancellationToken token)
        {
            SearchListResponse       searchResponse       = null;
            PlaylistItemListResponse playlistItemResponse = null;
            PlaylistListResponse     playlistResponse     = null;

            SearchResource.ListRequest        searchRequest        = request as SearchResource.ListRequest;
            PlaylistItemsResource.ListRequest playlistItemsRequest = request as PlaylistItemsResource.ListRequest;
            PlaylistsResource.ListRequest     playlistRequest      = request as PlaylistsResource.ListRequest;

            List <YoutubeItem> items = new List <YoutubeItem>();
            int relevance;

            if (isNextPage)
            {
                if (NextPageToken == null)
                {
                    // Final page
                    return;
                }

                if (searchRequest != null)
                {
                    searchRequest.PageToken = NextPageToken;
                }
                else if (playlistItemsRequest != null)
                {
                    playlistItemsRequest.PageToken = NextPageToken;
                }
                else if (playlistRequest != null)
                {
                    playlistRequest.PageToken = NextPageToken;
                }

                relevance = MediaState.UIMediaCollection.Count;
            }
            else
            {
                MediaState.clearUIState(searchInfo, DateTime.Now, MediaStateType.SearchResult);

                CurrentQuery = request;
                relevance    = 0;
            }

            // Call the search.list method to retrieve results matching the specified query term.
            if (searchRequest != null)
            {
                searchResponse = await searchRequest.ExecuteAsync(token);

                NextPageToken = searchResponse.NextPageToken;

                foreach (SearchResult searchResult in searchResponse.Items)
                {
                    YoutubeItem newItem = null;

                    switch (searchResult.Id.Kind)
                    {
                    case "youtube#video":
                        newItem = new YoutubeVideoItem(searchResult, relevance);
                        break;

                    case "youtube#channel":
                        newItem = new YoutubeChannelItem(searchResult, relevance);
                        break;

                    case "youtube#playlist":
                        newItem = new YoutubePlaylistItem(searchResult, relevance);
                        break;

                    default:
                        break;
                    }

                    if (newItem == null || MediaState.UIMediaCollection.Contains(newItem))
                    {
                        continue;
                    }

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistItemsRequest != null)
            {
                playlistItemResponse = await playlistItemsRequest.ExecuteAsync(token);

                NextPageToken = playlistItemResponse.NextPageToken;

                foreach (PlaylistItem playlistItem in playlistItemResponse.Items)
                {
                    YoutubeVideoItem newItem = new YoutubeVideoItem(playlistItem, relevance);

                    items.Add(newItem);

                    relevance++;
                }
            }

            if (playlistRequest != null)
            {
                playlistResponse = await playlistRequest.ExecuteAsync(token);

                NextPageToken = playlistResponse.NextPageToken;

                foreach (Playlist playlist in playlistResponse.Items)
                {
                    YoutubePlaylistItem newItem = new YoutubePlaylistItem(playlist, relevance);

                    if (!items.Contains(newItem))
                    {
                        items.Add(newItem);
                    }

                    relevance++;
                }
            }

            // Add each result to the appropriate list, and then display the lists of
            // matching videos, channels, and playlists.
            MediaState.addUIState(items);
        }
Ejemplo n.º 19
0
        public static async Task ExecuteAndAwaitOperationAsync(
            this IClientServiceRequest <Google.Apis.Compute.v1.Data.Operation> request,
            string projectId,
            CancellationToken token)
        {
            var operation = await request.ExecuteAsync(token).ConfigureAwait(false);

            while (true)
            {
                token.ThrowIfCancellationRequested();

                if (operation.Status == DoneStatus)
                {
                    if (operation.HttpErrorStatusCode >= 400)
                    {
                        // Operation failed. Translate error details into an
                        // exception.

                        var errors = operation.Error != null && operation.Error.Errors != null
                            ? operation.Error.Errors
                                     .Select(e => new SingleError()
                        {
                            Message  = e.Message,
                            Location = e.Location
                        })
                                     .ToList()
                            : NoErrors;

                        TraceSources.Common.TraceWarning("Operation failed: {0}", operation.HttpErrorMessage);

                        throw new GoogleApiException(
                                  "ComputeEngine",
                                  operation.HttpErrorMessage)
                              {
                                  Error = new RequestError()
                                  {
                                      Code    = operation.HttpErrorStatusCode ?? 0,
                                      Message = operation.HttpErrorMessage,
                                      Errors  = errors
                                  }
                              };
                    }
                    else
                    {
                        TraceSources.Common.TraceVerbose("Operation completed");
                        return;
                    }
                }

                await Task.Delay(200).ConfigureAwait(false);

                var pollRequest = new ZoneOperationsResource(request.Service).Get(
                    projectId,
                    ShortIdFromUrl(operation.Zone),
                    operation.Name);

                operation = await pollRequest
                            .ExecuteAsync(token)
                            .ConfigureAwait(false);
            }
        }
Ejemplo n.º 20
0
 public static async Task <TResponse> SafeExecuteAsync <TResponse>(IClientServiceRequest <TResponse> request)
 {
     return(await RequestsExecutor.SafeExecuteAsync <TResponse>(request, 0));
 }
Ejemplo n.º 21
0
 public static TResponse SafeExecuteSync <TResponse>(IClientServiceRequest <TResponse> request)
 {
     return(RequestsExecutor.SafeExecuteSync <TResponse>(request, 0));
 }
Ejemplo n.º 22
0
 public YoutubeSearchQuery(IClientServiceRequest request, String queryName = "")
 {
     Request   = request;
     QueryName = queryName;
 }
 protected RequestExecutionUnexpectedException(SerializationInfo info, StreamingContext context) : base(info, context)
 {
     this.Request = info.GetValue("Request", typeof(IClientServiceRequest)) as IClientServiceRequest;
 }