Example #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();
        }
Example #2
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;
        }
Example #4
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;
		}
Example #6
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);
        }
        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);
        }
 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;
 }
Example #9
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;
     }
 }
Example #10
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);
        }
Example #11
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();
        }
Example #12
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;
        }
Example #14
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;
        }
        // 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;
        }
Example #17
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;
        }
Example #18
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);
        }
Example #19
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;
        }
        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();
            });
        }
Example #21
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;
        }
Example #22
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;
        }
Example #23
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);
        }
        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);
        }
        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;
        }
Example #26
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;
        }
        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;
        }
Example #28
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;
    }
Example #29
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);
                    }
                }
            }
        }
Example #30
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;
        }