コード例 #1
0
ファイル: UnionTests.cs プロジェクト: cureos/dictionarylinq
        public void UnionDefaultEqualityComparer_SameKeyDifferentValues_Throws()
        {
            var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 }, { 6, 4 } };
            var second = new SortedList<int, int> { { 3, 2 }, { 6, 4 } };

            var actual = first.Union(second, EqualityComparer<KeyValuePair<int, int>>.Default);
        }
コード例 #2
0
        static void ARPScan(ScanOptions options)
        {
            Dictionary<IPAddress, List<ArpEntry>> results = new Dictionary<IPAddress, List<ArpEntry>>();

            IEnumerable<string> targets;

            if (options.FromFile)
            {
                List<string> targetList = new List<string>();
                foreach (string filename in options.StringSeq)
                {
                    using (System.IO.TextReader r = System.IO.File.OpenText(filename))
                    {
                        string s = String.Empty;
                        while ((s = r.ReadLine()) != null)
                        {
                            string[] separators = options.separator == "" ?
                                new string[] { System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator } :
                                new string[] { options.separator };
                            string[] lineElts = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                            if(lineElts.Length == 1) //IP only
                            {
                                targetList.Add(lineElts[0]);
                            }
                            else if (lineElts.Length == 2) //Target name,IP
                            {
                                targetList.Add(lineElts[1]);
                            }
                        }
                    }
                }
                targets = targetList;
            }
            else
            {
                targets = options.StringSeq;
            }

            foreach (string target in targets)
            {
                Dictionary<IPAddress, List<ArpEntry>> scanresult = ScanTarget(target, options);
                results = results.Union(scanresult).ToDictionary(k => k.Key, v => v.Value);
            }

            if (options.OutputFileName != "")
            {
                OutputToCSV(results, options);
            }
            else
            {
                foreach (IPAddress ipaddr in results.Keys)
                {
                    foreach (ArpEntry entry in results[ipaddr])
                        Console.WriteLine("On {0}, IP {1} : MAC {2}", ipaddr, entry.ipEntry.AddressList[0], entry.physAddress);
                }
                Console.ReadLine();
            }
        }
コード例 #3
0
ファイル: UnionTests.cs プロジェクト: cureos/dictionarylinq
        public void UnionNoEqualityComparer_SameKeyInSecondDict_TakesDuplicateKeyValuePair()
        {
            var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 }, { 6, 4 } };
            var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } };

            var expected = 4;
            var actual = first.Union(second).Count;
            Assert.AreEqual(expected, actual);
        }
コード例 #4
0
ファイル: JsonDB.cs プロジェクト: badjer/Lasy
 public Dictionary<string, object> Insert(string tableName, Dictionary<string, object> row)
 {
     var allRows = _getTable(tableName);
     var keys = _getKeys(tableName, row, allRows);
     var prepedRow = row.Union(keys);
     var toWrite = allRows.And(prepedRow);
     _writeTable(tableName, toWrite);
     return keys;
 }
コード例 #5
0
 public IDictionary<TestCase, int> ReadTestDurations(IEnumerable<TestCase> testcases)
 {
     IDictionary<string, List<TestCase>> groupedTestcases = testcases.GroupByExecutable();
     var durations = new Dictionary<TestCase, int>();
     foreach (string executable in groupedTestcases.Keys)
     {
         durations = durations.Union(ReadTestDurations(executable, groupedTestcases[executable])).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
     }
     return durations;
 }
コード例 #6
0
ファイル: MatrixPetriNet.cs プロジェクト: aabs/PetriNets
 public MatrixPetriNet(string id,
     Dictionary<int, string> placeNames,
     Dictionary<int, string> transitionNames,
     Dictionary<int, List<InArc>> inArcs,
     Dictionary<int, List<OutArc>> outArcs,
     Dictionary<int, int> transitionOrdering)
     : this(id, placeNames, transitionNames, inArcs, outArcs)
 {
     var x = transitionNames.Select(t => t.Key).Except(transitionOrdering.Select(t => t.Key));
     var y = transitionOrdering.Union(x.ToDictionary(t => t, t => 0)); // baseline priority level
     TransitionPriorities = y.ToDictionary(a => a.Key, a => a.Value);
 }
コード例 #7
0
        static AuditActionMapper()
        {
            actions = new Dictionary<MessageAction, MessageMaps>();

            actions = actions
                .Union(LoginActionsMapper.GetMaps())
                .Union(ProjectsActionsMapper.GetMaps())
                .Union(CrmActionMapper.GetMaps())
                .Union(PeopleActionMapper.GetMaps())
                .Union(DocumentsActionMapper.GetMaps())
                .Union(SettingsActionsMapper.GetMaps())
                .ToDictionary(x => x.Key, x => x.Value);
        }
コード例 #8
0
ファイル: Data.cs プロジェクト: CreepGin/D3Bit
 public static void LoadAffixes(string languageCode)
 {
     string json = File.ReadAllText(string.Format(@"data\affixes.{0}.json", languageCode));
     affixMatches = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
     json = File.ReadAllText(string.Format(@"data\strings.{0}.json", languageCode));
     var strings = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(json);
     ItemQualities = strings["ItemQualities"];
     WeaponTypes = strings["WeaponTypes"];
     OffHandTypes = strings["OffHandTypes"];
     FollowerTypes = strings["FollowerTypes"];
     CommonTypes = strings["CommonTypes"];
     ItemTypes = WeaponTypes.Union(OffHandTypes).Union(CommonTypes).ToDictionary(a => a.Key, b => b.Value);
 }
コード例 #9
0
ファイル: IReadWrite.cs プロジェクト: badjer/Lasy
 /// <summary>
 /// Inserts the row if it doesn't exist, update the row(s) if they do
 /// </summary>
 /// <param name="readWrite"></param>
 /// <param name="tablename"></param>
 /// <param name="dataFields"></param>
 /// <param name="keyFields"></param>
 /// <param name="trans"></param>
 public static void Ensure(this IReadWrite readWrite,
     string tablename,
     Dictionary<string, object> dataFields,
     Dictionary<string, object> keyFields)
 {
     // See if the keyFields exist
     // If so, update them, otherwise insert them
     var existing = readWrite.Read(tablename, keyFields);
     if (existing.Any())
         readWrite.Update(tablename, dataFields, keyFields);
     else
     {
         var newRow = dataFields.Union(keyFields);
         var newKeys = readWrite.Insert(tablename, newRow);
     }
 }
コード例 #10
0
        public override Dictionary <string, string> ReadXML(XmlDocument xmlDoc)
        {
            var doc               = xmlDoc;
            var PositiveReply     = doc.GetElementsByTagName("PositiveReply").Item(0).InnerText;
            var calibAngle        = doc.GetElementsByTagName("CalibrationAngle").Item(0).InnerText;
            var manipAdvanceAngle = doc.GetElementsByTagName("ManipulatorAdvanceAngle").Item(0).InnerText;
            var distBetCenters    = doc.GetElementsByTagName("DistanceBetweenCenters").Item(0).InnerText;

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

            ret.Add("PositiveReply", PositiveReply);
            ret.Add("CalibrationAngle", calibAngle);
            ret.Add("ManipulatorAdvanceAngle", manipAdvanceAngle);
            ret.Add("DistanceBetweenCenters", distBetCenters);
            return(ret.Union(base.ReadXML(xmlDoc)).ToDictionary(k => k.Key, k => k.Value));
        }
コード例 #11
0
        /// <summary>
        /// 获取参数到键值集合根据页面Request参数
        /// </summary>
        /// <returns></returns>
        public static Dictionary <string, string> GetParameterDictionary(bool isNotNullAndEmpty = false)
        {
            Dictionary <string, string> paraDictionaryByGet = HttpContext.Current.Request.QueryString.Keys.Cast <string>()
                                                              .ToDictionary(k => k, v => HttpContext.Current.Request.QueryString[v]);

            Dictionary <string, string> paraDictionaryByPost = HttpContext.Current.Request.Form.Keys.Cast <string>()
                                                               .ToDictionary(k => k, v => HttpContext.Current.Request.Form[v]);

            var paraDictionarAll = paraDictionaryByGet.Union(paraDictionaryByPost);

            if (isNotNullAndEmpty)
            {
                paraDictionarAll = paraDictionarAll.Where(it => !string.IsNullOrEmpty(it.Value));
            }
            return(paraDictionarAll.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value));;
        }
コード例 #12
0
ファイル: SqlSugarTool.cs プロジェクト: TestOrg002/SqlSugar
        /// <summary>
        /// 获取参数到键值集合根据页面Request参数
        /// </summary>
        /// <returns></returns>
        public static SqlParameter[] GetParameterArray(bool isNotNullAndEmpty = false)
        {
            Dictionary <string, string> paraDictionaryByGet = HttpContext.Current.Request.QueryString.Keys.Cast <string>()
                                                              .ToDictionary(k => k, v => HttpContext.Current.Request.QueryString[v]);

            Dictionary <string, string> paraDictionaryByPost = HttpContext.Current.Request.Form.Keys.Cast <string>()
                                                               .ToDictionary(k => k, v => HttpContext.Current.Request.Form[v]);

            var paraDictionarAll = paraDictionaryByGet.Union(paraDictionaryByPost);

            if (isNotNullAndEmpty)
            {
                paraDictionarAll = paraDictionarAll.Where(it => !string.IsNullOrEmpty(it.Value));
            }
            return(paraDictionarAll.Select(it => new SqlParameter("@" + it.Key, it.Value)).ToArray());
        }
コード例 #13
0
        public string CreateHtmlText(string testHtmlTemplate, Dictionary <string, string> frameworkReplacements)
        {
            var testJsReplacement                = new StringBuilder();
            var testFrameworkDependencies        = new StringBuilder();
            var codeCoverageDependencies         = new StringBuilder();
            var referenceJsReplacement           = new StringBuilder();
            var referenceCssReplacement          = new StringBuilder();
            var referenceHtmlTemplateReplacement = new StringBuilder();

            BuildReferenceHtml(testFrameworkDependencies,
                               referenceCssReplacement,
                               testJsReplacement,
                               referenceJsReplacement,
                               referenceHtmlTemplateReplacement,
                               codeCoverageDependencies);


            string amdTestFilePath = "";
            string amdModuleMap    = "";

            if (chutzpahTestSettings.TestHarnessReferenceMode == TestHarnessReferenceMode.AMD)
            {
                amdTestFilePath = referencedFiles.First(x => x.IsFileUnderTest).AmdFilePath;
                amdModuleMap    = BuildModuleMapForGeneratedFiles();
            }

            var replacements = new Dictionary <string, string>
            {
                { "TestFrameworkDependencies", testFrameworkDependencies.ToString() },
                { "CodeCoverageDependencies", codeCoverageDependencies.ToString() },
                { "TestJSFile", testJsReplacement.ToString() },
                { "ReferencedJSFiles", referenceJsReplacement.ToString() },
                { "ReferencedCSSFiles", referenceCssReplacement.ToString() },
                { "TestHtmlTemplateFiles", referenceHtmlTemplateReplacement.ToString() },
                { "AMDTestPath", amdTestFilePath },
                { "AMDModuleMap", amdModuleMap }
            };

            var testHtmlStringBuilder = new StringBuilder(testHtmlTemplate);

            foreach (var replacement in replacements.Union(frameworkReplacements))
            {
                testHtmlStringBuilder.Replace("@@" + replacement.Key + "@@", replacement.Value);
            }

            return(testHtmlStringBuilder.ToString());
        }
コード例 #14
0
        protected override void RunProcess()
        {
            string json;

            using (WebClient wc = new WebClient())
            {
                wc.Encoding = Encoding.UTF8;
                json        = wc.DownloadString(string.Format(Resources.UrlSteamCuratorRecommendations, curatorId, 0));
            }

            JObject parsedJson = JObject.Parse(json);

            if (int.TryParse(parsedJson["total_count"].ToString(), out TotalCount))
            {
                SetText(GlobalStrings.CDlgCurator_GettingRecommendations + " " + string.Format(GlobalStrings.CDlg_Progress, 0, TotalCount));
                string resultsHtml = parsedJson["results_html"].ToString();
                CuratorRecommendations = CuratorRecommendations.Union(GetCuratorRecommendationsFromPage(resultsHtml)).ToDictionary(k => k.Key, v => v.Value);
                for (int currentPosition = 50; currentPosition < TotalCount; currentPosition += 50)
                {
                    SetText(GlobalStrings.CDlgCurator_GettingRecommendations + " " + string.Format(GlobalStrings.CDlg_Progress, currentPosition, TotalCount));
                    using (WebClient wc = new WebClient())
                    {
                        wc.Encoding = Encoding.UTF8;
                        json        = wc.DownloadString(string.Format(Resources.UrlSteamCuratorRecommendations, curatorId, currentPosition));
                    }

                    parsedJson             = JObject.Parse(json);
                    resultsHtml            = parsedJson["results_html"].ToString();
                    CuratorRecommendations = CuratorRecommendations.Union(GetCuratorRecommendationsFromPage(resultsHtml)).ToDictionary(k => k.Key, v => v.Value);
                }
            }
            else
            {
                Program.Logger.Write(LoggerLevel.Error, "Error: CDlgCurator: Couldn't determine total count of recommendations");
            }

            if (CuratorRecommendations.Count != TotalCount)
            {
                Program.Logger.Write(LoggerLevel.Error, "Error: CDlgCurator: Count of recommendations retrieved is different than expected");
            }
            else
            {
                Program.Logger.Write(LoggerLevel.Error, string.Format("Retrieved {0} curator recommendations.", TotalCount));
            }

            OnThreadCompletion();
        }
コード例 #15
0
        /// <summary>
        /// Merges the activities if they are in a collection
        /// </summary>
        private void CollectionMerge()
        {
            // Duplicate activities collection to allow modifications
            var clone = Activities.ToDictionary(entry => entry.Key, entry => entry.Value);

            // Select distinct collection id's
            var query = clone.Values.Select(item => item.CollectionId).Distinct();

            foreach (var item in query)
            {
                var list = Activities.Values.Where(x => x.CollectionId != 0 && x.CollectionId.Equals(item) && x.IsCollection == true);

                // Groups the lessons by the number of lesson of the week.
                var group = from a in list
                            group a by new { a.NumberLessonOfWeek, a.GradeId } into g
                select g;

                foreach (var i in group)
                {
                    var students = new Dictionary <string, int>();
                    var teachers = new List <int>();

                    // Select all students and teachers for this group
                    i.Select(x => x.Students).ToList().ForEach(l => students = students.Union(l).ToDictionary(s => s.Key, s => s.Value));
                    i.Select(x => x.Teachers).ToList().ForEach(teachers.AddRange);

                    // Create collection activity
                    var act = new Activity
                    {
                        Teachers           = teachers.Distinct().ToList(),
                        Students           = students,
                        Id                 = i.First().Id,
                        GroupId            = i.First().GroupId,
                        Duration           = i.First().Duration,
                        TotalDuration      = i.First().TotalDuration,
                        NumberLessonOfWeek = i.First().NumberLessonOfWeek,
                        IsCollection       = true,
                        CollectionId       = i.First().CollectionId
                    };

                    // Remove the original activities
                    i.Select(x => x.Id).ToList().ForEach(x => Activities.Remove(x));
                    Activities.Add(act.Id, act);
                }
            }
        }
コード例 #16
0
        private Dictionary <string, IEnumerable <string> > GetAppConfigSettings(string sysConfigSetName, string appConfigSetName)
        {
            // Get the AppSettings DbCommand from the cache - create one if NOT exist in the cache
            DbCommand dbCmd = _daMgr.DbCmdCacheGetOrAdd(Configuration.Constants.AppSettingCacheName, CreateAppSettingsDbCommand);

            // Get the system config set name
            Dictionary <string, IEnumerable <string> > sys =
                _daMgr.ExecuteReader(dbCmd, null, rdr => CreateAppConfigSettingDictionary(rdr, sysConfigSetName),
                                     _daMgr.BuildParamName(Configuration.Constants.ConfigSetName), sysConfigSetName);

            // Get the application config set name
            Dictionary <string, IEnumerable <string> > app =
                _daMgr.ExecuteReader(dbCmd, null, rdr => CreateAppConfigSettingDictionary(rdr, null),
                                     _daMgr.BuildParamName(Configuration.Constants.ConfigSetName), appConfigSetName);

            return(sys.Union(app).ToDictionary(kv => kv.Key, kv => kv.Value));
        }
        public static Dictionary <string, object> ToUpdateGuestUserInput(this UserData userData)
        {
            var data = new Dictionary <string, object>();

            data.Add("displayName", userData.DisplayName);
            data.Add("givenName", userData.GivenName);
            data.Add("surname", userData.SurName);

            var customAttributes = GetCustomAttributes(userData);

            if (customAttributes.Any())
            {
                data = data.Union(customAttributes).ToDictionary(d => d.Key, d => d.Value);
            }

            return(data);
        }
コード例 #18
0
        public async Task Send(IDictionary <string, string> headers, string content, string contentType = "plain/text", Encoding encoding = null)
        {
            encoding = encoding ?? Encoding.UTF8;

            var byteContent = encoding.GetBytes(content);

            var standardHeaders = new Dictionary <string, string>
            {
                ["session"]        = CurrentSession.SessionId,
                ["content-length"] = byteContent.Length.ToString(),
                ["content-type"]   = $"{contentType};charset=utf-8"
            };

            Parser.WriteStompFrame(NetStream, new StompFrame(StompCommand.SEND, standardHeaders.Union(headers), byteContent));

            var response = await Parser.ReadStompFrame(NetStream).UnWrapFrame();
        }
コード例 #19
0
        private static MvcHtmlString DatetimeFormFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper,
                                                                         Expression <Func <TModel, TProperty> > expression,
                                                                         IDictionary <string, object> htmlAttributes = null, string format = null)
        {
            var tmpHtmlAttribute = new Dictionary <string, object>
            {
                {
                    "onclick",
                    "WdatePicker({name:'simple', charset:'gb2312',dateFmt:'" + (string.IsNullOrEmpty(format) ? sysConfig.DefaultDateFormat:format) + "'})"
                },
                { "class", "txt txt_short Wdate" },
            };

            tmpHtmlAttribute.Union(htmlAttributes);

            return(htmlHelper.TextBoxFor(expression, tmpHtmlAttribute));
        }
コード例 #20
0
        public IReadOnlyCollection<RCompletion> GetEntries(RCompletionContext context) {
            List<RCompletion> completions = new List<RCompletion>();
            ImageSource functionGlyph = GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupValueType, StandardGlyphItem.GlyphItemPublic);

            // Safety checks
            FunctionCall funcCall = context.AstRoot.GetNodeOfTypeFromPosition<FunctionCall>(context.Position);
            if (funcCall == null || funcCall.OpenBrace == null || funcCall.Arguments == null) {
                return completions;
            }

            if (context.Position < funcCall.OpenBrace.End || context.Position >= funcCall.SignatureEnd) {
                return completions;
            }

            // Retrieve parameter positions from the current text buffer snapshot
            ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(context.AstRoot, context.TextBuffer.CurrentSnapshot, context.Position);
            if (parametersInfo == null) {
                return completions;
            }

            // Get collection of function signatures from documentation (parsed RD file)
            IFunctionInfo functionInfo = FunctionIndex.GetFunctionInfo(parametersInfo.FunctionName, o => { }, context.Session.TextView);
            if (functionInfo == null) {
                return completions;
            }

            // Collect parameter names from all signatures
            IEnumerable<KeyValuePair<string, IArgumentInfo>> arguments = new Dictionary<string, IArgumentInfo>();
            foreach (ISignatureInfo signature in functionInfo.Signatures) {
                var args = signature.Arguments.ToDictionary(x => x.Name);
                arguments = arguments.Union(args);
            }

            // Add names of arguments that  are not yet specified to the completion
            // list with '=' sign so user can tell them from function names.
            IEnumerable<string> declaredArguments = funcCall.Arguments.Where(x => x is NamedArgument).Select(x => ((NamedArgument)x).Name);
            IEnumerable<KeyValuePair<string, IArgumentInfo>> possibleArguments = arguments.Where(x => x.Key != "..." && !declaredArguments.Contains(x.Key));

            foreach (KeyValuePair<string, IArgumentInfo> arg in possibleArguments) {
                string displayText = arg.Key + " =";
                string insertionText = arg.Key + " = ";
                completions.Add(new RCompletion(displayText, insertionText, arg.Value.Description, functionGlyph));
            }

            return completions;
        }
コード例 #21
0
        /// <summary>
        ///     Sends money to specified destination user
        /// </summary>
        /// <param name="destinationId">Destination Dwolla ID</param>
        /// <param name="amount">Amount to send</param>
        /// <param name="aParams">Additional parameters</param>
        /// <param name="altToken">Alternate OAuth token</param>
        /// <param name="altPin">Alternate pin</param>
        /// <returns>Resulting transaction ID</returns>
        public int?Send(string destinationId, double amount, Dictionary <string, string> aParams = null,
                        string altToken = null, int?altPin = null)
        {
            var data = new Dictionary <string, string>
            {
                { "oauth_token", altToken ?? C.dwolla_access_token },
                { "pin", altPin.ToString() ?? C.dwolla_pin.ToString() },
                { "destinationId", destinationId },
                { "amount", amount.ToString() }
            };

            if (aParams != null)
            {
                data = aParams.Union(data).ToDictionary(k => k.Key, v => v.Value);
            }
            return(DwollaParse <int?>(Post("/transactions/send", data)));
        }
        private void CheckData(int size)
        {
            var result = new Dictionary <TKey, TValue>();

            using (var nativeHashMapEnumerator = _nativeHashMap.GetEnumerator())
            {
                while (nativeHashMapEnumerator.MoveNext())
                {
                    var data = nativeHashMapEnumerator.Current;
                    Assert.IsFalse(result.ContainsKey(data.Key));
                    result.Add(data.Key, data.Value);
                }
            }

            Assert.AreEqual(size, result.Count);
            Assert.AreEqual(result.Intersect(_checkingResults).Count(), result.Union(_checkingResults).Count());
        }
コード例 #23
0
        public static Dictionary <string, string> Adapt(Readme readme)
        {
            var keyValues = new Dictionary <string, string>
            {
                { "@VERSION", readme.Version }, { "@DATE", DateTime.Now.ToShortDateString() }, { "@OBJECTIVE", "Mejoras generales al Software" }
            };



            var tickets = AdaptTickets(readme);

            var result = keyValues.Union(tickets).ToDictionary(k => k.Key, v => v.Value);

            CleanPlaceholders(result);

            return(result);
        }
コード例 #24
0
        /// <summary>
        ///     Creates MassPay job
        /// </summary>
        /// <param name="fundingSource">Funding source for jobs</param>
        /// <param name="items">List of MassPayItem objects</param>
        /// <param name="aParams">Additional parameters</param>
        /// <param name="altToken">Alternate OAuth token</param>
        /// <param name="altPin">Alternate PIN</param>
        /// <returns>MassPayJob object</returns>
        public MassPayJob Create(string fundingSource, List <MassPayItem> items, Dictionary <string, object> aParams = null, string altToken = null,
                                 int?altPin = null)
        {
            var data = new Dictionary <string, object>
            {
                { "oauth_token", altToken ?? C.dwolla_access_token },
                { "pin", altPin.ToString() ?? C.dwolla_pin.ToString() },
                { "fundsSource", fundingSource },
                { "items", items }
            };

            if (aParams != null)
            {
                data = aParams.Union(data).ToDictionary(k => k.Key, v => v.Value);
            }
            return(DwollaParse <MassPayJob>(PostSpecial("/masspay", data)));
        }
コード例 #25
0
ファイル: DefaultController.cs プロジェクト: frapid/frapid
        public async Task<ActionResult> GetCustomVariablesAsync()
        {
            var meta = await AppUsers.GetCurrentAsync().ConfigureAwait(true);

            var model = new Dictionary<string, string>();
            var iType = typeof(ICustomJavascriptVariable);
            var members = iType.GetTypeMembers<ICustomJavascriptVariable>();

            foreach (var member in members)
            {
                var items = await member.GetAsync(this.Tenant, meta.OfficeId).ConfigureAwait(true);
                model = model.Union(items).ToDictionary(k => k.Key, v => v.Value);
            }


            return this.Ok(model);
        }
コード例 #26
0
        /// <summary>
        ///     Generate an OAuth signature from OAuth header values.
        /// </summary>
        private string GenerateSignature(string url, Dictionary <string, string> data, Method method)
        {
            var sigString = string.Join(
                "&",
                data
                .Union(data)
                .Select(kvp =>
                        $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}")
                .OrderBy(s => s)
                );

            var fullSigData =
                $"{(method == Method.POST ? "POST" : "GET")}&{Uri.EscapeDataString(url)}&{Uri.EscapeDataString(sigString)}";

            return(Convert.ToBase64String(
                       _sigHasher.ComputeHash(new ASCIIEncoding().GetBytes(fullSigData))));
        }
コード例 #27
0
        public void DictionaryShouldBeUnified()
        {
            Dictionary <string, object> dic1 = new Dictionary <string, object>();

            dic1.Add("a", new Cobaia());
            dic1.Add("b", new Cobaia());

            Dictionary <string, object> dic2 = new Dictionary <string, object>();

            dic2.Add("a", new Cobaia());
            dic2.Add("c", new Cobaia());

            Dictionary <string, object> dic3 = dic1.Union(dic2)
                                               //.ToDictionary(d => d.Key, d => d.Value);
                                               .GroupBy(d => d.Key)
                                               .ToDictionary(d => d.Key, d => d.First().Value);
        }
コード例 #28
0
ファイル: Table.razor.cs プロジェクト: lzyzlzy/TabBlazor
        protected async override Task OnInitializedAsync()
        {
            DataFactory = new TheGridDataFactory <Item>(Columns, this);
            var baseAttributes = new Dictionary <string, object>()
            {
                { "class", TableClass }
            };

            if (UnknownParameters?.ContainsKey("class") == true)
            {
                baseAttributes["class"] = TableClass + " " + UnknownParameters["class"];
                baseAttributes.Union(UnknownParameters.Where(x => x.Key != "class") ?? new Dictionary <string, object>()).ToDictionary(x => x.Key, x => x.Value);
            }

            Attributes = baseAttributes;
            await Update();
        }
コード例 #29
0
        public async Task <ActionResult> GetCustomVariablesAsync()
        {
            var meta = await AppUsers.GetCurrentAsync().ConfigureAwait(true);

            var model   = new Dictionary <string, string>();
            var iType   = typeof(ICustomJavascriptVariable);
            var members = iType.GetTypeMembers <ICustomJavascriptVariable>();

            foreach (var member in members)
            {
                var items = await member.GetAsync(this.Tenant, meta.OfficeId).ConfigureAwait(true);

                model = model.Union(items).ToDictionary(k => k.Key, v => v.Value);
            }

            return(this.Ok(model));
        }
コード例 #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                AllCompanyList              = _companyCussent.GetCompanyCussentList();
                AllCompanyBalanceList       = _companyCussent.GetCompanyBalanceList();
                AllCompanyClassList         = _companyClass.GetCompanyClassList();
                AllCompanyBalanceDetailList = _companyCussent.GetCompanyBalanceDetailList();

                Dictionary <Guid, string> dataSource = new Dictionary <Guid, string> {
                    { Guid.Empty, "--所有--" }
                };
                RCB_Warehouse.DataSource = dataSource.Union(WMSSao.GetAllCanUseWarehouseDics());

                var filialeList = FilialeList.Where(f => f.FilialeTypes.Contains((int)FilialeType.SaleCompany) || f.FilialeTypes.Contains((int)FilialeType.LogisticsCompany) && !f.FilialeTypes.Contains((int)FilialeType.EntityShop));

                RCB_FilialeList.DataSource = filialeList;
                var personnelInfo = CurrentSession.Personnel.Get();
                if (personnelInfo.CurrentFilialeId == Guid.Empty)
                {
                    personnelInfo.CurrentFilialeId = filialeList.First().ID;
                    CurrentSession.Personnel.Set(personnelInfo);
                }
                SelectFilialeId = personnelInfo.CurrentFilialeId;
                GetCompanyCussent();

                RCB_Warehouse.DataBind();
                RCB_FilialeList.DataTextField  = "Name";
                RCB_FilialeList.DataValueField = "ID";
                RCB_FilialeList.DataBind();
                RCB_FilialeList.SelectedValue = string.Format("{0}", personnelInfo.CurrentFilialeId);


                RDP_StartDate.SelectedDate = DateTime.Now.AddDays(-30);
                RDP_EndDate.SelectedDate   = DateTime.Now;
            }

            if (GetPowerOperationPoint("CBIsOut") && !string.IsNullOrWhiteSpace(RCB_FilialeList.SelectedValue) && new Guid(RCB_FilialeList.SelectedValue) != Guid.Empty)
            {
                CB_IsOut.Visible = true;
            }
            else
            {
                CB_IsOut.Visible = false;
            }
        }
コード例 #31
0
        private void SetRequestHeaders(HttpWebRequest client, string token, Dictionary <string, string> body)
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");            //时间戳
            IDictionary <string, string> headerParames = new Dictionary <string, string>(); //参数摘要计算得map

            headerParames.Add("X-FDD-Api-App-Id", AppId);
            headerParames.Add("X-FDD-Api-Sign-Type", "HMAC-SHA256");
            headerParames.Add("X-FDD-Api-Timestamp", timestamp);
            headerParames.Add("X-FDD-Api-Nonce", Guid.NewGuid().ToString("N"));
            headerParames.Add("X-FDD-Api-Token", token);
            headerParames.Add("X-FDD-Api-Sign", Utility.SignUtil.GetSign(headerParames.Union(body), timestamp, AppKey));

            foreach (var p in headerParames)
            {
                client.Headers[p.Key] = p.Value;
            }
        }
コード例 #32
0
        private static IEnumerable <KeyValuePair <string, string> > ProcessDataSetGetParameters(string dataSetName, int pageNumber, int pageSize,
                                                                                                DateTimeOffset startDate, DateTimeOffset endDate, IEnumerable <string> includeColumns)
        {
            Argument.IsNotNullOrEmpty(dataSetName, nameof(dataSetName));
            Argument.IsNotNull(includeColumns, nameof(includeColumns));

            var parameters = new Dictionary <string, string>
            {
                { "page", pageNumber.ToString() },
                { "pageSize", pageSize.ToString() },
                { "startDate", startDate.ToString("O") },
                { "endDate", endDate.ToString("O") },
            };
            var includes = includeColumns.Select(ic => new KeyValuePair <string, string>("include", ic));

            return(parameters.Union(includes));
        }
コード例 #33
0
        public static IHtmlString Button(this HtmlHelper helper, Expression <Func <bool> > checkPermission, string text, object authorHtmlAttributes = null, object bHtmlAttributes = null, bool isIncludeTitle = false, bool isToolBtn = true, bool isHaveLine = true)
        {
            if (!checkPermission.Compile().Invoke())
            {
                return(MvcHtmlString.Create(string.Empty));
            }

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

            if (isToolBtn)
            {
                authorDic.Add("class", "tools_btn");
            }
            if (!isIncludeTitle)
            {
                authorDic.Add("title", text);
            }
            if (authorHtmlAttributes != null)
            {
                //Merge htmlAttributes
                authorDic = authorDic.Union(authorHtmlAttributes.ToDictionary())
                            .ToLookup(pair => pair.Key, pair => pair.Value)
                            .ToDictionary(group => group.Key, group => (object)string.Join(" ", group.ToArray().Cast <string>()));
            }
            var authorAttr = string.Join(" ", authorDic.Select(n => string.Format("{0}=\"{1}\"", n.Key, n.Value)));

            var bAttr = string.Empty;

            if (bHtmlAttributes != null)
            {
                var bDic = bHtmlAttributes.ToDictionary();
                bAttr = string.Join(" ", bDic.Select(n => string.Format("{0}=\"{1}\"", n.Key, n.Value)));
            }
            string LineHtml = "";

            if (isHaveLine == true)
            {
                LineHtml = "<div class='tools_separator'> </div>";
            }
            var str = string.Format("<a {0}><span><b {1}>{2}</b></span></a>{3}", authorAttr, bAttr, text, LineHtml);

            return(MvcHtmlString.Create(str));

            //<a title="刷新当前页面" onclick="Replace();" class="tools_btn"><span><b  class="btn_Refresh">刷新</b></span></a>
        }
コード例 #34
0
        public static string BuildApiUrl(string endpoint, Dictionary <string, string> queryValues, Pagination pagination = null)
        {
            var sb = new StringBuilder($"{endpoint}");

            if (queryValues.Any() || pagination != null)
            {
                sb.Append("?");

                if (pagination != null)
                {
                    queryValues = queryValues.Union(BuildPaginationQueryDictionary(pagination.From, pagination.To, pagination.Limit)).ToDictionary(k => k.Key, v => v.Value);
                }

                sb.Append(GetQueryStringValues(queryValues));
            }

            return(sb.ToString());
        }
コード例 #35
0
        protected virtual string GenerateSignature(string url, Dictionary <string, string> data)
        {
            var sigString = string.Join(
                "&",
                data.Union(data)
                .Select(kvp => string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value)))
                .OrderBy(s => s)
                );

            var fullSigData = string.Format(
                "{0}&{1}&{2}",
                "POST",
                Uri.EscapeDataString(url),
                Uri.EscapeDataString(sigString.ToString())
                );

            return(Convert.ToBase64String(sigHasher.ComputeHash(new ASCIIEncoding().GetBytes(fullSigData.ToString()))));
        }
コード例 #36
0
        public void Union_DistinctKeys_ContainsBoth()
        {
            IDictionary <string, string> first = new Dictionary <string, string>()
            {
                { "a", "1" }
            };

            IDictionary <string, string> second = new Dictionary <string, string> {
                { "b", "2" }
            };

            IDictionary <string, string> result = first.Union(second);

            result.Should().Have.SameValuesAs(new Dictionary <string, string> {
                { "a", "1" },
                { "b", "2" }
            });
        }
コード例 #37
0
        /// <summary>
        /// Splice a sub tree into the parent tree.
        /// </summary>
        public BehaviourTreeBuilder Splice(IBehaviourTreeNode subTree)
        {
            if (subTree == null)
            {
                throw new ArgumentNullException("subTree");
            }

            if (parentNodeStack.Count <= 0)
            {
                throw new ApplicationException("Can't splice an unnested sub-tree, there must be a parent-tree.");
            }

            parentNodeStack.Peek().AddChild(subTree);
            // Merge the nodeMaps and set subtree nodemap to null
            nodeMap         = nodeMap.Union(subTree.nodeMap).ToDictionary(k => k.Key, v => v.Value);
            subTree.nodeMap = null;
            return(this);
        }
コード例 #38
0
        /// <summary>
        ///     Refunds (either completely or partially) funds to
        ///     the sending user for a transaction.
        /// </summary>
        /// <param name="transactionId">Transaction ID</param>
        /// <param name="fundingSource">Funding source to fund transaction</param>
        /// <param name="amount">Amount to refund</param>
        /// <param name="aParams">Additional parameters</param>
        /// <param name="altToken">Alternate OAuth token</param>
        /// <param name="altPin">Alternate parameters</param>
        /// <returns>Refund object</returns>
        public Refund Refund(string transactionId, string fundingSource, double amount,
                             Dictionary <string, string> aParams, string altToken = null, int?altPin = null)
        {
            var data = new Dictionary <string, string>
            {
                { "oauth_token", altToken ?? C.dwolla_access_token },
                { "pin", altPin.ToString() ?? C.dwolla_pin.ToString() },
                { "fundsSource", fundingSource },
                { "transactionId", transactionId },
                { "amount", amount.ToString() }
            };

            if (aParams != null)
            {
                data = aParams.Union(data).ToDictionary(k => k.Key, v => v.Value);
            }
            return(DwollaParse <Refund>(Post("/transactions/refund", data)));
        }
コード例 #39
0
        public override IValue Serialize()
        {
            var values = new Dictionary <IKey, IValue>
            {
                [(Text)"unlockBlockIndex"] = UnlockBlockIndex.Serialize(),
                [(Text)"unlockStage"]      = UnlockStage.Serialize(),
                [(Text)"startBlockIndex"]  = StartBlockIndex.Serialize(),
            };

            if (!(Result is null))
            {
                values.Add((Text)"result", Result.Serialize());
            }
#pragma warning disable LAA1002
            return(new Dictionary(values.Union((Dictionary)base.Serialize())));

#pragma warning restore LAA1002
        }
コード例 #40
0
        private static Dictionary <string, Exception> ExecuteFindJunctions(DirectoryInfo dir)
        {
            var errors = new Dictionary <string, Exception>();

            var subdirs = dir.GetDirectories();

            foreach (var subdir in subdirs.Where(d => !d.Name.StartsWith(".hg")))
            {
                var isJunction = subdir.Attributes.HasFlag(FileAttributes.ReparsePoint);
                if (isJunction)
                {
                    Console.WriteLine(subdir.FullName);
                    continue;
                }
                errors = errors.Union(ExecuteFindJunctions(subdir)).ToDictionary(e => e.Key, e => e.Value);
            }
            return(errors);
        }
コード例 #41
0
        private Dictionary <string, string> ValidateResponse(List <SurveyInfoBO> SurveyBOList, PreFilledAnswerRequest request)
        {
            XDocument SurveyXml = new XDocument();

            foreach (var item in SurveyBOList)
            {
                SurveyXml = XDocument.Parse(item.XML);
            }
            Dictionary <string, string> MessageList        = new Dictionary <string, string>();
            Dictionary <string, string> FieldNotFoundList  = new Dictionary <string, string>();
            Dictionary <string, string> WrongFieldTypeList = new Dictionary <string, string>();
            SurveyResponseXML           Implementation     = new SurveyResponseXML(request, SurveyXml);

            FieldNotFoundList = Implementation.ValidateResponseFileds();
            //WrongFieldTypeList = Implementation.ValidateResponseFiledTypes();
            MessageList = MessageList.Union(FieldNotFoundList).Union(WrongFieldTypeList).ToDictionary(k => k.Key, v => v.Value);
            return(MessageList);
        }
        public void Generate__GeneratedProperly()
        {
            // Prepare expected results
            var joinedModels = new Dictionary<string, string> {
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerFirstName), "Customer.FirstName" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerLastName), "Customer.LastName" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerFingersCount), "Customer.FingersCount" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerHairLength), "Customer.HairLength" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerPreviousSurgeryDate), "Customer.PreviousSurgeryDate" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerType), "Customer.Type" },
            };

            var components = new Dictionary<string, string> {
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoOrderedDate), "PaymentInfo.OrderedDate" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoState), "PaymentInfo.State" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoDouble), "PaymentInfo.Double" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoExternalPaymentId), "PaymentInfo.ExternalPaymentId" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoNumber), "PaymentInfo.Number" },
            };

            var simpleProps = new Dictionary<string, string> {
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.Id), "Id" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.Type), "Type" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.OrderDate), "OrderDate" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.TotalPrice), "TotalPrice" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.Note), "Note" },
                { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.ItemsCount), "ItemsCount" },
            };

            var allProps = joinedModels.Union(components).Union(simpleProps).ToDictionary(x => x.Key, x => x.Value);

            // ACT
            var modelDescription = GetTestModelDescription();
            var map = ViewModelToPersistenceModelPropertyNamesMapsGenerator.Generate(typeof(OrderGridModel), modelDescription);

            // ASSERT
            map.Should(Be.Not.Null);
            map.AllProperties.Count.Should(Be.EqualTo(17));
            map.AllProperties.Should(Be.EquivalentTo(allProps));
        }
コード例 #43
0
ファイル: Settings.aspx.cs プロジェクト: kiquenet/B4F
        protected void Page_Init(object sender, EventArgs e)
        {
            changeableOptions = new Dictionary<CheckBox, OptionView>()
            {
                { cbNotasAndQuarterlyReportsByPost,  new OptionView { Category = SendableDocumentCategories.NotasAndQuarterlyReports,
                                                                      Option   = SendingOptions.ByPost } },

                { cbNotasAndQuarterlyReportsByEmail, new OptionView { Category = SendableDocumentCategories.NotasAndQuarterlyReports,
                                                                      Option   = SendingOptions.ByEmail } }
            };

            nonChangeableOptions = new Dictionary<CheckBox, OptionView>()
            {
                { cbYearlyReportsByPost,             new OptionView { Category = SendableDocumentCategories.YearlyReports,
                                                                      Option   = SendingOptions.ByPost } },

                { cbYearlyReportsByEmail,            new OptionView { Category = SendableDocumentCategories.YearlyReports,
                                                                      Option   = SendingOptions.ByEmail } }
            };

            allOptions = changeableOptions.Union(nonChangeableOptions).ToDictionary(pair => pair.Key, pair => pair.Value);
        }
コード例 #44
0
        public static MultiSelectList GetPossibleValues(
            this PropertyValue propertyValue,
            bool addChooseItem = true)
        {
            if (propertyValue.Property.IsForeignKey)
            {
                var options = new Dictionary<string, string>();

                if (addChooseItem)
                {
                    options.Add(String.Empty, IlaroAdminResources.Choose);
                }
                options = options.Union(propertyValue.PossibleValues).ToDictionary(x => x.Key, x => x.Value);

                return propertyValue.Property.TypeInfo.IsCollection ?
                    new MultiSelectList(options, "Key", "Value", propertyValue.Values) :
                    new SelectList(options, "Key", "Value", propertyValue.AsString);
            }
            else
            {
                var options = addChooseItem ?
                    propertyValue.Property.TypeInfo.EnumType.GetOptions(String.Empty, IlaroAdminResources.Choose) :
                    propertyValue.Property.TypeInfo.EnumType.GetOptions();

                if (propertyValue.Property.TypeInfo.IsEnum)
                {
                    return new SelectList(
                        options,
                        "Key",
                        "Value",
                        propertyValue.AsObject);
                }

                return new SelectList(options, "Key", "Value", propertyValue.AsString);
            }
        }
コード例 #45
0
        public IReadOnlyCollection<RCompletion> GetEntries(RCompletionContext context) {
            List<RCompletion> completions = new List<RCompletion>();
            FunctionCall funcCall;
            ImageSource functionGlyph = _glyphService.GetGlyphThreadSafe(StandardGlyphGroup.GlyphGroupValueType, StandardGlyphItem.GlyphItemPublic);

            // Safety checks
            if (!ShouldProvideCompletions(context, out funcCall)) {
                return completions;
            }

            // Get collection of function signatures from documentation (parsed RD file)
            IFunctionInfo functionInfo = GetFunctionInfo(context);
            if (functionInfo == null) {
                return completions;
            }

            // Collect parameter names from all signatures
            IEnumerable<KeyValuePair<string, IArgumentInfo>> arguments = new Dictionary<string, IArgumentInfo>();
            foreach (ISignatureInfo signature in functionInfo.Signatures) {
                var args = signature.Arguments.ToDictionary(x => x.Name);
                arguments = arguments.Union(args);
            }

            // Add names of arguments that  are not yet specified to the completion
            // list with '=' sign so user can tell them from function names.
            IEnumerable<string> declaredArguments = funcCall.Arguments.Where(x => x is NamedArgument).Select(x => ((NamedArgument)x).Name);
            var possibleArguments = arguments.Where(x => !x.Key.EqualsOrdinal("...") && !declaredArguments.Contains(x.Key, StringComparer.OrdinalIgnoreCase));

            foreach (var arg in possibleArguments) {
                string displayText = arg.Key + " =";
                string insertionText = arg.Key + " = ";
                completions.Add(new RCompletion(displayText, insertionText, arg.Value.Description, functionGlyph));
            }

            return completions;
        }
コード例 #46
0
        public AuthorizationManager(IAuthorizationConfiguration authorizationConfiguration) {
            defaultAuthorizer = authorizationConfiguration.DefaultAuthorizer;
            if (defaultAuthorizer == null) {
                throw new InitialisationException("Default Authorizer cannot be null");
            }

            var isVisibleDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() {
                {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsVisible"))}
            };

            var isEditableDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() {
                {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsEditable"))}
            };

            if (authorizationConfiguration.NamespaceAuthorizers.Any()) {
                namespaceAuthorizers = authorizationConfiguration.NamespaceAuthorizers.OrderByDescending(x => x.Key.Length).ToImmutableDictionary();
            }
            if (authorizationConfiguration.TypeAuthorizers.Any()) {
                if (authorizationConfiguration.TypeAuthorizers.Values.Any(t => typeof(ITypeAuthorizer<object>).IsAssignableFrom(t))) {
                    throw new InitialisationException("Only Default Authorizer can be ITypeAuthorizer<object>");
                }

                typeAuthorizers = authorizationConfiguration.TypeAuthorizers.ToImmutableDictionary();
                isVisibleDelegates = isVisibleDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsVisible")))).ToImmutableDictionary();
                isEditableDelegates = isEditableDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsEditable")))).ToImmutableDictionary();
            } else { // default authorizer must be the only TypeAuthorizer
                isVisibleDelegates = isVisibleDict.ToImmutableDictionary();
                isEditableDelegates = isEditableDict.ToImmutableDictionary();
            }
        }
コード例 #47
0
ファイル: FaceRestAPI.cs プロジェクト: slashP/CIBER-NDC
        protected FaceApi CallMethod(string method, Dictionary<string, string> param)
        {
            // Remember keys for removal
            var keys = new List<string>();

            foreach (var s in param)
            {
                if (String.IsNullOrWhiteSpace(s.Value))
                {
                    keys.Add(s.Key);
                }
                else
                {
                    if (s.Key == "_file" && s.Value == "@")
                    {
                        keys.Add(s.Key);
                    }
                }
            }
            foreach (string s in keys)
            {
                param.Remove(s);
            }

            var authParams = new Dictionary<string, string>();

            if (!String.IsNullOrWhiteSpace(this._apiKey))
            {
                authParams.Add("api_key", this._apiKey);
            }

            if (!String.IsNullOrWhiteSpace(this._apiSecret))
            {
                authParams.Add("api_secret", this._apiSecret);
            }

            if (_userAuth.Count > 0)
            {
                authParams.Add("user_auth", getUserAuthString(this._userAuth));
            }

            if (!String.IsNullOrWhiteSpace(_password))
            {
                authParams.Add("password", _password);
            }

            var paramMerge = authParams.Union(param).ToDictionary(pair => pair.Key, pair => pair.Value);

            var request = method + "." + _format;

            return PostMethod(request, paramMerge);
        }
コード例 #48
0
    protected void InternalBuildSmoothBondSeries(KnownCurve knownCurve, SmoothBondCurveCalculationParams parameters,
      bool buildCMT = true)
    {
      if (mConstituentsOnly)
      {
        return;
      }

      var curve = SObjectManager.Instance().LoadSObject<DiscountCurve>(new Moniker
      {
        Close = parameters.Close,
        Source = parameters.Source,
        Type = "DiscountCurve",
        Date = ValueDate,
        Name = KnownCurveHelpers.GetKnownCurveCode(knownCurve)
      });

      if (curve == null)
      {
        SLog.log.ErrorFormat("Unable to load curve {0} for smooth series construction.", knownCurve.ToString());
        return;
      }

      // delete the old data else might have residual stuff saved that confuses things
      {
        SLog.log.Debug("Deleting any previous data from the database...");

        foreach (var ending in new[] { string.Empty, "%" })
          SObjectManager.Instance().DeleteCachedObject(
            monikerDate_: ValueDate,
            monikerSource_: parameters.Source,
            likeMonikerName_: string.Format("{0}%{1}{2}", parameters.Country, parameters.CurveName, ending));
      }

      SLog.log.DebugFormat("Building {0} smooth curve over {1} on {2}", parameters.Country, parameters.CurveName,
        ValueDate);

      IEnumerable<KeyValuePair<string, AnySObject>> allObjects = new Dictionary<string, AnySObject>();

      Dictionary<string, Dictionary<int, RateCurve>> cmtGlobal =
        new Dictionary<string, Dictionary<int, RateCurve>>();

      foreach (var maturity in parameters.Maturities)
      {
        try
        {
          var smoothCurves = new SmoothBondCurveCalculator(ValueDate, new SmoothBondCurveParameters
          {
            SpotDelay = parameters.SpotDelay,
            SettleDelay = parameters.SettleDelay,
            HolidayCenter = parameters.HolidayCenter,
            Close = parameters.Close,
            Source = parameters.Source,
            CurveStart = parameters.CurveStart,
            CurveStep = parameters.CurveStep,
            YieldLambda = parameters.YieldLambdas[maturity],
            SpreadLambda = parameters.SpreadLambdas[maturity],
            TrueSpreadLambda = parameters.TrueSpreadLambdas[maturity],
            CurveName = parameters.CurveName,
            Markets = parameters.Markets,
            Currency = parameters.Currency,
            Country = parameters.Country,
            AnalyticsCountry = parameters.AnalyticsCountry,
            Maturity = maturity,
            SwapCurveType = parameters.SwapCurveType,
            TermDrift = parameters.BondTermDrift,
            ShouldIncludeDelegate = parameters.ShouldIncludeBondInTargetMaturityDelegate,
          }, curve).Calculate();

          if (smoothCurves.ContainsKey("Yield"))
          {
            var yieldMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "yield", parameters.Country, maturity,
              parameters.Close,
              parameters.Source, parameters.CurveName);
            SObjectManager.Instance().SaveSObject(yieldMoniker, smoothCurves["Yield"]);
          }

          if (smoothCurves.ContainsKey("Spread"))
          {
            var spreadMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "spread", parameters.Country, maturity,
              parameters.Close,
              parameters.Source, parameters.CurveName);
            SObjectManager.Instance().SaveSObject(spreadMoniker, smoothCurves["Spread"]);
          }

          if (smoothCurves.ContainsKey("MMS"))
          {
            var mmsMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "mms", parameters.Country, maturity,
              parameters.Close,
              parameters.Source, parameters.CurveName);
            SObjectManager.Instance().SaveSObject(mmsMoniker, smoothCurves["MMS"]);
          }

          if (smoothCurves.ContainsKey("TrueSpread"))
          {
            var trueSpreadMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "truespread", parameters.Country,
              maturity, parameters.Close,
              parameters.Source, parameters.CurveName);
            SObjectManager.Instance().SaveSObject(trueSpreadMoniker, smoothCurves["TrueSpread"]);
          }

          foreach (var kvp in smoothCurves)
          {
            if (Moniker.IsMoniker(kvp.Key))
            {
              SObjectManager.Instance().SaveSObject(Moniker.FromString(kvp.Key), kvp.Value);
            }
          }

          if (buildCMT)
          {
            var bsObjects = new CMTBondSpreadCalculator(ValueDate, new CMTBondSpreadParameters
            {
              Close = parameters.Close,
              CurveName = parameters.CurveName,
              Country = parameters.Country,
              Maturity = maturity,
              Source = parameters.Source,
              Maturities = parameters.Maturities
            }, smoothCurves, ref cmtGlobal).Calculate();

            foreach (var bso in bsObjects)
            {
              SObjectManager.Instance().SaveSObject(Moniker.FromString(bso.Key), bso.Value);
            }

            allObjects = allObjects.Union(bsObjects.AsEnumerable());
          }
        }
        catch (Exception ex)
        {
          SLog.log.Error("Error calculating smooth series", ex);
        }
      }

      if (buildCMT)
      {
        try
        {
          foreach (var curveType in cmtGlobal.Keys)
            foreach (var series in cmtGlobal[curveType].Keys)
            {
              var moniker = RateCurve.CreateBondSeriesCurveMoniker(ValueDate, curveType, parameters.Country, series,
                parameters.Close, parameters.Source, parameters.CurveName);

              SObjectManager.Instance().SaveSObject(moniker, cmtGlobal[curveType][series]);
            }
        }
        catch (Exception ex)
        {
          SLog.log.Error("Error saving cmt rate curves", ex);
        }
      }
    }
コード例 #49
0
ファイル: TestHarness.cs プロジェクト: WolfyUK/chutzpah
        public string CreateHtmlText(string testHtmlTemplate, Dictionary<string, string> frameworkReplacements)
        {
            var testJsReplacement = new StringBuilder();
            var testFrameworkDependencies = new StringBuilder();
            var codeCoverageDependencies = new StringBuilder();
            var referenceJsReplacement = new StringBuilder();
            var referenceCssReplacement = new StringBuilder();
            var referenceHtmlTemplateReplacement = new StringBuilder();

            BuildReferenceHtml(testFrameworkDependencies,
                               referenceCssReplacement,
                               testJsReplacement,
                               referenceJsReplacement,
                               referenceHtmlTemplateReplacement,
                               codeCoverageDependencies);

            string amdTestFilePathArrayString = "";
            string amdModuleMap = "";
            if (chutzpahTestSettings.TestHarnessReferenceMode == TestHarnessReferenceMode.AMD)
            {
                amdTestFilePathArrayString = BuildAmdTestFileArrayString();
                amdModuleMap = BuildModuleMapForGeneratedFiles();
            }

            var amdBasePathUrl = "";

            if (!string.IsNullOrEmpty(chutzpahTestSettings.AMDBasePath))
            {
                amdBasePathUrl = FileProbe.GenerateFileUrl(chutzpahTestSettings.AMDBasePath);
            }
            else if (!string.IsNullOrEmpty(chutzpahTestSettings.AMDBaseUrl))
            {
                amdBasePathUrl = FileProbe.GenerateFileUrl(chutzpahTestSettings.AMDBaseUrl);
            }

            var replacements = new Dictionary<string, string>
            {
                {"TestFrameworkDependencies", testFrameworkDependencies.ToString()},
                {"CodeCoverageDependencies", codeCoverageDependencies.ToString()},
                {"TestJSFile", testJsReplacement.ToString()},
                {"ReferencedJSFiles", referenceJsReplacement.ToString()},
                {"ReferencedCSSFiles", referenceCssReplacement.ToString()},
                {"TestHtmlTemplateFiles", referenceHtmlTemplateReplacement.ToString()},
                {"AMDTestPath", amdTestFilePathArrayString},
                {"AMDModuleMap", amdModuleMap},
                {"AMDBasePath",  amdBasePathUrl }
            };

            var testHtmlStringBuilder = new StringBuilder(testHtmlTemplate);

            foreach (var replacement in replacements.Union(frameworkReplacements))
            {
                testHtmlStringBuilder.Replace("@@" + replacement.Key + "@@", replacement.Value);
            }

            return testHtmlStringBuilder.ToString();
        }
コード例 #50
0
ファイル: Property.cs プロジェクト: Anupam-/Ilaro.Admin
        public MultiSelectList GetPossibleValues(bool addChooseItem = true)
        {
            if (IsForeignKey)
            {
                var options = new Dictionary<string, string>();

                if (addChooseItem)
                {
                    options.Add(String.Empty, IlaroAdminResources.Choose);
                }
                options = options.Union(Value.PossibleValues).ToDictionary(x => x.Key, x => x.Value);

                return TypeInfo.IsCollection ?
                    new MultiSelectList(options, "Key", "Value", Value.Values) :
                    new SelectList(options, "Key", "Value", Value);
            }
            else
            {
                var options = addChooseItem ?
                    TypeInfo.EnumType.GetOptions(String.Empty, IlaroAdminResources.Choose) :
                    TypeInfo.EnumType.GetOptions();

                if (Value != null && Value.GetType().IsEnum)
                {
                    return new SelectList(
                        options,
                        "Key",
                        "Value",
                        Convert.ToInt32(Value));
                }

                return new SelectList(options, "Key", "Value", Value);
            }
        }
コード例 #51
0
ファイル: RealDB.cs プロジェクト: TrinityWestern/Lasy
        /// <summary>
        /// Does an insert and returns the keys of the row just inserted
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="dataFields"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public Dictionary<string, object> Insert(string tableName, Dictionary<string, object> dataFields, ITransaction transaction = null)
        {
            //Retrieve the AutoNumbered key name if there is one
            var autoNumberKeyName = Analyzer.GetAutoNumberKey(tableName);

            //Retrieve all of the primary keys to be sure they are all set, except we don't want the autonumbered key since the DB will set it
            var requiredKeys = Analyzer.GetPrimaryKeys(tableName).Except(autoNumberKeyName);

            //Check that all of the required keys are actually set
            var invalid = requiredKeys.Where(key => dataFields[key] == null);
            if (invalid.Any())
                throw new KeyNotSetException(tableName, invalid);

            // Keep in mind that GetFields might return an empty list, which means that it doesn't know
            var dbFields = Analyzer.GetFields(tableName).Or(dataFields.Keys);
            // Take out the autonumber keys, and take out any supplied data fields
            // that aren't actually fields in the DB
            var fieldNames = dataFields.Keys.Except(autoNumberKeyName)
                .Intersect(dbFields);

            var sql = "INSERT INTO " + tableName + " (" + fieldNames.Join(", ") + ") VALUES (" + fieldNames.Select(x => "@" + x).Join(", ") + ")\n";
            sql += "SELECT SCOPE_IDENTITY()";

            var autoKey =  sqlInsert(sql, transaction, dataFields);

            if (autoNumberKeyName != null && autoKey == null)
                throw new ThisSadlyHappenedException("The SQL ran beautifully, but you were expecting an autogenerated number and you did not get it");

            if (autoNumberKeyName != null)
            {
                var autoKeyDict = new Dictionary<string, object>() { { autoNumberKeyName, autoKey } };
                dataFields = dataFields.Union(autoKeyDict);
            }

            return dataFields.WhereKeys(key => Analyzer.GetPrimaryKeys(tableName).Contains(key));
        }
コード例 #52
0
ファイル: FaceRestAPI.cs プロジェクト: Clancey/Facetroids
    protected FaceAPI call_method(string method, Dictionary<string, string> param)
    {
        // Remember keys for removal
        List<string> keys = new List<string>();

        foreach (KeyValuePair<string, string> s in param)
        {
            if (String.IsNullOrWhiteSpace(s.Value))
            {
                keys.Add(s.Key);
            }
            else
            {
                if (s.Key == "_file" && s.Value == "@")
                {
                    keys.Add(s.Key);
                }
            }
        }
        foreach (string s in keys)
        {
            param.Remove(s);
        }

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

        if (!String.IsNullOrWhiteSpace(this.apiKey))
        {
            authParams.Add("api_key", this.apiKey);
        }

        if (!String.IsNullOrWhiteSpace(this.apiSecret))
        {
            authParams.Add("api_secret", this.apiSecret);
        }

        if (userAuth.Count > 0)
        {
            authParams.Add("user_auth", getUserAuthString(this.userAuth));
        }

        if (!String.IsNullOrWhiteSpace(this.password))
        {
            authParams.Add("password", this.password);
        }

        Dictionary<String, String> paramMerge = new Dictionary<String, String>();
        paramMerge = authParams.Union(param).ToDictionary(pair => pair.Key, pair => pair.Value);

        string request = method + "." + this.format;

        return this.post_method(request, paramMerge);
    }
コード例 #53
0
 public void Union()
 {
     var dict = new Dictionary<int, int>()
         { { 1, 1 }, { 2, 2 }, { 3, 3 } };
     var dictCopy = new Dictionary<int, int>()
         { { 1, 17 }, { 4, 4 }, { 5, 5 } };
     var dictOther = new Dictionary<int, int>()
         { { 1, 17 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 5, 5 } };
     Assert.AreEqual(dictOther, dict.Union(dictCopy));
 }
コード例 #54
0
 Dictionary<string, string> CreateExpectedConfigDictionary(Dictionary<string, string> config, string url, WebHookContentType contentType, string secret)
 {
     return config.Union(new Dictionary<string, string>
     {
         { "url", url },
         { "content_type", contentType.ToString().ToLowerInvariant() },
         { "secret", secret },
         { "insecure_ssl", "False" }
     }).ToDictionary(k => k.Key, v => v.Value);
 } 
コード例 #55
0
ファイル: QualityService.cs プロジェクト: breslavsky/queue
 public async Task<Dictionary<byte, byte>> GetAnswers()
 {
     return await Task.Run(() =>
     {
         var answers = new Dictionary<byte, byte>();
         foreach (var d in Drivers)
         {
             answers = answers.Union(d.Answers).ToDictionary(x => x.Key, x => x.Value);
         }
         return answers;
     });
 }
コード例 #56
0
        private Dictionary<SiloAddress, ConsistentRingProvider> Combine(Dictionary<SiloAddress, ConsistentRingProvider> set1, Dictionary<SiloAddress, ConsistentRingProvider> set2)
        {
            // tell set1 about every node in set2
            foreach (ConsistentRingProvider crp in set1.Values)
            {
                foreach (ConsistentRingProvider other in set2.Values)
                {
                    if (!crp.MyAddress.Equals(other.MyAddress))
                    {
                        other.AddServer(crp.MyAddress);
                    }
                }
            }

            // tell set2 about every node in set1 ... even if set1 and set2 overlap, ConsistentRingProvider should be able to handle
            foreach (ConsistentRingProvider crp in set2.Values)
            {
                foreach (ConsistentRingProvider other in set1.Values)
                {
                    if (!crp.MyAddress.Equals(other.MyAddress))
                    {
                        other.AddServer(crp.MyAddress);
                    }
                }
            }

            // tell set2 about every node in set2 ... note that set1 already knows about nodes in set1
            foreach (ConsistentRingProvider crp in set2.Values)
            {
                foreach (ConsistentRingProvider other in set2.Values)
                {
                    if (!crp.MyAddress.Equals(other.MyAddress))
                    {
                        other.AddServer(crp.MyAddress);
                    }
                }
            }

            // merge the sets
            return set1.Union(set2).ToDictionary(pair => pair.Key, pair => pair.Value);
        }
コード例 #57
0
        public FeatureCollectionResult ImportFeed(SyndicationFeed feed)
        {
            if (feed == null)
                throw new ArgumentNullException("feed");

            FeatureCollectionResult fc = new FeatureCollectionResult();

            NameValueCollection namespaces = null;
            XmlNamespaceManager xnsm = null;
            string prefix = "";

            if (options.KeepNamespaces) {

                // Initialize namespaces
                namespaces = new NameValueCollection();
                namespaces.Set("", "http://geojson.org/ns#");
                namespaces.Set("atom", "http://www.w3.org/2005/Atom");
                XmlReader reader = feed.ElementExtensions.GetReaderAtElementExtensions();
                xnsm = new XmlNamespaceManager(reader.NameTable);
                foreach (var names in xnsm.GetNamespacesInScope(XmlNamespaceScope.All)) {
                    namespaces.Set(names.Key, names.Value);
                }
                fc.Properties.Add("@namespaces", namespaces);
                prefix = "atom:";
            }

            // Import Feed
            if (feed != null) {
                if ((feed.Authors != null) && (feed.Authors.Count > 0)) {
                    object[] authors = new object[feed.Authors.Count];
                    fc.Properties.Add(prefix + "authors", authors);
                    for (int i = 0; i < feed.Authors.Count; i++) {
                        Dictionary<string,object> author = new Dictionary<string, object>();
                        author.Add(prefix + "name", feed.Authors[i].Name);
                        author.Add(prefix + "email", feed.Authors[i].Email);
                        author.Add(prefix + "uri", feed.Authors[i].Uri);
                        author = author.Concat(util.ImportAttributeExtensions(feed.Authors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        author = author.Concat(util.ImportElementExtensions(feed.Authors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        authors[i] = author;
                    }
                }
                if (feed.BaseUri != null) {
                    fc.Properties.Add(prefix + "uri", feed.BaseUri.ToString());
                }
                if ((feed.Categories != null) && (feed.Categories.Count > 0)) {
                    object[] categories = new object[feed.Categories.Count];
                    fc.Properties.Add(prefix + "categories", categories);
                    for (int i = 0; i < feed.Categories.Count; i++) {
                        Dictionary<string,object> category = new Dictionary<string, object>();
                        category.Add(prefix + "name", feed.Categories[i].Name);
                        category.Add(prefix + "label", feed.Categories[i].Label);
                        category.Add(prefix + "scheme", feed.Categories[i].Scheme);
                        category = category.Union(util.ImportAttributeExtensions(feed.Categories[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        category = category.Union(util.ImportElementExtensions(feed.Categories[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        categories[i] = category;
                    }
                }
                if ((feed.Contributors != null) && (feed.Contributors.Count > 0)) {
                    object[] contributors = new object[feed.Contributors.Count];
                    fc.Properties.Add(prefix + "categories", contributors);
                    for (int i = 0; i < feed.Contributors.Count; i++) {
                        Dictionary<string,object> contributor = new Dictionary<string, object>();
                        contributor.Add(prefix + "name", feed.Contributors[i].Name);
                        contributor.Add(prefix + "email", feed.Contributors[i].Email);
                        contributor.Add(prefix + "uri", feed.Contributors[i].Uri);
                        contributor = contributor.Union(util.ImportAttributeExtensions(feed.Contributors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value);
                        contributor = contributor.Union(util.ImportElementExtensions(feed.Contributors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value);
                        contributors[i] = contributor;
                    }
                }
                if (feed.Copyright != null) {
                    fc.Properties.Add(prefix + "rights", feed.Copyright.Text);
                }
                if (feed.Description != null) {
                    fc.Properties.Add(prefix + "content", feed.Description.Text);
                }
                if (feed.Generator != null) {
                    fc.Properties.Add(prefix + "generator", feed.Generator);
                }
                fc.Properties.Add(prefix + "id", feed.Id);
                if (feed.ImageUrl != null)
                    fc.Properties.Add(prefix + "logo", feed.ImageUrl.ToString());
                if (feed.Language != null)
                    fc.Properties.Add(prefix + "language", feed.Language);
                if (feed.LastUpdatedTime != null)
                    fc.Properties.Add(prefix + "updated", feed.LastUpdatedTime);
                if ((feed.Links != null) && (feed.Links.Count > 0)) {
                    fc.Links = feed.Links;
                }
                if (feed.Title != null)
                    fc.Properties.Add(prefix + "title", feed.Title);

                if (feed.Items != null) {
                    foreach (var item in feed.Items) {
                        fc.FeatureResults.Add(ImportItem(item));
                    }
                }

                return fc;

            }
            return null;
        }
コード例 #58
0
ファイル: TestHarness.cs プロジェクト: pimterry/chutzpah
        public string CreateHtmlText(string testHtmlTemplate, Dictionary<string, string> frameworkReplacements)
        {
            var testJsReplacement = new StringBuilder();
            var testFrameworkDependencies = new StringBuilder();
            var codeCoverageDependencies = new StringBuilder();
            var referenceJsReplacement = new StringBuilder();
            var referenceCssReplacement = new StringBuilder();
            var referenceHtmlTemplateReplacement = new StringBuilder();

            BuildReferenceHtml(testFrameworkDependencies,
                               referenceCssReplacement,
                               testJsReplacement,
                               referenceJsReplacement,
                               referenceHtmlTemplateReplacement,
                               codeCoverageDependencies);

            var replacements = new Dictionary<string, string>
            {
                {"TestFrameworkDependencies", testFrameworkDependencies.ToString()},
                {"CodeCoverageDependencies", codeCoverageDependencies.ToString()},
                {"TestJSFile", testJsReplacement.ToString()},
                {"ReferencedJSFiles", referenceJsReplacement.ToString()},
                {"ReferencedCSSFiles", referenceCssReplacement.ToString()},
                {"TestHtmlTemplateFiles", referenceHtmlTemplateReplacement.ToString()},
                {"AMDTestPath", amdModulePath}
            };

            var testHtmlStringBuilder = new StringBuilder(testHtmlTemplate);

            foreach (var replacement in replacements.Union(frameworkReplacements))
            {
                testHtmlStringBuilder.Replace("@@" + replacement.Key + "@@", replacement.Value);
            }

            return testHtmlStringBuilder.ToString();
        }
コード例 #59
0
ファイル: OAuth.cs プロジェクト: pz7gc3/DashBuddyWin
        private static string GetSignature(string url, string method, string nonce, string timestamp, string token, string tokenSecret, Dictionary<string, object> parameters)
        {
            var dict = new Dictionary<string, object>();
            dict.Add("oauth_consumer_key", ConsumerKey);
            dict.Add("oauth_nonce", nonce.ToString());
            dict.Add("oauth_signature_method", "HMAC-SHA1");
            dict.Add("oauth_timestamp", timestamp);
            dict.Add("oauth_token", token);
            dict.Add("oauth_version", "1.0");
            var sigBase = new StringBuilder();
            var first = true;
            foreach (var d in (parameters == null ? dict : dict.Union(parameters)).OrderBy(p => p.Key))
            {
                if (!first)
                {
                    sigBase.Append("&");
                }
                first = false;
                if (d.Key.StartsWith("data"))
                {
                    sigBase.Append(d.Key);
                }
                else
                {
                    UrlEncode(sigBase, d.Key);
                }
                sigBase.Append("=");
                if (d.Value is byte[])
                {
                    EncodeSigStream(sigBase, (byte[])d.Value);
                }
                else
                {
                    UrlEncode(sigBase, d.Value.ToString());
                }
            }

            String SigBaseString = method.ToUpper() + "&";
            SigBaseString += UrlEncode(url) + "&" + UrlEncode(sigBase.ToString(), false);

            var keyMaterial = Encoding.UTF8.GetBytes(ConsumerSecret + "&" + tokenSecret);
            var HmacSha1Provider = new System.Security.Cryptography.HMACSHA1 { Key = keyMaterial };
            return Convert.ToBase64String(HmacSha1Provider.ComputeHash(Encoding.UTF8.GetBytes(SigBaseString)));
        }
コード例 #60
0
        public ActionResult ManagePointItems()
        {
            PointSettings pointSettings = pointSettingsManger.Get();

            pageResourceManager.InsertTitlePart("积分规则");
            IEnumerable<PointCategory> pointCategories = pointService.GetPointCategories();
            ViewData["traPoint"] = pointCategories.FirstOrDefault(n => n.CategoryKey.Equals("TradePoints")).CategoryName;
            ViewData["expPoint"] = pointCategories.FirstOrDefault(n => n.CategoryKey.Equals("ExperiencePoints")).CategoryName;
            ViewData["prePoint"] = pointCategories.FirstOrDefault(n => n.CategoryKey.Equals("ReputationPoints")).CategoryName;

            ViewData["TransactionTax"] = pointSettings.TransactionTax;
            ViewData["PointCategories"] = pointService.GetPointCategories();

            ViewData["UserIntegratedPointRuleText"] = pointSettings.UserIntegratedPointRuleText;

            IEnumerable<PointItem> pointItems = pointService.GetPointItems(null);
            Dictionary<int, string> applicationDictionary = new Dictionary<int, string> { { 0, "通用" } };

            ViewData["Applications"] = applicationDictionary.Union(applicationService.GetAll().ToDictionary(m => m.ApplicationId, n => n.Config.ApplicationName));

            return View(pointItems);
        }