private static async Task<DocumentCollection> CreateDocumentCollection(DocumentClient client, Database database, string collectionId)
        {
            var collectionSpec = new DocumentCollection { Id = collectionId };
            var requestOptions = new RequestOptions { OfferType = "S1" };

            return await client.CreateDocumentCollectionAsync(database.SelfLink, collectionSpec, requestOptions);
        }
示例#2
0
        public Task<object> GetAsync(string uri, Type type, RequestOptions requestOptions)
        {
            if (requestOptions != null)
                requestOptions.ResourceLoader = this;

            return this.loader.GetAsync(uri, type, requestOptions);
        }
        public void ClaimCreationWithClaimParamsObjectTest()
        {
            ClaimParams input = JsonConvert.DeserializeObject<ClaimParams>(ClaimInput);
            RequestOptions options = new RequestOptions();
            options.IsTest = true;

            ClaimResponse actualResponse = claim.Create(input, options);
            ClaimSuccessCheck(actualResponse.JsonResponse());
        }
示例#4
0
 private void AssertRequestOptionCall(Action<IRequestOptions> options,
                                      Action<HttpRequestMessage> assertions,
                                      string uri = "http://whatever")
 {
     var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
     var requestOptions = new RequestOptions();
     options(requestOptions);
     requestOptions.ApplyRequestModifications(requestMessage);
     assertions(requestMessage);
 }
        /// <summary>
        /// Issues the web request asynchronous.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="method">The method.</param>
        /// <param name="input">The input.</param>
        /// <param name="options">request options</param>
        /// <returns></returns>
        public async Task<Response> IssueWebRequestAsync(
            string endpoint, string query, string method, Stream input, RequestOptions options)
        {
            options.Validate();
            Stopwatch watch = Stopwatch.StartNew();
            UriBuilder builder = new UriBuilder(
                _credentials.ClusterUri.Scheme,
                _credentials.ClusterUri.Host,
                options.Port,
                options.AlternativeEndpoint + endpoint);

            if (query != null)
            {
                builder.Query = query;
            }
            
            Debug.WriteLine("Issuing request {0} to endpoint {1}", Trace.CorrelationManager.ActivityId, builder.Uri);
            HttpWebRequest httpWebRequest = WebRequest.CreateHttp(builder.Uri);
            httpWebRequest.ServicePoint.ReceiveBufferSize = options.ReceiveBufferSize;
            httpWebRequest.ServicePoint.UseNagleAlgorithm = options.UseNagle;
            httpWebRequest.Timeout = options.TimeoutMillis;
            httpWebRequest.KeepAlive = options.KeepAlive;
            httpWebRequest.Credentials = _credentialCache;
            httpWebRequest.PreAuthenticate = true;
            httpWebRequest.Method = method;
            httpWebRequest.Accept = _contentType;
            httpWebRequest.ContentType = _contentType;
            // This allows 304 (NotModified) requests to catch
            //https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect(v=vs.110).aspx
            httpWebRequest.AllowAutoRedirect = false;

            if (options.AdditionalHeaders != null)
            {
                foreach (var kv in options.AdditionalHeaders)
                {
                    httpWebRequest.Headers.Add(kv.Key, kv.Value);
                }
            }

            if (input != null)
            {
                // expecting the caller to seek to the beginning or to the location where it needs to be copied from
                using (Stream req = await httpWebRequest.GetRequestStreamAsync())
                {
                    await input.CopyToAsync(req);
                }
            }

            var response = (await httpWebRequest.GetResponseAsync()) as HttpWebResponse;
            return new Response()
            {
                WebResponse = response,
                RequestLatency = watch.Elapsed
            };
        }
        public void ClaimCreationWithRequestOptionsTest()
        {
            RequestOptions options = new RequestOptions();
            options.IsTest = true;
            options.ApiKey = null;
            Hashtable input = JsonConvert.DeserializeObject<Hashtable>(ClaimInput);

            ClaimResponse actualResponse = claim.Create(input, options);

            ClaimSuccessCheck(actualResponse.JsonResponse());
        }
        private static async Task ReadOrCreateCollection(string databaseLink)
        {
            Collection = Client.CreateDocumentCollectionQuery(databaseLink).Where(col => col.Id == _collectionId).AsEnumerable().FirstOrDefault();

            if (Collection == null)
            {
                var collectionSpec = new DocumentCollection {Id = _collectionId};
                var requestOptions = new RequestOptions {OfferType = "S1"};

                Collection = await Client.CreateDocumentCollectionAsync(databaseLink, collectionSpec, requestOptions);
            }
        }
        /// <summary>
        /// Issues the web request asynchronous.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="method">The method.</param>
        /// <param name="query">The query.</param>
        /// <param name="input">The input.</param>
        /// <param name="options">request options</param>
        /// <returns></returns>
        public async Task<Response> IssueWebRequestAsync(
            string endpoint, string method, string query, Stream input, RequestOptions options)
        {
            options.Validate();
            Stopwatch watch = Stopwatch.StartNew();
            UriBuilder builder = new UriBuilder(
                _credentials.ClusterUri.Scheme,
                _credentials.ClusterUri.Host,
                options.Port,
                options.AlternativeEndpoint + endpoint);

            if (query != null)
            {
                builder.Query = query;
            }

            Debug.WriteLine("Issuing request {0} to endpoint {1}", Trace.CorrelationManager.ActivityId, builder.Uri);
            HttpWebRequest httpWebRequest = WebRequest.CreateHttp(builder.Uri);
            httpWebRequest.ServicePoint.ReceiveBufferSize = options.ReceiveBufferSize;
            httpWebRequest.ServicePoint.UseNagleAlgorithm = options.UseNagle;
            httpWebRequest.Timeout = options.TimeoutMillis;
            httpWebRequest.KeepAlive = options.KeepAlive;
            httpWebRequest.Credentials = _credentialCache;
            httpWebRequest.PreAuthenticate = true;
            httpWebRequest.Method = method;
            httpWebRequest.Accept = _contentType;
            httpWebRequest.ContentType = _contentType;

            if (options.AdditionalHeaders != null)
            {
                foreach (var kv in options.AdditionalHeaders)
                {
                    httpWebRequest.Headers.Add(kv.Key, kv.Value);
                }
            }

            if (input != null)
            {
                // seek to the beginning, so we copy everything in this buffer
                input.Seek(0, SeekOrigin.Begin);
                using (Stream req = httpWebRequest.GetRequestStream())
                {
                    await input.CopyToAsync(req);
                }
            }

            var response = (await httpWebRequest.GetResponseAsync()) as HttpWebResponse;
            return new Response()
            {
                WebResponse = response,
                RequestLatency = watch.Elapsed
            };
        }
示例#9
0
 public ApiRequest(RequestOptions options)
 {
     // BasicConfigurator.Configure();
     requestOptions = options;
     client = new RestClient(requestOptions.Url);
     request = new RestRequest();
     request.AddHeader("Content-Type", "application/json");
     request.AddHeader("X-Key", requestOptions.ApiKey);
     request.AddHeader("X-Password", requestOptions.Password);
     request.AddHeader("X-Dat-Channel", "link-dotnet");
     request.RequestFormat = DataFormat.Json;
 }
示例#10
0
		private static async Task<HttpResponseMessage> UrlRequest(string request, HttpMethod httpMethod, Dictionary<string, string> data = null, Dictionary<string, string> cookies = null, string referer = null, RequestOptions requestOptions = RequestOptions.None) {
			if (string.IsNullOrEmpty(request) || httpMethod == null) {
				return null;
			}

			HttpResponseMessage responseMessage;
			using (HttpRequestMessage requestMessage = new HttpRequestMessage(httpMethod, request)) {
				if (data != null) {
					try {
						requestMessage.Content = new FormUrlEncodedContent(data);
					} catch (UriFormatException e) {
						Logging.LogGenericException(e);
						return null;
					}
				}

				if (cookies != null && cookies.Count > 0) {
					StringBuilder cookieHeader = new StringBuilder();
					foreach (KeyValuePair<string, string> cookie in cookies) {
						cookieHeader.Append(cookie.Key + "=" + cookie.Value + ";");
					}
					requestMessage.Headers.Add("Cookie", cookieHeader.ToString());
				}

				if (referer != null) {
					requestMessage.Headers.Referrer = new Uri(referer);
				}

				if (requestOptions.HasFlag(RequestOptions.FakeUserAgent)) {
					requestMessage.Headers.UserAgent.ParseAdd(FakeUserAgent);
				}

				if (requestOptions.HasFlag(RequestOptions.XMLHttpRequest)) {
					requestMessage.Headers.Add("X-Requested-With", "XMLHttpRequest");
				}

				try {
					responseMessage = await HttpClient.SendAsync(requestMessage).ConfigureAwait(false);
				} catch { // Request failed, we don't need to know the exact reason, swallow exception
					return null;
				}
			}

			if (responseMessage == null || !responseMessage.IsSuccessStatusCode) {
				return null;
			}

			return responseMessage;
		}
 /// <summary>
 /// List all Organization Quota Definitions
 /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/195/organization_quota_definitions/list_all_organization_quota_definitions.html"</para>
 /// </summary>
 public async Task<PagedResponseCollection<ListAllOrganizationQuotaDefinitionsResponse>> ListAllOrganizationQuotaDefinitions(RequestOptions options)
 {
     UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget);
     uriBuilder.Path = "/v2/quota_definitions";
     uriBuilder.Query = options.ToString();
     var client = this.GetHttpClient();
     client.Uri = uriBuilder.Uri;
     client.Method = HttpMethod.Get;
     var authHeader = await BuildAuthenticationHeader();
     if (!string.IsNullOrWhiteSpace(authHeader.Key))
     {
         client.Headers.Add(authHeader);
     }
     var expectedReturnStatus = 200;
     var response = await this.SendAsync(client, expectedReturnStatus);
     return Utilities.DeserializePage<ListAllOrganizationQuotaDefinitionsResponse>(await response.ReadContentAsStringAsync(), this.Client);
 }
        protected async void ButtonSend_Click(object sender, EventArgs e)
        {

            RequestOptions requestOptions = null;
 
            //Request response in JSON format            
            requestOptions = new RequestOptions();
            requestOptions.Headers.Add("Accept", "application/json");

            //Send Request
            var response = await Global.HelloServiceClient.GetAsync(Uri + TextBoxName.Text, requestOptions);

            //Display result
            PanelResponse.Visible = true;
            LabelResponse.Text = response.Content.ReadAsStringAsync().Result;

        }
 /// <summary>
 /// List all Spaces for the Domain (deprecated)
 /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/195/domains__deprecated_/list_all_spaces_for_the_domain_(deprecated).html"</para>
 /// </summary>
 public async Task<PagedResponseCollection<ListAllSpacesForDomainDeprecatedResponse>> ListAllSpacesForDomainDeprecated(Guid? guid, RequestOptions options)
 {
     UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget);
     uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/domains/{0}/spaces", guid);
     uriBuilder.Query = options.ToString();
     var client = this.GetHttpClient();
     client.Uri = uriBuilder.Uri;
     client.Method = HttpMethod.Get;
     var authHeader = await BuildAuthenticationHeader();
     if (!string.IsNullOrWhiteSpace(authHeader.Key))
     {
         client.Headers.Add(authHeader);
     }
     var expectedReturnStatus = 200;
     var response = await this.SendAsync(client, expectedReturnStatus);
     return Utilities.DeserializePage<ListAllSpacesForDomainDeprecatedResponse>(await response.ReadContentAsStringAsync(), this.Client);
 }
示例#14
0
 public static Response Get(string uri, RequestOptions options = null)
 {
     try
     {
         using (var client = new HttpClient())
         {
             var result = client.GetAsync(new Uri(uri)).Result;
             return new Response
             {
                 Content = result.Content,
                 StatusCode = result.StatusCode
             };
         }
     } catch(Exception exception) {
         throw exception;
     }
 }
        /// <summary>
        /// This request is used as a short-hand for create a Statement and fetching the first batch 
        /// of results in a single call without any parameter substitution.
        /// </summary>
        public async Task<ExecuteResponse> PrepareAndExecuteRequestAsync(string connectionId, string sql, uint statementId, long maxRowsTotal, int firstFrameMaxSize, RequestOptions options)
        {
            PrepareAndExecuteRequest req = new PrepareAndExecuteRequest
            {
                Sql = sql,
                ConnectionId = connectionId,
                StatementId = statementId,
                MaxRowsTotal = maxRowsTotal,
                FirstFrameMaxSize = firstFrameMaxSize
            };

            WireMessage msg = new WireMessage
            {
                Name = Constants.WireMessagePrefix + "PrepareAndExecuteRequest",
                WrappedMessage = req.ToByteString()
            };

            using (Response webResponse = await PostRequestAsync(msg.ToByteArray(), options))
            {
                if (webResponse.WebResponse.StatusCode != HttpStatusCode.OK)
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ErrorResponse res = ErrorResponse.Parser.ParseFrom(output.WrappedMessage);
                    throw new WebException(
                        string.Format(
                            "PrepareAndExecuteRequestAsync failed! connectionId: {0}, Response code was: {1}, Response body was: {2}",
                            connectionId,
                            webResponse.WebResponse.StatusCode,
                            res.ToString()));
                }
                else
                {
                    WireMessage output = WireMessage.Parser.ParseFrom(webResponse.WebResponse.GetResponseStream());
                    ExecuteResponse res = ExecuteResponse.Parser.ParseFrom(output.WrappedMessage);
                    return res;
                }
            }
        }
示例#16
0
 /// <inheritdoc />
 async Task <IReadOnlyCollection <IGuildIntegration> > IGuild.GetIntegrationsAsync(RequestOptions options)
 => await GetIntegrationsAsync(options).ConfigureAwait(false);
示例#17
0
 private async static Task<System.Net.Http.HttpResponseMessage> SendMessage(RestBusClient client, RequestOptions requestOptions)
 {
     //Send Request
     var uri = "api/values"; //Substitute "hello/random" for the ServiceStack example
     return await client.GetAsync(uri, requestOptions);
 }
示例#18
0
 /// <inheritdoc />
 async Task <IReadOnlyCollection <IVoiceChannel> > IGuild.GetVoiceChannelsAsync(CacheMode mode, RequestOptions options)
 {
     if (mode == CacheMode.AllowDownload)
     {
         return(await GetVoiceChannelsAsync(options).ConfigureAwait(false));
     }
     else
     {
         return(ImmutableArray.Create <IVoiceChannel>());
     }
 }
示例#19
0
 /// <inheritdoc />
 async Task <IInviteMetadata> IGuild.GetVanityInviteAsync(RequestOptions options)
 => await GetVanityInviteAsync(options).ConfigureAwait(false);
示例#20
0
 public Task <RestGuildUser> GetGuildUserAsync(ulong guildId, ulong id, RequestOptions options = null)
 => ClientHelper.GetGuildUserAsync(this, guildId, id, options);
示例#21
0
 public Task <RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null)
 => ClientHelper.GetVoiceRegionAsync(this, id, options);
示例#22
0
 public static Task DeleteUnknownApplicationCommandAsync(BaseDiscordClient client, ulong? guildId, IApplicationCommand command, RequestOptions options = null)
 {
     return guildId.HasValue
         ? DeleteGuildCommandAsync(client, guildId.Value, command, options)
         : DeleteGlobalCommandAsync(client, command, options);
 }
示例#23
0
        //Use the DocumentCollection if it exists, if not create a new Collection
        private static DocumentCollection ReadOrCreateCollection(string databaseLink)
        {
            var col = Client.CreateDocumentCollectionQuery(databaseLink)
                              .Where(c => c.Id == CollectionId)
                              .AsEnumerable()
                              .FirstOrDefault();

            if (col == null)
            {
                var collectionSpec = new DocumentCollection { Id = CollectionId };
                var requestOptions = new RequestOptions { OfferType = "S1" };

                col = Client.CreateDocumentCollectionAsync(databaseLink, collectionSpec, requestOptions).Result;
            }

            return col;
        }
示例#24
0
 public static Task DeleteAllGlobalCommandsAsync(BaseDiscordClient client, RequestOptions options = null)
 {
     return client.ApiClient.BulkOverwriteGlobalApplicationCommandsAsync(Array.Empty<CreateApplicationCommandParams>(), options);
 }
示例#25
0
        public static async Task DeleteGuildCommandAsync(BaseDiscordClient client, ulong guildId, IApplicationCommand command, RequestOptions options = null)
        {
            Preconditions.NotNull(command, nameof(command));
            Preconditions.NotEqual(command.Id, 0, nameof(command.Id));

            await client.ApiClient.DeleteGuildApplicationCommandAsync(guildId, command.Id, options).ConfigureAwait(false);
        }
示例#26
0
 public static Task DeleteAllGuildCommandsAsync(BaseDiscordClient client, ulong guildId, RequestOptions options = null)
 {
     return client.ApiClient.BulkOverwriteGuildApplicationCommandsAsync(guildId, Array.Empty<CreateApplicationCommandParams>(), options);
 }
示例#27
0
 /// <inheritdoc />
 async Task <IGuildUser> IGuild.AddGuildUserAsync(ulong userId, string accessToken, Action <AddGuildUserProperties> func, RequestOptions options)
 => await AddGuildUserAsync(userId, accessToken, func, options);
示例#28
0
 /// <inheritdoc />
 async Task <IRole> IGuild.CreateRoleAsync(string name, GuildPermissions?permissions, Color?color, bool isHoisted, RequestOptions options)
 => await CreateRoleAsync(name, permissions, color, isHoisted, options).ConfigureAwait(false);
        /// <summary>
        /// Issues the web request asynchronous.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="method">The method.</param>
        /// <param name="input">The input.</param>
        /// <param name="options">request options</param>
        /// <returns></returns>
        public async Task<Response> IssueWebRequestAsync(string endpoint, string query, string method, Stream input, RequestOptions options)
        {
            options.Validate();
            Stopwatch watch = Stopwatch.StartNew();
            Trace.CorrelationManager.ActivityId = Guid.NewGuid();
            var balancedEndpoint = _balancer.GetEndpoint();

            // Grab the host. Use the alternative host if one is specified
            string host = (options.AlternativeHost != null) ? options.AlternativeHost : balancedEndpoint.Host;

            UriBuilder builder = new UriBuilder(
                balancedEndpoint.Scheme,
                host,
                options.Port,
                options.AlternativeEndpoint + endpoint);

            if (query != null)
            {
                builder.Query = query;
            }

            var target = builder.Uri;

            try
            {
                Debug.WriteLine("Issuing request {0} to endpoint {1}", Trace.CorrelationManager.ActivityId, target);

                HttpWebRequest httpWebRequest = WebRequest.CreateHttp(target);
                httpWebRequest.ServicePoint.ReceiveBufferSize = options.ReceiveBufferSize;
                httpWebRequest.ServicePoint.UseNagleAlgorithm = options.UseNagle;
                httpWebRequest.Timeout = options.TimeoutMillis; // This has no influence for calls that are made Async
                httpWebRequest.KeepAlive = options.KeepAlive;
                httpWebRequest.Credentials = _credentialCache;
                httpWebRequest.PreAuthenticate = true;
                httpWebRequest.Method = method;
                httpWebRequest.Accept = _contentType;
                httpWebRequest.ContentType = _contentType;
                // This allows 304 (NotModified) requests to catch
                //https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect(v=vs.110).aspx
                httpWebRequest.AllowAutoRedirect = false;

                if (options.AdditionalHeaders != null)
                {
                    foreach (var kv in options.AdditionalHeaders)
                    {
                        httpWebRequest.Headers.Add(kv.Key, kv.Value);
                    }
                }
                long remainingTime = options.TimeoutMillis;

                if (input != null)
                {
                    // expecting the caller to seek to the beginning or to the location where it needs to be copied from
                    Stream req = null;
                    try
                    {
                        req = await httpWebRequest.GetRequestStreamAsync().WithTimeout(
                                                    TimeSpan.FromMilliseconds(remainingTime),
                                                    "Waiting for RequestStream");

                        remainingTime = options.TimeoutMillis - watch.ElapsedMilliseconds;
                        if (remainingTime <= 0)
                        {
                            remainingTime = 0;
                        }

                        await input.CopyToAsync(req).WithTimeout(
                                    TimeSpan.FromMilliseconds(remainingTime),
                                    "Waiting for CopyToAsync",
                                    CancellationToken.None);
                    }
                    catch (TimeoutException)
                    {
                        httpWebRequest.Abort();
                        throw;
                    }
                    finally
                    {
                        req?.Close();
                    }
                }

                try
                {
                    remainingTime = options.TimeoutMillis - watch.ElapsedMilliseconds;
                    if (remainingTime <= 0)
                    {
                        remainingTime = 0;
                    }

                    Debug.WriteLine("Waiting for response for request {0} to endpoint {1}", Trace.CorrelationManager.ActivityId, target);

                    HttpWebResponse response = (HttpWebResponse)await httpWebRequest.GetResponseAsync().WithTimeout(
                                                                    TimeSpan.FromMilliseconds(remainingTime),
                                                                    "Waiting for GetResponseAsync");

                    Debug.WriteLine("Web request {0} to endpoint {1} successful!", Trace.CorrelationManager.ActivityId, target);

                    return new Response()
                    {
                        WebResponse = response,
                        RequestLatency = watch.Elapsed,
                        PostRequestAction = (r) =>
                        {
                            if (r.WebResponse.StatusCode == HttpStatusCode.OK || r.WebResponse.StatusCode == HttpStatusCode.Created || r.WebResponse.StatusCode == HttpStatusCode.NotModified)
                            {
                                _balancer.RecordSuccess(balancedEndpoint);
                            }
                            else
                            {
                                _balancer.RecordFailure(balancedEndpoint);
                            }
                        }
                    };
                }
                catch (TimeoutException)
                {
                    httpWebRequest.Abort();
                    throw;
                }
            }
            catch(WebException we)
            {
                // 404 is valid response
                var resp = we.Response as HttpWebResponse;
                if(resp.StatusCode == HttpStatusCode.NotFound)
                {
                    _balancer.RecordSuccess(balancedEndpoint);
                    Debug.WriteLine("Web request {0} to endpoint {1} successful!", Trace.CorrelationManager.ActivityId, target);
                }
                else
                {
                    _balancer.RecordFailure(balancedEndpoint);
                    Debug.WriteLine("Web request {0} to endpoint {1} failed!", Trace.CorrelationManager.ActivityId, target);
                }
                throw we;
            }
            catch (Exception e)
            {
                _balancer.RecordFailure(balancedEndpoint);
                Debug.WriteLine("Web request {0} to endpoint {1} failed!", Trace.CorrelationManager.ActivityId, target);
                throw e;
            }
        }
示例#30
0
 public static async Task SendInteractionResponseAsync(BaseDiscordClient client, UploadInteractionFileParams response,
     IDiscordInteraction interaction, IMessageChannel channel = null, RequestOptions options = null)
 {
     await client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options).ConfigureAwait(false);
 }
示例#31
0
        /// <summary>
        /// Create a post trigger that updates metadata: for each inserted doc it will look at doc.size
        /// and update aggregate properties: { minSize, maxSize, totalSize } in the metadata doc.
        /// In the end print to show the aggregate values of min, max, total for all docs.
        /// </summary>
        private static async Task RunPostTrigger(string colSelfLink)
        {
            Random rnd = new Random();

            // 1. Create a trigger.
            string triggerPath = @"js\UpdateMetadata.js";
            string triggerId = Path.GetFileNameWithoutExtension(triggerPath);
            string triggerBody = File.ReadAllText(triggerPath);
            Trigger trigger = new Trigger
            {
                Id = Path.GetFileName(triggerId),
                Body = triggerBody,
                TriggerOperation = TriggerOperation.Create,
                TriggerType = TriggerType.Post
            };

            await TryDeleteStoredProcedure(colSelfLink, trigger.Id);
            await client.CreateTriggerAsync(colSelfLink, trigger);
            
            // 2. Create the metadata document.
            var metaDoc = new 
            {
                    id = "meta", 
                    isMetadata = true, 
                    minSize = 0, 
                    maxSize = 0, 
                    totalSize = 0 
            };

            await client.CreateDocumentAsync(colSelfLink, metaDoc); 
            
            // 3. Import a number of docs with trigger. Use client API this time, we already have sample fot using script.
            var requestOptions = new RequestOptions { PostTriggerInclude = new List<string> { triggerId } };

            await client.CreateDocumentAsync(colSelfLink, new
            {
                size = rnd.Next(1000),
            }, requestOptions);

            await client.CreateDocumentAsync(colSelfLink, new
            {
                size = rnd.Next(1000),
            }, requestOptions);

            await client.CreateDocumentAsync(colSelfLink, new
            {
                size = rnd.Next(1000),
            }, requestOptions);

            await client.CreateDocumentAsync(colSelfLink, new
            {
                size = rnd.Next(1000),
            }, requestOptions);

            await client.CreateDocumentAsync(colSelfLink, new
            {
                size = rnd.Next(1000),
            }, requestOptions);
            
            // 4. Print aggregate info from the metadata document.
            metaDoc = client.CreateDocumentQuery<dynamic>(colSelfLink, "SELECT * FROM root r WHERE r.isMetadata = true").AsEnumerable().First();

            Console.WriteLine("Document statistics: min size: {0}, max size: {1}, total size: {2}", metaDoc.minSize, metaDoc.maxSize, metaDoc.totalSize);
        }
示例#32
0
 public static async Task DeleteInteractionResponseAsync(BaseDiscordClient client, RestInteractionMessage message, RequestOptions options = null)
     => await client.ApiClient.DeleteInteractionFollowupMessageAsync(message.Id, message.Token, options);
示例#33
0
 /// <inheritdoc />
 async Task <IVoiceChannel> IGuild.GetVoiceChannelAsync(ulong id, CacheMode mode, RequestOptions options)
 {
     if (mode == CacheMode.AllowDownload)
     {
         return(await GetVoiceChannelAsync(id, options).ConfigureAwait(false));
     }
     else
     {
         return(null);
     }
 }
示例#34
0
 public static async Task DeleteInteractionResponseAsync(BaseDiscordClient client, IDiscordInteraction interaction, RequestOptions options = null)
     => await client.ApiClient.DeleteInteractionFollowupMessageAsync(interaction.Id, interaction.Token, options);
示例#35
0
 public Task <IReadOnlyCollection <RestVoiceRegion> > GetVoiceRegionsAsync(RequestOptions options = null)
 => ClientHelper.GetVoiceRegionsAsync(this, options);
示例#36
0
 /// <inheritdoc />
 async Task <ICategoryChannel> IGuild.CreateCategoryAsync(string name, Action <GuildChannelProperties> func, RequestOptions options)
 => await CreateCategoryChannelAsync(name, func, options).ConfigureAwait(false);
示例#37
0
 public Task <RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null)
 => ClientHelper.GetWebhookAsync(this, id, options);
示例#38
0
 /// <inheritdoc />
 async Task <IGuildIntegration> IGuild.CreateIntegrationAsync(ulong id, string type, RequestOptions options)
 => await CreateIntegrationAsync(id, type, options).ConfigureAwait(false);
示例#39
0
        private async Task<object> SendRequestInnerAsync(string uri,
                                                         string httpMethod,
                                                         object body,
                                                         ISerializationContextProvider provider,
                                                         RequestOptions options)
        {
            if (provider == null)
                throw new ArgumentNullException(nameof(provider));
            if (uri == null)
                throw new ArgumentNullException(nameof(uri));
            if (httpMethod == null)
                throw new ArgumentNullException(nameof(httpMethod));
            if (options == null)
                options = new RequestOptions();

            if (body is IExtendedResourceProxy)
                throw new ArgumentException("SendRequestInner should never get a body of type IExtendedResourceProxy");

            var response = await SendHttpRequestAsync(provider, uri, httpMethod, body, null, options);
            return response != null ? Deserialize(response, options.ExpectedResponseType, provider) : null;
        }
示例#40
0
 /// <inheritdoc />
 async Task <IReadOnlyCollection <IInviteMetadata> > IGuild.GetInvitesAsync(RequestOptions options)
 => await GetInvitesAsync(options).ConfigureAwait(false);
示例#41
0
        public async Task<object> SendRequestAsync(string uri,
                                                   string httpMethod,
                                                   object body,
                                                   ISerializationContextProvider provider,
                                                   RequestOptions options = null)
        {
            if (provider == null)
                throw new ArgumentNullException(nameof(provider));
            if (uri == null)
                throw new ArgumentNullException(nameof(uri));
            if (httpMethod == null)
                throw new ArgumentNullException(nameof(httpMethod));
            if (options == null)
                options = new RequestOptions();

            var innerBody = body;
            var proxyBody = body as IExtendedResourceProxy;
            if (proxyBody != null)
                innerBody = proxyBody.WrappedResource;

            // Figure out server side response type
            ExtendedResourceInfo responseExtendedTypeInfo;
            var responseType = options.ExpectedResponseType;
            var innerOptions = options;
            var innerResponseType = options.ExpectedResponseType;
            if (innerResponseType != null)
            {
                if (this.typeMapper.TryGetExtendedTypeInfo(innerResponseType, out responseExtendedTypeInfo))
                {
                    innerResponseType = responseExtendedTypeInfo.ServerType;
                    innerOptions = new RequestOptions(options) { ExpectedResponseType = innerResponseType };
                }
            }

            var innerResult = await SendRequestInnerAsync(uri, httpMethod, innerBody, provider, innerOptions);
            if (innerResponseType == null && proxyBody != null && innerResult != null)
            {
                // Special case: No response type specified, but response has same type as posted body,
                // and the posted body was of an extended type. In this case we will wrap the response
                // to the same type if possible.
                var proxyBodyInfo = proxyBody.UserTypeInfo;
                if (proxyBodyInfo.ServerType.IsInstanceOfType(innerResult))
                {
                    responseType = proxyBodyInfo.ExtendedType;
                    innerResponseType = proxyBodyInfo.ServerType;
                }
            }

            if (responseType != innerResponseType)
                return this.typeMapper.WrapResource(innerResult, innerResponseType, responseType);
            return innerResult;
        }
示例#42
0
 public object Get(string uri, Type type, RequestOptions requestOptions)
 {
     throw new LoadException(uri, type);
 }
示例#43
0
        /// <summary>
        /// Deletes the documents for the specified where clause.
        /// </summary>
        /// <param name="whereClause">The where clause.</param>
        /// <returns></returns>
        public IEnumerable <string> Delete(string whereClause)
        {
            var query       = $"SELECT TOP 500 c.id AS Id, c.{_client.PartitionKey} AS PartitionKey FROM c WHERE {whereClause}";
            var uri         = UriFactory.CreateDocumentCollectionUri(_client.DatabaseId, _client.CollectionId);
            var feedOptions = _client.EnableCrossPartitionQuery ? new FeedOptions {
                EnableCrossPartitionQuery = true
            } : null;

            var retries = 0;

            do
            {
                List <IdPartitionKeyDto> result = null;

                try
                {
                    result = _client.Client.CreateDocumentQuery <IdPartitionKeyDto>(uri, query, feedOptions).AsEnumerable().ToList();
                }
                catch (Exception e)
                {
                    if (++retries >= 10)
                    {
                        Console.WriteLine("ERROR: TOO MANY RETRIES. FETCHING DOCUMENTS NOT POSSIBLE. TERMINATING.");
                        throw;
                    }

                    Console.WriteLine($"EXCEPTION WHILE FETCHING DOCUMENTS - {e.Message}");
                    Task.Delay(1000);
                }

                if (result != null)
                {
                    retries = 0;
                    foreach (var doc in result)
                    {
                        var docId       = doc.Id;
                        var noException = true;

                        try
                        {
                            RequestOptions requestOptions = null;

                            if (_client.EnableCrossPartitionQuery)
                            {
                                requestOptions = new RequestOptions()
                                {
                                    PartitionKey = new PartitionKey(doc.PartitionKey)
                                }
                            }
                            ;

                            var docUri = UriFactory.CreateDocumentUri(_client.DatabaseId, _client.CollectionId, docId);
                            _client.Client.DeleteDocumentAsync(docUri, requestOptions).Wait();
                        }
                        catch (Exception e)
                        {
                            noException = false;
                            Console.WriteLine($"EXCEPTION WHILE DELETING {docId} - {e.Message}");
                            Task.Delay(500);
                        }

                        if (noException)
                        {
                            yield return(docId);
                        }
                    }
                }

                Task.Delay(1000);
            } while (HasResults(whereClause));
        }
示例#44
0
 /// <inheritdoc />
 async Task <IReadOnlyCollection <IVoiceRegion> > IGuild.GetVoiceRegionsAsync(RequestOptions options)
 => await GetVoiceRegionsAsync(options).ConfigureAwait(false);
示例#45
0
 public object SendRequest(string uri,
                           string httpMethod,
                           object body,
                           ISerializationContextProvider provider,
                           RequestOptions options = null)
 {
     try
     {
         return Task.Run(() => SendRequestAsync(uri, httpMethod, body, provider, options)).Result;
     }
     catch (AggregateException aggregateException)
         when (aggregateException.InnerExceptions.Count == 1 && aggregateException.InnerException is WebClientException)
     {
         throw aggregateException.InnerException;
     }
 }
示例#46
0
        public override void GrabAndParseHtml()
        {
            //今日
            int pageNum    = 0;
            int page       = 1;
            int match_type = 2;

            do
            {
                int            nTryCount = 0;
                string         uriFormat = Config.GetString(StaticData.SN_URL, "Uri", configFile, "Uri");
                string         uri       = string.Format(uriFormat, page, match_type);
                RequestOptions op        = new RequestOptions(uri);
                op.Method  = Config.GetString(StaticData.SN_URL, "Method", configFile, "GET");
                op.Accept  = Config.GetString(StaticData.SN_URL, "Accept", configFile, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                op.Referer = Config.GetString(StaticData.SN_URL, "Referer", configFile, "");
                //获取网页
                html = RequestAction(op);
                while (string.IsNullOrEmpty(html) && nTryCount < MAX_TRY_COUNT)
                {
                    html = RequestAction(op);
                    nTryCount++;
                }
                if (nTryCount == MAX_TRY_COUNT)
                {
                    ShowLog("抓取失败!");
                    html = "";
                    return;
                }
                else
                {
                    pageNum = Parse();
                }
                page++;
            } while (pageNum == PAGE_MAX_NUM);

            //赛前
            pageNum    = 0;
            page       = 1;
            match_type = 3;
            do
            {
                int            nTryCount = 0;
                string         uriFormat = Config.GetString(StaticData.SN_URL, "Uri", configFile, "Uri");
                string         uri       = string.Format(uriFormat, page, match_type);
                RequestOptions op        = new RequestOptions(uri);
                op.Method  = Config.GetString(StaticData.SN_URL, "Method", configFile, "GET");
                op.Accept  = Config.GetString(StaticData.SN_URL, "Accept", configFile, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                op.Referer = Config.GetString(StaticData.SN_URL, "Referer", configFile, "");
                //获取网页
                html = RequestAction(op);
                while (string.IsNullOrEmpty(html) && nTryCount < MAX_TRY_COUNT)
                {
                    html = RequestAction(op);
                    nTryCount++;
                }
                if (nTryCount == MAX_TRY_COUNT)
                {
                    ShowLog("抓取失败!");
                    html = "";
                    return;
                }
                else
                {
                    pageNum = Parse();
                }
                page++;
            } while (pageNum == PAGE_MAX_NUM);

            if (betItems.Count > 0)
            {
                ShowLog(string.Format("页面解析成功,解析个数:{0}!", betItems.Count));
            }
        }
示例#47
0
        private async Task<string> SendHttpRequestAsync(ISerializationContextProvider serializationContextProvider,
                                                        string uri,
                                                        string httpMethod,
                                                        object requestBodyEntity,
                                                        TypeSpec requestBodyBaseType,
                                                        RequestOptions options)
        {
            byte[] requestBytes = null;
            HttpResponseMessage response = null;
            if (requestBodyEntity != null)
            {
                requestBytes = this.serializerFactory
                                   .GetSerializer(serializationContextProvider)
                                   .SerializeToBytes(requestBodyEntity, new SerializeOptions
                                   {
                                       ExpectedBaseType = requestBodyBaseType
                                   });
            }
            var request = new HttpRequestMessage(new System.Net.Http.HttpMethod(httpMethod), uri);

            string responseString = null;
            Exception thrownException = null;
            try
            {
                if (options != null)
                    options.ApplyRequestModifications(request);

                AddDefaultHeaders(request);

                const string jsonContentType = "application/json; charset=utf-8";
                request.Headers.Add("Accept", jsonContentType);
                if (requestBytes != null)
                {
                    var requestContent = new ByteArrayContent(requestBytes);
                    requestContent.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonContentType);
                    request.Content = requestContent;
                }

                using (Profiler.Step("client: " + request.Method + " " + request.RequestUri))
                {
                    response = await WebClient.SendAsync(request, CancellationToken.None);
                }

                if (response.Content != null)
                {
                    responseString = await response.Content.ReadAsStringAsync();
                    if (responseString.Length == 0)
                        responseString = null;
                }

                if ((int)response.StatusCode >= 400)
                {
                    var gotJsonResponseBody = responseString != null && response.Content.Headers.ContentType.MediaType == "application/json";

                    var responseObject = gotJsonResponseBody
                        ? Deserialize(responseString, null, serializationContextProvider)
                        : null;

                    throw WebClientException.Create(this.typeMapper, request, response, responseObject, null);
                }
            }
            catch (Exception ex)
            {
                thrownException = ex;
                throw;
            }
            finally
            {
                var eh = RequestCompleted;
                if (eh != null)
                {
                    // Since request content has been disposed at this point we recreate it..
                    if (request.Content != null)
                    {
                        var nonDisposedContent = new ByteArrayContent(requestBytes);
                        nonDisposedContent.Headers.CopyHeadersFrom(request.Content.Headers);
                        request.Content = nonDisposedContent;
                    }
                    eh(this, new ClientRequestLogEventArgs(request, response, thrownException));
                }
            }

            return responseString;
        }
示例#48
0
 public IAsyncEnumerable <IReadOnlyCollection <RestUserGuild> > GetGuildSummariesAsync(RequestOptions options = null)
 => ClientHelper.GetGuildSummariesAsync(this, null, null, options);
示例#49
0
 public Task<object> GetAsync(string uri, Type type, RequestOptions requestOptions)
 {
     throw new LoadException(uri, type);
 }
示例#50
0
 /// <summary>
 /// Consultar información de la nota de débito previamente enviada.
 /// </summary>
 /// <param name="requestOptions"></param>
 /// <returns>Información de la nota de débito enviada</returns>
 public static string Consultar(RequestOptions requestOptions)
 {
     Console.WriteLine("Consultando nota de débito");
     var apiRequest = new ApiRequest(requestOptions);
     return apiRequest.Get();
 }
 /// <summary>
 /// Issues the web request.
 /// </summary>
 /// <param name="endpoint">The endpoint.</param>
 /// <param name="method">The method.</param>
 /// <param name="input">The input.</param>
 /// <param name="options">request options</param>
 /// <returns></returns>
 public Response IssueWebRequest(string endpoint, string query, string method, Stream input, RequestOptions options)
 {
     return IssueWebRequestAsync(endpoint, query, method, input, options).Result;
 }
示例#52
0
 public Task <IReadOnlyCollection <RestGuild> > GetGuildsAsync(bool withCounts, RequestOptions options = null)
 => ClientHelper.GetGuildsAsync(this, withCounts, options);
示例#53
0
        /// <summary>
        /// Create a pre-trigger that updates the document by the following for each doc:
        /// - Validate and canonicalize the weekday name.
        /// - Auto-create createdTime field.
        /// </summary>
        private static async Task RunPreTrigger(string colSelfLink)
        {
            // 1. Create a trigger.
            string triggerId = "CanonicalizeSchedule";
            string body = File.ReadAllText(@"JS\CanonicalizeSchedule.js");
            Trigger trigger = new Trigger
            {
                Id =  triggerId,
                Body = body,
                TriggerOperation = TriggerOperation.Create,
                TriggerType = TriggerType.Pre
            };

            await TryDeleteStoredProcedure(colSelfLink, trigger.Id);
            await client.CreateTriggerAsync(colSelfLink, trigger);

            // 2. Create a few documents with the trigger.
            var requestOptions = new RequestOptions { PreTriggerInclude = new List<string> { triggerId } };
            
            await client.CreateDocumentAsync(colSelfLink, new 
                {
                    type = "Schedule",
                    name = "Music",
                    weekday = "mon",
                    startTime = DateTime.Parse("18:00", CultureInfo.InvariantCulture),
                    endTime = DateTime.Parse("19:00", CultureInfo.InvariantCulture)
                }, requestOptions);

            await client.CreateDocumentAsync(colSelfLink, new 
                {
                    type = "Schedule",
                    name = "Judo",
                    weekday = "tues",
                    startTime = DateTime.Parse("17:30", CultureInfo.InvariantCulture),
                    endTime = DateTime.Parse("19:00", CultureInfo.InvariantCulture)
                }, requestOptions);

            await client.CreateDocumentAsync(colSelfLink, new 
                {
                    type = "Schedule",
                    name = "Swimming",
                    weekday = "FRIDAY",
                    startTime = DateTime.Parse("19:00", CultureInfo.InvariantCulture),
                    endTime = DateTime.Parse("20:00", CultureInfo.InvariantCulture)
                }, requestOptions);

            // 3. Read the documents from the store. 
            var results = client.CreateDocumentQuery<Document>(colSelfLink, "SELECT * FROM root r WHERE r.type='Schedule'");

            // 4. Prints the results: see what the trigger did.
            Console.WriteLine("Weekly schedule of classes:");
            foreach (var result in results)
            {
                Console.WriteLine("{0}", result);
            }
        }
示例#54
0
 public Task <RestGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null)
 => ClientHelper.CreateGuildAsync(this, name, region, jpegIcon, options);
 public XHRRequest(RequestOptions options)
 {
     Method = options.Method ?? "GET";
     Uri = options.Uri;
     Data = options.Data;
     CookieHeaderValue = options.CookieHeaderValue;
 }
示例#56
0
 public Task <RestUser> GetUserAsync(ulong id, RequestOptions options = null)
 => ClientHelper.GetUserAsync(this, id, options);
示例#57
0
 public IAsyncEnumerable <IReadOnlyCollection <RestUserGuild> > GetGuildSummariesAsync(ulong fromGuildId, int limit, RequestOptions options = null)
 => ClientHelper.GetGuildSummariesAsync(this, fromGuildId, limit, options);
示例#58
0
 /// <inheritdoc />
 async Task <IReadOnlyCollection <ICategoryChannel> > IGuild.GetCategoriesAsync(CacheMode mode, RequestOptions options)
 {
     if (mode == CacheMode.AllowDownload)
     {
         return(await GetCategoryChannelsAsync(options).ConfigureAwait(false));
     }
     else
     {
         return(null);
     }
 }
示例#59
0
        /// <summary>
        /// Enviar información de la nota de débito para generarla electrónicamente.
        /// </summary>
        /// <param name="requestOptions"></param>
        /// <returns>Información de la nota de débito enviada</returns>
        public String Enviar(RequestOptions requestOptions)
        {
            Console.WriteLine("Enviando nota de débito");
            var jsonSettings = new JsonSerializerSettings
            {
                ContractResolver = new SnakeCaseContractResolver(),
                NullValueHandling = NullValueHandling.Ignore

            };
            var json = JsonConvert.SerializeObject(this, jsonSettings);
            var apiRequest = new ApiRequest(requestOptions);
            return apiRequest.Post(json);
        }
示例#60
0
 public Task <IReadOnlyCollection <RestGuild> > GetGuildsAsync(RequestOptions options = null)
 => ClientHelper.GetGuildsAsync(this, false, options);