void SetService(ApiType api) { if (TranslationService == null) { if (api == ApiType.Google) { TranslationService = new GoogleApi.GoogleTranslator(); } else if (api == ApiType.Microsoft) { TranslationService = new MicrosoftApi.MicrosoftTranslator(); } else if (api == ApiType.Amazon) { TranslationService = new AmazonApi.AmazonTranslator(); } else if (api == ApiType.IBM) { TranslationService = new IBMApi.IBMTranslator(); } else { throw new InvalidOperationException($"Invalid API type: {api}"); } } }
private Update(int tenantId, ApiType api, string matterNumber) { TenantId = tenantId; Api = api; MatterNumber = matterNumber; Timestamp = DateTime.UtcNow; }
private static CosmosHttpClient CreateHelper( HttpClient httpClient, HttpMessageHandler httpMessageHandler, TimeSpan requestTimeout, UserAgentContainer userAgentContainer, ApiType apiType, ICommunicationEventSource eventSource) { if (httpClient == null) { throw new ArgumentNullException(nameof(httpClient)); } httpClient.Timeout = requestTimeout > CosmosHttpClientCore.GatewayRequestTimeout ? requestTimeout : CosmosHttpClientCore.GatewayRequestTimeout; httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true }; httpClient.AddUserAgentHeader(userAgentContainer); httpClient.AddApiTypeHeader(apiType); // Set requested API version header that can be used for // version enforcement. httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Version, HttpConstants.Versions.CurrentVersion); httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Accept, RuntimeConstants.MediaTypes.Json); return(new CosmosHttpClientCore( httpClient, httpMessageHandler, eventSource)); }
private static void WriteMembers(TextWriter writer, ApiType t) { foreach (var item in t.Fields) { writer.WriteLine("\t\t\t\t\t\t" + item); } foreach (var item in t.Properties) { writer.WriteLine("\t\t\t\t\t\t" + item); } foreach (var item in t.Events) { writer.WriteLine("\t\t\t\t\t\t" + item); } foreach (var item in t.Constructors) { writer.WriteLine("\t\t\t\t\t\t" + item); } foreach (var item in t.Methods) { writer.WriteLine("\t\t\t\t\t\t" + item); } foreach (var item in t.NestedClasses) { writer.WriteLine("\t\t\t\t\t\t" + item); } foreach (var item in t.OtherMembers) { writer.WriteLine("\t\t\t\t\t\t" + item); } }
public async Task <IResponse> SendCustomBytesRequest(HttpMethod method, ApiType type, string path, byte[] file) { if (string.IsNullOrEmpty(path)) { return(new ErrorResponse(400, "The request endpoint can't be empty.")); } string Url = type == ApiType.Fluxpoint ? "" : "https://gallery.fluxpoint.dev/api"; try { HttpRequestMessage Req = new HttpRequestMessage(method, path[0] == '/' ? Url + path : Url + '/' + path); Req.Content = new ByteArrayContent(file); HttpResponseMessage Res = await Client.SendAsync(Req).ConfigureAwait(false); Res.EnsureSuccessStatusCode(); string Message = await Res.Content.ReadAsStringAsync().ConfigureAwait(false); return(JsonConvert.DeserializeObject <IResponse>(Message)); } catch (Exception ex) { return(new IResponse(400, ex.Message)); } }
public async Task <T> SendRequest <T>(HttpType method, ApiType type, string path) where T : IResponse { if (string.IsNullOrEmpty(path)) { return(new ErrorResponse(400, "The request endpoint can't be empty.") as T); } string Url = type == ApiType.Fluxpoint ? "" : "https://gallery.fluxpoint.dev/api"; try { HttpMethod mt = HttpMethod.Get; if (method == HttpType.Post) { mt = HttpMethod.Post; } HttpRequestMessage Req = new HttpRequestMessage(mt, path[0] == '/' ? Url + path : Url + '/' + path); HttpResponseMessage Res = await Client.SendAsync(Req).ConfigureAwait(false); Stream Stream = await Res.Content.ReadAsStreamAsync().ConfigureAwait(false); using (TextReader text = new StreamReader(Stream)) using (JsonReader reader = new JsonTextReader(text)) { return(Json.Deserialize <T>(reader)); } } catch (Exception ex) { return(new ErrorResponse(400, ex.Message) as T); } }
public JsonResult GetRecentResponses([FromBody] string selectedApiType) { ApiType apiType = (ApiType)Enum.Parse(typeof(ApiType), selectedApiType); if (apiType == ApiType.WeboxAppApi) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Constants.StorageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(Constants.WeboxAppApiHooksContainer); BlobContinuationToken continuationToken = null; List <Hook> receivedHooks = new List <Hook>(); do { var response = container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, new int?(), continuationToken, null, null); continuationToken = response.Result.ContinuationToken; foreach (var blob in response.Result.Results.OfType <CloudBlockBlob>()) { var blobData = blob.DownloadTextAsync().Result; receivedHooks.Add(JsonConvert.DeserializeObject <Hook>(blobData)); } } while (continuationToken != null); List <ReceviedResponseModel> receviedResponses = MapResponseToHoks(receivedHooks); if (receviedResponses != null && receviedResponses.Count > 0) { receviedResponses = receviedResponses.OrderByDescending(eachResponse => eachResponse.ReceivedAt).ToList <ReceviedResponseModel>(); } return(Json(receviedResponses)); } else if (apiType == ApiType.ChatApi) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Constants.StorageConnectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(Constants.ChatApiHooksContainer); BlobContinuationToken continuationToken = null; List <WhatsAppDemo.ApiContracts.ChatApi.Hook> receivedHooks = new List <WhatsAppDemo.ApiContracts.ChatApi.Hook>(); do { var response = container.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.None, new int?(), continuationToken, null, null); continuationToken = response.Result.ContinuationToken; foreach (var blob in response.Result.Results.OfType <CloudBlockBlob>()) { var blobData = blob.DownloadTextAsync().Result; receivedHooks.Add(JsonConvert.DeserializeObject <WhatsAppDemo.ApiContracts.ChatApi.Hook>(JsonConvert.DeserializeObject <string>(blobData))); } } while (continuationToken != null); List <ReceviedResponseModel> receviedResponses = MapResponseToHoks(receivedHooks); if (receviedResponses != null && receviedResponses.Count > 0) { receviedResponses = receviedResponses.OrderByDescending(eachResponse => eachResponse.ReceivedAt).ToList <ReceviedResponseModel>(); } return(Json(receviedResponses)); } return(null); }
public override int GetHashCode() { int hash = 1; if (ApiType != global::Envoy.Api.V2.Core.ApiConfigSource.Types.ApiType.UnsupportedRestLegacy) { hash ^= ApiType.GetHashCode(); } hash ^= clusterNames_.GetHashCode(); hash ^= grpcServices_.GetHashCode(); if (refreshDelay_ != null) { hash ^= RefreshDelay.GetHashCode(); } if (requestTimeout_ != null) { hash ^= RequestTimeout.GetHashCode(); } if (rateLimitSettings_ != null) { hash ^= RateLimitSettings.GetHashCode(); } if (SetNodeOnFirstMessageOnly != false) { hash ^= SetNodeOnFirstMessageOnly.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
public XApi GetXApi(ApiType type) { switch (type) { case ApiType.Trade: return(_TdApi); case ApiType.MarketData: return(_MdApi); case ApiType.Level2: return(_L2Api); case ApiType.HistoricalData: return(_HdApi); case ApiType.Instrument: return(_ItApi); case ApiType.Query: return(_QueryApi); default: return(null); } }
public async Task <JObject> SendCustomRequest(HttpMethod method, ApiType type, string path) { if (string.IsNullOrEmpty(path)) { return(JsonConvert.DeserializeObject <JObject>(JsonConvert.SerializeObject(new IResponse(400, "The request endpoint can't be empty.")))); } string Url = type == ApiType.Fluxpoint ? "" : "https://gallery.fluxpoint.dev/api"; try { HttpRequestMessage Req = new HttpRequestMessage(method, path[0] == '/' ? Url + path : Url + '/' + path); HttpResponseMessage Res = await Client.SendAsync(Req).ConfigureAwait(false); string Message = await Res.Content.ReadAsStringAsync().ConfigureAwait(false); JObject response = (JObject)JsonConvert.DeserializeObject(Message); if (response == null) { return(JsonConvert.DeserializeObject <JObject>(JsonConvert.SerializeObject(new IResponse(500, "Could not parse json response")))); } return(response); } catch (Exception ex) { return(JsonConvert.DeserializeObject <JObject>(JsonConvert.SerializeObject(new IResponse(400, ex.Message)))); } }
public T GetData <T>(ApiType api, UrlType type, string sortBy = "", int?numResults = null, int?resultOffset = null) where T : class { if (numResults.HasValue) { parameters.Add("numResults", numResults.Value.ToString()); } if (resultOffset.HasValue) { parameters.Add("resultOffset", resultOffset.Value.ToString()); } if (sortBy == "DESC") { parameters.Add("sortBy", sortBy); } requestUrl = string.Concat(string.Format(ApiUrl, api.ToDescriptionString(), type.ToDescriptionString()), parameters.ToQueryString(true)); var xmlString = PostRequest(); if (string.IsNullOrEmpty(xmlString)) { return(default(T)); } T response; using (var reader = new StringReader(xmlString)) { var serializer = new XmlSerializer(typeof(T)); response = serializer.Deserialize(reader) as T; } return(response); }
/// <summary> /// Toggles any 'media player' associated with a particular Kml type represented by a tree node. /// So far this includes KmlTours (GETourPlayer) and KmlPhotoOverlays (GEPhotoOverlayViewer) /// </summary> /// <param name="ge">The plug-in instance</param> /// <param name="feature">The feature to check</param> /// <param name="visible">Value indicating whether the player should be visible or not.</param> public static void ToggleMediaPlayer(dynamic ge, dynamic feature, bool visible = true) { if (!IsGE(ge)) { throw new ArgumentException("ge is not of the type GEPlugin"); } ApiType type = GEHelpers.GetApiType(feature); if (visible) { if (type == ApiType.KmlTour) { ge.setBalloon(null); ge.getTourPlayer().setTour(feature); } else if (type == ApiType.KmlPhotoOverlay) { ge.getPhotoOverlayViewer().setPhotoOverlay(feature); } } else { if (type == ApiType.KmlTour) { ge.getTourPlayer().setTour(null); } else if (type == ApiType.KmlPhotoOverlay) { ge.getPhotoOverlayViewer().setPhotoOverlay(null); } } }
public void TestUrlResolution() { // Test we can get an endpoint from a single resolver correctly when the service exists, and when it doesn't const string serviceName = "test-service-for-url"; const string serviceEndpoint = "http://localhost:5000/"; // note the final slash, this should be removed const string route = "/my-route"; const ApiVersion apiVersion = ApiVersion.V2; const ApiType apiType = ApiType.Private; var queryParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("test1", "%#$%^%"), new KeyValuePair <string, string>("parameter2", "just-a-normal-value") }; const string expectedUrl = "http://localhost:5000/internal/v2/my-route?test1=%25%23%24%25%5E%25¶meter2=just-a-normal-value"; var mockServiceResolver = new MockServiceResolver(ServiceResultType.Configuration, 0); // Register our service mockServiceResolver.ServiceMap[serviceName] = serviceEndpoint; serviceCollection.AddSingleton <IServiceResolver>(mockServiceResolver); var resolver = serviceCollection.BuildServiceProvider().GetService <IServiceResolution>(); Assert.NotNull(resolver); var url = resolver.ResolveRemoteServiceEndpoint(serviceName, apiType, apiVersion, route, queryParams).Result; Assert.Equal(expectedUrl, url); }
public GatewayStoreModel( GlobalEndpointManager endpointManager, ISessionContainer sessionContainer, TimeSpan requestTimeout, ConsistencyLevel defaultConsistencyLevel, DocumentClientEventSource eventSource, JsonSerializerSettings serializerSettings, UserAgentContainer userAgent, ApiType apiType, Func <HttpClient> httpClientFactory) : this(endpointManager, sessionContainer, defaultConsistencyLevel, eventSource) { HttpClient httpClient = httpClientFactory(); if (httpClient == null) { throw new InvalidOperationException("HttpClientFactory did not produce an HttpClient"); } this.InitializeGatewayStoreClient( requestTimeout, serializerSettings, userAgent, apiType, httpClient); }
protected Signature(Signature s) { Type = s.Type; Arguments = s.Arguments; ReturnType = s.ReturnType; ReturnValueIsConst = s.ReturnValueIsConst; }
public override int GetHashCode() { int hash = 1; if (HasDescriptorName) { hash ^= DescriptorName.GetHashCode(); } if (HasVersion) { hash ^= Version.GetHashCode(); } if (HasShardName) { hash ^= ShardName.GetHashCode(); } if (HasResolveClientInstance) { hash ^= ResolveClientInstance.GetHashCode(); } if (HasType) { hash ^= Type.GetHashCode(); } if (HasApiType) { hash ^= ApiType.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
private void InitializeGatewayStoreClient( TimeSpan requestTimeout, JsonSerializerSettings serializerSettings, UserAgentContainer userAgent, ApiType apiType, HttpClient httpClient) { // Use max of client specified and our own request timeout value when sending // requests to gateway. Otherwise, we will have gateway's transient // error hiding retries are of no use. httpClient.Timeout = (requestTimeout > this.requestTimeout) ? requestTimeout : this.requestTimeout; httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true }; httpClient.AddUserAgentHeader(userAgent); httpClient.AddApiTypeHeader(apiType); // Set requested API version header that can be used for // version enforcement. httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Version, HttpConstants.Versions.CurrentVersion); httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Accept, RuntimeConstants.MediaTypes.Json); this.gatewayStoreClient = new GatewayStoreClient( httpClient, this.eventSource, serializerSettings); }
public ApiClientFactory( string developerToken, IAuthenticationTokenFactory authTokenFactory, long?customerId = null, long?customerAccountId = null, ApiEnvironment apiEnvironment = ApiEnvironment.Production, ApiType apiType = ApiType.V13) { if (string.IsNullOrWhiteSpace(developerToken)) { throw new ArgumentNullException(nameof(developerToken)); } if (authTokenFactory == null) { throw new ArgumentNullException(nameof(authTokenFactory)); } this.apiType = apiType; this.apiEnvironment = apiEnvironment; this.authTokenFactory = authTokenFactory; this.authDataTemplate = new AuthData() { DeveloperToken = developerToken, CustomerId = customerId?.ToString(), CustomerAccountId = customerAccountId?.ToString(), HeaderNamespace = Config.HeaderNamespace[apiEnvironment] }; }
public void AddType(ApiType t) { foreach (var m in t.ParserMatches) { apiTypes.Add(m, t); } }
internal MockDocumentClient( Uri serviceEndpoint, string authKeyOrResourceToken, EventHandler <SendingRequestEventArgs> sendingRequestEventArgs, ConnectionPolicy connectionPolicy = null, Documents.ConsistencyLevel?desiredConsistencyLevel = null, JsonSerializerSettings serializerSettings = null, ApiType apitype = ApiType.None, EventHandler <ReceivedResponseEventArgs> receivedResponseEventArgs = null, Func <TransportClient, TransportClient> transportClientHandlerFactory = null) : base(serviceEndpoint, authKeyOrResourceToken, sendingRequestEventArgs, connectionPolicy, desiredConsistencyLevel, serializerSettings, apitype, receivedResponseEventArgs, null, null, true, transportClientHandlerFactory) { this.Init(); }
protected Signature(Signature s) { Type = s.Type; Parameters = s.Parameters; ReturnType = s.ReturnType; ReturnValueIsConst = s.ReturnValueIsConst; }
private T Execute <T>(ApiType apiType, IRestRequest request) where T : new() { IRestResponse <T> response; if (apiType == ApiType.Base) { response = _restClient.Execute <T>(request); if (response.StatusCode != HttpStatusCode.OK) { throw new DropboxRestException(response, HttpStatusCode.OK); } } else if (apiType == ApiType.Content) { response = _restClientContent.Execute <T>(request); if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.PartialContent) { throw new DropboxRestException(response, HttpStatusCode.OK, HttpStatusCode.PartialContent); } } else { response = _restClientNotify.Execute <T>(request); if (response.StatusCode != HttpStatusCode.OK) { throw new DropboxRestException(response); } } return(response.Data); }
public AuthQuery(ApiType forApi) { switch (forApi) { case ApiType.Mal: Request = WebRequest.Create( Uri.EscapeUriString("http://myanimelist.net/api/account/verify_credentials.xml")); Request.Credentials = Credentials.GetHttpCreditentials(); Request.Method = "GET"; break; case ApiType.Hummingbird: Request = WebRequest.Create( Uri.EscapeUriString( $"https://hummingbird.me/api/v1/users/authenticate?{Credentials.GetHummingbirdCredentialChain()}")); Request.ContentType = "application/x-www-form-urlencoded"; Request.Method = "POST"; break; default: throw new ArgumentOutOfRangeException(); } }
public GatewayAddressCache( Uri serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, IServiceConfigurationReader serviceConfigReader, long suboptimalPartitionForceRefreshIntervalInSeconds = 600, HttpMessageHandler messageHandler = null, ApiType apiType = ApiType.None) { this.addressEndpoint = new Uri(serviceEndpoint + "/" + Paths.AddressPathSegment); this.protocol = protocol; this.tokenProvider = tokenProvider; this.serviceEndpoint = serviceEndpoint; this.serviceConfigReader = serviceConfigReader; this.serverPartitionAddressCache = new AsyncCache <PartitionKeyRangeIdentity, PartitionAddressInformation>(); this.suboptimalServerPartitionTimestamps = new ConcurrentDictionary <PartitionKeyRangeIdentity, DateTime>(); this.suboptimalMasterPartitionTimestamp = DateTime.MaxValue; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.httpClient = messageHandler == null ? new HttpClient() : new HttpClient(messageHandler); this.protocolFilter = string.Format(CultureInfo.InvariantCulture, GatewayAddressCache.protocolFilterFormat, Constants.Properties.Protocol, GatewayAddressCache.ProtocolString(this.protocol)); // Set requested API version header for version enforcement. this.httpClient.DefaultRequestHeaders.Add(HttpConstants.HttpHeaders.Version, HttpConstants.Versions.CurrentVersion); this.httpClient.AddUserAgentHeader(userAgent); this.httpClient.AddApiTypeHeader(apiType); }
public void TestExplicitUrlResolution() { // Test we can get an endpoint from a single resolver correctly when the service exists, and when it doesn't const string serviceName = "test-service-for-url"; const string serviceConfigurationKey = "test-service-for-url_public_v2"; // Modified to include the api type and version const string serviceEndpoint = "http://localhost:5023/test-endpoint/rewritten/for/simplicity/v1.99/"; // Something like a TPaaS URL which doesn't match our naming convention const string route = "/explicit-route"; const ApiVersion apiVersion = ApiVersion.V2; const ApiType apiType = ApiType.Public; const string expectedUrl = "http://localhost:5023/test-endpoint/rewritten/for/simplicity/v1.99/explicit-route"; var mockServiceResolver = new MockServiceResolver(ServiceResultType.Configuration, 0); // Register our service, using the new config key which clear describes the exact endpoint (so no generation occurs in our logic) mockServiceResolver.ServiceMap[serviceConfigurationKey] = serviceEndpoint; serviceCollection.AddSingleton <IServiceResolver>(mockServiceResolver); var resolver = serviceCollection.BuildServiceProvider().GetService <IServiceResolution>(); Assert.NotNull(resolver); var url = resolver.ResolveRemoteServiceEndpoint(serviceName, apiType, apiVersion, route).Result; Assert.Equal(expectedUrl, url); }
public bool Update(ApiType apiType, long?refId) { var data = Find(apiType, refId); data.LastRun = DateTime.Now; return(Save()); }
/// <summary> /// 初始化 <see cref="CQPSimulator"/> 类的新实例 /// </summary> /// <param name="cqpType">初始化新模拟器的类型</param> public CQPSimulator(CQPType cqpType, ApiType apiType) { #region 初始化数据池 this.CQPApps = new List <CQPSimulatorApp> (); this.DataPool = new CQPSimulatorDataPool().Generate(); Logger.Instance.InfoSuccess(CQPErrorCode.TYPE_INIT, $"已加载 {this.DataPool.QQCollection.Count} 个QQ、{this.DataPool.FriendCollection.Count} 个好友、{this.DataPool.GroupCollection.Count} 个群、{this.DataPool.DiscussCollection.Count} 个讨论组"); #endregion #region 初始化目录 string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; this.AppDirectory = Path.Combine(baseDirectory, "app"); // app 目录 this.DevDirectory = Path.Combine(baseDirectory, "dev"); // dev 目录 this.DataDirectory = Path.Combine(baseDirectory, "data"); // data 目录 this.ConfDirectory = Path.Combine(baseDirectory, "conf"); // conf 目录 this.BinDirectory = Path.Combine(baseDirectory, "bin"); // bin 目录 Directory.CreateDirectory(this.AppDirectory); Directory.CreateDirectory(this.DevDirectory); Directory.CreateDirectory(this.DataDirectory); Directory.CreateDirectory(this.ConfDirectory); Directory.CreateDirectory(this.BinDirectory); this.DataAppDirectory = Path.Combine(this.DataDirectory, "app"); // data/app 目录 this.DataBfaceDirectory = Path.Combine(this.DataDirectory, "bface"); // data/bface 目录 this.DataShowDirectory = Path.Combine(this.DataDirectory, "show"); // data/show 目录 this.DataImageDirectory = Path.Combine(this.DataDirectory, "image"); // data/image 目录 this.DataRecordDirectory = Path.Combine(this.DataDirectory, "record"); // data/record 目录 this.DataLogDirectory = Path.Combine(this.DataDirectory, "log"); // data/log 目录 this.DataTmpDirectory = Path.Combine(this.DataDirectory, "tmp"); // data/tmp 目录 Directory.CreateDirectory(this.DataAppDirectory); Directory.CreateDirectory(this.DataBfaceDirectory); Directory.CreateDirectory(this.DataImageDirectory); Directory.CreateDirectory(this.DataRecordDirectory); Directory.CreateDirectory(this.DataLogDirectory); Directory.CreateDirectory(this.DataTmpDirectory); this.AppRunTimeDirectory = Path.Combine(this.DataTmpDirectory, "capp"); // data/tmp/capp 目录 Directory.CreateDirectory(this.AppRunTimeDirectory); Logger.Instance.InfoSuccess(CQPErrorCode.TYPE_INIT, "已创建数据目录"); #endregion #region 初始化版本 this.CQPType = cqpType; this.ApiType = apiType; Logger.Instance.InfoSuccess(CQPErrorCode.TYPE_INIT, $"{cqpType.GetDescription ()}, {apiType.GetDescription ()}"); #endregion #region 初始化任务队列 this._taskSource = new CancellationTokenSource(); this._taskProcess = new Task(this.ProcessTask, this._taskSource.Token); this._taskContexts = new ConcurrentQueue <TaskContext> (); // 任务表达式 TaskExpressions.Add(new GroupMessageExpression(this)); Logger.Instance.InfoSuccess(CQPErrorCode.TYPE_INIT, $"已创建任务队列"); #endregion #region 设置服务 // 设置 CQExport 服务 CQPExport.Instance.FuncProcess = this; #endregion }
private IRestResponse Execute(ApiType apiType, IRestRequest request) { IRestResponse response; if (apiType == ApiType.Base) { response = _restClient.Execute(request); if (response.StatusCode != HttpStatusCode.OK) { throw new DropboxException(response); } } else { response = _restClientContent.Execute(request); if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.PartialContent) { throw new DropboxException(response); } } return(response); }
public static CosmosHttpClient CreateWithConnectionPolicy( ApiType apiType, ICommunicationEventSource eventSource, ConnectionPolicy connectionPolicy, HttpMessageHandler httpMessageHandler, EventHandler <SendingRequestEventArgs> sendingRequestEventArgs, EventHandler <ReceivedResponseEventArgs> receivedResponseEventArgs) { if (connectionPolicy == null) { throw new ArgumentNullException(nameof(connectionPolicy)); } Func <HttpClient> httpClientFactory = connectionPolicy.HttpClientFactory; if (httpClientFactory != null) { if (sendingRequestEventArgs != null && receivedResponseEventArgs != null) { throw new InvalidOperationException($"{nameof(connectionPolicy.HttpClientFactory)} can not be set at the same time as {nameof(sendingRequestEventArgs)} or {nameof(ReceivedResponseEventArgs)}"); } HttpClient userHttpClient = httpClientFactory.Invoke() ?? throw new ArgumentNullException($"{nameof(httpClientFactory)} returned null. {nameof(httpClientFactory)} must return a HttpClient instance."); return(CosmosHttpClientCore.CreateHelper( httpClient: userHttpClient, httpMessageHandler: httpMessageHandler, requestTimeout: connectionPolicy.RequestTimeout, userAgentContainer: connectionPolicy.UserAgentContainer, apiType: apiType, eventSource: eventSource)); } if (httpMessageHandler == null) { httpMessageHandler = CosmosHttpClientCore.CreateHttpClientHandler( gatewayModeMaxConnectionLimit: connectionPolicy.MaxConnectionLimit, webProxy: null); } if (sendingRequestEventArgs != null || receivedResponseEventArgs != null) { httpMessageHandler = CosmosHttpClientCore.CreateHttpMessageHandler( httpMessageHandler, sendingRequestEventArgs, receivedResponseEventArgs); } HttpClient httpClient = new HttpClient(httpMessageHandler); return(CosmosHttpClientCore.CreateHelper( httpClient: httpClient, httpMessageHandler: httpMessageHandler, requestTimeout: connectionPolicy.RequestTimeout, userAgentContainer: connectionPolicy.UserAgentContainer, apiType: apiType, eventSource: eventSource)); }
public Argument(Parser.ArgumentData ad, ApiTypeBuilder api, int index) { this.ArgumentType = api.GetApiType(ad.ArgumentType, ad.IsConst); this.VarName = ad.Var; this.Index = index; this.IsConst = ad.IsConst; this.IsThisArgument = this.VarName.Equals("self"); }
public static void Update(string name, string passwd, ApiType type) { PasswordVault.Reset(); UserName = name; Password = passwd; if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(passwd)) PasswordVault.Add(new VaultCredential((type == ApiType.Mal ? "MALClient" : "MALClientHum"), UserName, Password)); }
public void Init(string comPort, ApiType apiType = ApiType.EnabledWithEscaped) { if (m_FirstTime) { m_XBee = new XBee(comPort, m_BaudRate, apiType); m_XBee.FrameReceived += new FrameReceivedEventHandler(m_XBee_FrameReceived); m_FirstTime = false; //m_XBee2 = new XBee("COM10", m_BaudRate, apiType); //m_XBee2.FrameReceived += new FrameReceivedEventHandler(m_XBee_FrameReceived2); //m_XBee2.Open(); } }
private static string GetBaseUrl(ApiType apiType) { switch (apiType) { case ApiType.Base: return ApiBaseUrl; case ApiType.Content: return ApiContentBaseUrl; case ApiType.Notify: return ApiNotifyBaseUrl; default: throw new ArgumentOutOfRangeException("apiType"); } }
public Argument([NotNull] string type, int index, int total, string namespaceHint) { Name = total > 1 ? $"arg{index + 1}" : @"arg"; if (type.Contains(' ')) { var parts = type.Split(' '); Type = new ApiType(parts[0], namespaceHint); Name = parts[1]; } else { Type = new ApiType(type, namespaceHint); } }
/// <summary> /// Initializes a new dictionary that represent the tuples for the REST-api request /// </summary> /// <param name="_apiType">The type of the api request</param> /// <param name="_keyValuePairs">A list of the key-value pairs</param> private static Dictionary<string, string> PairsDictinaryForApi(ApiType _apiType, params string[] _keyValuePairs) { SetApiType(_apiType); Dictionary<string, string> pairs = new Dictionary<string, string>(); pairs.Add("api", ApiTypeString); pairs.Add("clientKey", clientKey); for (int i = 0; i < _keyValuePairs.Length; i+=2) { pairs.Add(_keyValuePairs[i], _keyValuePairs[i + 1]); } return pairs; }
/// <inheritdoc /> public async Task<AddUserResult> AddUserAsync(string username,string password, InstitutionType institution, AddUserOptions options = null, string pin = null, ApiType api = ApiType.Connect) { Condition.Requires(username).IsNotNullOrWhiteSpace(); Condition.Requires(password).IsNotNullOrWhiteSpace(); Condition.Requires(institution).IsNotNull(); AddUserRequest userRequest = new AddUserRequest(this.clientId, this.clientSecret) { Username = username, Password = password, Type = institution.Value, Options = new AddUserOptionsRequest(options), Pin = pin }; HttpResponseMessage response = await this.httpClient.PostAsJsonAsync(GetEndpoint(api), userRequest); return await this.ProcessAddOrAuthResponse(response); }
/// <summary> /// Change the type of the api request /// </summary> /// <param name="_apiType">The type of the api request</param> private static void SetApiType(ApiType _apiType) { switch (_apiType) { case ApiType.AppLogin: ApiTypeString = "app-login"; break; case ApiType.GetUserData: ApiTypeString = "get-user-data"; break; case ApiType.GetTreatment: ApiTypeString = "get-treatment"; break; case ApiType.GetTraining: ApiTypeString = "get-training"; break; case ApiType.GetExerciseGestures: ApiTypeString = "get-exercise-gestures"; break; case ApiType.ReportExercise: ApiTypeString = "report-treatment-session-usage"; break; case ApiType.GetTreatmentByUser: ApiTypeString = "treatments/get-treatments-by-user"; break; case ApiType.ReportTrainingFeedback: ApiTypeString = "treatments/report-training-feedback"; break; case ApiType.ReportTrainingCompliance: ApiTypeString = "calendar/set-completed-event"; break; } }
public AnimeSearchQuery(string query, ApiType? apiOverride = null) { var targettedApi = apiOverride ?? CurrentApiType; switch (targettedApi) { case ApiType.Mal: Request = WebRequest.Create(Uri.EscapeUriString($"https://myanimelist.net/api/anime/search.xml?q={query}")); Request.Credentials = Credentials.GetHttpCreditentials(); Request.ContentType = "application/x-www-form-urlencoded"; Request.Method = "GET"; break; case ApiType.Hummingbird: Request = WebRequest.Create(Uri.EscapeUriString($"http://hummingbird.me/api/v1/search/anime?query={query}")); Request.ContentType = "application/x-www-form-urlencoded"; Request.Method = "GET"; break; default: throw new ArgumentOutOfRangeException(); } }
public AuthQuery(ApiType forApi) { switch (forApi) { case ApiType.Mal: Request = WebRequest.Create( Uri.EscapeUriString("https://myanimelist.net/api/account/verify_credentials.xml")); Request.Credentials = Credentials.GetHttpCreditentials(); Request.Method = "GET"; break; case ApiType.Hummingbird: Request = WebRequest.Create( Uri.EscapeUriString( $"https://hummingbird.me/api/v1/users/authenticate?{Credentials.GetHummingbirdCredentialChain()}")); Request.ContentType = "application/x-www-form-urlencoded"; Request.Method = "POST"; break; default: throw new ArgumentOutOfRangeException(); } }
public XApi GetXApi(ApiType type) { switch(type) { case ApiType.Trade: return _TdApi; case ApiType.MarketData: return _MdApi; case ApiType.Level2: return _L2Api; case ApiType.HistoricalData: return _HdApi; case ApiType.Instrument: return _ItApi; case ApiType.Query: return _QueryApi; default: return null; } }
/// <summary> /// Internal method to build the full request Url /// </summary> /// <param name="action"></param> /// <param name="apiType"></param> /// <returns></returns> private string MakeRequestString(string action, ApiType apiType) { //TODO - check for / return string.Format("{0}/{1}", apiType == ApiType.Base ? ApiBaseUrl : ApiContentBaseUrl, action); }
public Service(string baseUrl, ApiType aptype ) { this.baseUrl = baseUrl; this.SvcApiType = aptype; Startup(); }
/// <summary> /// Checks if a given <paramref name="feature">feature</paramref> /// is of a given type <paramref name="type">type</paramref> /// </summary> /// <param name="feature">The feature to test</param> /// <param name="type">The type to check</param> /// <returns> /// True if the <paramref name="feature">feature</paramref> /// is the given <paramref name="type">type</paramref> /// </returns> public static bool IsApiType(dynamic feature, ApiType type) { return GetApiType(feature) == type; }
// Gets return type and argument names from example private static Tuple<ApiType, string[]> ParseDetailsFromExample(string messageName, ApiNode example, string owningMessageNamespace) { var blankCleanup1 = new Regex(@"\s+"); var blankCleanup2 = new Regex(@"\s*(\W)\s*"); var exampleText = example.Text; exampleText = blankCleanup1.Replace(exampleText, " "); exampleText = blankCleanup2.Replace(exampleText, "$1"); var jsRegex = new Regex($@"(?:\W|^)function {messageName}\(([^)]*)\)(?::(\w+))?\{{"); var m = jsRegex.Match(exampleText); if (m.Success) { var returnType = new ApiType(m.Groups[2].Value, owningMessageNamespace); var parameters = m.Groups[1].Value.Split(','); var arguments = new string[parameters.Length]; for (var i = 0; i < parameters.Length; ++i) { arguments[i] = parameters[i].Split(':')[0]; } return Tuple.Create(returnType, arguments); } var csRegex = new Regex($@"(\w+) {messageName}\(([^)]*)\)"); m = csRegex.Match(exampleText); if (m.Success) { var nameRegex = new Regex(@"\W(\w+)$"); var returnType = new ApiType(m.Groups[1].Value, owningMessageNamespace); var parameters = m.Groups[2].Value.Split(','); var arguments = new string[parameters.Length]; for (var i = 0; i < parameters.Length; ++i) { arguments[i] = nameRegex.Replace(parameters[i], "$1"); } return Tuple.Create(returnType, arguments); } return null; }
/// <inheritdoc /> public Task<AddUserResult> AuthenticateUserAsync(AccessToken accessToken, string deviceMask, bool isUpdate = false, ApiType api = ApiType.Connect) { Condition.Requires(accessToken).IsNotNull(); Condition.Requires(deviceMask).IsNotNullOrWhiteSpace(); AuthUserRequest authRequest = new AuthUserRequest(this.clientId, this.clientSecret, accessToken); authRequest.Options = new SendMethodRequest(); authRequest.Options.SendMethod = new ExpandoObject(); authRequest.Options.SendMethod.mask = deviceMask; return this.AuthUserInternal(authRequest, api, isUpdate); }
public async Task<AnimeGeneralDetailsData> GetAnimeDetails(bool force, string id, string title, bool animeMode, ApiType? apiOverride = null) { var output = force ? null : await DataCache.RetrieveAnimeSearchResultsData(id, animeMode); if (output != null) return output; var requestedApiType = apiOverride ?? CurrentApiType; try { switch (requestedApiType) { case ApiType.Mal: var data = animeMode ? await new AnimeSearchQuery(Utilities.CleanAnimeTitle(title),requestedApiType).GetRequestResponse(false) : await new MangaSearchQuery(Utilities.CleanAnimeTitle(title)).GetRequestResponse(false); data = WebUtility.HtmlDecode(data); data = data.Replace("&", ""); //unparsable stuff ahaead :( var parsedData = XDocument.Parse(data); var elements = parsedData.Element(animeMode ? "anime" : "manga").Elements("entry"); var xmlObj = elements.First(element => element.Element("id").Value == id); output = new AnimeGeneralDetailsData(); output.ParseXElement(xmlObj, animeMode); DataCache.SaveAnimeSearchResultsData(id, output, animeMode); break; case ApiType.Hummingbird: Request = WebRequest.Create( Uri.EscapeUriString($"https://hummingbird.me/api/v1/anime/{id}")); Request.ContentType = "application/x-www-form-urlencoded"; Request.Method = "GET"; var raw = await GetRequestResponse(); if (string.IsNullOrEmpty(raw)) break; dynamic jsonObj = JsonConvert.DeserializeObject(raw); var allEps = 0; if (jsonObj.episode_count != null) allEps = Convert.ToInt32(jsonObj.episode_count.ToString()); output = new AnimeGeneralDetailsData { Title = jsonObj.title.ToString(), ImgUrl = jsonObj.cover_image.ToString(), Type = jsonObj.show_type.ToString(), Id = Convert.ToInt32(jsonObj.id.ToString()), MalId = Convert.ToInt32(jsonObj.mal_id.ToString()), AllEpisodes = allEps, StartDate = jsonObj.started_airing.ToString(), EndDate = jsonObj.finished_airing.ToString(), Status = jsonObj.status, Synopsis = jsonObj.synopsis, GlobalScore = jsonObj.community_rating, Synonyms = new List<string> { jsonObj.alternate_title.ToString() } }; break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception) { // probably MAl garbled response } return output; }
/// <inheritdoc /> public Task<AddUserResult> AuthenticateUserAsync(AccessToken accessToken, bool isUpdate = false, ApiType api = ApiType.Connect, params string[] mfaValues) { Condition.Requires(accessToken).IsNotNull(); Condition.Requires(mfaValues).IsNotNull().IsNotEmpty(); AuthUserRequest authRequest = new AuthUserRequest(this.clientId, this.clientSecret, accessToken); if (mfaValues.Length == 1) authRequest.MfaValue = mfaValues.FirstOrDefault(); else authRequest.MfaValue = new List<string>(mfaValues); return this.AuthUserInternal(authRequest, api, isUpdate); }
public XBeeDevice(string comPort, ApiType apiType = ApiType.EnabledWithEscaped) { Init(comPort, apiType); }
public ApiParameter(string n, ApiType t) { this.name = n; this.type = t; }
// Open the device with new parameters public bool Open(string comPort, ApiType apiType = ApiType.EnabledWithEscaped) { Init(comPort, apiType); if (m_IsOpen) { m_XBee.Close(); } m_IsOpen = m_XBee.Open(comPort, m_BaudRate); return m_IsOpen; }
/// <summary> /// Internal helper for user auth. /// </summary> private async Task<AddUserResult> AuthUserInternal(AuthUserRequest request, ApiType api, bool isUpdate) { string endpoint = GetEndpoint(api, "step"); HttpResponseMessage response = isUpdate ? await this.httpClient.PatchAsJsonAsync(endpoint, request) : await this.httpClient.PostAsJsonAsync(endpoint, request); return await this.ProcessAddOrAuthResponse(response); }
/// <inheritdoc /> public Task<AddUserResult> AuthenticateUserAsync(AccessToken accessToken, DeliveryType deliveryType, bool isUpdate = false, ApiType api = ApiType.Connect) { Condition.Requires(accessToken).IsNotNull(); Condition.Requires(deliveryType).IsNotNull(); AuthUserRequest authRequest = new AuthUserRequest(this.clientId, this.clientSecret, accessToken); authRequest.Options = new SendMethodRequest(); authRequest.Options.SendMethod = new ExpandoObject(); authRequest.Options.SendMethod.type = deliveryType.Value; return this.AuthUserInternal(authRequest, api, isUpdate); }
/// <summary> /// Internal method to build the full request Url /// </summary> /// <param name="action"></param> /// <param name="apiType"></param> /// <returns></returns> private string MakeRequestString(string action, ApiType apiType) { //TODO - check for / return string.Format("{0}/{1}", GetBaseUrl(apiType), action); }
/// <inheritdoc /> public async Task<PlaidResult<bool>> DeleteUserAsync(AccessToken accessToken, ApiType api = ApiType.Connect) { Condition.Requires(accessToken).IsNotNull(); PlaidRequest deleteRequest = new PlaidRequest(this.clientId, this.clientSecret, accessToken.Value); HttpResponseMessage response = await this.httpClient.DeleteAsJsonAsync(GetEndpoint(api), deleteRequest); PlaidResult<bool> result = new PlaidResult<bool>(response.StatusCode == HttpStatusCode.OK); result.Exception = await this.ParseException(response); return result; }
public UnityApiParameter(string name, ApiType type, string description) { myName = name; myType = type; myDescription = description; }
/// <summary> /// Private helper to get the endpoint for an api. /// </summary> private static string GetEndpoint(ApiType api) { switch (api) { case ApiType.Connect: return "connect"; case ApiType.Auth: return "auth"; } throw new InvalidOperationException("Cannot get endpoint for unknown ApiType: " + api); }
/// <inheritdoc /> public async Task<AddUserResult> UpdateUserAsync(AccessToken accessToken, string username, string password, string pin = null, Uri webhookUri = null, ApiType api = ApiType.Connect) { Condition.Requires(accessToken).IsNotNull(); if ((string.IsNullOrWhiteSpace(username) || password == null) && webhookUri == null) throw new ArgumentException("Username/password required unless only updating webhookUri"); UpdateUserRequest updateRequest = new UpdateUserRequest(this.clientId, this.clientSecret, accessToken.Value); updateRequest.Username = username; updateRequest.Password = password; updateRequest.Pin = pin; if (webhookUri != null) updateRequest.Options = new UpdateUserRequestOptions { Webhook = webhookUri.ToString() }; HttpResponseMessage response = await this.httpClient.PatchAsJsonAsync(GetEndpoint(api), updateRequest); return await this.ProcessAddOrAuthResponse(response); }
// NB this is not the long term approach - will be using hypermedia and HAL to navigate instead of computing urls the way anything relaiant on this currently does // TODO TP 1105 these should be determined by going to an api landing location public string GetApiPrefix( ApiType apiType ) { return IsCloudEnvironment ? _azureApiPrefixes[ apiType ] : _iisApiPrefixes[ apiType ]; }
/// <summary> /// Private helper to get the endpoint for an api. /// </summary> /// <example> /// GetEndpoint(ApiType.Connect, "get") => "connect/get" /// </example> private static string GetEndpoint(ApiType api, string path) { string endpoint = HttpPlaidClient.GetEndpoint(api); return $"{endpoint}/{path}"; }
public UnityApiParameter AddParameter(string name, ApiType type, string description = null) { var parmaeter = new UnityApiParameter(name, type, description); myParameters.Add(parmaeter); return parmaeter; }