示例#1
0
        internal static string BuildCanonicalHeaders(Dictionary <string, string> headers, string prefix)
        {
            List <string> list = new List <string>();
            Dictionary <string, string> fcHeaders = new Dictionary <string, string>();

            foreach (var keypair in headers)
            {
                string lowerKey = keypair.Key.ToLower().Trim();
                if (lowerKey.StartsWith(prefix))
                {
                    list.Add(lowerKey);
                    fcHeaders[lowerKey] = DictUtils.GetDicValue(headers, keypair.Key);
                }
            }

            list.Sort();

            string canonical = string.Empty;

            foreach (string key in list)
            {
                canonical += string.Format("{0}:{1}\n", key, fcHeaders[key]);
            }

            return(canonical);
        }
示例#2
0
        public TeaException(IDictionary dict)
        {
            Dictionary <string, object> dicObj = dict.Keys.Cast <string>().ToDictionary(key => key, key => dict[key]);

            code    = DictUtils.GetDicValue(dicObj, "code").ToSafeString();
            message = DictUtils.GetDicValue(dicObj, "message").ToSafeString();
            object obj = DictUtils.GetDicValue(dicObj, "data");

            if (obj == null)
            {
                return;
            }
            if (typeof(IDictionary).IsAssignableFrom(obj.GetType()))
            {
                IDictionary dicData = (IDictionary)obj;
                data = dicData.Keys.Cast <string>().ToDictionary(key => key, key => dicData[key]);
                return;
            }

            Dictionary <string, object> filedsDict = new Dictionary <string, object>();
            Type type = obj.GetType();

            PropertyInfo[] properties = type.GetProperties();
            for (int i = 0; i < properties.Length; i++)
            {
                PropertyInfo p = properties[i];
                filedsDict.Add(p.Name, p.GetValue(obj));
            }
            data = filedsDict;
        }
示例#3
0
        internal void RefreshAccessToken()
        {
            TeaRequest request = new TeaRequest();

            request.Protocol = "http";
            request.Method   = "POST";
            request.Pathname = "/v2/oauth/token";
            request.Headers  = new Dictionary <string, string>();
            request.Headers.Add("host", GetHost(this.endpoint, this.domainId + ".api.alicloudccp.com"));
            request.Headers.Add("content-type", "application/x-www-form-urlencoded; charset=utf-8");
            request.Headers.Add("date", TimeUtils.GetGMTDate());
            request.Headers.Add("accept", "application/json");
            request.Headers.Add("x-acs-signature-method", "HMAC-SHA1");
            request.Headers.Add("x-acs-signature-version", "1.0");
            string bodyStr = string.Format("grant_type=refresh_token&refresh_token={0}&client_id={1}&client_secret={2}",
                                           this.refreshToken, this.clientId, this.clientSecret);
            MemoryStream stream = new MemoryStream();

            byte[] bytes = Encoding.UTF8.GetBytes(bodyStr);
            stream.Write(bytes, 0, bytes.Length);
            request.Body = stream;
            TeaResponse response = TeaCore.DoAction(request, new Dictionary <string, object>());
            string      body     = TeaCore.GetResponseBody(response);
            Dictionary <string, object> bodyDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(body);

            if (response.StatusCode == 200)
            {
                expireTime   = DictUtils.GetDicValue(bodyDict, "expire_time").ToSafeString();
                accessToken  = DictUtils.GetDicValue(bodyDict, "access_token").ToSafeString();
                refreshToken = DictUtils.GetDicValue(bodyDict, "refresh_token").ToSafeString();
            }
        }
示例#4
0
        internal static string GetSignedStrV1(TeaRequest teaRequest, string canonicalizedResource, string accessKeySecret)
        {
            Dictionary <string, string> temp = new Dictionary <string, string>();

            foreach (var keypair in teaRequest.Headers)
            {
                if (keypair.Key.ToLower().StartsWith("x-oss-"))
                {
                    temp.Add(keypair.Key.ToLower(), keypair.Value);
                }
            }

            Dictionary <string, string> hs = (from dic in temp orderby dic.Key ascending select dic).ToDictionary(p => p.Key, o => o.Value);
            string canonicalizedOSSHeaders = string.Empty;

            foreach (var keypair in hs)
            {
                canonicalizedOSSHeaders += keypair.Key + ":" + keypair.Value + "\n";
            }
            string date        = DictUtils.GetDicValue(teaRequest.Headers, "date");
            string contentType = DictUtils.GetDicValue(teaRequest.Headers, "content-type");
            string contentMd5  = DictUtils.GetDicValue(teaRequest.Headers, "content-md5");
            string signStr     = teaRequest.Method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource;

            System.Diagnostics.Debug.WriteLine(signStr);
            byte[] signData;
            using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName("HMACSHA1") as KeyedHashAlgorithm)
            {
                algorithm.Key = Encoding.UTF8.GetBytes(accessKeySecret);
                signData      = algorithm.ComputeHash(Encoding.UTF8.GetBytes(signStr.ToCharArray()));
            }
            string signedStr = Convert.ToBase64String(signData);

            return(signedStr);
        }
示例#5
0
        internal static string ComposeStringToSign(string method, string path, Dictionary <string, string> headers, Dictionary <string, string> queries)
        {
            string contentMD5  = DictUtils.GetDicValue(headers, "content-md5").ToSafeString(string.Empty);
            string contentType = DictUtils.GetDicValue(headers, "content-type").ToSafeString(string.Empty);
            string date        = DictUtils.GetDicValue(headers, "date").ToSafeString(string.Empty);
            string signHeaders = BuildCanonicalHeaders(headers, "x-fc-");

            //Uri uri = new Uri(path);
            string pathName = HttpUtility.UrlDecode(path);
            string str      = string.Format("{0}\n{1}\n{2}\n{3}\n{4}{5}", method, contentMD5, contentType, date, signHeaders, pathName);

            if (queries != null && queries.Count > 0)
            {
                List <string> sortedKeys = queries.Keys.ToList();
                sortedKeys.Sort();
                List <string> canonicalizedQueryList = new List <string>();
                foreach (string key in sortedKeys)
                {
                    canonicalizedQueryList.Add(PercentEncode(key) + "=" + PercentEncode(queries[key]));
                }
                str += "\n" + string.Join("\n", canonicalizedQueryList);
            }

            return(str);
        }
示例#6
0
        public void Test_GetDicValue()
        {
            Dictionary <string, object> dict = new Dictionary <string, object>();

            dict.Add("testKey", "testValue");
            Assert.Null(DictUtils.GetDicValue(dict, "testNull"));
            Assert.Equal("testValue", DictUtils.GetDicValue(dict, "testKey"));
        }
示例#7
0
 public BaseClient(Dictionary <string, object> config)
 {
     _regionId  = DictUtils.GetDicValue(config, "regionId").ToSafeString();
     _protocol  = DictUtils.GetDicValue(config, "protocol").ToSafeString();
     _domain    = DictUtils.GetDicValue(config, "domain").ToSafeString();
     _token     = DictUtils.GetDicValue(config, "token").ToSafeString();
     _appKey    = DictUtils.GetDicValue(config, "appKey").ToSafeString();
     _appSecret = DictUtils.GetDicValue(config, "appSecret").ToSafeString();
 }
示例#8
0
        protected string _getSpecialValue(object obj, string key)
        {
            Dictionary <string, string> ditc;

            string jsonStr = JsonConvert.SerializeObject(obj);

            ditc = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonStr);
            return(DictUtils.GetDicValue(ditc, key));
        }
示例#9
0
        public static string GetContentType(string filePath)
        {
            string type = Utils.MimeMapping.GetMimeMapping(filePath);

            if (string.IsNullOrWhiteSpace(type))
            {
                type = DictUtils.GetDicValue(StaticConst.extToMimeType, Path.GetExtension(filePath).ToLower());
            }
            return(type);
        }
示例#10
0
 protected bool _hasError(Dictionary <string, object> body)
 {
     if (null == body)
     {
         return(true);
     }
     if (null == DictUtils.GetDicValue(body, "Code"))
     {
         return(false);
     }
     return(true);
 }
示例#11
0
        protected void SetCredential(Dictionary <string, object> config)
        {
            Configuration credentialConfig = new Configuration()
            {
                AccessKeyId     = DictUtils.GetDicValue(config, "accessKeyId").ToSafeString(),
                AccessKeySecret = DictUtils.GetDicValue(config, "accessKeySecret").ToSafeString(),
                SecurityToken   = DictUtils.GetDicValue(config, "securityToken").ToSafeString(),
                Type            = DictUtils.GetDicValue(config, "type").ToSafeString()
            };

            if (string.IsNullOrWhiteSpace(credentialConfig.Type))
            {
                credentialConfig.Type = AuthConstant.AccessKey;
            }
            credential = new Credential(credentialConfig);
        }
示例#12
0
 public RPCClient(Dictionary <string, object> config)
 {
     _domain           = DictUtils.GetDicValue(config, "domain").ToSafeString();
     _endpoint         = DictUtils.GetDicValue(config, "endpoint").ToSafeString();
     _authToken        = DictUtils.GetDicValue(config, "authToken").ToSafeString();
     _accessKeyId      = DictUtils.GetDicValue(config, "accessKeyId").ToSafeString();
     _accessKeySecret  = DictUtils.GetDicValue(config, "accessKeySecret").ToSafeString();
     _userAgent        = DictUtils.GetDicValue(config, "userAgent").ToSafeString();
     _regionId         = DictUtils.GetDicValue(config, "regionId").ToSafeString();
     _readTimeout      = DictUtils.GetDicValue(config, "readTimeout").ToSafeInt();
     _connectTimeout   = DictUtils.GetDicValue(config, "connectTimeout").ToSafeInt();
     _httpProxy        = DictUtils.GetDicValue(config, "httpProxy").ToSafeString();
     _httpsProxy       = DictUtils.GetDicValue(config, "httpsProxy").ToSafeString();
     _noProxy          = DictUtils.GetDicValue(config, "noProxy").ToSafeString();
     _maxIdleConns     = DictUtils.GetDicValue(config, "maxIdleConns").ToSafeInt();
     _endpointType     = DictUtils.GetDicValue(config, "endpointType").ToSafeString();
     _defaultUserAgent = GetDefaultUserAgent();
 }
示例#13
0
        internal static HttpRequestMessage GetRequestMessage(TeaRequest request, Dictionary <string, object> runtimeOptions, out int timeout)
        {
            var url = ComposeUrl(request);
            HttpRequestMessage req = new HttpRequestMessage();

            req.Method     = HttpUtils.GetHttpMethod(request.Method);
            req.RequestUri = new Uri(url);
            timeout        = 100000;
            int readTimeout    = DictUtils.GetDicValue(runtimeOptions, "readTimeout").ToSafeInt(0);
            int connectTimeout = DictUtils.GetDicValue(runtimeOptions, "connectTimeout").ToSafeInt(0);

            if (readTimeout != 0 || connectTimeout != 0)
            {
                timeout = readTimeout + connectTimeout;
            }

            if (request.Body != null)
            {
                Stream requestStream = new MemoryStream();
                request.Body.Position = 0;

                byte[] buffer = new byte[4096];
                int    bytesRead;
                while ((bytesRead = request.Body.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                requestStream.Position = 0;
                StreamContent streamContent = new StreamContent(requestStream);
                req.Content = streamContent;
            }

            foreach (var header in request.Headers)
            {
                req.Headers.TryAddWithoutValidation(header.Key, header.Value);
                if (header.Key.ToLower().StartsWith("content-") && req.Content != null)
                {
                    req.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            return(req);
        }
示例#14
0
        public static string ComposeUrl(TeaRequest request)
        {
            var urlBuilder = new StringBuilder("");

            urlBuilder.Append(TeaConverter.StrToLower(request.Protocol)).Append("://");
            urlBuilder.Append(DictUtils.GetDicValue(request.Headers, "host"));
            if (request.Port > 0)
            {
                urlBuilder.Append(":");
                urlBuilder.Append(request.Port);
            }
            urlBuilder.Append(request.Pathname);

            if (request.Query != null && request.Query.Count > 0)
            {
                if (urlBuilder.ToString().Contains("?"))
                {
                    if (!urlBuilder.ToString().EndsWith("&"))
                    {
                        urlBuilder.Append("&");
                    }
                }
                else
                {
                    urlBuilder.Append("?");
                }
                foreach (var entry in request.Query)
                {
                    var key = entry.Key;
                    var val = entry.Value;
                    if (val == null)
                    {
                        continue;
                    }
                    urlBuilder.Append(PercentEncode(key));
                    urlBuilder.Append("=");
                    urlBuilder.Append(PercentEncode(val));
                    urlBuilder.Append("&");
                }
            }
            return(urlBuilder.ToString().TrimEnd('?').TrimEnd('&'));
        }
示例#15
0
        protected string _getSignature(TeaRequest request)
        {
            string signedHeader = BaseUtils.GetSignedHeader(request);
            string url          = BaseUtils.BuildUrl(request);
            string date         = DictUtils.GetDicValue(request.Headers, "date").ToSafeString();
            string accept       = DictUtils.GetDicValue(request.Headers, "accept").ToSafeString();
            string contentType  = DictUtils.GetDicValue(request.Headers, "content-type").ToSafeString();
            string contentMd5   = DictUtils.GetDicValue(request.Headers, "content-md5").ToSafeString();
            string signStr      = request.Method + "\n" + accept + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + signedHeader + "\n" + url;

            byte[] signData;
            using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName("HMACSHA256") as KeyedHashAlgorithm)
            {
                algorithm.Key = Encoding.UTF8.GetBytes(_appSecret);
                signData      = algorithm.ComputeHash(Encoding.UTF8.GetBytes(signStr.ToCharArray()));
            }
            string signedStr = Convert.ToBase64String(signData);

            return(signedStr);
        }
示例#16
0
        public BaseClient(Dictionary <string, object> config)
        {
            _regionId         = DictUtils.GetDicValue(config, "regionId").ToSafeString();
            _protocol         = DictUtils.GetDicValue(config, "protocol").ToSafeString();
            _endpoint         = DictUtils.GetDicValue(config, "endpoint").ToSafeString();
            _signatureVersion = DictUtils.GetDicValue(config, "signatureVersion").ToSafeString();
            _hostModel        = DictUtils.GetDicValue(config, "hostModel").ToSafeString();
            _isEnableMD5      = DictUtils.GetDicValue(config, "isEnableMD5").ToSafeBool();
            _isEnableCrc      = DictUtils.GetDicValue(config, "isEnableCrc").ToSafeBool();
            _readTimeout      = DictUtils.GetDicValue(config, "readTimeout").ToSafeInt32();
            _connectTimeout   = DictUtils.GetDicValue(config, "connectTimeout").ToSafeInt32();
            _localAddr        = DictUtils.GetDicValue(config, "localAddr").ToSafeString();
            _httpProxy        = DictUtils.GetDicValue(config, "httpProxy").ToSafeString();
            _httpsProxy       = DictUtils.GetDicValue(config, "httpsProxy").ToSafeString();
            _noProxy          = DictUtils.GetDicValue(config, "noProxy").ToSafeString();
            _socks5Proxy      = DictUtils.GetDicValue(config, "socks5Proxy").ToSafeString();
            _socks5NetWork    = DictUtils.GetDicValue(config, "socks5NetWork").ToSafeString();
            _maxIdleConns     = DictUtils.GetDicValue(config, "maxIdleConns").ToSafeInt32();
            AddtionalHeaders  = (List <string>)DictUtils.GetDicValue(config, "addtionalHeaders");
            _config           = config;
            _defaultUserAgent = GetDefaultUserAgent();

            SetCredential(config);
        }
示例#17
0
 private int GetMemory(int index)
 {
     return(DictUtils.GetFromDict(_memory, index, 0));
 }
示例#18
0
 public int GetVariable(string name)
 {
     return(DictUtils.GetFromDict(_variables, name, 0));
 }
示例#19
0
 MoneyState GetMoney(Country country)
 {
     return(DictUtils.GetOrCreate(country, _moneyStates, () => new MoneyState()));
 }
示例#20
0
 ArmyState GetArmy(Country country)
 {
     return(DictUtils.GetOrCreate(country, _armyStates, () => CreateState(country.Kind)));
 }
示例#21
0
 public Engineer Get(EngineerId id) => DictUtils.GetOrDefault(_units, id);
示例#22
0
 PopulationState GetPopulation(Country country)
 {
     return(DictUtils.GetOrCreate(country, _populationStates, () => CreateState(country.Kind)));
 }
示例#23
0
 Dictionary <Location, bool> GetCountryState(Country country)
 {
     return(DictUtils.GetOrCreate(country, _discoveredStates, () => new Dictionary <Location, bool>()));
 }
示例#24
0
        private void ProcessMcaFile()
        {
            Dictionary <string, List <int> > badTips = new Dictionary <string, List <int> >();

            timetableFilenameDict.TryGetValue("mca", out var filename);
            return;

            if (!string.IsNullOrWhiteSpace(filename))
            {
                using (var fileStream = File.OpenRead(filename))
                    using (var streamReader = new StreamReader(fileStream))
                    {
                        string   line;
                        int      linenumber = 0;
                        TrainRun onerun     = null;
                        while ((line = streamReader.ReadLine()) != null)
                        {
                            if (line.Length == 80 && line[0] == 'L')
                            {
                                if (onerun == null)
                                {
                                    onerun = new TrainRun();
                                }
                                var tiploc = line.Substring(2, 7).TrimEnd();
                                var crs    = idms.GetCrsFromTiploc(tiploc);
                                if (string.IsNullOrWhiteSpace(crs) || crs.Length != 3)
                                {
                                    if (line[1] == 'O' || line[1] == 'T' || (line[1] == 'I' && !IsPassingPoint(line)))
                                    {
                                        DictUtils.AddEntry(badTips, tiploc, linenumber + 1);
                                    }
                                }
                                if (line[1] == 'O')
                                {
                                    var callingPoint = new CallingPoint
                                    {
                                        CallingType     = CallingType.Origin,
                                        Crs             = crs,
                                        Tiploc          = tiploc,
                                        PublicDeparture = GetMinutes(line, 15),
                                        LineNumber      = linenumber
                                    };
                                    onerun.CallingPoints.Add(callingPoint);
                                }
                                else if (line[1] == 'I' && !IsPassingPoint(line))
                                {
                                    // intermediate station
                                    var callingPoint = new CallingPoint
                                    {
                                        CallingType     = CallingType.Intermediate,
                                        Crs             = crs,
                                        Tiploc          = tiploc,
                                        Arrival         = GetMinutes(line, 10),
                                        Departure       = GetMinutes(line, 15),
                                        PublicArrival   = GetMinutes(line, 25),
                                        PublicDeparture = GetMinutes(line, 29),
                                        Platform        = line.Substring(33, 3),
                                        LineNumber      = linenumber
                                    };
                                    onerun.CallingPoints.Add(callingPoint);
                                    if (linenumber >= 108192)
                                    {
                                        Console.WriteLine();
                                    }
                                }
                                else if (line[1] == 'T')
                                {
                                    // terminating station
                                    var callingPoint = new CallingPoint
                                    {
                                        CallingType   = CallingType.Terminating,
                                        Crs           = crs,
                                        Tiploc        = tiploc,
                                        Arrival       = GetMinutes(line, 10),
                                        PublicArrival = GetMinutes(line, 15),
                                        Platform      = line.Substring(19, 3),
                                        LineNumber    = linenumber
                                    };
                                    onerun.CallingPoints.Add(callingPoint);
                                    if (onerun.CallingPoints.Count() > 200)
                                    {
                                        Console.WriteLine();
                                    }
                                    fullTimetable.TrainRuns.Add(onerun);
                                    onerun = null;
                                }
                            }
                            linenumber++;
                            if (linenumber % 1_000_000 == 999_999)
                            {
                                System.Diagnostics.Debug.WriteLine($"line {linenumber + 1}");
                            }
                        }
                    }// using



                connections = new Dictionary <string, List <Connection> >();

                System.Diagnostics.Debug.WriteLine($"There are {fullTimetable.TrainRuns.Count} train runs.");
                var currentRun = 0;
                var innerCount = 0;
                foreach (var run in fullTimetable.TrainRuns)
                {
                    if (run.CallingPoints[0].Crs != null)
                    {
                        for (var i = 0; i < run.CallingPoints.Count - 1; i++)
                        {
                            for (var j = 1; j < run.CallingPoints.Count; j++)
                            {
                                if (run.CallingPoints[i].Crs != null && run.CallingPoints[j].Crs != null)
                                {
                                    var crsFlow    = run.CallingPoints[i].Crs + run.CallingPoints[j].Crs;
                                    var connection = new Connection {
                                        Trainrun = run, StartIndex = i, EndIndex = j, DoesTerminate = j == run.CallingPoints.Count()
                                    };
                                    DictUtils.AddEntry(connections, crsFlow, connection);
                                    innerCount++;
                                }
                            }
                        }
                    }
                    currentRun++;
                    if (currentRun % 10000 == 9999)
                    {
                        System.Diagnostics.Debug.WriteLine($"Current run: {currentRun + 1}");
                    }
                }
            }
        }
示例#25
0
        public World AsReadOnly()
        {
            var entities     = new List <Entity>();
            var idsToIndexes = new Dictionary <int, int>();

            foreach (var id in Entities.Keys)
            {
                entities.Add(Entities[id]);
                idsToIndexes.Add(id, entities.Count - 1);
            }

            return(new World(Width, Height, Timestamp, IDCounter, entities.ToImmutableList(), new ReadOnlyDictionary <int, int>(idsToIndexes), DictUtils.FromEnumerable(Teams.Select((kvp) => new KeyValuePair <int, Team>(kvp.Key, kvp.Value.AsReadOnly())))));
        }
示例#26
0
 bool GetDiscoveredState(Country country, Location loc)
 {
     return(DictUtils.GetOrCreate(loc, GetCountryState(country), () => false));
 }
示例#27
0
 BotBehaviour GetBehaviour(Country country)
 {
     return(DictUtils.GetOrCreate(country, _behaviors, () => new BotBehaviour()));
 }
示例#28
0
 public TContainedNode GetObjectAt(Vector2 pos)
 {
     return(DictUtils.GetFromDict(_posToObjMap, pos, null));
 }
示例#29
0
 ConsoleColor GetCountryColor(Country country)
 {
     return(DictUtils.GetOrCreate(country, _colorMap, () => GetNewCountryColor(_colorMap.Values)));
 }
示例#30
0
 HashSet <Location> GetRoutes(Country country)
 {
     return(DictUtils.GetOrCreate(country, _curRoutes, () => new HashSet <Location>()));
 }