public static IRequest CreateApiRequest(ApiRequestType requestType) { IRequest request = null; switch (requestType) { case ApiRequestType.Evemon: request = new EvemonRequest(); break; case ApiRequestType.History: request = new HistoryRequest(); break; case ApiRequestType.MarketStat: request = new MarketStatRequest(); break; case ApiRequestType.QuickLook: request = new QuickLookRequest(); break; case ApiRequestType.QuickLookOnPath: request = new QuickLookOnPathRequest(); break; case ApiRequestType.Route: request = new RouteRequest(); break; } return(request); }
public static async Task <IResponse> SendRequest(ApiRequestType type, params string[] data) { IApiRequest request; switch (type) { case ApiRequestType.Annotations: request = new AnnotationsApiRequest(); break; case ApiRequestType.Search: request = new SearchApiRequest(); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } var req = await request.SendWebRequest(data); var lyricsData = string.Empty; while (lyricsData == string.Empty) { lyricsData = await GetLyrics(req); } req.Lyrics = lyricsData; return(req); }
public ApiRequest(ApiRequestType requestType) { Stopwatch = new Stopwatch(); RequestType = requestType; Flavor = string.Empty; Status = 200; Message = "OK"; }
public MovieDatabaseApiRequest(string apiKey, ApiRequestType requestType) { _apiKey = apiKey; RequestType = requestType; AddQueryParameter("api_key", _apiKey); }
private long GetMinCallingInterval(ApiRequestType requestType) { switch (requestType) { case ApiRequestType.Timer: return(2000); case ApiRequestType.TimerControlStart: case ApiRequestType.TimerControlStop: return(500); case ApiRequestType.ClockData: return(500); default: // ReSharper disable RedundantCaseLabel case ApiRequestType.Version: case ApiRequestType.ClockPage: case ApiRequestType.Bell: case ApiRequestType.DateTime: case ApiRequestType.System: // ReSharper restore RedundantCaseLabel return(1000); } }
public void CheckRateLimit(ApiRequestType requestType, HttpListenerRequest request) { if (_optionsService.Options.IsApiThrottled) { _requestHistory.Add(GetClientId(request) ?? "unknown client", requestType, _stopwatch.ElapsedMilliseconds); } }
private static UriAttribute GetUriAttribute(ApiRequestType value) { var type = value.GetType(); var name = Enum.GetName(type, value); return(type.GetField(name).GetCustomAttribute <UriAttribute>()); }
public async Task <string> EncodeDecodeAsync(string text, ApiRequestType apiRequestType) { using (var httpClient = new HttpClient()) { DateTime timeBegin = DateTime.UtcNow; httpClient.BaseAddress = new Uri(_mashapeOptions.UrlDecode); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Add(Constants.ApiSettings.HEADER_MASHAPE_X_KEY, _mashapeOptions.XMashapeKey); httpClient.DefaultRequestHeaders.Add(Constants.ApiSettings.HEADER_ACCEPT, Constants.ApiSettings.HEADER_ACCEPT_TEXT_PLAIN); var relativePath = ApiRequestType.Encode == apiRequestType? $"/encode?text={text}" : $"/decode?text={text}"; var response = await httpClient.GetAsync(relativePath); var textResponse = await response.Content.ReadAsStringAsync(); await _apiRequestRepository.AddApiRequestAsync(new Data.Entities.ApiRequest { ApiRequestType = apiRequestType, HttpMethod = Common.HttpMethod.Get, RequestBeginTime = timeBegin, RequestEndTime = DateTime.UtcNow, IsDeleted = false, RequestUrl = response.RequestMessage.RequestUri.ToString(), Error = response.IsSuccessStatusCode ? null : response.ReasonPhrase, ResponseText = textResponse, ResponseCode = (int)response.StatusCode }); return(textResponse); } }
public string GetApiUrl(ApiRequestType urlRequest) { var response = string.Empty; switch (urlRequest) { case ApiRequestType.WorkCreateUrl: response = "api/work/create"; break; case ApiRequestType.WorkSearchUrl: response = "api/work/search"; break; case ApiRequestType.WorkGetUrl: response = "api/work/get"; break; case ApiRequestType.WorkUpdateUrl: response = "api/work/update"; break; case ApiRequestType.WorkDeleteUrl: response = "api/work/delete"; break; } return($"{Settings.BaseUrl}/{response}"); }
public ApiRequest(ApiRequestType requestType) { Stopwatch = new Stopwatch(); RequestType = requestType; Flavor = string.Empty; Status = 200; Message = "OK"; }
/// <summary> /// Creates an API request to execute /// </summary> /// <param name="httpMethod">Http method to use</param> /// <param name="type"><see cref="ApiRequestType"/> of the request</param> /// <param name="request">Actual API call to issue</param> /// <param name="body">Optional body of the request</param> /// <param name="headers">Optional headers for the request</param> public ApiRequest(HttpMethod httpMethod, ApiRequestType type, string request, string body, Dictionary <string, string> headers = null) { HttpMethod = httpMethod; Type = type; Request = request; Body = body; Headers = headers; }
public Object Post(ApiRequestType requestType) { var curUser = _userservice.GetCurrentUser(); if (requestType.RequestType == "currentUserDetail") { return(_userservice.GetCurrentUser()); } return(null); }
internal KayakoApiRequest(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) { this.apiKey = apiKey; this.secretKey = secretKey; this.apiUrl = apiUrl; this.proxy = proxy; this.requestType = requestType; this.ComputeSaltAndSignature(); }
internal KayakoApiRequest(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) { _apiKey = apiKey; _secretKey = secretKey; _apiUrl = apiUrl; _proxy = proxy; _requestType = requestType; ComputeSaltAndSignature(); }
/// <summary> /// Gets the UriString from the attribute <see cref="UriAttribute"/> of the <see cref="ApiRequestType"/> values and replaces path parameters /// </summary> /// <param name="_pathParameters">Path parameters to replace from the <see cref="UriAttribute.UriString"/></param> /// <returns>UriString from the <see cref="UriAttribute"/> with replaced path parameters specified in _pathParameters</returns> public static string GetUriString(this ApiRequestType value, Dictionary <string, string> _pathParameters) { StringBuilder uriStringBuilder = new StringBuilder(value.GetUriString()); foreach (KeyValuePair <string, string> kvp in _pathParameters) { uriStringBuilder.Replace(kvp.Key, kvp.Value); } return(uriStringBuilder.ToString()); }
/// <summary> /// Initializes a new instance of the KayakoRestApi.KayakoService class. /// </summary> /// <param name="apiKey">Api Key.</param> /// <param name="secretKey">Secret Api Key.</param> /// <param name="apiUrl">URL of Kayako REST Api</param> /// <param name="requestType">Determines how the request URL is formed</param> public KayakoClient(string apiKey, string secretKey, string apiUrl, ApiRequestType requestType) { _coreController = new CoreController(apiKey, secretKey, apiUrl, null, requestType); _customFields = new CustomFieldController(apiKey, secretKey, apiUrl, null, requestType); _departments = new DepartmentController(apiKey, secretKey, apiUrl, null, requestType); _knowledgebase = new KnowledgebaseController(apiKey, secretKey, apiUrl, null, requestType); _news = new NewsController(apiKey, secretKey, apiUrl, null, requestType); _staff = new StaffController(apiKey, secretKey, apiUrl, null, requestType); _tickets = new TicketController(apiKey, secretKey, apiUrl, null, requestType); _troubleshooter = new TroubleshooterController(apiKey, secretKey, apiUrl, null, requestType); _users = new UserController(apiKey, secretKey, apiUrl, null, requestType); }
private string GetMethod(ApiRequestType type) { switch (type) { case ApiRequestType.Post: return(HttpMethod.Post.Method); case ApiRequestType.Update: return(HttpMethod.Put.Method); case ApiRequestType.Remove: return(HttpMethod.Delete.Method); default: return(HttpMethod.Get.Method); } }
private static long GetMinCallingInterval(ApiRequestType requestType) { return(requestType switch { ApiRequestType.Timer => 2000, ApiRequestType.TimerControlStart => 500, ApiRequestType.TimerControlStop => 500, ApiRequestType.ClockData => 500, ApiRequestType.Version => 1000, ApiRequestType.ClockPage => 1000, ApiRequestType.Bell => 1000, ApiRequestType.DateTime => 1000, ApiRequestType.System => 1000, _ => 1000 });
private async Task <TModel> GetItemDetailAsync <TModel>(int id) { ApiRequestTypeAttribute attribute = GetAttribute <ApiRequestTypeAttribute>(typeof(TModel)); ApiRequestType requestType = attribute.RequestType; if (!requestType.GetUriString().Contains(Parameters.Id)) { throw new ArgumentException("This Model requires ID."); } MovieDatabaseApiRequest request = new MovieDatabaseApiRequest(_apiKey, requestType); request.AddQueryParameter("language", Settings.CultureInfo.TwoLetterISOLanguageName); request.AddPathParameter(Parameters.Id, id.ToString()); string responseString = await request.GetResponseAsync(); return(JsonConvert.DeserializeObject <TModel>(responseString, _jsonSettings)); }
public string GetApiUrl(ApiRequestType urlRequest) { var response = string.Empty; switch (urlRequest) { case ApiRequestType.PlanetGetUrl: response = "planets/"; break; case ApiRequestType.PlanetSearchUrl: response = "planets/"; break; case ApiRequestType.VehicleSearchUrl: response = "vehicles/"; break; } return($"{AppSettings.BaseUrl}/{response}"); }
public void Add(string clientId, ApiRequestType requestType, long currentStamp) { if (string.IsNullOrEmpty(clientId)) { return; } var key = new ApiClientIdAndRequestType(clientId, requestType); var found = _clientHistory.TryGetValue(key, out var stamp); _clientHistory.AddOrUpdate(key, currentStamp, (keyType, stampType) => currentStamp); if (found) { var minIntervalMillisecs = GetMinCallingInterval(requestType); if (currentStamp - stamp < minIntervalMillisecs) { throw new WebServerException(WebServerErrorCode.Throttled); } } }
private long GetMinCallingInterval(ApiRequestType requestType) { switch (requestType) { case ApiRequestType.Timer: return(2000); case ApiRequestType.TimerControlStart: case ApiRequestType.TimerControlStop: return(500); case ApiRequestType.ClockData: return(500); default: case ApiRequestType.Version: case ApiRequestType.ClockPage: case ApiRequestType.Bell: case ApiRequestType.DateTime: case ApiRequestType.System: return(1000); } }
internal BaseController(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) { Connector = new KayakoApiRequest(apiKey, secretKey, apiUrl, proxy, requestType); }
public string GetRequestPath(ApiRequestType request) { return(request == ApiRequestType.GetCustomers ? "-removed-" : "-removed-"); }
internal KnowledgebaseController(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) : base(apiKey, secretKey, apiUrl, proxy, requestType) { }
internal TroubleshooterController(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) : base(apiKey, secretKey, apiUrl, proxy, requestType) { }
public async Task <TResult> SendAsync <TResult, TModel>(ApiRequestTarget reqTarget, ApiRequestType type, TModel model) { if (IntegrityCheck.IsCompromised) { return(default(TResult)); } // string target, string method, var target = GetTargetUrl(reqTarget); var request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(target, UriKind.Absolute)); var requestData = ""; //request.Accept = "application/json"; if (reqTarget == ApiRequestTarget.Game || reqTarget == ApiRequestTarget.Players) { request.Timeout = 25000; } request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"; request.Method = GetMethod(type); request.CookieContainer = cookieContainer; request.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true; if (authToken != null) { request.Headers["auth-token"] = JsonConvert.SerializeObject(authToken).Base64Encode(); } if (sessionToken != null) { request.Headers["session-token"] = JsonConvert.SerializeObject(sessionToken).Base64Encode(); } if (parameters != null) { var named = parameters.Where(x => !string.IsNullOrEmpty(x.Key)).ToList(); if (model != null) { foreach (var param in named) { request.Headers[param.Key] = param.Value; } } else if (named.Count > 0) { requestData = "{" + string.Join(",", named.Select(x => "\"" + x.Key + "\": " + x.Value)) + "}"; } } if (model != null) { requestData = JsonConvert.SerializeObject(model); } if (!string.IsNullOrEmpty(requestData)) { request.ContentType = "application/json"; request.ContentLength = Encoding.UTF8.GetByteCount(requestData); using (var reqStream = await request.GetRequestStreamAsync()) using (var writer = new StreamWriter(reqStream)) { await writer.WriteAsync(requestData); await writer.FlushAsync(); } } try { using (var response = await request.GetResponseAsync()) using (var resStream = response.GetResponseStream()) using (var reader = new StreamReader(resStream)) { if (((HttpWebResponse)response).StatusCode == HttpStatusCode.Forbidden) { return(default(TResult)); } if (typeof(TResult) == typeof(object)) { return(default(TResult)); } var responseData = await reader.ReadToEndAsync(); return(JsonConvert.DeserializeObject <TResult>(responseData)); } } catch (Exception exc) { return(default(TResult)); } }
public Task <TResult> SendAsync <TResult>(ApiRequestTarget reqTarget, ApiRequestType type) { return(SendAsync <TResult, object>(reqTarget, type, null)); }
internal DepartmentController(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) : base(apiKey, secretKey, apiUrl, proxy, requestType) { }
public Task SendAsync(ApiRequestTarget target, ApiRequestType type) { return(SendAsync <object>(target, type)); }
/// <summary> /// Initializes a new instance of the KayakoRestApi.KayakoService class. /// </summary> /// <param name="apiKey">Api Key.</param> /// <param name="secretKey">Secret Api Key.</param> /// <param name="apiUrl">URL of Kayako REST Api</param> /// <param name="requestType">Determines how the request URL is formed</param> public KayakoClient(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) { _coreController = new CoreController(apiKey, secretKey, apiUrl, proxy, requestType); _customFields = new CustomFieldController(apiKey, secretKey, apiUrl, proxy, requestType); _departments = new DepartmentController(apiKey, secretKey, apiUrl, proxy, requestType); _knowledgebase = new KnowledgebaseController(apiKey, secretKey, apiUrl, proxy, requestType); _news = new NewsController(apiKey, secretKey, apiUrl, proxy, requestType); _staff = new StaffController(apiKey, secretKey, apiUrl, proxy, requestType); _tickets = new TicketController(apiKey, secretKey, apiUrl, proxy, requestType); _troubleshooter = new TroubleshooterController(apiKey, secretKey, apiUrl, proxy, requestType); _users = new UserController(apiKey, secretKey, apiUrl, proxy, requestType); }
public ApiRequest(ApiRequestType apiRequestType) { ApiRequestType = apiRequestType; }
/// <summary> /// Gets the UriString from attribute <see cref="UriAttribute"/> of the <see cref="ApiRequestType"/> values /// </summary> /// <returns>UriString from the <see cref="UriAttribute"/></returns> public static string GetUriString(this ApiRequestType value) { return(GetUriAttribute(value).UriString); }
internal NewsController(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) : base(apiKey, secretKey, apiUrl, proxy, requestType) { }
internal CustomFieldController(string apiKey, string secretKey, string apiUrl, IWebProxy proxy, ApiRequestType requestType) : base(apiKey, secretKey, apiUrl, proxy, requestType) { }
/// <exception cref="DatabaseException"></exception> private async Task ConvertLongIdAsync(object obj, long id, PropertyInfo propertyInfo, ApiRequestType requestType, ChangeDirection direction, string requestId) { if (id < 0) { return; } if (propertyInfo.Name == nameof(ApiResource.Id) && requestType == ApiRequestType.Add && direction == ChangeDirection.ToServer) { _addRequestClientIdDict[requestId].Add(id); propertyInfo.SetValue(obj, -1); return; } long changedId = direction switch { ChangeDirection.ToServer => await _idBarrierRepo.GetServerIdAsync(id).ConfigureAwait(false), ChangeDirection.FromServer => await _idBarrierRepo.GetClientIdAsync(id).ConfigureAwait(false), _ => - 1, }; if (direction == ChangeDirection.FromServer && changedId < 0 && id > 0 && (requestType == ApiRequestType.Get || requestType == ApiRequestType.GetSingle)) { changedId = StaticIdGen.GetId(); await AddServerIdToClientIdAsync(id, changedId).ConfigureAwait(false); } //如果服务器返回Id=-1,即这个数据不是使用Id来作为主键的,客户端实体应该避免使用IdGenEntity propertyInfo.SetValue(obj, changedId); }
/// <summary> /// Specifies a function is an API method /// </summary> /// <param name="MethodName">The name of this method request</param> /// <param name="RequiresValidation">Whether or not this method requires validation (default = false)</param> /// <param name="Type">The type of HTTP request this method expects (default = get)</param> public ApiMethod(string MethodName, bool RequiresValidation = false, ApiRequestType Type = ApiRequestType.GET) { this.MethodName = MethodName.ToUpper(); this.RequiresValidation = RequiresValidation; this.Type = Type; }