public void SetVersion(string version) { base.Version = version; DictionaryUtil.Add(Headers, "x-acs-version", version); }
public void AddPathParameters(string name, string value) { DictionaryUtil.Add(PathParameters, name, value); }
private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token) { if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) { var instanceDiscoveryService = new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel); var agentUUID = Guid.NewGuid().ToString("N"); var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var hostName = Dns.GetHostName(); var osInfo = new OSInfo { Hostname = hostName, OsName = PlatformInformation.GetOSName(), ProcessNo = Process.GetCurrentProcess().Id }; osInfo.Ipv4S.AddRange(GetIpV4S(hostName)); var applicationInstance = new ApplicationInstance { ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId, AgentUUID = agentUUID, RegisterTime = registerTime, Osinfo = osInfo }; var retry = 0; var applicationInstanceId = 0; while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId)) { var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance); applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId; if (!DictionaryUtil.IsNull(applicationInstanceId)) { break; } await Task.Delay(500, token); } if (!DictionaryUtil.IsNull(applicationInstanceId)) { RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId; _logger.Info( $"Register application instance success. [applicationInstanceId] = {applicationInstanceId}"); } else { _logger.Warning( "Register application instance fail. Server response null."); } } }
public void AddQueryParameters(string name, string value) { DictionaryUtil.Add(queryParameters, name, value); }
public void AddBodyParameters(string name, string value) { DictionaryUtil.Add(bodyParameters, name, value); }
public static HttpWebRequest GetWebRequest(HttpRequest request) { var uri = new Uri(request.Url); var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); httpWebRequest.Proxy = request.WebProxy; httpWebRequest.Method = request.Method.ToString(); httpWebRequest.KeepAlive = true; httpWebRequest.Timeout = request.ConnectTimeout > 0 ? request.ConnectTimeout : DEFAULT_CONNECT_TIMEOUT_In_MilliSeconds; httpWebRequest.ReadWriteTimeout = request.ReadTimeout > 0 ? request.ReadTimeout : DEFAULT_READ_TIMEOUT_IN_MilliSeconds; if (request.IgnoreCertificate) { httpWebRequest.ServerCertificateValidationCallback = (s, cert, chains, sslPolicyError) => true; } if (DictionaryUtil.Get(request.Headers, "Accept") != null) { httpWebRequest.Accept = DictionaryUtil.Pop(request.Headers, "Accept"); } if (DictionaryUtil.Get(request.Headers, "Date") != null) { var headerDate = DictionaryUtil.Pop(request.Headers, "Date"); httpWebRequest.Date = Convert.ToDateTime(headerDate); } foreach (var header in request.Headers) { if (header.Key.Equals("Content-Length")) { httpWebRequest.ContentLength = long.Parse(header.Value); continue; } if (header.Key.Equals("Content-Type")) { httpWebRequest.ContentType = header.Value; continue; } if (header.Key.Equals("User-Agent")) { httpWebRequest.UserAgent = header.Value; continue; } httpWebRequest.Headers.Add(header.Key, header.Value); } if ((request.Method == MethodType.POST || request.Method == MethodType.PUT) && request.Content != null) { using (var stream = httpWebRequest.GetRequestStream()) { stream.Write(request.Content, 0, request.Content.Length); } } return(httpWebRequest); }
/// <summary> /// <inheritdoc cref="DictionaryUtil.SortDictionary{Tkey, Tvalue}(IDictionary{Tkey, Tvalue}, bool)"/> /// </summary> /// <typeparam name="TKey">键值对的键</typeparam> /// <typeparam name="TValue">键值对的值</typeparam> /// <param name="dictionary">要排序的键值对</param> /// <param name="sortByValue">是否根据值进行排序<para>为true时按照Value排序,否则按照Key排序</para></param> /// <returns></returns> public static IList <KeyValuePair <TKey, TValue> > Sort <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, bool sortByValue = true) where TValue : struct { return(DictionaryUtil.SortDictionary <TKey, TValue>(dictionary, sortByValue)); }
public virtual HttpResponse DoAction <T>(AcsRequest <T> request, bool autoRetry, int maxRetryNumber, string regionId, AlibabaCloudCredentials credentials, Signer signer, FormatType?format, List <Endpoint> endpoints) where T : AcsResponse { var httpStatusCode = ""; var retryAttemptTimes = 0; ClientException exception; RetryPolicyContext retryPolicyContext; do { try { var watch = Stopwatch.StartNew(); FormatType?requestFormatType = request.AcceptFormat; format = requestFormatType; var domain = request.ProductDomain ?? Endpoint.FindProductDomain(regionId, request.Product, endpoints); if (null == domain) { throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access."); } var userAgent = UserAgent.Resolve(request.GetSysUserAgentConfig(), userAgentConfig); DictionaryUtil.Add(request.Headers, "User-Agent", userAgent); DictionaryUtil.Add(request.Headers, "x-acs-version", request.Version); if (!string.IsNullOrWhiteSpace(request.ActionName)) { DictionaryUtil.Add(request.Headers, "x-acs-action", request.ActionName); } var httpRequest = request.SignRequest(signer, credentials, format, domain); ResolveTimeout(httpRequest, request.Product, request.Version, request.ActionName); SetHttpsInsecure(IgnoreCertificate); ResolveProxy(httpRequest, request); var response = GetResponse(httpRequest); httpStatusCode = response.Status.ToString(); PrintHttpDebugMsg(request, response); watch.Stop(); CommonLog.ExecuteTime = watch.ElapsedMilliseconds; return(response); } catch (ClientException ex) { retryPolicyContext = new RetryPolicyContext(ex, httpStatusCode, retryAttemptTimes, request.Product, request.Version, request.ActionName, RetryCondition.BlankStatus); CommonLog.LogException(ex, ex.ErrorCode, ex.ErrorMessage); exception = ex; } Thread.Sleep(retryPolicy.GetDelayTimeBeforeNextRetry(retryPolicyContext)); } while ((retryPolicy.ShouldRetry(retryPolicyContext) & RetryCondition.NoRetry) != RetryCondition.NoRetry); if (exception != null) { CommonLog.LogException(exception, exception.ErrorCode, exception.ErrorMessage); throw new ClientException(exception.ErrorCode, exception.ErrorMessage); } return(null); }
public void Add(string key, object value) { DictionaryUtil.Add(QueryParameters, key, value); }
public AcsRequest(String product) : base(null) { DictionaryUtil.Add(Headers, "x-sdk-client", "Net/2.0.0"); Product = product; }
public AcsRequest(string product) : base(null) { DictionaryUtil.Add(Headers, "x-sdk-client", "Net/2.0.0"); DictionaryUtil.Add(Headers, "x-sdk-invoke-type", "normal"); Product = product; }
/// <summary> /// Geography Information Retrieval (WHAT - REL - WHERE) /// Analyze input query to 3 different phases of What - Relation - Where /// </summary> /// <param name="inputQuery">inputQuery</param> public async Task GIRQueryAnalyzerAsync(string inputQuery) { string what = string.Empty; // What phrase string tempWhat = string.Empty; // Temporary value for What phrase string relation = string.Empty; // Relation word string tempRelation = string.Empty; // Temporary value for Relation word string where = string.Empty; // Where phrase string tempWhere = string.Empty; // Temporary value for Where phrase bool isComplete = false; // Indicate if the process is complete or not // Remove redundant white space between words in inputquery inputQuery = Regex.Replace(inputQuery, @"\s+", " "); // Create a list of tokens List <string> tokens = StringUtil.StringTokenizer(inputQuery); int sizeOfTokens = tokens.Count(); // Load relation word dictionary List <string> wordDic = await DictionaryUtil.LoadRelationWordAsync(); // Load list of cities List <City> cityList = await LocationUtil.LoadCityAsync(); // Load list of districts List <District> districtList = await LocationUtil.LoadAllDistrictAsync(); // Check if the lists are load successfully if ((wordDic == null) && (cityList == null) && (districtList == null)) { return; } what = StringUtil.ConcatTokens(tokens, 0, sizeOfTokens - 1); // Check every token in the list for (int n = 0; n < sizeOfTokens; n++) { for (int i = n; i < sizeOfTokens; i++) { // Concate tokens to create a string with the original starting // word is the first token, and this word is shift to left one index every n loop // if relaton word is not found. // New tokens is add to original token every i loop to check for valid relation word tempRelation = StringUtil.ConcatTokens(tokens, n, i); // Check if token string is matched with relation word in database if (IsValidRelationWord(tempRelation, wordDic)) { // If it matches, assign temporary What phrase value with // the value of leading words before Relation word tempWhat = inputQuery.Substring(0, inputQuery.IndexOf(tempRelation) - 1); // Assign Where phrase value with the value of trailing // words after Relation word where = StringUtil.ConcatTokens(tokens, i + 1, sizeOfTokens - 1).Trim().ToLower(); // Check if Where phrase is matched with locaitons in database // and handle Where phrase to locate exactly search locations if (IsValidWherePhrase(where, cityList, districtList)) { // Change status of isComplete varialbe isComplete = true; // If matches, assign Relation word is with the value // of temporary relation relation = tempRelation; // Assign n value again to break the outside loop n = sizeOfTokens; break; } // Assign Relation word with the value of temporary relation // every i loop relation = tempRelation; } } } // Check if the process is completely finished if (!isComplete) { // Handle query in case of input string is not well-formed // with Relation word and Where phrase is not found. // Auto check Where phrase with the first location value in input query, // if Where phrase is valid, auto assign Relation word with default value. if (string.IsNullOrEmpty(relation) && string.IsNullOrEmpty(where)) { int i = 0; // Take first location in input query string // and handle Where phrase (if any) to locate exactly search locations string firstLocation = TakeFirstLocationInQueryString(inputQuery, cityList, districtList); if (!string.IsNullOrEmpty(firstLocation)) { i = inputQuery.IndexOf(firstLocation.ToLower()); tempWhat = inputQuery.Substring(0, i); if (string.IsNullOrEmpty(tempWhat)) { where = firstLocation; if (firstLocation.Length != inputQuery.Length) { tempWhat = inputQuery.Substring(firstLocation.Length).Trim().ToLower(); } } else { where = inputQuery.Substring(i).Trim().ToLower(); } } else { tempWhat = what; relation = string.Empty; where = string.Empty; } } } // Make sure What phrase have the value. // At the worst case if the input query is not well-formed, // assign What phrase with the input query if (!string.IsNullOrEmpty(tempWhat)) { what = tempWhat.Trim().ToLower(); } // Check if What phrase is equal to Where phrase if (what.Equals(where)) { what = string.Empty; } string a = string.Format("[{0}][{1}][{2}]", what, relation, where); int hospitalId = this.HospitalID; string hospitalName = this.HospitalName; int cityId = this.CityID; string cityName = this.CityName; int districtId = this.DistrictID; string districtName = this.DistrictName; int specialityId = this.SpecialityID; string speacialityName = this.SpecialityName; int diseaseId = this.DiseaseID; string diseaseName = this.DiseaseName; this.WhatPhrase = what; }
public void WhenNullCollectionThenShouldThrowException() { Assert.ThrowsException <ArgumentNullException>(() => DictionaryUtil.ToDictionaryList <int, int>(null, ks => ks)); }
public override void OnSuccess(WWW www) { Dictionary <string, object> plist = Plist.readPlist(DESUtil.Decrypt(www.bytes, FileUtil.sKey)) as Dictionary <string, object>; _sgAds = DictionaryUtil.GetDictionaryValue(plist, "Data", "SGAds"); List <object> InterstitialAds = DictionaryUtil.GetListValue(_sgAds, "InterstitialAds"); Dictionary <string, object> v1 = InterstitialAds [0] as Dictionary <string, object>; Debug.Log("InterstitialAdConfig ..... OnSuccess"); InterstitialAdLoader interstitialAdLoader = new InterstitialAdLoader(DictionaryUtil.GetStringValue(v1, "", IMAGE_URL), DictionaryUtil.GetStringValue(v1, "", APP_NAME), DictionaryUtil.GetStringValue(v1, "", APP_URL)); isOn = true; interstitialAdLoader.StartLoader(); Dictionary <string, object> BannerAds = DictionaryUtil.GetDictionaryValue(_sgAds, BANNER_ADS); iconsImageLoader = new SimpleZipDownloader(DictionaryUtil.GetStringValue(BannerAds, "", ICONS_URL), OnIconsLoad, false); iconsImageLoader.StartLoader(); _bannerInfos = DictionaryUtil.GetListValue(BannerAds, APPS_INFO); }
private void OnLayersListChanging() { base.AllowReorder = false; this.layersAndItemsBeforeChanging = this.layers.Select <Layer, KeyValuePair <Layer, VerticalImageStrip.Item> >(l => new KeyValuePair <Layer, VerticalImageStrip.Item>(l, this.layerToItemMap[l])).ToArrayEx <KeyValuePair <Layer, VerticalImageStrip.Item> >(); this.renderSlotsBeforeChanging = DictionaryUtil.From <Layer, double>(this.layersAndItemsBeforeChanging.Select <KeyValuePair <Layer, VerticalImageStrip.Item>, Layer>(kv => kv.Key), this.layersAndItemsBeforeChanging.Select <KeyValuePair <Layer, VerticalImageStrip.Item>, double>(kv => kv.Value.RenderSlot.Value)); }
/// <summary> /// Re-scanns all the media queries on demand /// </summary> /// <exception cref="Exception"></exception> public void Rescan() { _methodInfos = new Dictionary <string, MethodInfo>(); _queries = new Dictionary <string, MediaQuery>(); /*foreach (Type type in GlobalTypeDictionary.Instance.Values) * { * if (typeof(MediaQueryBase).IsAssignableFrom(type) && typeof(MediaQueryBase) != type) * { * MediaQueryBase query = (MediaQueryBase)Activator.CreateInstance(type); * _queries[query.Id] = query; * } * }*/ var queries = GuiReflector.GetMethodsInAllLoadedTypesDecoratedWith(typeof(MediaQueryAttribute)); #if DEBUG if (DebugMode) { Debug.Log(string.Format(@"Found {0} media queries", queries.Count)); } #endif foreach (var methodInfo in queries) { if (null == methodInfo.ReturnParameter || methodInfo.ReturnType != typeof(bool)) { throw new Exception(@"Method decorated with MediaQuery attribute should return a boolean value: " + methodInfo); } var p = methodInfo.GetParameters(); var parameters = new List <Type>(); foreach (var parameterInfo in p) { parameters.Add(parameterInfo.ParameterType); } // get attribute var attributes = CoreReflector.GetMethodAttributes <MediaQueryAttribute>(methodInfo); if (attributes.Count == 0) { throw new Exception(@"Cannot find MediaQuery attribute: " + methodInfo); } var attribute = attributes[0]; /** * If there is already an existing query with a same ID, allow overriding * only if this is an editor override. This way we'll get all the editor overrides * override the Play mode media queries. * */ if (_methodInfos.ContainsKey(attribute.Id) && !attribute.EditorOverride) { continue; } _methodInfos[attribute.Id] = methodInfo; MediaQuery query; if (parameters.Count > 0) { var type = parameters[0]; query = (MediaQuery)NameValueBase.CreateProperty <MediaQuery>(attribute.Id, type); //query.Value = type. } else { query = new MediaQuery { Name = attribute.Id, Parameters = parameters.ToArray() }; } _queries[attribute.Id] = query; } #if DEBUG if (DebugMode) { Debug.Log(string.Format(@"Number of queries after overrides: {0}", _queries.Keys.Count)); } #endif #if DEBUG if (DebugMode) { Debug.Log(string.Format(@"Retrieved {0} media queries: {1}", _queries.Count, DictionaryUtil <string, MediaQuery> .Format(_queries))); } #endif }