protected ApiRepositoryBase(IApiConfiguration configuration, string path = "") { this.ConnectionString = string.Format("{0}://{1}:{2}{3}{4}", configuration.Protocol, configuration.Host, configuration.Port, configuration.Path, path); this.jsonSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, DateTimeZoneHandling = DateTimeZoneHandling.Utc, DateFormatHandling = DateFormatHandling.IsoDateFormat }; this.request = new RESTRequest { Timeout = new TimeSpan(0, 0, 150), UseTransferEncodingChunked = false, SerializationSettings = this.jsonSettings, UseJsonSerialization = true, UseContinueHeader = false }; }
public bool Profile_SetXNML(string api_key, string method, float call_id, string sig, string v, string session_key, int uid, string profile, string profile_action) { AssignRequiredParameters(api_key, session_key, method); if (uid != 0) { parameters.Add("uid", uid.ToString()); } if (!string.IsNullOrEmpty(profile)) { parameters.Add("profile", profile); } if (!string.IsNullOrEmpty(profile_action)) { parameters.Add("profile_action", profile_action); } client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); return(root.Value == "1"); }
public string Request(string command) { var res = new RESTRequest("/command"); res.AddQuery("q", command); return(_client.Execute(res).Content); }
// Use this for initialization public CoffeeMachineActuator(string id, string state, string shortName) : base(id, state, shortName, "Icons/Coffeemaker", "Brew", null) { this.id = id; this.state = state; this.shortName = shortName; request = RESTRequestFactory.createGETRequest(Settings.URL_CoffeeMachine_GET_Brew); }
public DimmerActuator(string id, string state, string shortName) : base(id, state, shortName, "Icons/Dimmer") { this.INCREASErequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, Settings.POST_INCREASE); this.DECREASErequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, Settings.POST_DECREASE); this.ONrequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, Settings.POST_ON); this.OFFrequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, Settings.POST_OFF); }
public friends_getFriends_response Friends_GetFriends(string api_key, string method, string session_key, float call_id, string sig, string v) { AssignRequiredParameters(api_key, session_key, method); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var fgf = new friends_getFriends_response() { list = (bool)root.Attribute("list"), friend = (from fel in root.Elements(ns + "friend") select new friend() { id = (int)fel.Element(ns + "id"), name = (string)fel.Element(ns + "name"), headurl = (string)fel.Element(ns + "headurl"), }).ToArray(), }; return(fgf); }
public invitations_getOsInfo_response Invitations_GetOsInfo(string api_key, string session_key, string method, float call_id, string sig, string v, string invite_ids) { if (string.IsNullOrEmpty(invite_ids)) { throw new ArgumentNullException("invite_ids", "必须指定站外邀请id"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("invite_ids", invite_ids); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var osinfo = new invitations_getOsInfo_response() { os_invitation_infos = (from infoel in root.Elements(ns + "os_invitation_info") select new os_invitation_info() { inviter_uid = (int)infoel.Element(ns + "inviter_uid"), invite_time = (string)infoel.Element(ns + "invite_time"), invitee_uid = (int)infoel.Element(ns + "invitee_uid"), install_time = (string)infoel.Element(ns + "install_time") }).ToArray() }; return(osinfo); }
public bool Feed_PublishTemplatizedAction(string api_key, string method, string session_key, float call_id, string sig, string v, int template_id, string title_data, string body_data, int resource_id) { if (string.IsNullOrEmpty(title_data)) { throw new ArgumentNullException("title_data", "必须指定Feed的标题数据"); } if (string.IsNullOrEmpty(body_data)) { throw new ArgumentNullException("body_data", "必须指定Feed的内容数据"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("template_id", template_id.ToString()); parameters.Add("title_data", title_data); parameters.Add("body_data", body_data); parameters.Add("resource_id", resource_id.ToString()); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); return(root.Value == "1"); }
// GET: /<controller>/ public IActionResult Index(Dictionary <string, string> parameters) { try { logger.LogWarning("Authorization started"); if (!parameters.ContainsKey("code")) { logger.LogDebug("Authorization declined"); return(View("AuthorizationFail")); } string code = parameters["code"]; logger.LogWarning("Code recieved: " + code); dynamic tokenResponse = RESTRequest.PostAsUrlEncodedWithJsonResponse("https://oauth.vk.com/access_token", new Dictionary <string, string>() { { "client_id", "5671241" }, { "client_secret", "7nHh8NwJJeaZrW7juOyZ" }, { "redirect_uri", "http://localhost:56230/VkAuthorization" }, { "code", code } }); string accessToken = tokenResponse.access_token; string userId = tokenResponse.user_id.ToString(); logger.LogWarning("Access token recieved: " + accessToken); HttpContext.Session.SetString("VkAccessToken", accessToken); HttpContext.Session.SetString("VkUserId", userId); return(RedirectToAction("AuthorizationSucceeded", "Status")); } catch (Exception e) { logger.LogError(new EventId(), e, "Error"); return(RedirectToAction("Exception", "Status", new { exception = JsonConvert.SerializeObject(e) })); } }
public async Task PlaceAutocompleteSearchProcessTest_WithRequiredValues() { var httpClient = new HttpClient(); var restService = new RESTRequest <PlacesResponse, Dictionary <string, string> >(httpClient); BusinessResult <SearchPlacesResponse> result = default; try { var request = new SearchPlacesRequest() { ApiKey = Globals.Credentials.PlacesApiKey, //Address = "1600 Amphitheatre Pkwy, Mountain View, CA 94043", Address = "1600 Amphitheatre", PlaceBaseUrl = _baseUrl, OperationId = $"{Guid.NewGuid()}", CancellationToken = CancellationToken.None, }; var searchProcessor = new PlaceAutocompleteSearchProcessor(restService, _logger); result = await searchProcessor.ExecuteAsync(request); _output.WriteLine(JsonConvert.SerializeObject(result)); Assert.NotNull(result); Assert.NotNull(result.Result); Assert.IsType <SearchPlacesResponse>(result.Result); Assert.Empty(result.Error); } catch (Exception ex) { result.Error.Add(new BusinessError(LogLevel.Critical, "test exception", ex, result?.Result?.OperationId)); _output.WriteLine($"{result.Error}"); Assert.True(false); } }
// Use this for initialization public NormalItemActuator(string id, string state, string shortName, string icon, string On = "On", string Off = "Off") : base(id, state, shortName, icon) { this.id = id; this.state = state; this.shortName = shortName; this.ONrequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, Settings.POST_ON); this.OFFrequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, Settings.POST_OFF); }
/// <summary> /// Sends a knowledge query to the server. /// </summary> /// <param name="entity"></param> private void SendKnowledgeQuery(string entity) { Debug.Log("Sending knowledge query for : " + entity); RESTRequest rr = new RESTRequest(HTTPMethod.GET, KnowledgeQueryCallback); rr.AddParameter("entity", entity); StartCoroutine(knowledge.sendRequest(rr)); }
public IEnumerator sendColor(int h, int s, int v) { string color = h + "," + s + "," + v; this.Colorrequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + hueColor.id, color); return(Colorrequest.performAction()); }
public IActionResult Get(int lowerBorder, int upBorder) { try { return(Json(RESTRequest.GetWithJsonResponse <List <Room> >(appSettings.RoomServerUri + $"api/rooms/{lowerBorder}/{upBorder}"))); } catch (Exception e) { return(Json(new { error = "Internal server error", error_description = JsonConvert.SerializeObject(e, Formatting.Indented) })); } }
public string GetMessages(string uri, Args args = null) { var request = new RESTRequest(uri); if (args != null) { foreach (var arg in args) { request.AddQuery(arg.Key, arg.Value + ""); } } return(_client.Execute(request).Content); }
public IActionResult Post(Booking booking) { try { if (!Request.Headers.ContainsKey("access_token")) { return(Unauthorized()); } string token = Request.Headers["access_token"]; var authManager = new AuthorizationManager(); var tokenStatus = authManager.CheckToken(token); if (tokenStatus == TokenStatusesEnum.Invalid) { return(Json(new { error = "Invalid token", error_description = "Given token is invalid" })); } else if (tokenStatus == TokenStatusesEnum.Expired) { return(Json(new { error = "Expired token", error_description = "Given token is expired. Please refresh it." })); } booking.InitId(); var savedBooking = RESTRequest.PostAsJsonWithJsonResponse <Booking>(appSettings.BookingServerUri + "api/bookings", booking); Bill bill = null; try { bill = RESTRequest.PostAsJsonWithJsonResponse <Bill>(appSettings.BillingServerUri + "api/bills", new Bill() { Price = booking.DaysCount * 1500, Requisites = "OOO Sberbank 91929393234923", BookingId = savedBooking.Id }); if (bill == null) { throw new JsonException("Bill remote saving failed"); } } catch (Exception ex) { RESTRequest.DeleteWithJsonResponse <Booking>(appSettings.BookingServerUri + $"api/bookings/{savedBooking.Id}"); throw; } savedBooking.Bill = bill; return(Json(savedBooking)); } catch (Exception e) { return(Json(new { error = "Internal server error", error_description = JsonConvert.SerializeObject(e, Formatting.Indented) })); } }
private void btnSubmitRest_Click(object sender, RoutedEventArgs e) { var request = new RESTRequest { EndPoint = txtboxUrlRest.Text + txtboxParams.Text, Method = dropdownMethod.Text, PostData = txtboxRestRequest.Text, ContentType = contentTypeList.Text, }; var test = TestsController.GetRESTResponse(request, User); txtboxRestResponse.Text = test.Response; timeProcessing_Rest.Text = test.ProcessingTime.ToString(); if (!string.IsNullOrWhiteSpace(key1rest.Text) && (!string.IsNullOrWhiteSpace(value1rest.Text))) { var validare = TestsController.ValidateResponseREST(key1rest.Text, value1rest.Text, test.Response); if (validare == 1) { assert1rest.Background = System.Windows.Media.Brushes.Green; } else if (validare == 0) { assert1rest.Background = System.Windows.Media.Brushes.Red; } else { assert1rest.Background = System.Windows.Media.Brushes.Yellow; } } ; if (!string.IsNullOrWhiteSpace(key2rest.Text) && (!string.IsNullOrWhiteSpace(value2rest.Text))) { var validare = TestsController.ValidateResponseREST(key2rest.Text, value2rest.Text, test.Response); if (validare == 1) { assert2rest.Background = System.Windows.Media.Brushes.Green; } else if (validare == 0) { assert2rest.Background = System.Windows.Media.Brushes.Red; } else { assert2rest.Background = System.Windows.Media.Brushes.Yellow; } } }
/// <summary> /// Submits an image to be indexed by the server. /// </summary> /// <param name="encodedImg">The image to be indexed, encoded as a base 64 string.</param> /// <param name="name">The label to attach to this image.</param> private void SendCapturedImagePostRequest(string encodedImg, string name) { string json = "{\"name\": \"" + name + "\", \"imageData\": \"" + encodedImg + "\"}"; byte[] data = System.Text.UnicodeEncoding.Unicode.GetBytes(json); RESTRequest rr = new RESTRequest(HTTPMethod.POST, data, SubmitCompleteCallback); StartCoroutine(submit.sendRequest(rr)); // // WebClient client = new WebClient(); // client.Headers[HttpRequestHeader.ContentType] = "application/json"; // client.UploadStringCompleted += new UploadStringCompletedEventHandler(SubmitCompleteCallback); // client.UploadStringAsync(submitUri, "POST", json); }
public async Task <ActionResult> PlacesAutocomplete(SearchPlacesRequest request) { BusinessResult <SearchPlacesResponse> response = default; request.ApiKey = Globals.Credentials?.PlacesApiKey; request.PlaceBaseUrl = Globals.Configuration?.PlaceBaseUrl; using (var httpClient = new HttpClient()) { var restService = new RESTRequest <PlacesResponse, Dictionary <string, string> >(httpClient); response = await new PlaceAutocompleteSearchProcessor(restService, _logger).ExecuteAsync(request); } return(new ActionResponse <SearchPlacesResponse>(response, _displayErrors, _logger)); }
static void Main(string[] args) { RESTClient gc = new RESTClient("http://localhost:1234"); //gc.NetworkCredentials = new Grapevine.NetworkCredential("username", "password"); //var cookie = new Grapevine.Cookie("sessionid", "A113"); //gc.Cookies.Add(cookie); var request = new RESTRequest("/user/{id}"); request.AddParameter("id", "1234"); request.Method = Grapevine.HttpMethod.GET; request.ContentType = Grapevine.ContentType.JSON; request.Payload = "{\"key\":\"value\"}"; request.ContentType = Grapevine.ContentType.JSON; request.Payload = "{\"key\":\"value\"}"; var response = gc.Execute(request); }
public friends_areFriends_response Friends_AreFriends(string api_key, string method, string session_key, float call_id, string sig, string v, string uids1, string uids2) { if (string.IsNullOrEmpty(uids1)) { throw new ArgumentNullException("uids1", "必须指定第一组进行比较的用户id"); } if (string.IsNullOrEmpty(uids2)) { throw new ArgumentNullException("uids2", "必须指定第二组进行比较的用户id"); } var ids1 = uids1.Split(','); var ids2 = uids2.Split(','); if (ids1.Length != ids2.Length) { throw new ArgumentException("两组进行比较的用户id数量必须相同", "uids1 or uids2"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("uids1", uids1); parameters.Add("uids2", uids2); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var faf = new friends_areFriends_response() { //list = (bool)root.Attribute("list"), list = true, friend_info = (from fel in root.Elements(ns + "friend_info") select new friend_info() { uid1 = (int)fel.Element(ns + "uid1"), uid2 = (int)fel.Element(ns + "uid2"), are_friends = fel.Element(ns + "are_friends").Value == "1", }).ToArray(), }; return(faf); }
public string Profile_GetXNML(string api_key, string method, float call_id, string sig, string v, string session_key, int uid) { AssignRequiredParameters(api_key, session_key, method); if (uid != 0) { parameters.Add("uid", uid.ToString()); } client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); return(root.Value); }
public users_getLoggedInUser_response Users_GetLoggedInUser(string api_key, string method, string session_key, float call_id, string sig, string v) { AssignRequiredParameters(api_key, session_key, method); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var uservalue = new users_getLoggedInUser_response() { Value = Int32.Parse(root.Value) }; return(uservalue); }
/// <summary> /// Sends a query request to the image search server. /// </summary> /// <param name="encodedImg">A base-64 encoded string of the query image.</param> /// <returns>A string response from the server.</returns> private string SendCapturedImageQuery(string encodedImg) { // Send packet to server containing jpeg bytes - to be reassembled on other side. Debug.Log("Sending img query"); Debug.Log(encodedImg); string json = "{\"name\": \"none\", \"imageData\": \"" + encodedImg + "\"}"; byte[] data = System.Text.UnicodeEncoding.Unicode.GetBytes(json); Debug.Log("Json: " + json); RESTRequest rr = new RESTRequest(HTTPMethod.POST, data, QueryCompleteCallback); StartCoroutine(query.sendRequest(rr)); // WebClient client = new WebClient(); // client.UploadStringCompleted += new UploadStringCompletedEventHandler(QueryCompleteCallback); // client.Headers[HttpRequestHeader.ContentType] = "application/json"; // client.UploadStringAsync(queryUri, "POST", json); return(""); }
public void Notifications_Send(string api_key, string method, string session_key, float call_id, string sig, string v, string to_ids, string notification) { if (string.IsNullOrEmpty(notification)) { throw new ArgumentNullException("notification", "必须指定通知内容"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("to_ids", to_ids); parameters.Add("notification", notification); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); //everything is ok if no error occured. }
public IEnumerator sendDECREASE() { int value; int currentValue; int.TryParse(state, out currentValue); if (currentValue < 10) { value = 0; } else { value = currentValue - 10; } this.DECREASErequest = RESTRequestFactory.createPOSTRequest(Settings.RestBaseURL + id, value.ToString()); return(DECREASErequest.performAction()); }
public friends_get_response Friends_Get(string api_key, string method, string session_key, float call_id, string sig, string v) { AssignRequiredParameters(api_key, session_key, method); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var fidsget = new friends_get_response() { list = (bool)root.Attribute("list"), uid = (from idel in root.Elements(ns + "uid") select Int32.Parse(idel.Value)).ToArray() }; return(fidsget); }
// GET: /<controller>/ public IActionResult Index() { try { if (!HttpContext.Session.Keys.Contains("VkAccessToken") || !HttpContext.Session.Keys.Contains("VkUserId")) { return(RedirectToAction("AuthorizationFail", "Status")); } string accessToken = HttpContext.Session.GetString("VkAccessToken"); string userId = HttpContext.Session.GetString("VkUserId"); dynamic userInfoResponse = RESTRequest.PostAsUrlEncodedWithJsonResponse("https://api.vk.com/method/users.get", new Dictionary <string, string>() { { "access_token", accessToken }, { "v", "5.59" }, { "user_ids", userId }, { "fields", "sex, bdate, photo_100" }, { "name_case", "nom" } }); logger.LogWarning("User info recieved"); VkUserInfo userInfo = new VkUserInfo() { Id = userInfoResponse.response[0].id.ToString(), Name = userInfoResponse.response[0].first_name, Surname = userInfoResponse.response[0].last_name, Sex = userInfoResponse.response[0].sex == 1 ? "Female" : "Male", BirthDate = userInfoResponse.response[0].bdate, PhotoUrl = userInfoResponse.response[0].photo_100 }; return(View("VkUserInfoPage", userInfo)); } catch (Exception e) { logger.LogError(new EventId(), e, "Error"); return(RedirectToAction("Exception", "Status", new { exception = JsonConvert.SerializeObject(e) })); } }
public RESTRequestTest(ITestOutputHelper output) { _output = output; _testInputClass = new InputClass() { Message = "test input" }; _testOutputClass = new OutputClass() { Message = "test output" }; var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(_testOutputClass)) }; var httpMessageHanderStub = new HttpMessageHandlerStub((request, cancellationToken) => Task.FromResult(httpResponseMessage)); _httpClient = new HttpClient(httpMessageHanderStub); _restRequest = new RESTRequest <OutputClass, InputClass>(_httpClient); }
public IActionResult Get(string userLogin) { try { if (!Request.Headers.ContainsKey("access_token")) { return(Unauthorized()); } string token = Request.Headers["access_token"]; var authManager = new AuthorizationManager(); if (!authManager.CheckTokenBelonging(token, userLogin)) { return(Json(new { error = "Invalid token", error_description = "Given token doesn't belong to this user" })); } var tokenStatus = authManager.CheckToken(token); if (tokenStatus == TokenStatusesEnum.Invalid) { return(Json(new { error = "Invalid token", error_description = "Given token is invalid" })); } else if (tokenStatus == TokenStatusesEnum.Expired) { return(Json(new { error = "Expired token", error_description = "Given token is expired. Please refresh it." })); } var bookings = RESTRequest.GetWithJsonResponse <List <Booking> >(appSettings.BookingServerUri + $"api/bookings/{userLogin}"); foreach (var booking in bookings) { booking.Bill = RESTRequest.GetWithJsonResponse <Bill>(appSettings.BillingServerUri + $"api/bills/{booking.Id}"); } return(Json(bookings)); } catch (Exception e) { return(Json(new { error = "Internal server error", error_description = JsonConvert.SerializeObject(e, Formatting.Indented) })); } }