/// <summary> /// Creates a simple GET request for a "TestMethod". /// </summary> private Request GetSimpleRequest() { var service = new MockService() { BaseUri = new Uri("http://example.com") }; var request = (Request) Request.CreateRequest( service, new MockMethod { HttpMethod = "GET", Name = "TestMethod", RestPath = "" }); request.WithParameters(""); return(request); }
public void WithDeveloperKeyAssignTest() { var request = (Request) Request.CreateRequest( new MockClientService(), new MockClientServiceRequest { HttpMethod = "GET", MethodName = "TestMethod", RestPath = "https://example.com" }); request.WithKey(SimpleDeveloperKey); Assert.AreEqual(SimpleDeveloperKey, request.DeveloperKey); }
public void BuildRequestUrlWithDeveloperKeysTest() { var service = new MockService(); var request = (Request) Request.CreateRequest( service, new MockMethod { HttpMethod = "GET", Name = "TestMethod", RestPath = "https://example.com" }); request.WithKey(SimpleDeveloperKey).WithParameters(new Dictionary <string, string>()); var url = request.BuildRequest().RequestUri; Assert.AreEqual("https://example.com/?alt=json" + "&key=" + SimpleDeveloperKey, url.ToString()); }
private void AssertBody(bool gzipEnabled, string body, Action <Request, WebHeaderCollection, byte[]> additionalAsserts) { // Create the request. var mockservice = new MockService { GZipEnabled = gzipEnabled }; var mockmethod = new MockMethod { HttpMethod = "GET", Name = "Test", RestPath = "https://example.com" }; var request = (Request)Request.CreateRequest(mockservice, mockmethod); var headers = new WebHeaderCollection(); // Create a mock webrequest. var requestStream = new MemoryStream(); var mockWebrequest = new Mock <WebRequest>(); mockWebrequest.Setup(r => r.EndGetRequestStream(It.IsAny <IAsyncResult>())).Returns(requestStream); mockWebrequest.Setup(r => r.Headers).Returns(headers); var waitHandle = new System.Threading.AutoResetEvent(false); // Call the method we are testing request.WithBody(body); Action <WebRequest> x = (r) => waitHandle.Set(); var mockasync = new Mock <IAsyncResult>(); mockasync.Setup(r => r.AsyncState).Returns(new object[] { mockWebrequest.Object, x }); request.EndAttachBody(mockasync.Object); if (!waitHandle.WaitOne(3000)) { Assert.Fail("AttachBody did not complete."); } // Confirm the results. mockWebrequest.Verify(r => r.EndGetRequestStream(It.IsAny <System.IAsyncResult>()), Times.Once()); if (additionalAsserts != null) { additionalAsserts(request, headers, requestStream.ToArray()); } }
public void CreateRequestOnRequestUserAgentTest() { var service = new MockClientService(new BaseClientService.Initializer() { GZipEnabled = false }); var request = (Request) Request.CreateRequest(service, new MockClientServiceRequest { HttpMethod = "GET", MethodName = "TestMethod", RestPath = "https://example.com/test", }); HttpWebRequest webRequest = (HttpWebRequest)request.CreateWebRequest((r) => { }); // Test the user agent (without gzip): string expectedUserAgent = string.Format( "Unknown_Application google-api-dotnet-client/{0} {1}/{2} {3}", Utilities.GetLibraryVersion(), Environment.OSVersion.Platform, Environment.OSVersion.Version, Environment.Version); Assert.AreEqual(expectedUserAgent, webRequest.UserAgent); // Confirm that the (gzip) tag is added if GZip is supported. service = new MockClientService(new BaseClientService.Initializer() { GZipEnabled = true }); request = (Request) Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "GET", MethodName = "TestMethod", RestPath = "https://example.com/test", }); webRequest = (HttpWebRequest)request.CreateWebRequest((r) => { }); expectedUserAgent += " (gzip)"; Assert.AreEqual(expectedUserAgent, webRequest.UserAgent); }
private void StartGame(object sender, EventArgs e) { Request request = new Request(_gameAddress); var zones = Split2DArrayIntoParts(N, Hosts); var processed = 0; for (int i = 0; i < Hosts; i++) { int rows = zones[i].GetUpperBound(0) - zones[i].GetLowerBound(0) + 1; int cols = M; bool isFirst = i == 0; bool isLast = i == Hosts - 1; var host = new Host(i + 1, _ip, _port + i + 1, false); BalService.RegisterHost(host); var lifeData = new LifeData(Convert2DTo1DArray(zones[i], rows, cols), isFirst, isLast, cols, isFirst || isLast ? rows - 1 : rows - 2); var task = new Task(i + 1, host.Id, lifeData, Loops); JavaScriptSerializer js = new JavaScriptSerializer(); string postData = js.Serialize(task); string data = request.CreateRequest(postData, "task"); //_gameAddress, List <TaskResult> taskResults = js.Deserialize <List <TaskResult> >(data); var taskResult = taskResults[0]; var matrix = Convert1DTo2DArray(taskResult.Data.Array, rows, cols, taskResult.Data.IsFirst, taskResult.Data.IsLast); for (int j = processed; j < processed + taskResult.Data.Height; j++) //taskResult.Data.Height; j++) { int g = 0; for (int k = 0; k < cols; k++) { Matrix[j, k] = matrix[g, k]; Boxes[j, k].Text = Matrix[j, k].ToString(); } g++; } processed += taskResult.Data.Height; //State state = request.GetState(data); } }
protected override void SendImageDataMessage(byte[] pixeldata, int width, int height) { if (!prioritySet) { SendPriorityRegistrationMessage(); SendPriorityRegistrationMessage(); // Sending twice just in case a message errors out. TODO: de-dupe prioritySet = true; } var builder = new FlatBufferBuilder(1024); var rawImageDataOffset = RawImage.CreateDataVector(builder, pixeldata); var rawImageOffset = RawImage.CreateRawImage(builder, rawImageDataOffset, width, height); var imageOffset = Image.CreateImage(builder, ImageType.RawImage, rawImageOffset.Value, _messageDuration); var requestOffset = Request.CreateRequest(builder, Command.Image, imageOffset.Value); builder.Finish(requestOffset.Value); SendFinishedMessage(builder); }
public void BuildRequestUrlWithDeveloperKeysTest_RequiresEscape() { var service = new MockClientService(); var request = (Request) Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "GET", MethodName = "TestMethod", RestPath = "https://example.com" }); request.WithKey(ComplexDeveloperKey).WithParameters(new Dictionary <string, string>()); var url = request.BuildRequest().RequestUri; Assert.AreEqual("https://example.com/?" + "key=%3F%26%5E%25%20%20ABC123", url.AbsoluteUri); }
public void TestAsyncSystem() { var request = (Request) Request.CreateRequest( new MockService(), new MockMethod { HttpMethod = "GET", Name = "TestMethod", // Define an invalid URI which will cause a WebException to be thrown. RestPath = "https://localhost:12345/", Parameters = new Dictionary <string, IParameter>() }); AutoResetEvent mainThread = new AutoResetEvent(false); AutoResetEvent workerThread = new AutoResetEvent(false); request.WithParameters(new Dictionary <string, string>()); request.ExecuteRequestAsync(result => { // Check whether the request is indeed async. if (!mainThread.WaitOne(5000)) { Assert.Fail("Async-Request was blocking."); } // Check whether retrieving an response will throw an exception // because of the invalid rest URI of this request. Assert.Throws <GoogleApiRequestException>( () => result.GetResponse()); workerThread.Set(); }); mainThread.Set(); // Confirm that the code in the anonymous method was executed. if (!workerThread.WaitOne(5000)) { Assert.Fail("Async-Request did not terminate."); } }
public void CreateRequestSimpleCreateTest() { var service = new MockClientService(); Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "GET", MethodName = "TestMethod", RestPath = "https://example.com", }); Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "POST", MethodName = "TestMethod", RestPath = "https://example.com", }); Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "PUT", MethodName = "TestMethod", RestPath = "https://example.com", }); Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "DELETE", MethodName = "TestMethod", RestPath = "https://example.com", }); Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "PATCH", MethodName = "TestMethod", RestPath = "https://example.com", }); }
public static async Task <List <Illust> > GetBookmark(string accessToken, long userID, bool privateMode) { string PublicAPI = "https://app-api.pixiv.net/v1/user/bookmarks/illust?restrict=public&user_id="; string PrivateAPI = "https://app-api.pixiv.net/v1/user/bookmarks/illust?restrict=private&user_id="; List <Illust> list = new List <Illust>(); int i = 0; string API = privateMode ? PrivateAPI + $"{userID}" : PublicAPI + $"{userID}"; Dictionary <string, string> headers = new Dictionary <string, string> { { "Authorization", "Bearer " + accessToken }, }; do { string json = await(await Request.CreateRequest(MethodType.GET, API, null, headers)).GetResponseStringAsync(); IllustList ranking = JsonConvert.DeserializeObject <IllustList>(json); if (ranking.NextUrl != null) { API = ranking.NextUrl; } else { if (privateMode || i >= 3) { break; } ; i++; } list.AddRange(ranking.Illusts); } while (list.Count < Properties.Settings.Default.countNum); return(list); }
public void GetErrorResponseHandlersTest() { var request = (Request) Request.CreateRequest( new MockService(), new MockMethod { HttpMethod = "GET", Name = "TestMethod", RestPath = "https://example.com" }); // Confirm that there are no error response handlers by default. CollectionAssert.IsEmpty(request.GetErrorResponseHandlers()); // Confirm that a standard authenticator won't result in an error response handler. request.WithAuthentication(new MockAuthenticator()); CollectionAssert.IsEmpty(request.GetErrorResponseHandlers()); // Confirm that an error handling response handler will change the enumeration var auth = new MockErrorHandlingAuthenticator(); request.WithAuthentication(auth); CollectionAssert.AreEqual(new IErrorResponseHandler[] { auth }, request.GetErrorResponseHandlers()); }
public void CreateRequestOnRequestContentLengthTest() { var service = new MockService(); var request = (Request) Request.CreateRequest( service, new MockMethod { HttpMethod = "POST", Name = "TestMethod", RestPath = "https://example.com/test", }); request.WithParameters(""); HttpWebRequest webRequest = (HttpWebRequest)request.CreateWebRequest((r) => { }); // Test that the header is set, even if no body is specified. Assert.AreEqual("POST", webRequest.Method); Assert.AreEqual(0, webRequest.ContentLength); // The content-length field will be automatically set as soon as content is written into the // request stream. We cannot test it here as writing to the request stream requires us to have // a valid connection to the server. }
public void CreateRequestOnRequestTest() { var service = new MockService(); var request = (Request) Request.CreateRequest( service, new MockMethod { HttpMethod = "GET", Name = "TestMethod", RestPath = "https://example.com", Parameters = new Dictionary <string, IParameter> { { "TestParam", null } } }); request.WithParameters(""); HttpWebRequest webRequest = (HttpWebRequest)request.CreateWebRequest((r) => { }); Assert.IsTrue(webRequest.Headers[HttpRequestHeader.ContentType].Contains("charset=utf-8")); Assert.IsNotNull(webRequest); }
public void BuildRequestWithQueryStringTest() { const string query = "required=yes&optionalWithValue=%26test"; var parameterDefinitions = new Dictionary <string, IParameter>(); parameterDefinitions.Add( "required", new MockParameter { Name = "required", IsRequired = true, ParameterType = "query" }); parameterDefinitions.Add( "optionalWithValue", new MockParameter { Name = "optionalWithValue", IsRequired = false, ParameterType = "query" }); var service = new MockService(); // Cast the IRequest to a Request to access internal construction methods. var request = (Request) Request.CreateRequest( service, new MockMethod { HttpMethod = "GET", Name = "TestMethod", RestPath = "https://test.google.com", Parameters = parameterDefinitions }); request.WithParameters(query); var url = request.BuildRequest().RequestUri; // Check that the resulting query string is identical with the input. Assert.AreEqual("?alt=json&" + query, url.Query); }
/// <summary> /// Sends activities to the conversation. /// </summary> /// <param name="turnContext">The context object for the turn.</param> /// <param name="activities">The activities to send.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the activities are successfully sent, the task result contains /// an array of <see cref="ResourceResponse"/> objects containing the IDs that /// the receiving channel assigned to the activities.</remarks> /// <seealso cref="ITurnContext.OnSendActivities(SendActivitiesHandler)"/> public override async Task <ResourceResponse[]> SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } if (activities == null) { throw new ArgumentNullException(nameof(activities)); } if (activities.Length == 0) { throw new ArgumentException("Expecting one or more activities, but the array was empty.", nameof(activities)); } var responses = new ResourceResponse[activities.Length]; /* * NOTE: we're using for here (vs. foreach) because we want to simultaneously index into the * activities array to get the activity to process as well as use that index to assign * the response to the responses array and this is the most cost effective way to do that. */ for (var index = 0; index < activities.Length; index++) { var activity = activities[index]; var response = default(ResourceResponse); _logger.LogInformation($"Sending activity. ReplyToId: {activity.ReplyToId}"); if (activity.Type == ActivityTypesEx.Delay) { // The Activity Schema doesn't have a delay type build in, so it's simulated // here in the Bot. This matches the behavior in the Node connector. var delayMs = (int)activity.Value; await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); // No need to create a response. One will be created below. } else if (activity.Type == ActivityTypesEx.InvokeResponse) { turnContext.TurnState.Add(InvokeReponseKey, activity); // No need to create a response. One will be created below. } else if (activity.Type == ActivityTypes.Trace && activity.ChannelId != "emulator") { // if it is a Trace activity we only send to the channel if it's the emulator. } var baseUrl = activity.ServiceUrl + (activity.ServiceUrl.EndsWith("/") ? string.Empty : "/"); var requestPath = $"{baseUrl}v3/conversations/{activity.Conversation.Id}/activities/{activity.Id}"; var requestBody = JsonConvert.SerializeObject(activity, SerializationSettings.BotSchemaSerializationSettings); var serverResponse = await server.SendAsync(Request.CreateRequest(Request.POST, requestPath, new StringContent(requestBody, System.Text.Encoding.UTF8))).ConfigureAwait(false); response = serverResponse.ReadBodyAsJson <ResourceResponse>(); // If No response is set, then defult to a "simple" response. This can't really be done // above, as there are cases where the ReplyTo/SendTo methods will also return null // (See below) so the check has to happen here. // Note: In addition to the Invoke / Delay / Activity cases, this code also applies // with Skype and Teams with regards to typing events. When sending a typing event in // these _channels they do not return a RequestResponse which causes the bot to blow up. // https://github.com/Microsoft/botbuilder-dotnet/issues/460 // bug report : https://github.com/Microsoft/botbuilder-dotnet/issues/465 if (response == null) { response = new ResourceResponse(activity.Id ?? string.Empty); } responses[index] = response; } return(responses); }
public void BuildRequestUrlWithDefaultedParameters() { var parameterDefinitions = new Dictionary <string, IParameter>(); parameterDefinitions.Add( "required", new MockParameter { Name = "required", IsRequired = true, ParameterType = "query" }); parameterDefinitions.Add( "optionalWithValue", new MockParameter { Name = "optionalWithValue", IsRequired = false, ParameterType = "query", DefaultValue = "DoesNotDisplay" }); parameterDefinitions.Add( "optionalWithNull", new MockParameter { Name = "optionalWithNull", IsRequired = false, ParameterType = "query", DefaultValue = "c" }); parameterDefinitions.Add( "optionalWithEmpty", new MockParameter { Name = "optionalWithEmpty", IsRequired = false, ParameterType = "query", DefaultValue = "d" }); parameterDefinitions.Add( "optionalNotPressent", new MockParameter { Name = "optionalNotPressent", IsRequired = false, ParameterType = "query", DefaultValue = "DoesNotDisplay" }); var parameterValues = new SortedDictionary <string, string>(); parameterValues.Add("required", "a"); parameterValues.Add("optionalWithValue", "b"); parameterValues.Add("optionalWithNull", null); parameterValues.Add("optionalWithEmpty", ""); var service = new MockService(); var request = (Request) Request.CreateRequest( service, new MockMethod { HttpMethod = "GET", Name = "TestMethod", RestPath = "https://example.com", Parameters = parameterDefinitions }); request.WithParameters(parameterValues); var url = request.BuildRequest().RequestUri; Assert.AreEqual( "https://example.com/?alt=json&optionalWithEmpty=d&" + "optionalWithNull=c&optionalWithValue=b&required=a", url.AbsoluteUri); }
public void BuildRequestUrlWithDefaultedParameters() { var parameterDefinitions = new Dictionary <string, IParameter>(); parameterDefinitions.Add( "required", new MockParameter { Name = "required", IsRequired = true, ParameterType = "query" }); parameterDefinitions.Add( "optionalWithValue", new MockParameter { Name = "optionalWithValue", IsRequired = false, ParameterType = "query", DefaultValue = "DoesNotDisplay" }); parameterDefinitions.Add( "optionalWithValue2", new MockParameter { Name = "optionalWithValue", IsRequired = false, ParameterType = "query", DefaultValue = "DoesNotDisplay" }); parameterDefinitions.Add( "optionalWithNull", new MockParameter { Name = "optionalWithNull", IsRequired = false, ParameterType = "query", DefaultValue = "c" }); parameterDefinitions.Add( "optionalWithEmpty", new MockParameter { Name = "optionalWithEmpty", IsRequired = false, ParameterType = "query", DefaultValue = "d" }); parameterDefinitions.Add( "optionalNotPressent", new MockParameter { Name = "optionalNotPressent", IsRequired = false, ParameterType = "query", DefaultValue = "DoesNotDisplay" }); var parameterValues = new SortedDictionary <string, string>(); // requierd paramter, will be added to query parameterValues.Add("required", "a"); // different from default, will be added to query parameterValues.Add("optionalWithValue", "b"); // set default value, will not be added to query parameterValues.Add("optionalWithValue2", "DoesNotDisplay"); // null value, will not be added to query parameterValues.Add("optionalWithNull", null); // different from default, "" and not "d", will be added to query parameterValues.Add("optionalWithEmpty", ""); var service = new MockClientService(); var request = (Request) Request.CreateRequest( service, new MockClientServiceRequest { HttpMethod = "GET", MethodName = "TestMethod", RestPath = "https://example.com", RequestParameters = parameterDefinitions }); request.WithParameters(parameterValues); var url = request.BuildRequest().RequestUri; Assert.AreEqual( "https://example.com/?" + "optionalWithEmpty&optionalWithValue=b&required=a", url.AbsoluteUri); }