Exemplo n.º 1
0
        public object[] GetArguments(RouteInvocation route, IRequest request, MethodInfo method)
        {
            var foundArgs = new Dictionary<string, string[]>(ParameterComparer);
            foundArgs.Concat(route.RouteData);
            foundArgs.Concat(request.Query);
            foundArgs.Concat(request.Form);

            var args = new List<object>();
            foreach (var parameter in method.GetParameters())
            {
                object arg = null;
                var converter = Converters.FirstOrDefault
                    (x => x.CanConvert(parameter.ParameterType));
                if (converter != null) {
                    arg = converter.Convert(parameter.ParameterType, parameter.Name, foundArgs);
                }
                if ((converter == null || arg == null) && parameter.IsOptional)
                {
                    arg = (parameter.HasDefaultValue ? parameter.DefaultValue : null);
                }

                if (arg != null || parameter.IsOptional)
                {
                    args.Add(arg);
                }
                else
                {
                    throw new InvalidOperationException(String.Format(
                        "Required argument {0} was not supplied to method {1} on controller {2}",
                        parameter.Name, method.Name, method.DeclaringType));
                }
            }

            return args.ToArray();
        }
        public Dictionary <string, string> GetBirthdays()
        {
            IntializeService();
            Dictionary <string, string> result = new Dictionary <string, string>();

            var facebookCalendarId = GetCalendarByString("Friends");

            if (facebookCalendarId != null)
            {
                CreateRequest(facebookCalendarId);
                log.Info("The facebook calendar for user " + _userId + "has been found");
                result = GetEvents(0);
            }

            if (result != null && result.Count == 5)
            {
                return(result);
            }

            var primaryCalendarId = GetCalendarByString("primary");

            log.Info("The google calendar for user " + _userId + " has been found");
            CreateRequest(primaryCalendarId);
            result = result?.Concat(GetEvents(result.Count)).ToDictionary(x => x.Key, x => x.Value) ?? GetEvents(0);

            return(result);
        }
Exemplo n.º 3
0
        private static IDictionary<SyntaxNode, SyntaxNode> GetRetroChanges(Compilation compilation, INamedTypeSymbol objectType)
        {
            var syntaxNodes = new Dictionary<SyntaxNode, SyntaxNode>();

            var semanticModels = compilation.SyntaxTrees.Select(x => compilation.GetSemanticModel(x));

            var genRefs = FindGenericClassMembers(semanticModels);

             //CHANGE
             //1. Generic references with cast
             //2. Generic T to Object
             //======

            foreach (var semanticModel in semanticModels)
            {
                var root = semanticModel.SyntaxTree.GetRoot();

                // get cast changes
                var castReferences = new Dictionary<SyntaxNode, SyntaxNode>();
                CastResursiveMethod(root, semanticModel, genRefs, castReferences);
                
                // get generic T to object
                var retroProperties = GenericToObject(root, semanticModel, objectType);

                var allChanges = castReferences.Concat(retroProperties);

                foreach (var ch in allChanges)
                    syntaxNodes.Add(ch.Key, ch.Value);
            }

            return syntaxNodes;
        }
        public Dictionary<string, object> Convert(string propertyName, CustomAttributeData attr)
        {
            var validations = new Dictionary<string, object>();

            var maxLength = GetConstructorArgumentValue(attr, 0);
            if (!string.IsNullOrWhiteSpace(maxLength))
            {
                var maxValidations = SetMaxLengthAAValidation(propertyName, attr, maxLength);
                validations = validations.Concat(maxValidations).ToDictionary(x => x.Key, x => x.Value);
            }

            var minLength = base.GetNamedArgumentValue(propertyName, attr, DataAnnotationConstants.MinimumLength, false);
            if (!string.IsNullOrWhiteSpace(minLength))
            {
                var minValidations = SetMinLengthAAValidation(propertyName, attr, minLength);
                validations = validations.Concat(minValidations).ToDictionary(x => x.Key, x => x.Value);
            }

            return validations;
        }
        /// <summary>
        /// Add OAuth access_token to headers
        /// </summary>
        /// <param name="currentHeader"></param>
        /// <returns></returns>
        public async Task <Dictionary <string, string> > PrepareHeader(Dictionary <string, string> currentHeader)
        {
            var token = await OAuthService.RefreshTokenIfExpiredAsync();

            var headers = new Dictionary <string, string>()
            {
                { "Authorization", $"Bearer {token.AccessToken}" },
            };

            var combinedHeaders = currentHeader?.Concat(headers).ToDictionary(k => k.Key, v => v.Value) ?? headers;

            return(combinedHeaders);
        }
Exemplo n.º 6
0
        public void ReadSubstitionVariablesFromConfigFile()
        {
            var configFilePath = ConfigFile;
            var result = new Dictionary<string, string>
            {
                {"SERVERNAME", TargetDatabaseName},
                {"CRMDBNAME", CrmDatabaseName}
            };

            var config =
                JsonConvert.DeserializeObject<Config>(File.ReadAllText(configFilePath), new JsonSerializerSettings { });
            Variables = result.Concat(config.UsernameReplacements)
                .ToDictionary(x => x.Key, x => x.Value);
        }
		/// <summary>
		/// Merge given dictionaries
		/// </summary>
		/// <param name="dictionaries">dictionaries to merge</param>
		/// <param name="overrideDueplicateWithLatterDictionaryValue">
		/// If true and duplicate key exists, then dupe key's values are overriden by latter dictionary values
		/// </param>
		public Dictionary<string, string> MergeDictionaries(
			Dictionary<int, Dictionary<string, string>> dictionaries, 
			bool overrideDueplicateWithLatterDictionaryValue = true)
		{
			Dictionary<string, string> result = new Dictionary<string, string>(dictionaries.Count);
			var query = overrideDueplicateWithLatterDictionaryValue ? dictionaries.Reverse() : dictionaries;

			foreach (var index in query)
			{
				Dictionary<string, string> d2 = index.Value;
				result = result.Concat(d2.Where(x => !result.Keys.Contains(x.Key))).ToDictionary(o => o.Key, o => o.Value);
			}

			return result;
		}
Exemplo n.º 8
0
        public static FormUrlEncodedContent CreatePostBody(string method, string apikey, string apisig,
                                                          IEnumerable<KeyValuePair<string, string>> parameters)
        {
            var init = new Dictionary<string, string>
                           {
                               {"method", method},
                               {"api_key", apikey},
                               {"api_sig", apisig},
                               {"format", ResponseFormat}
                           };

            // TODO ordering
            var requestParameters = init.Concat(parameters);

            return new FormUrlEncodedContent(requestParameters);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Merge a into b removing the duplicates from b if they exists
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <returns></returns>
        public static Dictionary <TKey, TValue> MergeWith <TKey, TValue>(this Dictionary <TKey, TValue> a,
                                                                         Dictionary <TKey, TValue> b)
        {
            if (a == null && b != null)
            {
                return(b);
            }

            if (a != null && b == null)
            {
                return(a);
            }

            return(a?.Concat(b.Where(kvp => !a.ContainsKey(kvp.Key) && kvp.Value != null))
                   .ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
        }
 private Dictionary<string, CCNode> getAllNodeNamesHelper(Dictionary<string, CCNode> children)
 {
     Dictionary<string, CCNode> list = new Dictionary<string, CCNode>();
     if (children != null)
     {
         foreach (KeyValuePair<string, CCNode> pair in children)
         {
             if (!pair.Key.StartsWith("__") && !pair.Key.StartsWith("#"))
             {
                 list.Add(pair.Key, pair.Value);
             }
             Dictionary<string, CCNode> list2 = getAllNodeNamesHelper(pair.Value.children);
             list = list.Concat(list2).ToDictionary(k => k.Key, v => v.Value);
         }
     }
     return list;
 }
Exemplo n.º 11
0
 /// <summary>
 /// Parses preprocessor instructions.
 /// </summary>
 public static void PreprocParse(ref lib8081.CPU cpu, ref Dictionary<String, lib8081.instructions.Function> funcs, String code)
 {
     // Split the string out.
     String[] args = util.SplitWithQuotes(code);
     switch (args[0])
     {
         // More ungodly case statements.
         case "#load":
             PreprocInclude(ref cpu, ref funcs, args);
             break;
         case "#include":
             // No need for a dedicated function.
             var Included = PCDParser.GetParsedFunctions(args[1], ref cpu, true);
             funcs = funcs.Concat(Included).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
             break;
     }
 }
Exemplo n.º 12
0
        private static string GetSignatureBaseString(string httpMethod, string url, Dictionary<string, string> oAuthOptions)
        {
            var uri = new Uri(url);

            var normalizedUrl = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath);

            var queryString = uri.Query;

            var queryParameters = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(queryString))
            {
                var querySegments = queryString.Split('&');
                foreach (string segment in querySegments)
                {
                    var parts = segment.Split('=');
                    if (parts.Length > 0)
                    {
                        var key = parts[0].Trim(new[] { '?', ' ' });
                        var val = parts[1].Trim();

                        queryParameters.Add(key, val);
                    }
                }
            }

            var signableOptionsRaw = oAuthOptions.Concat(queryParameters).OrderBy(k => k.Key);

            var signableOptions = new Dictionary<string, string>();
            foreach (var option in signableOptionsRaw)
            {
                var key = UrlEncode(option.Key);
                var val = UrlEncode(option.Value);

                signableOptions.Add(key,val);
            }

            IOrderedEnumerable<KeyValuePair<string, string>> orderedSignableOptions = signableOptions.OrderBy(k => k.Key);

            var signableOptionParts = orderedSignableOptions.Select(option => String.Format("{0}%3D{1}", option.Key, option.Value)).ToList();

            var signableOptionString = string.Join("%26", signableOptionParts);

            var signatureParts = new List<string> {httpMethod, UrlEncode(normalizedUrl), signableOptionString};

            return string.Join("&", signatureParts);
        }
Exemplo n.º 13
0
        /// <summary>Entry point</summary>
        public int Execute(CommandLine cmd, ConfigSource configuration)
        {
            Initialize(cmd, configuration);

            var proc = new Process();
            var runtime = configuration.GetRuntime();
            var ini = new Dictionary<string, IEnumerable<string>>()
            {
                { "magic_quotes_gpc", new string[] { "0" } },
                { "date.timezone", new string[] { TimeZoneInfo.Local.Olson() ?? "UTC" } },
                { "extension", configuration.GetExtensions(runtime) }
            };
            var use = configuration.GetUse() ?? UseComposer();

            Encoding encoding;
            Func<string, string> args;
            var main = Paths.TryLocate(use, new string[] { Paths.Compose("tools", MainFor(cmd) + ".php") }).FirstOrDefault();
            if (null == main)
            {
                main = Paths.Locate(new string[] { Paths.Binary().DirName() }, new string[] { MainFor(cmd) + "-main.php" }).First();
                encoding = Encoding.UTF8;

                // Arguments are encoded in utf-7, which is binary-safe
                args = Arguments.Encode;
            }
            else
            {
                args = Arguments.Escape;
                encoding = Encoding.GetEncoding("iso-8859-1");
            }

            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.FileName = configuration.GetExecutable(runtime) ?? "php";
            proc.StartInfo.Arguments = string.Format(
                "-C -q -d include_path=\".{0}{1}{0}{0}.{0}{2}\" {3} {4} {5}",
                Paths.Separator,
                string.Join(Paths.Separator, use.Concat(cmd.Options["modules"].Concat(ModulesFor(cmd)))),
                string.Join(Paths.Separator, cmd.Options["classpath"].Concat(ClassPathFor(cmd))),
                string.Join(" ", IniSettings(ini.Concat(configuration.GetArgs(runtime)))),
                main,
                string.Join(" ", ArgumentsFor(cmd).Select(args))
            );

            return cmd.ExecutionModel.Execute(proc, encoding);
        }
Exemplo n.º 14
0
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public string GetUsedCarPrice(Dictionary<string, string> paramList)
        {
            var paramBase = new Dictionary<string, string>
            {
                {"key", _appkey},
                {"dtype", "json"},
                {"method", "getUsedCarPrice"}
            };

            //合并参数
            var parameters = paramBase.Concat(paramList).ToDictionary(k => k.Key, v => v.Value);

            var result = DynamicWebService.SendPost(_url, parameters, "get");

            var obj = JObject.Parse(result);
            var errorCode = obj["reason"].ToString();
            return errorCode != "success" ? "0" : obj["result"].ToString();
        }
Exemplo n.º 15
0
        public static Dictionary<string, object> ConvertToDictionary(object data)
        {
            var result = new Dictionary<string, object>();
            if (data == null)
                return result;

            // Get all properties on the object
            var allPriperties = data.GetType().GetProperties()
                .Where(x => x.CanRead)
                .Where(x => x.GetValue(data, null) != null)
                .Where(x => !Attribute.IsDefined(x, typeof(QueryIgnore)));

            var nonTaggedProperties = allPriperties.Where(x => !Attribute.IsDefined(x, typeof(QueryProperty)))
                .ToDictionary(x => x.Name, x => x.GetValue(data, null));

            var taggedProperties = allPriperties.Where(x => Attribute.IsDefined(x, typeof(QueryProperty)))
                .ToDictionary(x => ((IEnumerable<QueryProperty>)x.GetCustomAttributes(typeof(QueryProperty), true)).First().Name, x => x.GetValue(data, null));

            return result.Concat(taggedProperties).Concat(nonTaggedProperties).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => d.First().Value);
        }
        public Dictionary<string, DateTime> GetMediaFilesList()
        {
            var searchOption = m_scanSubfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            var result = new Dictionary<string, DateTime>();

            foreach (var searchPattern in GetFolderSearchPatternsList())
            {
                var filesList = Directory.GetFiles(m_path, searchPattern, searchOption);
                m_totalItemsInProcess = filesList.Length;
                m_currentProgress = 0;
                m_logger.LogFormat(Resources.MediaMinerBase_GetMediaFilesList_Found__0__with__1__extension, m_totalItemsInProcess, searchPattern);

                Dictionary<string, DateTime> interimResult = filesList.AsParallel()
                    .Select(p => new { File = p, TakenDate = GetTakenDateEntry(p) })
                    .Where(p => p.TakenDate != null).ToDictionary(p => p.File, p => p.TakenDate.Value);

                result = result.Concat(interimResult).ToDictionary(p => p.Key, p => p.Value);
            }

            return result;
        }
Exemplo n.º 17
0
        protected IDictionary<string,object> ConstructBasicParameters(string url, MethodType methodType, Token token, params KeyValuePair<string,object>[] optionalParameters)
        {
            Enforce.NotNull(url, "url");
            Enforce.NotNull(optionalParameters, "optionalParameters");

            var parameters = new Dictionary<string, object>
            {
                { "oauth_consumer_key", ConsumerKey },
                { "oauth_nonce", _random.Next() },
                { "oauth_timestamp", DateTime.UtcNow.ToUnixTime() },
                { "oauth_signature_method", "HMAC-SHA1" },
                { "oauth_version", "1.0" }
            };
            if (token != null)
                parameters.Add("oauth_token", token.Key);

            var signature = GenerateSignature(new Uri(url), methodType, token, parameters.Concat(optionalParameters));
            parameters.Add("oauth_signature", signature);

            return parameters;
        }
        /// <summary>
        /// Loads all extension assemblies from the given base directory and all his sub folders.
        /// </summary>
        /// <param name="t">The Type to search for.</param>
        /// <param name="baseDirectory">The base directory.</param>
        /// <param name="prefix">The prefix added to the directory name (normally the parents directory key).</param>
        /// <returns>
        /// Dictionary of key [EXT_(subfoldername)] and list of available class types
        /// </returns>
        static Dictionary<String, List<Type>> loadAllExtensions(Type t, string baseDirectory, string prefix)
        {
            Dictionary<String, List<Type>> dic = new Dictionary<String, List<Type>>();
            if (t != null && Directory.Exists(baseDirectory))
            {
                //list all directly added types (without sub folder structure)
                var baseypes = LoadTypes(t, baseDirectory);

                if (baseypes != null && baseypes.Count > 0)
                {
                    dic.Add(prefix, baseypes);
                }

                // list all sub directories
                var subDirs = Directory.GetDirectories(baseDirectory);
                if (subDirs != null && subDirs.Length > 0)
                {
                    foreach (var subDir in subDirs)
                    {
                        try
                        {
                            if (Directory.Exists(subDir))
                            {
                                string name = new DirectoryInfo(subDir).Name;
                                name = (String.IsNullOrWhiteSpace(prefix) ? "" : (prefix + "_")) + name;
                                var subs = loadAllExtensions(t, subDir, name);

                                //combine the subs to the org
                                if (subs != null && subs.Count > 0)
                                {
                                    dic = dic.Concat(subs).ToDictionary(x => x.Key, x => x.Value);
                                }
                            }
                        }
                        catch(Exception){}
                    }
                }
            }
            return dic;
        }
        /// <inheritdoc />
        public Dictionary <string, OpenApiSchema> GetOpenApiSchemas(List <MethodInfo> elements, NamingStrategy namingStrategy, VisitorCollection collection)
        {
            var requests = elements.SelectMany(p => p.GetCustomAttributes <OpenApiRequestBodyAttribute>(inherit: false))
                           .Select(p => p.BodyType);
            var responses = elements.SelectMany(p => p.GetCustomAttributes <OpenApiResponseWithBodyAttribute>(inherit: false))
                            .Select(p => p.BodyType);
            var types = requests.Union(responses)
                        .Select(p => p.IsOpenApiArray() || p.IsOpenApiDictionary() ? p.GetOpenApiSubType() : p)
                        .Distinct()
                        .Where(p => !p.IsSimpleType())
                        .Where(p => p.IsReferentialType())
                        .Where(p => !typeof(Array).IsAssignableFrom(p))
                        .ToList();

            var rootSchemas = new Dictionary <string, OpenApiSchema>();
            var schemas     = new Dictionary <string, OpenApiSchema>();

            this._acceptor.Types       = types.ToDictionary(p => p.GetOpenApiReferenceId(p.IsOpenApiDictionary(), p.IsOpenApiArray(), namingStrategy), p => p);
            this._acceptor.RootSchemas = rootSchemas;
            this._acceptor.Schemas     = schemas;

            this._acceptor.Accept(collection, namingStrategy);

            var union = schemas.Concat(rootSchemas.Where(p => !schemas.Keys.Contains(p.Key)))
                        .Distinct()
                        .Where(p => p.Key.ToUpperInvariant() != "OBJECT")
                        .OrderBy(p => p.Key)
                        .ToDictionary(p => p.Key,
                                      p =>
            {
                // Title was intentionally added for schema key.
                // It's not necessary when it's added to the root schema.
                // Therefore, it's removed.
                p.Value.Title = null;
                return(p.Value);
            });

            return(union);
        }
Exemplo n.º 20
0
        private static Dictionary<string, string> RecurseConfig(IConfiguration source)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            foreach (var child in source.GetChildren())
            {
                if (child.GetChildren().Count() != 0)
                {
                    result = result.Concat(RecurseConfig(child)).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => d.First().Value);
                }

                if (child.GetChildren().Count() != 0 && string.IsNullOrEmpty(child.Value))
                {
                    continue;
                }

                result.Add(child.Path, child.Value);

            }

            return result;
        }
Exemplo n.º 21
0
        private IDictionary <string, List <File <IReplay> > > NestedSort(ISortCommand SortOnX, IDictionary <string, List <File <IReplay> > > SortOnXResult, List <string> replaysThrowingExceptions)
        {
            // Dictionary<directory, Files>
            IDictionary <string, List <File <IReplay> > > DirectoryFileReplay = new Dictionary <string, List <File <IReplay> > >();

            SortOnX.Sorter.SortCriteria = SortOnX.SortCriteria;
            foreach (var directory in SortOnXResult.Keys)
            {
                var FileReplays = SortOnXResult[directory];
                SortOnX.Sorter.CurrentDirectory = directory;
                SortOnX.Sorter.ListReplays      = FileReplays;
                var result        = SortOnX.Sort(replaysThrowingExceptions);
                var replaysSorted = result.SelectMany(dir => dir.Value);

                if (replaysSorted.Count() != FileReplays.Count())
                {
                    result.Add(directory, FileReplays.Except(replaysSorted).ToList());
                }
                DirectoryFileReplay = DirectoryFileReplay.Concat(result).ToDictionary(k => k.Key, k => k.Value);
            }
            return(DirectoryFileReplay);
        }
        // direct join two candidate mapping together.
        public static Dictionary<int, int> joinPieceCandidates(Dictionary<int, int> piece1, Dictionary<int, int> piece2)
        {
            bool joinable = true;
            Dictionary<int, int> jointPieceCandidate = new Dictionary<int, int>();
            foreach (KeyValuePair<int, int> pair in piece2)
            {
                if (piece1.ContainsKey(pair.Key))
                {
                    if (piece1[pair.Key] != pair.Value)
                    {
                        joinable = false;
                        break;

                    }
                }
            }
            if (joinable)
            {
                jointPieceCandidate = piece1.Concat(piece2.Where(kvp => !piece1.ContainsKey(kvp.Key))).ToDictionary(x => x.Key, x => x.Value);
            }
            return jointPieceCandidate;
        }
Exemplo n.º 23
0
        private Dictionary <string, string> driverParamToDictionary(DriverParam p)
        {
            QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Debug, "+ driverParamToDictionary()");

            Dictionary <string, string> retVal;

            try
            {
                retVal = new Dictionary <string, string>()
                {
                    { p.paramName, p.selectedValues.Keys.ToArray()[0] }
                };

                if (p.selectedValues.Values.ToArray()[0] != null)
                {
                    retVal = retVal.Concat(
                        p.selectedValues.Values.ToArray()[0]
                        .SelectMany(
                            f => driverParamToDictionary(f)
                            ).ToDictionary(
                            k => k.Key,
                            v => v.Value
                            )
                        ).ToDictionary(
                        k => k.Key,
                        v => v.Value
                        );
                }
            }
            catch (Exception e)
            {
                QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Error, "driverParamToDictionary() : " + e.Message);
                throw e;
            }

            QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Debug, "- driverParamToDictionary()");

            return(retVal);
        }
Exemplo n.º 24
0
        private static bool IsGenericArgumentsSubstitutionCompatible(Type declaringType, Type[] genericArguments, Type[] substitution)
        {
            Dictionary <Type, Type> methodMap =
                genericArguments.Zip(substitution,
                                     Tuple.Create)
                .ToDictionary(x => x.Item1, x => x.Item2);

            IDictionary <Type, Type> declaringTypeMap =
                TypeExtensions.GetTypeGenericArgumentsMap(declaringType);

            IDictionary <Type, Type> currentMap =
                methodMap.Concat(declaringTypeMap)
                .ToDictionary(x => x.Key, x => x.Value);

            ArgumentSubstituter substituter = new ArgumentSubstituter(currentMap);

            foreach (Type argument in genericArguments)
            {
                Type[] constraints = argument.GetGenericParameterConstraints();

                if (constraints.Length > 0)
                {
                    Type resolvedArgument = substituter.Substite(argument);

                    foreach (Type constraint in constraints)
                    {
                        Type resolvedConstraint = substituter.Substite(constraint);

                        if (!resolvedConstraint.IsAssignableFrom(resolvedArgument))
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 25
0
        public static IDictionary <string, string>?ToKeyValue(this object metaToken)
        {
            if (!(metaToken is JToken token))
            {
                return(ToKeyValue(JObject.FromObject(metaToken)));
            }

            if (token.HasValues)
            {
                var contentData = new Dictionary <string, string>();
                foreach (var child in token.Children().ToList())
                {
                    var childContent = child.ToKeyValue();
                    if (childContent != null)
                    {
                        contentData = contentData.Concat(childContent)
                                      .ToDictionary(k => k.Key.ToLowerInvariant(), v => v.Value);
                    }
                }

                return(contentData);
            }

            var jValue = token as JValue;

            if (jValue?.Value == null)
            {
                return(null);
            }

            var value = jValue.Type == JTokenType.Date
                ? jValue.ToString("o", CultureInfo.InvariantCulture)
                : jValue.ToString(CultureInfo.InvariantCulture);

            return(new Dictionary <string, string> {
                { token.Path.ToLowerInvariant(), value }
            });
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            // Аргументы указыаются последовательно в формате:
            // <report name 1>, <begin date 1>, <end date 1>, ... , <report name N>, <begin date N>, <end date N>

            if (args.Length % 3 != 0)
            {
                throw new ArgumentException("Указаны не все аргументы!");
            }
            var reportArgs = Enumerable.Range(0, args.Length / 3).Select(i => args.Skip(3 * i).Take(3).ToList()).ToList();

            //var reportArgs = new List<List<string>> { new List<string> { "АКП-1", "01.08.2020", "19.08.2020" }, new List<string> { "АКП-3", "01.08.2020", "19.08.2020" }, new List<string> { "АКП-4", "01.08.2020", "19.08.2020" } };


            var portal = new BqrfPortal();


            var result = new Dictionary <string, object>();

            foreach (var rArg in reportArgs)
            {
                Dictionary <string, object> resp = null;
                var beginDate = DateTime.Parse(rArg[1], CultureInfo.GetCultureInfo("ru-RU"));
                var endDate   = DateTime.Parse(rArg[2], CultureInfo.GetCultureInfo("ru-RU"));

                var report = portal.FirstOrDefault(r => r.Name == rArg[0]);
                resp = report.GetReport(beginDate, endDate);

                if (resp != null)
                {
                    result = result.Concat(resp).ToDictionary(pair => pair.Key, pair => pair.Value);
                }
            }
            string filePath = Path.Join("/tmp/report_temporary", Path.GetRandomFileName());

            File.WriteAllText(filePath, JsonConvert.SerializeObject(result));
            Console.WriteLine(filePath);
        }
Exemplo n.º 27
0
        // not async yet
        private IDictionary <string, List <File <IReplay> > > NestedSortAsync(List <string> replaysThrowingExceptions, ISortCommand SortOnX, IDictionary <string, List <File <IReplay> > > SortOnXResult, BackgroundWorker worker_ReplaySorter, int currentCriteria, int numberOfCriteria)
        {
            // Dictionary<directory, dictionary<file, replay>>
            IDictionary <string, List <File <IReplay> > > DirectoryFileReplay = new Dictionary <string, List <File <IReplay> > >();

            // get replays
            // get files
            // set currentdirectory
            // on sorter
            // for replays and files, need to make return type for sort, which gives a dictionary for replays per directory

            SortOnX.Sorter.SortCriteria = SortOnX.SortCriteria;
            int currentPostion    = 0;
            int numberOfPositions = SortOnXResult.Keys.Count();

            foreach (var directory in SortOnXResult.Keys)
            {
                currentPostion++;
                var FileReplays = SortOnXResult[directory];
                SortOnX.Sorter.CurrentDirectory = directory;
                SortOnX.Sorter.ListReplays      = FileReplays;
                var result        = SortOnX.SortAsync(replaysThrowingExceptions, worker_ReplaySorter, currentCriteria, numberOfCriteria, currentPostion, numberOfPositions);
                var replaysSorted = result.SelectMany(dir => dir.Value);

                if (replaysSorted.Count() != FileReplays.Count())
                {
                    result.Add(directory, FileReplays.Except(replaysSorted).ToList());
                }

                if (worker_ReplaySorter.CancellationPending == true)
                {
                    return(null);
                }

                DirectoryFileReplay = DirectoryFileReplay.Concat(result).ToDictionary(k => k.Key, k => k.Value);
            }
            return(DirectoryFileReplay);
        }
Exemplo n.º 28
0
        public async Task <HttpClientResponse> Request(string Method, string Url, dynamic Data = null, Dictionary <string, string> Headers = null)
        {
            HttpClientResponse result = new HttpClientResponse();
            int attempts = 0;

            Console.WriteLine("Request running...");
            while (attempts < LoginAttempts)
            {
                ReadCookies();
                Console.WriteLine("Request Attempt: {0}", attempts + 1);

                var Headers_ = new Dictionary <string, string>()
                {
                    { "BPMCSRF", BPMCSRF }
                };
                Dictionary <string, string> temp_ = new Dictionary <string, string>();
                if (Headers != null && Headers.Count > 0)
                {
                    temp_ = Headers_.Concat(Headers).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => d.First().Value);
                }

                var response = await HttpClientRequest(Method, Url, Data, (temp_.Count > 0 ? temp_ : Headers_));

                if (!response.IsSuccessStatusCode)
                {
                    attempts++;
                    await login();
                }
                else
                {
                    WriteCookies();
                    result = response;
                    break;
                }
            }

            return(result);
        }
Exemplo n.º 29
0
        private static ApiBuildOutput FromModel(ItemViewModel model, Dictionary <string, ApiReferenceBuildOutput> references, Dictionary <string, object> metadata)
        {
            if (model == null)
            {
                return(null);
            }

            return(new ApiBuildOutput
            {
                Uid = model.Uid,
                Id = XrefDetails.GetHtmlId(model.Uid),
                Parent = ApiBuildOutputUtility.GetReferenceViewModel(model.Parent, references, model.SupportedLanguages),
                Children = GetReferenceList(model.Children, references, model.SupportedLanguages),
                Href = model.Href,
                SupportedLanguages = model.SupportedLanguages,
                Name = ApiBuildOutputUtility.TransformToLanguagePairList(model.Name, model.Names, model.SupportedLanguages),
                FullName = ApiBuildOutputUtility.TransformToLanguagePairList(model.FullName, model.FullNames, model.SupportedLanguages),
                Type = model.Type,
                Source = model.Source,
                Documentation = model.Documentation,
                AssemblyNameList = model.AssemblyNameList,
                NamespaceName = ApiBuildOutputUtility.GetReferenceViewModel(model.NamespaceName, references, model.SupportedLanguages),
                Summary = model.Summary,
                Remarks = model.Remarks,
                Examples = model.Examples,
                Syntax = ApiSyntaxBuildOutput.FromModel(model.Syntax, references, model.SupportedLanguages),
                Overridden = ApiBuildOutputUtility.GetReferenceViewModel(model.Overridden, references, model.SupportedLanguages),
                Exceptions = GetCrefInfoList(model.Exceptions, references, model.SupportedLanguages),
                SeeAlsos = GetCrefInfoList(model.SeeAlsos, references, model.SupportedLanguages),
                Sees = GetCrefInfoList(model.Sees, references, model.SupportedLanguages),
                Inheritance = GetReferenceList(model.Inheritance, references, model.SupportedLanguages, true),
                Implements = GetReferenceList(model.Implements, references, model.SupportedLanguages),
                InheritedMembers = GetReferenceList(model.InheritedMembers, references, model.SupportedLanguages),
                Conceptual = model.Conceptual,
                Platform = model.Platform,
                Metadata = metadata.Concat(model.Metadata.Where(p => !metadata.Keys.Contains(p.Key))).ToDictionary(p => p.Key, p => p.Value),
            });
        }
Exemplo n.º 30
0
    public static void sendEvent(string eventName, Dictionary <string, object> params1 = null, Dictionary <string, object> params2 = null)
    {
        Dictionary <string, object> params3 = new Dictionary <string, object>();

        if (params1 != null)
        {
            params3 = params1;
        }
        if (params2 != null)
        {
            params3 = params1.Concat(params2).ToDictionary(x => x.Key, x => x.Value);
        }

        params3["Level"] = LevelController.level;
        params3["Char"]  = GameController.charId;
        params3["Gems"]  = (int)GemsController.gems;
        params3["Skin"]  = LevelController.skin;

        //FB
        if (FB.IsInitialized)
        {
            FB.LogAppEvent(
                eventName,
                parameters: params3
                );
            //for Debug.Log
            string keys = eventName;
            foreach (KeyValuePair <string, object> param in params3)
            {
                keys += ":" + param.Key + "_" + param.Value;
            }
            Debug.Log("____________" + keys);
        }
        else
        {
            instance.StartCoroutine(sendEventCoroutine(eventName, params3));
        }
    }
    public static void Main() // 100/100
    {
        string inputLine = Console.ReadLine();

        Dictionary <string, string> defaultValues = new Dictionary <string, string>();

        while (inputLine != "end")
        {
            string[] tokens = inputLine.Split(" ->".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            string key   = tokens[0];
            string value = tokens[1];

            defaultValues[key] = value;

            inputLine = Console.ReadLine();
        }

        inputLine = Console.ReadLine();

        Dictionary <string, string> originalValues = defaultValues
                                                     .Where(x => x.Value != "null")
                                                     .OrderByDescending(x => x.Value.Length)
                                                     .ToDictionary(x => x.Key, x => x.Value);

        Dictionary <string, string> changedValues = defaultValues
                                                    .Where(x => x.Value == "null")
                                                    .ToDictionary(x => x.Key, x => inputLine);

        Dictionary <string, string> result = originalValues
                                             .Concat(changedValues)
                                             .ToDictionary(x => x.Key, x => x.Value);

        foreach (KeyValuePair <string, string> kvp in result)
        {
            Console.WriteLine($"{kvp.Key} <-> {kvp.Value}");
        }
    }
Exemplo n.º 32
0
        /// <summary>
        ///     Returns all the space contacts referenced by the given app.
        ///     <para>Podio API Reference: https://developers.podio.com/doc/contacts/get-space-contacts-on-app-79475279 </para>
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="fields">A value for the required field. For text fields partial matches will be returned.</param>
        /// <param name="limit">The maximum number of contacts that should be returned</param>
        /// <param name="offset">The offset to use when returning contacts</param>
        /// <param name="order">
        ///     The order in which the contacts can be returned. See the area for details on the ordering options.
        ///     Default value: name
        /// </param>
        /// <returns></returns>
        public async Task <List <Contact> > GetSpaceContactsOnApp(int appId, Dictionary <string, string> fields = null,
                                                                  int?limit = null, int?offset = null, string order = "name")
        {
            string url         = string.Format("/contact/app/{0}/", appId);
            var    requestData = new Dictionary <string, string>();
            var    parameters  = new Dictionary <string, string>()
            {
                { "limit", limit.ToStringOrNull() },
                { "offset", offset.ToStringOrNull() },
                { "order", order.ToStringOrNull() }
            };

            if (fields != null && fields.Any())
            {
                requestData = parameters.Concat(fields).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            }
            else
            {
                requestData = parameters;
            }

            return(await _podio.Get <List <Contact> >(url, requestData));
        }
Exemplo n.º 33
0
        private void LoadTles(bool threeLine, IEnumerable <string> sourceFilenames)
        {
            _tles = new Dictionary <int, Tle>();
            foreach (var sourceFilename in sourceFilenames)
            {
                using (var file = File.OpenRead(sourceFilename))
                {
                    using (var sr = new StreamReader(file))
                    {
                        var restOfFile = sr.ReadToEnd()
                                         .Replace("\r\n", "\n")                                               // normalize line endings
                                         .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); // split into lines

                        var elementSets = Tle.ParseElements(restOfFile, threeLine);

                        var tempSet = elementSets.ToDictionary(elementSet => (int)elementSet.NoradNumber);

                        _tles = _tles.Concat(tempSet.Where(kvp => !_tles.ContainsKey(kvp.Key)))
                                .ToDictionary(x => x.Key, x => x.Value);
                    }
                }
            }
        }
Exemplo n.º 34
0
        static void Main()
        {
            string[] input = File.ReadAllLines("Day12\\Input\\input.txt");
            List <VillageProgram>     village = new List <VillageProgram>();
            Dictionary <string, bool> groups  = new Dictionary <string, bool>();

            Part1.ParseAndSetupProblem(input, village);

            int groupTotal = 0;

            foreach (VillageProgram program in village)
            {
                if (!groups.ContainsKey(program.ID))
                {
                    Dictionary <string, bool> group = Part1.BreadthFirstTraversal(program, village);
                    groups = groups.Concat(group).ToDictionary(dict => dict.Key, dict => dict.Value);
                    groupTotal++;
                }
            }

            Console.WriteLine("Total number of groups: " + groupTotal);
            Console.ReadLine();
        }
Exemplo n.º 35
0
        /// <summary>
        /// 获取某目录下后缀为endsWith的文件,它的所有依赖
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="endsWith"></param>
        /// <returns></returns>
        public static Dictionary <string, List <string> > getDLLDependencies(string folder, List <string> endsWith)
        {
            Dictionary <string, List <string> > res = new Dictionary <string, List <string> >();
            //List去重复
            List <string> files = new List <string>(new HashSet <string>(getFilesAbsolutePath(folder, endsWith)));

            for (int i = 0; i < files.Count;)
            {
                string args = "/DEPENDENTS";
                int    end  = i + Math.Min(files.Count - i, 50); //每次最多分析50个模块
                for ( ; i < end; ++i)
                {
                    string file = files[i].ToLower();
                    if (!res.Keys.Contains(file.Substring(file.LastIndexOf('\\') + 1)))
                    {
                        args += (" \"" + file + "\"");
                    }
                }
                //合并两个Dictionary
                res = res.Concat(dumpbin(args)).ToDictionary(k => k.Key, v => v.Value);
            }
            return(res);
        }
Exemplo n.º 36
0
        public IDestroyedInfo Process()
        {
            var destroyedBullets = new Dictionary <string, Coordinates>();
            var destroyedObjects = new List <ICellContentInfo>();

            for (byte i = 0; i < this.bulletActionPointCount; ++i)
            {
                var firstObjects = this.CheckHits();
                this.MoveBullets();
                var secondObjects = this.CheckHits();

                destroyedBullets = destroyedBullets
                                   .Concat(firstObjects.DestroyedBullets)
                                   .Concat(secondObjects.DestroyedBullets)
                                   .GroupBy(x => x.Key)
                                   .ToDictionary(x => x.Key, x => x.First().Value);

                destroyedObjects.AddRange(firstObjects.DestroyedObjects);
                destroyedObjects.AddRange(secondObjects.DestroyedObjects);
            }

            return(new DestroyedInfo(destroyedBullets, destroyedObjects));
        }
Exemplo n.º 37
0
        /// <summary>
        /// Used to get a list of contacts for the user.
        /// <para>Podio API Reference: https://developers.podio.com/doc/contacts/get-contacts-22400 </para>
        /// </summary>
        /// <param name="fields">A value for the required field. For text fields partial matches will be returned.</param>
        /// <param name="contactType">The types of contacts to return, can be either "user" or "space". Separate by comma to get multiple types, or leave blank for all contacts. Default value: user</param>
        /// <param name="externalId">The external id of the contact</param>
        /// <param name="limit">The maximum number of contacts that should be returned</param>
        /// <param name="offset">The offset to use when returning contacts</param>
        /// <param name="required">A comma-separated list of fields that should exist for the contacts returned. Useful for only getting contacts with an email address or phone number.</param>
        /// <param name="excludeSelf">True to exclude self, False to include self. Default value: true</param>
        /// <param name="order">The order in which the contacts can be returned. See the area for details on the ordering options. Default value: name</param>
        /// <param name="type">Determines the way the result is returned. Valid options are "mini" and "full". Default value: mini</param>
        /// <returns></returns>
        public List<Contact> GetAllContacts(Dictionary<string, string> fields = null, string contactType = "user", string externalId = null, int? limit = null, int? offset = null, string required = null, bool excludeSelf = true, string order = "name", string type = "mini")
        {
            string url = "/contact/";
            var requestData = new Dictionary<string, string>();
            var parameters = new Dictionary<string, string>()
            {
                {"contact_type", contactType.ToStringOrNull()},
                {"exclude_self", excludeSelf.ToStringOrNull()},
                {"external_id", externalId.ToStringOrNull()},
                {"limit",limit.ToStringOrNull()},
                {"offset", offset.ToStringOrNull()},
                {"order",order.ToStringOrNull()},
                {"required",required.ToStringOrNull()},
                {"type", type.ToStringOrNull()}
            };

            if (fields != null && fields.Any())
                requestData = parameters.Concat(fields).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            else
                requestData = parameters;

            return _podio.Get<List<Contact>>(url, requestData);
        }
        /// <summary>
        /// Appends the given type to the order currently stored in the pipeline inspector.
        /// This method allows this pipeline inspector to be built incrementally, which
        /// was neede in order to support the fluent configuration API.
        /// </summary>
        public void AddToOrder(Type typeToAppendToOrder)
        {
            if (orders == null)
            {
                orders = new Dictionary <Type, int>();
            }

            if (orders.ContainsKey(typeToAppendToOrder))
            {
                throw new InvalidOperationException(string.Format(@"
Attempted to add {0} to fixed order list of handlers.

Each handler type can only be added once, because that is the only thing that makes
sense, because what would it mean if one particular handler should be first AND last
at the same time?", typeToAppendToOrder));
            }

            orders = orders
                     .Concat(new[] { new KeyValuePair <Type, int>(typeToAppendToOrder, maxIndex) })
                     .ToDictionary(k => k.Key, v => v.Value);

            SetMaxIndex();
        }
Exemplo n.º 39
0
        /// <summary>
        /// Uses the RecognizerResult to create a list of propeties to be included when tracking the result in telemetry.
        /// </summary>
        /// <param name="recognizerResult">Recognizer Result.</param>
        /// <param name="telemetryProperties">A list of properties to append or override the properties created using the RecognizerResult.</param>
        /// <param name="dialogContext">Dialog Context.</param>
        /// <returns>A dictionary that can be included when calling the TrackEvent method on the TelemetryClient.</returns>
        protected virtual Dictionary <string, string> FillRecognizerResultTelemetryProperties(RecognizerResult recognizerResult, Dictionary <string, string> telemetryProperties, DialogContext dialogContext = null)
        {
            var properties = new Dictionary <string, string>
            {
                { "Text", recognizerResult.Text },
                { "AlteredText", recognizerResult.AlteredText },
                { "TopIntent", recognizerResult.Intents.Any() ? recognizerResult.Intents.First().Key : null },
                { "TopIntentScore", recognizerResult.Intents.Any() ? recognizerResult.Intents.First().Value?.ToString() : null },
                { "Intents", recognizerResult.Intents.Any() ? JsonConvert.SerializeObject(recognizerResult.Intents) : null },
                { "Entities", recognizerResult.Entities != null?recognizerResult.Entities.ToString() : null },
                { "AdditionalProperties", recognizerResult.Properties.Any() ? JsonConvert.SerializeObject(recognizerResult.Properties) : null },
            };

            // Additional Properties can override "stock" properties.
            if (telemetryProperties != null)
            {
                return(telemetryProperties.Concat(properties)
                       .GroupBy(kv => kv.Key)
                       .ToDictionary(g => g.Key, g => g.First().Value));
            }

            return(properties);
        }
Exemplo n.º 40
0
        public static Dictionary <string, string> ToPathValueDictionary(this JObject source)
        {
            var ret = new Dictionary <string, string>();

            foreach (var jToken in (JToken)source)
            {
                var t = (JProperty)jToken;

                var k = t.Name;
                var v = t.Value;

                if (v is JObject)
                {
                    ret = ret.Concat(ToPathValueDictionary((JObject)v)).ToDictionary(x => x.Key, x => x.Value);
                }
                else
                {
                    ret.Add(t.Path, v.ToString());
                }
            }

            return(ret);
        }
        /// <summary>
        /// Converts an <see cref="IEvent"/> object to EventStore's <see cref="EventData"/>.
        /// </summary>
        public static EventData ToEventData(this IEvent ev, Guid eventId, IDictionary <string, object> headers = null)
        {
            var type = ev.GetType();

            var eventHeaders = new Dictionary <string, object>(headers ?? NoHeaders)
            {
                { EventClrTypeHeader, type.FullName }
            };

            if (typeof(IEventWithMetadata).IsAssignableFrom(type))
            {
                var customEvent = (IEventWithMetadata)ev;
                eventHeaders = eventHeaders.Concat(customEvent.GetAdditionalMetadata())
                               .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            }

            var json = JsonConvert.SerializeObject(ev is PropertyChangedEvent e ? e.Value : ev);

            var data     = Encoding.UTF8.GetBytes(json);
            var metadata = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(eventHeaders, HeaderSerializationSettings));

            return(new EventData(eventId, type.Name, true, data, metadata));
        }
Exemplo n.º 42
0
        // Token: 0x060006F6 RID: 1782 RVA: 0x000216FC File Offset: 0x0001F8FC
        private Dictionary <AmServerName, RpcDatabaseCopyStatus2> GetStatusTable(out Dictionary <AmServerName, RpcHealthStateInfo[]> healthTable)
        {
            Dictionary <AmServerName, CopyStatusClientCachedEntry> cachedEntryTable = null;
            List <AmServerName> serversToContact = this.m_statusFetcher.ServersToContact;

            healthTable = null;
            Dictionary <Guid, Dictionary <AmServerName, CopyStatusClientCachedEntry> > status = this.m_statusFetcher.GetStatus(out healthTable);
            Dictionary <AmServerName, RpcDatabaseCopyStatus2> dictionary;

            if (status.TryGetValue(this.m_bcsContext.DatabaseGuid, out cachedEntryTable))
            {
                Dictionary <AmServerName, Exception> rpcErrorTable = null;
                rpcErrorTable = (from server in serversToContact
                                 let possibleEx = this.m_statusFetcher.GetPossibleExceptionForServer(server)
                                                  where possibleEx != null
                                                  select new KeyValuePair <AmServerName, Exception>(server, possibleEx)).ToDictionary((KeyValuePair <AmServerName, Exception> kvp) => kvp.Key, (KeyValuePair <AmServerName, Exception> kvp) => kvp.Value);
                IEnumerable <KeyValuePair <AmServerName, Exception> > second = from kvp in cachedEntryTable
                                                                               where !rpcErrorTable.ContainsKey(kvp.Key) && kvp.Value != null && kvp.Value.CopyStatus == null
                                                                               select new KeyValuePair <AmServerName, Exception>(kvp.Key, kvp.Value.LastException);
                IEnumerable <KeyValuePair <AmServerName, Exception> > rpcErrors = rpcErrorTable.Concat(second);
                AmBestCopySelection.ReportRpcErrors(rpcErrors, this.m_bcsContext);
                IEnumerable <CopyStatusClientCachedEntry> source = from server in serversToContact
                                                                   let possibleEx = this.m_statusFetcher.GetPossibleExceptionForServer(server)
                                                                                    where possibleEx == null && cachedEntryTable.ContainsKey(server) && cachedEntryTable[server].CopyStatus != null
                                                                                    select cachedEntryTable[server];
                dictionary = source.ToDictionary((CopyStatusClientCachedEntry entry) => entry.ServerContacted, (CopyStatusClientCachedEntry entry) => entry.CopyStatus);
            }
            else
            {
                dictionary = new Dictionary <AmServerName, RpcDatabaseCopyStatus2>();
            }
            if (dictionary.Count == 0)
            {
                ReplayCrimsonEvents.BcsDbNodeCopyStatusRpcFailed.Log <string, Guid>(this.m_bcsContext.GetDatabaseNameOrGuid(), this.m_bcsContext.DatabaseGuid);
            }
            return(dictionary);
        }
    public Dictionary <string, string> getSegmentAsDict()
    {
        Dictionary <string, string> temp = new Dictionary <string, string> ();

        if (age != -1)
        {
            temp.Add("age", age + "");
        }
        if (!string.IsNullOrEmpty(gender))
        {
            temp.Add("gender", gender);
        }
        if (level != -1)
        {
            temp.Add("level", level + "");
        }
        if (isPaying > -1 && isPaying < 2)
        {
            temp.Add("isPaying", isPaying + "");
        }
        if (userCreationDate != -1)
        {
            temp.Add("userCreationDate", userCreationDate + "");
        }
        if (!string.IsNullOrEmpty(segmentName))
        {
            temp.Add("segmentName", segmentName);
        }
        if (iapt > 0)
        {
            temp.Add("iapt", iapt + "");
        }

        Dictionary <string, string> result = temp.Concat(customs).GroupBy(d => d.Key).ToDictionary(d => d.Key, d => d.First().Value);

        return(result);
    }
Exemplo n.º 44
0
            public bool Search(string word, int index, Dictionary <string, TrieNode> potentialMatches)
            {
                if (potentialMatches == null || potentialMatches.Keys.Count == 0)
                {
                    return(false);
                }

                var character = word[index];

                if (index == word.Length - 1)
                {
                    if (!potentialMatches.Any(kvp => kvp.Key.Length == word.Length))
                    {
                        return(false);
                    }

                    var lastCharMatchFound = potentialMatches.Any(kvp =>
                                                                  kvp.Value.Count > 0 && DoCharsMatch(character, kvp.Key[index])
                                                                  );
                    return(lastCharMatchFound);
                }

                var newDictionary = new Dictionary <string, TrieNode>();

                foreach (var kvp in potentialMatches)
                {
                    if (DoCharsMatch(character, kvp.Key[index]))
                    {
                        newDictionary = newDictionary
                                        .Concat(kvp.Value.Children)
                                        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
                    }
                }
                potentialMatches = newDictionary;

                return(Search(word, index + 1, potentialMatches));
            }
Exemplo n.º 45
0
        /// <summary>
        /// 非同期処理で現在ログインしているユーザに、authDataの追加を行います。<br/>
        /// authDataが登録されていないユーザならログインし、authDataの登録を行います。<br/>
        /// authDataが登録されているユーザなら、authDataの追加を行います。<br/>
        /// 通信結果が必要な場合はコールバックを指定するこちらを使用します。
        /// </summary>
        /// <param name="linkParam">authData</param>
        /// <param name="callback">コールバック</param>
        public void LinkWithAuthDataAsync(Dictionary <string, object> linkParam, NCMBCallback callback)
        {
            if (this.AuthData == null)
            {
                // authDataの登録
                this.AuthData = linkParam;
                LogInWithAuthDataAsync(callback);
            }

            // authDataの退避
            Dictionary <string, object> currentParam = new Dictionary <string, object> ();

            currentParam = this.AuthData;

            this.AuthData = linkParam;

            SignUpAsync((NCMBException error) => {
                if (error == null)
                {
                    // authDataのmerge
                    var mergeParam = linkParam.Concat(currentParam).ToDictionary(x => x.Key, x => x.Value);
                    this.AuthData  = mergeParam;
                }
                else
                {
                    this.AuthData = currentParam;
                }

                if (callback != null)
                {
                    // callbackを実施
                    Platform.RunOnMainThread(delegate {
                        callback(error);
                    });
                }
            });
        }
        // Token: 0x0600072B RID: 1835 RVA: 0x00023324 File Offset: 0x00021524
        private void ConstructBcsStatusTable(List <AmServerName> serversToContact)
        {
            Dictionary <AmServerName, RpcHealthStateInfo[]>        stateInfoMap     = null;
            Dictionary <AmServerName, CopyStatusClientCachedEntry> cachedEntryTable = null;

            this.m_statusFetcher = new AmMultiNodeCopyStatusFetcher(serversToContact, new Guid[]
            {
                this.m_bcsContext.DatabaseGuid
            }, null, RpcGetDatabaseCopyStatusFlags2.ReadThrough, null, true);
            Dictionary <Guid, Dictionary <AmServerName, CopyStatusClientCachedEntry> > status = this.m_statusFetcher.GetStatus(out stateInfoMap);
            Dictionary <AmServerName, RpcDatabaseCopyStatus2> statusTable;

            if (status.TryGetValue(this.m_bcsContext.DatabaseGuid, out cachedEntryTable))
            {
                Dictionary <AmServerName, Exception> rpcErrorTable = null;
                rpcErrorTable = (from server in serversToContact
                                 let possibleEx = this.m_statusFetcher.GetPossibleExceptionForServer(server)
                                                  where possibleEx != null
                                                  select new KeyValuePair <AmServerName, Exception>(server, possibleEx)).ToDictionary((KeyValuePair <AmServerName, Exception> kvp) => kvp.Key, (KeyValuePair <AmServerName, Exception> kvp) => kvp.Value);
                IEnumerable <KeyValuePair <AmServerName, Exception> > second = from kvp in cachedEntryTable
                                                                               where !rpcErrorTable.ContainsKey(kvp.Key) && kvp.Value != null && kvp.Value.CopyStatus == null
                                                                               select new KeyValuePair <AmServerName, Exception>(kvp.Key, kvp.Value.LastException);
                IEnumerable <KeyValuePair <AmServerName, Exception> > rpcErrors = rpcErrorTable.Concat(second);
                AmBestCopySelection.ReportRpcErrors(rpcErrors, this.m_bcsContext);
                IEnumerable <CopyStatusClientCachedEntry> source = from server in serversToContact
                                                                   let possibleEx = this.m_statusFetcher.GetPossibleExceptionForServer(server)
                                                                                    where possibleEx == null && cachedEntryTable.ContainsKey(server) && cachedEntryTable[server].CopyStatus != null
                                                                                    select cachedEntryTable[server];
                statusTable = source.ToDictionary((CopyStatusClientCachedEntry entry) => entry.ServerContacted, (CopyStatusClientCachedEntry entry) => entry.CopyStatus);
            }
            else
            {
                statusTable = new Dictionary <AmServerName, RpcDatabaseCopyStatus2>();
            }
            this.m_bcsContext.StatusTable           = statusTable;
            this.m_bcsContext.ComponentStateWrapper = new ComponentStateWrapper(this.m_bcsContext.Database.Name, this.m_bcsContext.InitiatingComponent, this.m_bcsContext.SourceServerName, this.m_bcsContext.ActionCode, stateInfoMap);
        }
Exemplo n.º 47
0
        /// <summary>
        /// 获取Pool预览图
        /// </summary>
        /// <param name="previewInfoList">预览信息列表</param>
        /// <returns></returns>
        public static List <PoolPreviewInfo> GetPreviewImage(List <PoolPreviewInfo> previewInfoList)
        {
            //按md5首位分类
            var md5LookUp = previewInfoList.Select(a => a.file_md5).ToLookup(b => b.Substring(0, 1));

            //多线程查询结果集
            IEnumerable <KeyValuePair <string, byte[]> > result = new Dictionary <string, byte[]>();

            //根据查询图站数量创建线程
            Task <Dictionary <string, byte[]> >[] tasks = new Task <Dictionary <string, byte[]> > [md5LookUp.Count];
            int x = 0;

            foreach (var md5Group in md5LookUp)
            {
                tasks[x] = new Task <Dictionary <string, byte[]> >(p =>
                {
                    return(GetPreviewImageByGroup((IGrouping <string, string>)p));
                }, md5Group);
                x++;
            }

            //开启多线程查询
            foreach (var t in tasks)
            {
                t.Start();
            }

            Task.WaitAll(tasks);

            //合并多线程结果集
            foreach (var t in tasks)
            {
                result = result.Concat(t.Result);
            }

            return(PoolPreviewInfo.AddPreview(previewInfoList, result.ToDictionary(k => k.Key, v => v.Value)));
        }
Exemplo n.º 48
0
        private static IDictionary <string, EdmPrimitiveTypeKind> BuildEdmTypeMap()
        {
            //TODO: chceck if all types from SQL are here
            var map = new Dictionary <string, EdmPrimitiveTypeKind>
            {
                { "tinyint", EdmPrimitiveTypeKind.Byte },
                { "smallint", EdmPrimitiveTypeKind.Int16 },
                { "int", EdmPrimitiveTypeKind.Int32 },
                { "bigint", EdmPrimitiveTypeKind.Int64 },
                { "float", EdmPrimitiveTypeKind.Double },
                { "real", EdmPrimitiveTypeKind.Single },
                { "uniqueidentifier", EdmPrimitiveTypeKind.Guid },
                { "geography", EdmPrimitiveTypeKind.Geography },
                { "bit", EdmPrimitiveTypeKind.Boolean },
                { "binary", EdmPrimitiveTypeKind.Binary }
            };

            var stringTypes = new[] { "char", "nchar", "varchar", "nvarchar", "text", "ntext" }
            .ToDictionary(s => s, _ => EdmPrimitiveTypeKind.String);

            var decimalTypes = new[] { "decimal", "numeric", "money", "smallmoney" }
            .ToDictionary(s => s, _ => EdmPrimitiveTypeKind.Decimal);

            var dateTimeTypes = new[] { "datetime", "smalldatetime", "date" }
            .ToDictionary(s => s, _ => EdmPrimitiveTypeKind.DateTime);

            var timeStampTypes = new[] { "time", "timestamp" }
            .ToDictionary(s => s, _ => EdmPrimitiveTypeKind.DateTimeOffset);

            map = map.Concat(stringTypes)
                  .Concat(decimalTypes)
                  .Concat(dateTimeTypes)
                  .Concat(timeStampTypes)
                  .ToDictionary(x => x.Key, x => x.Value);

            return(map);
        }
        public void LogClientSideErrorAsync(
                string clientSideError_Description,
                string clientSideError_Url,                     //--> where did the error happend Ex.: someFileName.js
                string clientSideError_Line,                 //--> line where the error happend 
                string clientSideError_ParentUrl,       //--> url view route where did the error happend Ex.: http://www.domain.com/someUrl
                string clientSideError_UserAgent)
        {
            AsyncManager.OutstandingOperations.Increment();

            string LogTitle = string.Format("{0} {1}", MvcApplication.Name, LoggerCategories.UIClientSideJavascriptError);
            Dictionary<string, object> paramVariables = (from key in System.Web.HttpContext.Current.Request.ServerVariables.AllKeys
                                                         where System.Web.HttpContext.Current.Request.ServerVariables[key] != string.Empty
                                                         select new KeyValuePair<string, object>(key, System.Web.HttpContext.Current.Request.ServerVariables[key])).ToDictionary(k => k.Key, k => k.Value);
            Dictionary<string, object> paramLogger = new Dictionary<string, object>();

            Task.Factory.StartNew(() =>
            {
                try
                {
                    paramLogger.Add("clientSideError_Description", clientSideError_Description);
                    paramLogger.Add("clientSideError_Url", clientSideError_Url);
                    paramLogger.Add("clientSideError_Line", clientSideError_Line);
                    paramLogger.Add("clientSideError_ParentUrl", clientSideError_ParentUrl);
                    paramLogger.Add("clientSideError_UserAgent", clientSideError_UserAgent);
                    Dictionary<string, object> parameters = paramLogger.Concat(paramVariables).ToDictionary(x => x.Key, x => x.Value);
                    LogEntry lEntry = new LogEntry(LogTitle, LoggerCategories.UIClientSideJavascriptError, 1, 1, TraceEventType.Error, LogTitle, parameters);
                    LoggingHelper.Write(lEntry);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                AsyncManager.OutstandingOperations.Decrement();
            });
        }
Exemplo n.º 50
0
        public static Dictionary<string, string> UrlTitleDic(string baseUrl)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            string pageTail = "?page=1";
            string url = baseUrl + pageTail;

            while (true)
            {
                string html = GetHtml(url);

                Dictionary<string, string> temp = new Dictionary<string, string>();
                string pattern = "HomePageDays_DaysList_ctl\\d+_DayList_TitleUrl_0\" class=\"postTitle2\" href=\"(.+?)\">(.+?)</a>";
                temp = GetDictionary(html, pattern);
                dic = dic.Concat(temp).ToDictionary(k => k.Key, v => v.Value);

                string nextPageTail = GetNextPage(html);
                if (nextPageTail != "")
                    url = baseUrl + nextPageTail;
                else
                    break;
            }
            return dic;
        }
Exemplo n.º 51
0
        internal static IDictionary<string, Schema> GenerateSwaggerDefinitionsForArticles(
            IEnumerable<ArticleType> templateTypes)
        {
            var definitions = new Dictionary<string, Schema>();
            var articleProperties = new Dictionary<string, Schema>
            {
                ["id"] = new Schema
                {
                    type = "string",
                    description = "unique identifier for the object",
                },
                ["parentid"] = new Schema
                {
                    type = "string",
                    description = "unique identifier for the parent object",
                },
                ["parenttype"] = new Schema
                {
                    type = "string",
                    description = "type of the parent object",
                }
            };

            var articleRequired = new List<string>
            {
                "id",
                "parentid",
                "parenttype"
            };

            foreach (var templateType in templateTypes)
            {
                var combinedProperties = articleProperties
                    .Concat(GenerateTypeProperties(templateType).OrderBy(pair => pair.Key))
                    .ToDictionary(pair => pair.Key, pair => pair.Value);

                var schema = new Schema
                {
                    type = "object",
                    required = articleRequired,
                    properties = combinedProperties
                };
                var type = templateType.Type;

                definitions.Add($"{type}", schema);

                var resultSchema = new Schema
                {
                    type = "object",
                    properties = new Dictionary<string, Schema>
                    {
                        ["results"] = new Schema {type = "array", items = new Schema {@ref = type}}
                    }
                };
                definitions.Add($"ResultOf{type}", resultSchema);
            }

            var multiReferenceSchema = new Schema
            {
                type = "object",
                required = new[] { "values", "type" },
                properties = new Dictionary<string, Schema>
                {
                    ["type"] = new Schema
                    {
                        type = "string",
                        description = "type of the reference"
                    },
                    ["values"] = new Schema
                    {
                        type = "array",
                        items = new Schema {type = "string", description = "The unique id of referenced objects"}
                    }
                }
            };

            var singleReferenceSchema = new Schema
            {
                type = "object",
                required = new[] {"values", "type"},
                properties = new Dictionary<string, Schema>
                {
                    ["type"] = new Schema
                    {
                        type = "string",
                        description = "type of the reference"
                    },
                    ["values"] = new Schema
                    {
                        type = "array",
                        maxItems = 1,
                        items = new Schema {type = "string", description = "The unique id of referenced objects"}
                    }
                }
            };

            definitions.Add("MultiReference", multiReferenceSchema);
            definitions.Add("SingleReference", singleReferenceSchema);

            return definitions;
        }
Exemplo n.º 52
0
        internal static string ToSwaggerType(this Type type, out TypeCategory category, out Type containedType, IDictionary<string, string> customTypeMappings = null)
        {
            if (type == typeof (HttpResponseMessage))
            {
                category = TypeCategory.Unkown;
                containedType = null;
                return null;
            }

            if (type == null)
            {
                category = TypeCategory.Primitive;
                containedType = null;
                return "void";
            }

            var primitiveTypeMap = new Dictionary<string, string>
                {
                    {"Byte", "byte"},
                    {"Boolean", "boolean"},
                    {"Int32", "int"},
                    {"Int64", "long"},
                    {"Single", "float"},
                    {"Double", "double"},
                    {"Decimal", "double"},
                    {"String", "string"},
                    {"DateTime", "date"}
                };
            if (customTypeMappings != null)
                primitiveTypeMap = primitiveTypeMap.Concat(customTypeMappings).ToDictionary(m => m.Key, m => m.Value);

            if (primitiveTypeMap.ContainsKey(type.Name))
            {
                category = TypeCategory.Primitive;
                containedType = null;
                return primitiveTypeMap[type.Name];
            }

            Type innerTypeOfNullable;
            if (type.IsNullableType(out innerTypeOfNullable))
            {
                return innerTypeOfNullable.ToSwaggerType(out category, out containedType);
            }

            if (type.IsEnum)
            {
                category = TypeCategory.Primitive;
                containedType = null;
                return "string";
            }

            var enumerable = type.AsGenericType(typeof(IEnumerable<>));
            if (enumerable != null)
            {
                category = TypeCategory.Container;
                containedType = enumerable.GetGenericArguments().First();
                return String.Format("List[{0}]", containedType.ToSwaggerType(customTypeMappings));
            }

            category = TypeCategory.Complex;
            containedType = null;
            return type.Name;
        }
Exemplo n.º 53
0
        private void InitFilter()
        {
            var allBranches = new Dictionary<int, string>
            {
                { 0, GetString("AllBranches") }
            };
            var branches = User.CurrentUser.Branches.ToDictionary(b => b.Id, b => b.Name);
            allBranches = allBranches.Concat(branches).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            _branchFilterComboBox.ValueMember = "Key";
            _branchFilterComboBox.DisplayMember = "Value";
            _branchFilterComboBox.DataSource = new BindingSource(allBranches, null);

            var allUsers = new Dictionary<int, string>
            {
                { 0, GetString("AllUsers") }
            };
            var users = User.CurrentUser.Subordinates.Where(i => !i.IsDeleted).ToDictionary(u => u.Id, u => u.Name);
            allUsers = allUsers.Concat(users).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            _userFilterComboBox.ValueMember = "Key";
            _userFilterComboBox.DisplayMember = "Value";
            _userFilterComboBox.DataSource = new BindingSource(allUsers, null);

            var allLoanProducts = new Dictionary<int, string>
            {
                { 0, GetString("AllLoanProducts") }
            };
            var service = ServicesProvider.GetInstance().GetProductServices();
            var loanProducts = service.FindAllPackages(false, OClientTypes.All).ToDictionary(lp => lp.Id, lp => lp.Name);
            allLoanProducts = allLoanProducts.Concat(loanProducts).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            _loanProductFilterComboBox.ValueMember = "Key";
            _loanProductFilterComboBox.DisplayMember = "Value";
            _loanProductFilterComboBox.DataSource = new BindingSource(allLoanProducts, null);
        }
Exemplo n.º 54
0
        private static ApiBuildOutput FromModel(ItemViewModel model, Dictionary<string, ApiReferenceBuildOutput> references, Dictionary<string, object> metadata)
        {
            if (model == null) return null;

            var output = new ApiBuildOutput
            {
                Uid = model.Uid,
                Id = Utility.GetHtmlId(model.Uid),
                IsExplicitInterfaceImplementation = model.IsExplicitInterfaceImplementation,
                IsExtensionMethod = model.IsExtensionMethod,
                Parent = ApiBuildOutputUtility.GetReferenceViewModel(model.Parent, references, model.SupportedLanguages),
                Children = GetReferenceList(model.Children, references, model.SupportedLanguages),
                Href = model.Href,
                SupportedLanguages = model.SupportedLanguages,
                Name = ApiBuildOutputUtility.TransformToLanguagePairList(model.Name, model.Names, model.SupportedLanguages),
                NameWithType = ApiBuildOutputUtility.TransformToLanguagePairList(model.NameWithType, model.NamesWithType, model.SupportedLanguages),
                FullName = ApiBuildOutputUtility.TransformToLanguagePairList(model.FullName, model.FullNames, model.SupportedLanguages),
                Type = model.Type,
                Source = model.Source,
                Documentation = model.Documentation,
                AssemblyNameList = model.AssemblyNameList,
                NamespaceName = ApiBuildOutputUtility.GetReferenceViewModel(model.NamespaceName, references, model.SupportedLanguages),
                Summary = model.Summary,
                Remarks = model.Remarks,
                Examples = model.Examples,
                Syntax = ApiSyntaxBuildOutput.FromModel(model.Syntax, references, model.SupportedLanguages),
                Overridden = ApiBuildOutputUtility.GetApiNames(model.Overridden, references, model.SupportedLanguages),
                Overload = ApiBuildOutputUtility.GetApiNames(model.Overload, references, model.SupportedLanguages),
                Exceptions = GetCrefInfoList(model.Exceptions, references, model.SupportedLanguages),
                SeeAlsos = GetLinkInfoList(model.SeeAlsos, references, model.SupportedLanguages),
                Sees = GetLinkInfoList(model.Sees, references, model.SupportedLanguages),
                Inheritance = GetReferenceList(model.Inheritance, references, model.SupportedLanguages, true),
                Implements = model.Implements?.Select(u => ApiBuildOutputUtility.GetApiNames(u, references, model.SupportedLanguages)).ToList(),
                InheritedMembers = GetReferenceList(model.InheritedMembers, references, model.SupportedLanguages),
                ExtensionMethods = GetReferenceList(model.ExtensionMethods, references, model.SupportedLanguages),
                Conceptual = model.Conceptual,
                Platform = model.Platform,
                Attributes = model.Attributes,
                Metadata = metadata.Concat(model.Metadata.Where(p => !metadata.Keys.Contains(p.Key))).ToDictionary(p => p.Key, p => p.Value),
            };
            output.DerivedClasses = GetReferenceList(model.DerivedClasses, references, model.SupportedLanguages, true, output.Level + 1);
            return output;
        }
Exemplo n.º 55
0
        /// <summary>
        /// Called by the <see cref="BlockChain"/> when the best chain (representing total work done) has changed. In this case,
        /// we need to go through our transactions and find out if any have become invalid. It's possible for our balance
        /// to go down in this case: money we thought we had can suddenly vanish if the rest of the network agrees it
        /// should be so.
        /// </summary>
        /// <remarks>
        /// The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.
        /// </remarks>
        /// <exception cref="VerificationException"/>
        internal void Reorganize(IList<StoredBlock> oldBlocks, IList<StoredBlock> newBlocks)
        {
            lock (this)
            {
                // This runs on any peer thread with the block chain synchronized.
                //
                // The reorganize functionality of the wallet is tested in ChainSplitTests.
                //
                // For each transaction we track which blocks they appeared in. Once a re-org takes place we have to find all
                // transactions in the old branch, all transactions in the new branch and find the difference of those sets.
                //
                // receive() has been called on the block that is triggering the re-org before this is called.

                _log.Info("  Old part of chain (top to bottom):");
                foreach (var b in oldBlocks) _log.InfoFormat("    {0}", b.Header.HashAsString);
                _log.InfoFormat("  New part of chain (top to bottom):");
                foreach (var b in newBlocks) _log.InfoFormat("    {0}", b.Header.HashAsString);

                // Transactions that appear in the old chain segment.
                IDictionary<Sha256Hash, Transaction> oldChainTransactions = new Dictionary<Sha256Hash, Transaction>();
                // Transactions that appear in the old chain segment and NOT the new chain segment.
                IDictionary<Sha256Hash, Transaction> onlyOldChainTransactions = new Dictionary<Sha256Hash, Transaction>();
                // Transactions that appear in the new chain segment.
                IDictionary<Sha256Hash, Transaction> newChainTransactions = new Dictionary<Sha256Hash, Transaction>();
                // Transactions that don't appear in either the new or the old section, ie, the shared trunk.
                IDictionary<Sha256Hash, Transaction> commonChainTransactions = new Dictionary<Sha256Hash, Transaction>();

                IDictionary<Sha256Hash, Transaction> all = new Dictionary<Sha256Hash, Transaction>();
                foreach (var pair in Unspent.Concat(Spent).Concat(_inactive))
                {
                    all[pair.Key] = pair.Value;
                }
                foreach (var tx in all.Values)
                {
                    var appearsIn = tx.AppearsIn;
                    Debug.Assert(appearsIn != null);
                    // If the set of blocks this transaction appears in is disjoint with one of the chain segments it means
                    // the transaction was never incorporated by a miner into that side of the chain.
                    var inOldSection = appearsIn.Any(oldBlocks.Contains) || oldBlocks.Any(appearsIn.Contains);
                    var inNewSection = appearsIn.Any(newBlocks.Contains) || newBlocks.Any(appearsIn.Contains);
                    var inCommonSection = !inNewSection && !inOldSection;

                    if (inCommonSection)
                    {
                        Debug.Assert(!commonChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in common chain segment");
                        commonChainTransactions[tx.Hash] = tx;
                    }
                    else
                    {
                        if (inOldSection)
                        {
                            Debug.Assert(!oldChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in old chain segment");
                            oldChainTransactions[tx.Hash] = tx;
                            if (!inNewSection)
                            {
                                Debug.Assert(!onlyOldChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in only-old map");
                                onlyOldChainTransactions[tx.Hash] = tx;
                            }
                        }
                        if (inNewSection)
                        {
                            Debug.Assert(!newChainTransactions.ContainsKey(tx.Hash), "Transaction appears twice in new chain segment");
                            newChainTransactions[tx.Hash] = tx;
                        }
                    }
                }

                // If there is no difference it means we have nothing we need to do and the user does not care.
                var affectedUs = oldChainTransactions.Count != newChainTransactions.Count ||
                                 !oldChainTransactions.All(
                                     item =>
                                     {
                                         Transaction rightValue;
                                         return newChainTransactions.TryGetValue(item.Key, out rightValue) && Equals(item.Value, rightValue);
                                     });
                _log.Info(affectedUs ? "Re-org affected our transactions" : "Re-org had no effect on our transactions");
                if (!affectedUs) return;

                // For simplicity we will reprocess every transaction to ensure it's in the right bucket and has the right
                // connections. Attempting to update each one with minimal work is possible but complex and was leading to
                // edge cases that were hard to fix. As re-orgs are rare the amount of work this implies should be manageable
                // unless the user has an enormous wallet. As an optimization fully spent transactions buried deeper than
                // 1000 blocks could be put into yet another bucket which we never touch and assume re-orgs cannot affect.

                foreach (var tx in onlyOldChainTransactions.Values) _log.InfoFormat("  Only Old: {0}", tx.HashAsString);
                foreach (var tx in oldChainTransactions.Values) _log.InfoFormat("  Old: {0}", tx.HashAsString);
                foreach (var tx in newChainTransactions.Values) _log.InfoFormat("  New: {0}", tx.HashAsString);

                // Break all the existing connections.
                foreach (var tx in all.Values)
                    tx.DisconnectInputs();
                foreach (var tx in Pending.Values)
                    tx.DisconnectInputs();
                // Reconnect the transactions in the common part of the chain.
                foreach (var tx in commonChainTransactions.Values)
                {
                    var badInput = tx.ConnectForReorganize(all);
                    Debug.Assert(badInput == null, "Failed to connect " + tx.HashAsString + ", " + badInput);
                }
                // Recalculate the unspent/spent buckets for the transactions the re-org did not affect.
                Unspent.Clear();
                Spent.Clear();
                _inactive.Clear();
                foreach (var tx in commonChainTransactions.Values)
                {
                    var unspentOutputs = 0;
                    foreach (var output in tx.Outputs)
                    {
                        if (output.IsAvailableForSpending) unspentOutputs++;
                    }
                    if (unspentOutputs > 0)
                    {
                        _log.InfoFormat("  TX {0}: ->unspent", tx.HashAsString);
                        Unspent[tx.Hash] = tx;
                    }
                    else
                    {
                        _log.InfoFormat("  TX {0}: ->spent", tx.HashAsString);
                        Spent[tx.Hash] = tx;
                    }
                }
                // Now replay the act of receiving the blocks that were previously in a side chain. This will:
                //   - Move any transactions that were pending and are now accepted into the right bucket.
                //   - Connect the newly active transactions.
                foreach (var b in newBlocks.Reverse()) // Need bottom-to-top but we get top-to-bottom.
                {
                    _log.InfoFormat("Replaying block {0}", b.Header.HashAsString);
                    ICollection<Transaction> txns = new HashSet<Transaction>();
                    foreach (var tx in newChainTransactions.Values)
                    {
                        if (tx.AppearsIn.Contains(b))
                        {
                            txns.Add(tx);
                            _log.InfoFormat("  containing tx {0}", tx.HashAsString);
                        }
                    }
                    foreach (var t in txns)
                    {
                        Receive(t, b, BlockChain.NewBlockType.BestChain, true);
                    }
                }

                // Find the transactions that didn't make it into the new chain yet. For each input, try to connect it to the
                // transactions that are in {spent,unspent,pending}. Check the status of each input. For inactive
                // transactions that only send us money, we put them into the inactive pool where they sit around waiting for
                // another re-org or re-inclusion into the main chain. For inactive transactions where we spent money we must
                // put them back into the pending pool if we can reconnect them, so we don't create a double spend whilst the
                // network heals itself.
                IDictionary<Sha256Hash, Transaction> pool = new Dictionary<Sha256Hash, Transaction>();
                foreach (var pair in Unspent.Concat(Spent).Concat(Pending))
                {
                    pool[pair.Key] = pair.Value;
                }
                IDictionary<Sha256Hash, Transaction> toReprocess = new Dictionary<Sha256Hash, Transaction>();
                foreach (var pair in onlyOldChainTransactions.Concat(Pending))
                {
                    toReprocess[pair.Key] = pair.Value;
                }
                _log.Info("Reprocessing:");
                // Note, we must reprocess dead transactions first. The reason is that if there is a double spend across
                // chains from our own coins we get a complicated situation:
                //
                // 1) We switch to a new chain (B) that contains a double spend overriding a pending transaction. It goes dead.
                // 2) We switch BACK to the first chain (A). The dead transaction must go pending again.
                // 3) We resurrect the transactions that were in chain (B) and assume the miners will start work on putting them
                //    in to the chain, but it's not possible because it's a double spend. So now that transaction must become
                //    dead instead of pending.
                //
                // This only occurs when we are double spending our own coins.
                foreach (var tx in _dead.Values.ToList())
                {
                    ReprocessTxAfterReorg(pool, tx);
                }
                foreach (var tx in toReprocess.Values)
                {
                    ReprocessTxAfterReorg(pool, tx);
                }

                _log.InfoFormat("post-reorg balance is {0}", Utils.BitcoinValueToFriendlyString(GetBalance()));

                // Inform event listeners that a re-org took place.
                if (Reorganized != null)
                {
                    // Synchronize on the event listener as well. This allows a single listener to handle events from
                    // multiple wallets without needing to worry about being thread safe.
                    lock (Reorganized)
                    {
                        Reorganized(this, EventArgs.Empty);
                    }
                }
            }
        }
Exemplo n.º 56
0
    private Dictionary<int, NowAndNext> GetNowAndNext(List<Channel> tvChannelList, DateTime nextEPGupdate)
    {
      Dictionary<int, NowAndNext> getNowAndNextSegment = new Dictionary<int, NowAndNext>();
      Dictionary<int, NowAndNext> getNowAndNext = new Dictionary<int, NowAndNext>();
      int idGroup = TVHome.Navigator.CurrentGroup.IdGroup;

      TvBusinessLayer layer = new TvBusinessLayer();
      if (_listNowNext.TryGetValue(idGroup, out getNowAndNext))
      {
        bool updateNow = (DateTime.Now >= nextEPGupdate);
        if (updateNow)
        {
          getNowAndNext = new Dictionary<int, NowAndNext>();
          List<List<Channel>> tvChannelListSegments = SplitChannelList(tvChannelList, 100);
          foreach (List<Channel> tvChannelListSegment in tvChannelListSegments)
          {
            getNowAndNextSegment = layer.GetNowAndNext(tvChannelListSegment);
            getNowAndNext = getNowAndNext.Concat(getNowAndNextSegment).ToDictionary(x => x.Key, x => x.Value);
          }

          _listNowNext[idGroup] = getNowAndNext;
        }
      }
      else
      {
        getNowAndNext = new Dictionary<int, NowAndNext>();
        List<List<Channel>> tvChannelListSegments = SplitChannelList(tvChannelList, 100);
        foreach (List<Channel> tvChannelListSegment in tvChannelListSegments)
        {
          getNowAndNextSegment = layer.GetNowAndNext(tvChannelListSegment);
          getNowAndNext = getNowAndNext.Concat(getNowAndNextSegment).ToDictionary(x => x.Key, x => x.Value);
        }
        _listNowNext.Add(idGroup, getNowAndNext);
      }
      return getNowAndNext;
    }
        private HttpCall SendSync(RestRequest request, bool retryInvalidToken)
        {
            string url = _instanceUrl + request.Path;
            Dictionary<string, string> headers = new Dictionary<string, string>() {};
            if (_accessToken != null) 
            {
                headers["Authorization"] = "Bearer " + _accessToken;
            }
            if (request.AdditionalHeaders != null)
            {
                headers.Concat(request.AdditionalHeaders);
            }

            HttpCall call = new HttpCall(request.Method, headers, url, request.Body, request.ContentType).Execute().Result;

            if (!call.HasResponse)
            {
                throw call.Error;
            }

            if (call.StatusCode == HttpStatusCode.Unauthorized)
            {
                if (retryInvalidToken && _accessTokenProvider != null)
                {
                    string newAccessToken = _accessTokenProvider().Result;
                    if (newAccessToken != null)
                    {
                        _accessToken = newAccessToken;
                        call = SendSync(request, false);
                    }
                }
            }

            // Done
            return call;
        }
        public static Dictionary<NPC, int> GetSpawnBuffByName(string theString)
        {
            Dictionary<NPC, int> theList = new Dictionary<NPC, int>();
            theString = theString.ToLower();
            for (int i = 0; i < spawnGroups.Keys.ToArray().Count(); i++)
            {
                if (spawnGroups.Keys.ToArray()[i].ToLower() == theString)
                {

                    theList = spawnGroups.Values.ToArray()[i];
                    return (theList);

                }
                else if (spawnGroups.Keys.ToArray()[i].ToLower().StartsWith(theString))
                {

                    theList.Concat(spawnGroups.Values.ToArray()[i]);

                }

            }
            return (theList);
        }
Exemplo n.º 59
0
        private static Dictionary<string, string> Merge(TokenClient client, Dictionary<string, string> explicitValues, object extra = null)
        {
            var merged = explicitValues;

            if (client.AuthenticationStyle == AuthenticationStyle.PostValues)
            {
                merged.Add(OidcConstants.TokenRequest.ClientId, client.ClientId);

                if (!string.IsNullOrEmpty(client.ClientSecret))
                {
                    merged.Add(OidcConstants.TokenRequest.ClientSecret, client.ClientSecret);
                }
            }

            var additionalValues = ObjectToDictionary(extra);

            if (additionalValues != null)
            {
                merged =
                    explicitValues.Concat(additionalValues.Where(add => !explicitValues.ContainsKey(add.Key)))
                                         .ToDictionary(final => final.Key, final => final.Value);
            }

            return merged;
        }
Exemplo n.º 60
0
        private void signRequest( HttpWebRequest con, string method, string resource, Dictionary<string, string> headers )
        {
            // Build the string to hash.
            StringBuilder hashStr = new StringBuilder();
            MemoryStream ms = new MemoryStream();

            hashStr.Append( method + "\n" );

            // If content type exists, add it.  Otherwise add a blank line.
            if( headers.ContainsKey( "Content-Type" ) ) {
                log.TraceEvent(TraceEventType.Verbose, 0,  "Content-Type: " + headers["Content-Type"] );
                hashStr.Append( headers["Content-Type"] + "\n" );
            } else {
                hashStr.Append( "\n" );
            }

            // If the range header exists, add it.  Otherwise add a blank line.
            if( headers.ContainsKey( "Range" ) ) {
                hashStr.Append( headers["Range"] + "\n" );
            } else {
                hashStr.Append( "\n" );
            }

            // Add the current date and the resource.
            hashStr.Append(headers["Date"] + "\n");
            hashStr.Append( resource.ToLower() + "\n" );

            // Up to here, we're using UTF-8 to encode the path.  Other headers will
            // Be ISO-8859-1, so write the bytes and start over.
            byte[] utfbytes = Encoding.UTF8.GetBytes(hashStr.ToString());
            ms.Write(utfbytes, 0, utfbytes.Length);
            hashStr = new StringBuilder();

            // Do the 'x-emc' headers.  The headers must be hashed in alphabetic
            // order and the values must be stripped of whitespace and newlines.
            List<string> keys = new List<string>();
            Dictionary<string, string> newheaders = new Dictionary<string, string>();

            // Extract the keys and values
            foreach( string key in headers.Keys ) {
                if( key.IndexOf( "x-emc" ) == 0 ) {
                    keys.Add( key.ToLower() );
                    newheaders.Add( key.ToLower(), normalizeHeaderValue(headers[key]) );
                }
            }

            // Sort the keys and add the headers to the hash string.
            keys.Sort();
            bool first = true;
            foreach( string key in keys ) {
                if( !first ) {
                    hashStr.Append( "\n" );
                } else {
                    first = false;
                }
                //this.trace( "xheader: " . k . "." . newheaders[k] );
                hashStr.Append( key + ':' + newheaders[key] );
            }
            byte[] latinbytes = headerEncoder.GetBytes(hashStr.ToString());
            ms.Write(latinbytes, 0, latinbytes.Length);

            string hashOut = sign(ms.ToArray());

            // add custom headers (i.e. for 3rd party authentication proxy)
            if (customHeaders != null) headers = headers.Concat(customHeaders).ToDictionary(e => e.Key, e => e.Value);

            // Can set all the headers, etc now.  Microsoft doesn't let you
            // set some of the headers directly.  Modify the headers through
            // reflection to get around this.
            MethodInfo m = con.Headers.GetType().GetMethod( "AddWithoutValidate", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance, null,
                new Type[] { typeof( string ), typeof( string ) }, null );

            foreach( string name in headers.Keys ) {
                log.TraceEvent(TraceEventType.Verbose, 0,  "Setting " + name );
                m.Invoke( con.Headers, new object[] { name, headers[name] } );
            }

            // Set the signature header
            con.Headers["x-emc-signature"] = hashOut;

            // Set the method.
            con.Method = method;
        }