/// <summary> /// 安全的转换成字典集 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TElement"></typeparam> /// <param name="source"></param> /// <param name="keySelector">键选择器</param> /// <param name="elementSelector">值选择器</param> /// <returns></returns> public static async Task <NullableDictionary <TKey, TElement> > ToDictionarySafetyAsync <TSource, TKey, TElement>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <TSource, Task <TElement> > elementSelector) { var dic = new NullableDictionary <TKey, TElement>(source.Count()); await source.ForeachAsync(async item => dic[keySelector(item)] = await elementSelector(item)); return(dic); }
public void SetUp() { _indexedEventOne = SupportEventBeanFactory.MakeEvents(new String[] { "s1_1", "s1_2" }); _indexedEventTwo = SupportEventBeanFactory.MakeEvents(new String[] { "s2_1", "s2_2" }); _newEventOne = SupportEventBeanFactory.MakeEvents(new String[] { "s1_3" }); _newEventTwo = SupportEventBeanFactory.MakeEvents(new String[] { "s2_3" }); _indexLeft = new UnindexedEventTableImpl(1); _indexLeft.Add(_indexedEventOne); _indexRight = new UnindexedEventTableImpl(1); _indexRight.Add(_indexedEventTwo); var queryStrategies = new QueryStrategy[2]; var lookupLeft = new TableLookupExecNode(1, new FullTableScanLookupStrategy(_indexRight)); var lookupRight = new TableLookupExecNode(0, new FullTableScanLookupStrategy(_indexLeft)); queryStrategies[0] = new ExecNodeQueryStrategy(0, 2, lookupLeft); queryStrategies[1] = new ExecNodeQueryStrategy(1, 2, lookupRight); var indexes = new IDictionary <TableLookupIndexReqKey, EventTable> [2]; indexes[0] = new NullableDictionary <TableLookupIndexReqKey, EventTable>(); indexes[1] = new NullableDictionary <TableLookupIndexReqKey, EventTable>(); indexes[0].Put(new TableLookupIndexReqKey("idxLeft"), _indexLeft); indexes[1].Put(new TableLookupIndexReqKey("idxLeft"), _indexRight); _joinSetComposerImpl = new JoinSetComposerImpl(true, indexes, queryStrategies, false, null, true); }
public static IDictionary <String, String> SplitAsDictionary(this String?value, String nameValueSeparator = "=", String separator = ";", Boolean trimQuotation = false) { var dic = new NullableDictionary <String, String>(StringComparer.OrdinalIgnoreCase); if (value == null || value.IsNullOrWhiteSpace()) { return(dic); } if (nameValueSeparator.IsNullOrEmpty()) { nameValueSeparator = "="; } //if (separator == null || separator.Length <= 0) separator = new String[] { ",", ";" }; var ss = value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); if (ss == null || ss.Length <= 0) { return(dic); } var k = 0; foreach (var item in ss) { var p = item.IndexOf(nameValueSeparator); if (p <= 0) { dic[$"[{k}]"] = item; k++; continue; } var key = item[..p].Trim();
public DarthVader() { Routes = new MessageReceived[] { PreBattle, Battle }; Buttons = new NullableDictionary <MessageReceived, Dictionary <string, MessageReceived> > { { null, new Dictionary <string, MessageReceived> { { "— НЕЕЕЕЕЕЕЕЕЕЕЕЕЕЕЕЕТ!", (user, message) => { SwitchAction(user, PreBattle); user.Info.MakeDamage(15); SendMessage(user, "Тебе отрубили руку. А теперь хорош рыдать и в бой.", GetButtons(user)); } } } }, { PreBattle, new Dictionary <string, MessageReceived> { { "Достать оружие", (user, message) => { SendMessage(user, "<b>щелк</b>"); user.RoomManager.Go(VaderBattle.Id); } } } } }; }
public Guild() { Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> > { { null, new Dictionary <string, MessageRecived> { { "Уйти", (user, message) => user.RoomManager.Leave() }, { "А насколько вы древний?", (user, message) => { SendMessage(user, "Маг чуть не треснул вас посохом, но молния всё-таки попала."); user.Info.Kill(); } }, { "Подучиться", (user, message) => { if (user.Info.ChangeStats(StatsProperty.Mana, -10)) { user.Info.ChangeStats(StatsProperty.Intelligence, 1.1m); SendMessage(user, "Вы стали чуточку умнее"); } else { SendMessage(user, "Вот когда будет мана, тогда и приходите"); } } } } } }; }
public Gym() { Buttons = new NullableDictionary <MessageReceived, Dictionary <string, MessageReceived> > { { null, new Dictionary <string, MessageReceived> { { "Уйти", (user, message) => user.RoomManager.Leave() }, { "Потренироваться", (user, message) => { SendMessage(user, "Вы не успели договорить, а уже отлетелии в дальний угол."); user.Info.MakeDamage(30); } }, { "Подкачаться", (user, message) => { if (user.Info.ChangeStats(StatsProperty.Stamina, -10)) { user.Info.ChangeStats(StatsProperty.Strength, 1.1m); SendMessage(user, "Вы стали чуточку сильнее"); } else { SendMessage(user, "Вы слишком устали и не можете сейчас тренироваться"); } } } } } }; }
public Mirror() { Routes = new MessageRecived[] { EditStats, Inventory }; Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> > { { null, new Dictionary <string, MessageRecived> { { "Перераспределить предметы", (user, message) => { SwitchAction(user, EditStats); SendMessage(user, "Ты начал тщательно рыться в карманах"); EditStats(user, message); } }, { "Имущество", (user, message) => { GetRoomVariables(user).Set("current_page", new Serializable.Int(0)); SwitchAction(user, Inventory); Inventory(user, message); } }, { "Уйти", (user, message) => user.RoomManager.Leave() } } } }; }
public Skitties() { Buttons = new NullableDictionary <MessageReceived, Dictionary <string, MessageReceived> > { { null, new Dictionary <string, MessageReceived> { { "Попробовать", (user, message) => { SendMessage(user, "Вполне себе обычные вкусненькие конфеты. Правда, ты не заметил, как съел полведра и теперь чувствуешь, как содержание глюкозы в твоей крови достигло критической отметки. Кажется, у тебя диабет. Но есть и плюсы: отойдя на метров двести, ты обнаружил у себя в кармане конфеты \"Skitties\". Да-да, те самые."); user.VariableManager.UserVariables.Set("skitties_diabetes", new Serializable.Int(10)); user.ItemManager.Add(new ItemInfo(Items.Skitties.Id, 10)); user.RoomManager.Leave(); } }, { "Нет, спасибо", (user, message) => { SendMessage(user, "— Ну ладно дружище, дело твое! — после этих слов он подобрал ведро, сел на жирафа и ускакал на Юго-Запад"); user.RoomManager.Leave(); } } } } }; }
protected override List <IDataTable> OnGetTables(String[] names) { #region 查表、字段信息、索引信息、主键信息 var session = Database.CreateSession(); //表信息 DataTable dt = null; dt = session.Query(_AllTableNameSql).Tables[0]; var data = new NullableDictionary <String, DataTable>(StringComparer.OrdinalIgnoreCase) { ["Columns"] = session.Query(_AllColumnSql).Tables[0], ["Indexes"] = session.Query(_AllIndexSql).Tables[0] }; ////数据类型DBType --〉DotNetType转换 //if (SqlCe.SqlCeProviderVersion < SQLCEVersion.SQLCE40) // DataTypes = CreateSqlCeDataType(session.Query(_DataTypeSql).Tables[0]); #endregion if (dt == null || dt.Rows == null || dt.Rows.Count < 1) { return(null); } // 默认列出所有字段 var rows = dt.Select("TABLE_TYPE='table'"); if (rows == null || rows.Length < 1) { return(null); } return(GetTables(rows, names, data)); }
private static IDictionary <String, String> ReadInfo(String file, Char separate = ':') { if (file.IsNullOrEmpty() || !File.Exists(file)) { return(null); } var dic = new NullableDictionary <String, String>(); using var reader = new StreamReader(file); while (!reader.EndOfStream) { // 按行读取 var line = reader.ReadLine(); if (line != null) { // 分割 var p = line.IndexOf(separate); if (p > 0) { var key = line.Substring(0, p).Trim(); var value = line.Substring(p + 1).Trim(); dic[key] = value; } } } return(dic); }
/// <summary>目标匿名参数对象转为字典</summary> /// <param name="target"></param> /// <returns></returns> public static IDictionary <String, Object> ToDictionary(this Object target) { //!! 即使传入为空,也返回字典,而不是null,避免业务层需要大量判空 //if (target == null) return null; if (target is IDictionary <String, Object> dic) { return(dic); } dic = new NullableDictionary <String, Object>(StringComparer.OrdinalIgnoreCase); if (target != null) { // 修正字符串字典的支持问题 if (target is IDictionary dic2) { foreach (DictionaryEntry item in dic2) { dic[item.Key + ""] = item.Value; } } else { foreach (var pi in target.GetType().GetProperties(true)) { var name = SerialHelper.GetName(pi); dic[name] = target.GetValue(pi); } } } return(dic); }
/// <summary>目标匿名参数对象转为字典</summary> /// <param name="target"></param> /// <returns></returns> public static IDictionary <String, Object> ToDictionary(this Object target) { if (target is IDictionary <String, Object> dic) { return(dic); } dic = new NullableDictionary <String, Object>(StringComparer.OrdinalIgnoreCase); if (target != null) { // 修正字符串字典的支持问题 if (target is IDictionary dic2) { foreach (DictionaryEntry item in dic2) { dic[item.Key + ""] = item.Value; } } else { foreach (var pi in target.GetType().GetProperties(true)) { dic[pi.Name] = target.GetValue(pi); } } } return(dic); }
/// <summary>拆分字符串成为不区分大小写的可空名值字典。逗号分组,等号分隔</summary> /// <param name="value">字符串</param> /// <param name="nameValueSeparator">名值分隔符,默认等于号</param> /// <param name="separator">分组分隔符,默认分号</param> /// <param name="trimQuotation">去掉括号</param> /// <returns></returns> public static IDictionary<String, String> SplitAsDictionary(this String value, String nameValueSeparator = "=", String separator = ";", Boolean trimQuotation = false) { var dic = new NullableDictionary<String, String>(StringComparer.OrdinalIgnoreCase); if (value.IsNullOrWhiteSpace()) return dic; if (nameValueSeparator.IsNullOrEmpty()) nameValueSeparator = "="; //if (separator == null || separator.Length < 1) separator = new String[] { ",", ";" }; var ss = value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); if (ss == null || ss.Length < 1) return null; foreach (var item in ss) { var p = item.IndexOf(nameValueSeparator); if (p <= 0) continue; var key = item.Substring(0, p).Trim(); var val = item.Substring(p + nameValueSeparator.Length).Trim(); // 处理单引号双引号 if (trimQuotation) { if (val[0] == '\'' && val[val.Length - 1] == '\'') val = val.Trim('\''); if (val[0] == '"' && val[val.Length - 1] == '"') val = val.Trim('"'); } dic[key] = val; } return dic; }
public Merchants() { Routes = new MessageRecived[] { Shop, Shop2 }; Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> > { { null, new Dictionary <string, MessageRecived> { { "Закупиться", (user, message) => { SwitchAction(user, Shop); HandleAction(user, message); } }, { "Ограбить", (user, message) => { SendMessage(user, "Несмотря на их натренированные языки, сами купцы были довольно хилыми даже по твоим меркам. Поэтому на каждое из этих слащавых лиц пришлось всего по одному удару. Ты заработал немного монет и мое личное неуважение."); user.Info.Gold += user.Random.Next(500, 850); user.RoomManager.Leave(); } }, { "Уйти", (user, message) => user.RoomManager.Leave() } } } }; }
/// <summary> /// Groups the data by the values in the given column, and computes aggregate quantities for each group. /// </summary> /// <param name="groupByColumnName">The name of the column to group by.</param> /// <param name="aggregator">A function that computes the aggregate quantities.</param> /// <returns>A new data frame containing the aggregates for each group.</returns> /// <remarks> /// <para>The first column of the returned <see cref="FrameTable"/> has the same name as the /// original <paramref name="groupByColumnName"/> and contains all the distinct /// values of that column in the original view. There is an additional column for each /// dictionary entry returned by <paramref name="aggregator"/>, whose name is the returned /// key and whose values are values returned for each group.</para> /// <para>The function that computes the aggregate receives a <see cref="FrameView"/> containing /// all the rows in the group. To produce aggregate results, it can use values in any of /// the columns. Each invocation of the <paramref name="aggregator"/> must return the same keys /// and values for the same keys must be of the same type. (Values for different keys may be /// of different types.) Aggregate column names are taken from the keys and storage types are /// inferred from the returned values.</para> /// <para>To produce just one aggregate value, you may find it simpler and more efficient /// to use the <see cref="GroupBy(string, Func{FrameView, IReadOnlyDictionary{string, object}})"/> /// overload.</para> /// </remarks> public FrameTable GroupBy(string groupByColumnName, Func <FrameView, IReadOnlyDictionary <string, object> > aggregator) { // Collect rows into groups. int groupByColumnIndex = GetColumnIndex(groupByColumnName); NamedList groupByColumn = columns[groupByColumnIndex]; NullableDictionary <object, List <int> > groups = FindGroups(groupByColumn); // Create a column to hold the group values. NamedList groupsColumn = NamedList.Create(groupByColumnName, groupByColumn.StorageType); // Create an enumerator that feeds the groups into the aggregator and presents them as dictionaries. IEnumerable <IReadOnlyDictionary <string, object> > aggregatesEnumerator = GetGroupEnumerator(groups, aggregator, groupsColumn); // Column-ify and validate the presented dictionaries. List <NamedList> aggregateColumns = DictionaryHelper.ReadDictionaries(aggregatesEnumerator); // Collect the results into a frame table. FrameTable result = new FrameTable(); // First column is the group values. result.AddColumn(groupsColumn); // Remaining columns are aggregate columns. foreach (NamedList aggregateColumn in aggregateColumns) { result.AddColumn(aggregateColumn); } return(result); }
/// <summary>初始化</summary> public XTable() { IsView = false; Columns = new List <IDataColumn>(); Indexes = new List <IDataIndex>(); Properties = new NullableDictionary <String, String>(StringComparer.OrdinalIgnoreCase); }
protected BetterRoomBase() { Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> >(); var routes = new List <Tuple <int, ActionBase <T> > >(); var indexes = new HashSet <int>(); var self = typeof(T); foreach (var type in self.GetNestedTypes()) { var action = type.GetCustomAttribute <ActionAttribute>(); if (action == null) { continue; } if (!typeof(ActionBase <T>).IsAssignableFrom(type)) { throw new Exception("Action must inherit from ActionBase"); } var ctor = type.GetConstructor(new[] { typeof(T) }); if (ctor == null) { throw new Exception("Action must have constructor with single BetterRoomBase argument"); } var instance = (ActionBase <T>)ctor.Invoke(new object[] { this }); MessageRecived handler = null; if (action.Index != null) { var index = (int)action.Index; if (indexes.Contains(index)) { throw new Exception($"Muliply definition of action with index {action.Index}"); } routes.Add(new Tuple <int, ActionBase <T> >(index, instance)); handler = instance.OnMessage; } else { if (_rootAction != null) { throw new Exception("Muliply definition of default action"); } _rootAction = instance.OnMessage; } _actions[type] = handler; Buttons[handler] = instance.Buttons; } Routes = routes.OrderBy(r => r.Item1).Select(r => (MessageRecived)r.Item2.OnMessage).ToArray(); }
/// <summary> /// 安全的转换成字典集 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TElement"></typeparam> /// <param name="source"></param> /// <param name="keySelector">键选择器</param> /// <param name="elementSelector">值选择器</param> /// <returns></returns> public static NullableDictionary <TKey, TElement> ToDictionarySafety <TSource, TKey, TElement>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <TSource, TElement> elementSelector) { var dic = new NullableDictionary <TKey, TElement>(); foreach (var item in source) { dic[keySelector(item)] = elementSelector(item); } return(dic); }
/// <summary> /// 安全的转换成字典集 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="source"></param> /// <param name="keySelector">键选择器</param> /// <returns></returns> public static NullableDictionary <TKey, TSource> ToDictionarySafety <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector) { var dic = new NullableDictionary <TKey, TSource>(source.Count()); foreach (var item in source) { dic[keySelector(item)] = item; } return(dic); }
public static IDictionary <string, object> ToDataMap(object value) { IDictionary <object, object> rawMap = (IDictionary <object, object>)value; IDictionary <string, object> outMap = new NullableDictionary <string, object>(); foreach (var entry in rawMap) { outMap.Put((string)entry.Key, entry.Value); } return(outMap); }
public Kiba() { Buttons = new NullableDictionary <MessageRecived, Dictionary <string, MessageRecived> > { { null, new Dictionary <string, MessageRecived> { { "Уйти", (user, message) => user.RoomManager.Leave() } } } }; }
/// <summary>加载模型文件</summary> /// <param name="xmlFile">Xml模型文件</param> /// <param name="option">生成可选项</param> /// <param name="atts">扩展属性字典</param> /// <returns></returns> public static IList <IDataTable> LoadModels(String xmlFile, BuilderOption option, out IDictionary <String, String> atts) { if (xmlFile.IsNullOrEmpty()) { var di = ".".GetBasePath().AsDirectory(); //XTrace.WriteLine("未指定模型文件,准备从目录中查找第一个xml文件 {0}", di.FullName); // 选当前目录第一个 xmlFile = di.GetFiles("*.xml", SearchOption.TopDirectoryOnly).FirstOrDefault()?.FullName; } if (xmlFile.IsNullOrEmpty()) { throw new Exception("找不到任何模型文件!"); } xmlFile = xmlFile.GetBasePath(); if (!File.Exists(xmlFile)) { throw new FileNotFoundException("指定模型文件不存在!", xmlFile); } // 导入模型 var xmlContent = File.ReadAllText(xmlFile); atts = new NullableDictionary <String, String>(StringComparer.OrdinalIgnoreCase) { ["xmlns"] = "http://www.newlifex.com/Model2022.xsd", ["xmlns:xs"] = "http://www.w3.org/2001/XMLSchema-instance", ["xs:schemaLocation"] = "http://www.newlifex.com http://www.newlifex.com/Model2022.xsd" }; if (Debug) { XTrace.WriteLine("导入模型:{0}", xmlFile); } // 导入模型 var tables = ModelHelper.FromXml(xmlContent, DAL.CreateTable, atts); if (option != null) { option.Output = atts["Output"] ?? Path.GetDirectoryName(xmlFile); option.Namespace = atts["NameSpace"] ?? Path.GetFileNameWithoutExtension(xmlFile); option.ConnName = atts["ConnName"]; option.BaseClass = atts["BaseClass"]; } // 保存文件名 atts["ModelFile"] = xmlFile; return(tables); }
/// <summary> /// 转换成普通字典集合 /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dic"></param> /// <param name="defaultValue">键未找到时的默认值</param> /// <returns></returns> public static NullableDictionary <TKey, TValue> AsDictionary <TKey, TValue>(this ConcurrentDictionary <TKey, TValue> dic, TValue defaultValue) { var nullableDictionary = new NullableDictionary <TKey, TValue>() { FallbackValue = defaultValue }; foreach (var p in dic) { nullableDictionary[p.Key] = p.Value; } return(nullableDictionary); }
public IContainer RegisterType(Type request, Type @return, IConstructor constructor, string name) { if (!IsRegistered(request)) { _iocMap[request] = new NullableDictionary <string, IConstructor>(); } if (constructor == null) { constructor = Constructors.Type(@return); } _iocMap[request][name] = constructor; return(this); }
public ParameterTranslationsImpl(IEnumerable <IParameterSpecification> parameterSpecifications) { List <ParameterInfo> ordinalParameterList = new List <ParameterInfo>(); NullableDictionary <string, NamedParamTempHolder> namedParameterMap = new NullableDictionary <string, NamedParamTempHolder>(); int i = 0; foreach (IParameterSpecification spec in parameterSpecifications) { if (spec is PositionalParameterSpecification) { PositionalParameterSpecification ordinalSpec = ( PositionalParameterSpecification )spec; ordinalParameterList.Add(new ParameterInfo(i, ordinalSpec.ExpectedType)); } else if (spec is NamedParameterSpecification) { NamedParameterSpecification namedSpec = ( NamedParameterSpecification )spec; NamedParamTempHolder paramHolder = namedParameterMap[namedSpec.Name]; if (paramHolder == null) { paramHolder = new NamedParamTempHolder(); paramHolder.name = namedSpec.Name; paramHolder.type = namedSpec.ExpectedType; namedParameterMap.Add(namedSpec.Name, paramHolder); } paramHolder.positions.Add(i); } else { // don't care about other param types here, just those explicitly user-defined... // Steve Strong Note: The original Java does not do this decrement; it increments i for // every parameter type. However, within the Loader.GetParameterTypes() method, this introduces // nulls into the paramTypeList array, which in turn causes Loader.ConvertITypesToSqlTypes() to crash // with a null dereference. An alternative fix is to change the Loader to handle the null. I'm // not sure which fix is the most appropriate. // Legacy.FumTest.CompositeIDQuery() shows the bug if you remove the decrement below... i--; } i++; } _ordinalParameters = ordinalParameterList.ToArray(); _namedParameters = new Dictionary <string, ParameterInfo>(); foreach (NamedParamTempHolder holder in namedParameterMap.Values) { _namedParameters.Add(holder.name, new ParameterInfo(ArrayHelper.ToIntArray(holder.positions), holder.type)); } }
private void AddTrigger(ScheduleSlot slot, ScheduleHandle handle, long triggerTime) { var handleSet = _timeHandleMap.Get(triggerTime); if (handleSet == null) { handleSet = new NullableDictionary <ScheduleSlot, ScheduleHandle>( new OrderedDictionary <ScheduleSlot, ScheduleHandle>()); _timeHandleMap.Put(triggerTime, handleSet); } handleSet.Put(slot, handle); _handleSetMap.Put(handle, handleSet); }
/// <summary> /// 安全的转换成字典集 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TElement"></typeparam> /// <param name="source"></param> /// <param name="keySelector">键选择器</param> /// <param name="elementSelector">值选择器</param> /// <param name="defaultValue">键未找到时的默认值</param> /// <returns></returns> public static NullableDictionary <TKey, TElement> ToDictionarySafety <TSource, TKey, TElement>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector, Func <TSource, TElement> elementSelector, TElement defaultValue) { var dic = new NullableDictionary <TKey, TElement>(source.Count()) { FallbackValue = defaultValue }; foreach (var item in source) { dic[keySelector(item)] = elementSelector(item); } return(dic); }
public void TestMakeExec() { var indexesPerStream = new IDictionary <TableLookupIndexReqKey, EventTable> [2]; indexesPerStream[1] = new NullableDictionary <TableLookupIndexReqKey, EventTable>(); indexesPerStream[1].Put(new TableLookupIndexReqKey("idx1"), new UnindexedEventTableImpl(0)); var spec = new TableLookupNode(new FullTableScanLookupPlan(0, 1, new TableLookupIndexReqKey("idx1"))); var execNode = spec.MakeExec("ABC", 1, null, indexesPerStream, null, new Viewable[2], null, new VirtualDWView[2], new ILockable[2]); var exec = (TableLookupExecNode)execNode; Assert.AreSame(indexesPerStream[1].Get(new TableLookupIndexReqKey("idx1")), ((FullTableScanLookupStrategy)exec.LookupStrategy).EventIndex); Assert.AreEqual(1, exec.IndexedStream); }
public static IDictionary <String, String> SplitAsDictionaryT(this String?value, Char nameValueSeparator = '=', Char separator = ';', Boolean trimQuotation = false) { var dic = new NullableDictionary <String, String>(StringComparer.OrdinalIgnoreCase); if (value == null || value.IsNullOrWhiteSpace()) { return(dic); } //if (nameValueSeparator == null) nameValueSeparator = '='; //if (separator == null || separator.Length < 1) separator = new String[] { ",", ";" }; var ss = value.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); if (ss == null || ss.Length < 1) { return(dic); } foreach (var item in ss) { var p = item.IndexOf(nameValueSeparator); if (p <= 0) { continue; } var key = item.Substring(0, p).Trim(); var val = item.Substring(p + 1).Trim(); // 处理单引号双引号 if (trimQuotation && !val.IsNullOrEmpty()) { if (val[0] == '\'' && val[val.Length - 1] == '\'') { val = val.Trim('\''); } if (val[0] == '"' && val[val.Length - 1] == '"') { val = val.Trim('"'); } } dic[key] = val; } return(dic); }
public ParameterTranslationsImpl(IEnumerable<IParameterSpecification> parameterSpecifications) { List<ParameterInfo> ordinalParameterList = new List<ParameterInfo>(); NullableDictionary<string, NamedParamTempHolder> namedParameterMap = new NullableDictionary<string, NamedParamTempHolder>(); int i = 0; foreach (IParameterSpecification spec in parameterSpecifications) { if ( spec is PositionalParameterSpecification) { PositionalParameterSpecification ordinalSpec = ( PositionalParameterSpecification ) spec; ordinalParameterList.Add( new ParameterInfo( i, ordinalSpec.ExpectedType) ); } else if ( spec is NamedParameterSpecification ) { NamedParameterSpecification namedSpec = ( NamedParameterSpecification ) spec; NamedParamTempHolder paramHolder = namedParameterMap[namedSpec.Name]; if ( paramHolder == null ) { paramHolder = new NamedParamTempHolder(); paramHolder.name = namedSpec.Name; paramHolder.type = namedSpec.ExpectedType; namedParameterMap.Add( namedSpec.Name, paramHolder ); } paramHolder.positions.Add( i ); } else { // don't care about other param types here, just those explicitly user-defined... // Steve Strong Note: The original Java does not do this decrement; it increments i for // every parameter type. However, within the Loader.GetParameterTypes() method, this introduces // nulls into the paramTypeList array, which in turn causes Loader.ConvertITypesToSqlTypes() to crash // with a null dereference. An alternative fix is to change the Loader to handle the null. I'm // not sure which fix is the most appropriate. // Legacy.FumTest.CompositeIDQuery() shows the bug if you remove the decrement below... i--; } i++; } _ordinalParameters = ordinalParameterList.ToArray(); _namedParameters = new Dictionary<string, ParameterInfo>(); foreach (NamedParamTempHolder holder in namedParameterMap.Values) { _namedParameters.Add(holder.name, new ParameterInfo( ArrayHelper.ToIntArray( holder.positions ), holder.type )); } }
private static IDictionary <string, ObjectFactory <string> > CreatePropertyConstructors(IDictionary <string, Type> propertyTypes) { var factories = new NullableDictionary <string, ObjectFactory <string> >(); foreach (var entry in propertyTypes) { var property = entry.Key; var propertyType = entry.Value; Log.Debug(".CreatePropertyConstructors property==" + property + ", type==" + propertyType); factories.Put(property, ObjectFactoryFor(propertyType)); } return(factories); }
/// <summary> /// Make a list of groups that should be shown according to the given parameters /// </summary> /// <param name="parms"></param> /// <returns>The list of groups to be created</returns> /// <remarks>This should not change the state of the control. It is possible that the /// groups created will not be used. They may simply be discarded.</remarks> protected virtual IList<OLVGroup> MakeGroups(GroupingParameters parms) { // There is a lot of overlap between this method and FastListGroupingStrategy.MakeGroups() // Any changes made here may need to be reflected there // Separate the list view items into groups, using the group key as the descrimanent NullableDictionary<object, List<OLVListItem>> map = new NullableDictionary<object, List<OLVListItem>>(); foreach (OLVListItem olvi in parms.ListView.Items) { object key = parms.GroupByColumn.GetGroupKey(olvi.RowObject); if (!map.ContainsKey(key)) map[key] = new List<OLVListItem>(); map[key].Add(olvi); } // Sort the items within each group (unless specifically turned off) OLVColumn primarySortColumn = parms.SortItemsByPrimaryColumn ? parms.ListView.GetColumn(0) : parms.PrimarySort; if (primarySortColumn != null && parms.PrimarySortOrder != SortOrder.None) { ColumnComparer itemSorter = new ColumnComparer(primarySortColumn, parms.PrimarySortOrder, parms.SecondarySort, parms.SecondarySortOrder); foreach (object key in map.Keys) { map[key].Sort(parms.ItemComparer ?? itemSorter); } } // Make a list of the required groups List<OLVGroup> groups = new List<OLVGroup>(); foreach (object key in map.Keys) { string title = parms.GroupByColumn.ConvertGroupKeyToTitle(key); if (!String.IsNullOrEmpty(parms.TitleFormat)) { int count = map[key].Count; string format = (count == 1 ? parms.TitleSingularFormat : parms.TitleFormat); try { title = String.Format(format, title, count); } catch (FormatException) { title = "Invalid group format: " + format; } } OLVGroup lvg = new OLVGroup(title); lvg.Collapsible = this.HasCollapsibleGroups; lvg.Key = key; lvg.SortValue = key as IComparable; lvg.Items = map[key]; if (parms.GroupByColumn.GroupFormatter != null) parms.GroupByColumn.GroupFormatter(lvg, parms); groups.Add(lvg); } // Sort the groups if (parms.GroupByOrder != SortOrder.None) groups.Sort(parms.GroupComparer ?? new OLVGroupComparer(parms.GroupByOrder)); return groups; }
private void ClusterOneModel(IClusteringStrategy strategy, NullableDictionary<object, ICluster> map, object model) { object clusterKey = strategy.GetClusterKey(model); // If the returned value is an IEnumerable, that means the given model can belong to more than one cluster IEnumerable keyEnumerable = clusterKey as IEnumerable; if (clusterKey is string || keyEnumerable == null) keyEnumerable = new object[] {clusterKey}; // Deal with nulls and DBNulls ArrayList nullCorrected = new ArrayList(); foreach (object key in keyEnumerable) { if (key == null || key == System.DBNull.Value) { if (this.TreatNullAsDataValue) nullCorrected.Add(null); } else nullCorrected.Add(key); } // Group by key foreach (object key in nullCorrected) { if (map.ContainsKey(key)) map[key].Count += 1; else map[key] = strategy.CreateCluster(key); } }
/// <summary> /// Create a collection of clusters that should be presented to the user /// </summary> /// <param name="strategy"></param> /// <param name="listView"></param> /// <param name="column"></param> /// <returns></returns> virtual protected List<ICluster> Cluster(IClusteringStrategy strategy, ObjectListView listView, OLVColumn column) { // Build a map that correlates cluster key to clusters NullableDictionary<object, ICluster> map = new NullableDictionary<object, ICluster>(); int count = 0; foreach (object model in listView.ObjectsForClustering) { this.ClusterOneModel(strategy, map, model); if (count++ > this.MaxObjectsToConsider) break; } // Now that we know exactly how many items are in each cluster, create a label for it foreach (ICluster cluster in map.Values) cluster.DisplayLabel = strategy.GetClusterDisplayLabel(cluster); return new List<ICluster>(map.Values); }
/// <summary> /// Create groups for FastListView /// </summary> /// <param name="parmameters"></param> /// <returns></returns> public override IList<OLVGroup> GetGroups(GroupingParameters parmameters) { // There is a lot of overlap between this method and ObjectListView.MakeGroups() // Any changes made here may need to be reflected there // This strategy can only be used on FastObjectListViews FastObjectListView folv = (FastObjectListView)parmameters.ListView; // Separate the list view items into groups, using the group key as the descrimanent int objectCount = 0; NullableDictionary<object, List<object>> map = new NullableDictionary<object, List<object>>(); foreach (object model in folv.FilteredObjects) { object key = parmameters.GroupByColumn.GetGroupKey(model); if (!map.ContainsKey(key)) map[key] = new List<object>(); map[key].Add(model); objectCount++; } // Sort the items within each group // TODO: Give parameters a ModelComparer property OLVColumn primarySortColumn = parmameters.SortItemsByPrimaryColumn ? parmameters.ListView.GetColumn(0) : parmameters.PrimarySort; ModelObjectComparer sorter = new ModelObjectComparer(primarySortColumn, parmameters.PrimarySortOrder, parmameters.SecondarySort, parmameters.SecondarySortOrder); foreach (object key in map.Keys) { map[key].Sort(sorter); } // Make a list of the required groups List<OLVGroup> groups = new List<OLVGroup>(); foreach (object key in map.Keys) { string title = parmameters.GroupByColumn.ConvertGroupKeyToTitle(key); if (!String.IsNullOrEmpty(parmameters.TitleFormat)) { int count = map[key].Count; string format = (count == 1 ? parmameters.TitleSingularFormat : parmameters.TitleFormat); try { title = String.Format(format, title, count); } catch (FormatException) { title = "Invalid group format: " + format; } } OLVGroup lvg = new OLVGroup(title); lvg.Collapsible = folv.HasCollapsibleGroups; lvg.Key = key; lvg.SortValue = key as IComparable; lvg.Contents = map[key].ConvertAll<int>(delegate(object x) { return folv.IndexOf(x); }); lvg.VirtualItemCount = map[key].Count; if (parmameters.GroupByColumn.GroupFormatter != null) parmameters.GroupByColumn.GroupFormatter(lvg, parmameters); groups.Add(lvg); } // Sort the groups if (parmameters.GroupByOrder != SortOrder.None) groups.Sort(parmameters.GroupComparer ?? new OLVGroupComparer(parmameters.GroupByOrder)); // Build an array that remembers which group each item belongs to. this.indexToGroupMap = new List<int>(objectCount); this.indexToGroupMap.AddRange(new int[objectCount]); for (int i = 0; i < groups.Count; i++) { OLVGroup group = groups[i]; List<int> members = (List<int>)group.Contents; foreach (int j in members) this.indexToGroupMap[j] = i; } return groups; }
/// <summary> /// Construct a new SessionFactoryHelperExtensions instance. /// </summary> /// <param name="sfi">The SessionFactory impl to be encapsulated.</param> public SessionFactoryHelperExtensions(ISessionFactoryImplementor sfi) { _sfi = sfi; helper = new SessionFactoryHelper(_sfi); _collectionPropertyMappingByRole = new NullableDictionary<string, IPropertyMapping>(); }
/// <summary> /// Create a collection of clusters that should be presented to the user /// </summary> /// <param name="strategy"></param> /// <param name="listView"></param> /// <param name="column"></param> /// <returns></returns> virtual protected List<ICluster> Cluster(IClusteringStrategy strategy, ObjectListView listView, OLVColumn column) { // Build a map that correlates cluster key to clusters NullableDictionary<object, ICluster> map = new NullableDictionary<object, ICluster>(); int count = 0; foreach (object model in listView.Objects) { object key = strategy.GetClusterKey(model); if (key == System.DBNull.Value) key = null; if (key == null && !this.TreatNullAsDataValue) continue; if (map.ContainsKey(key)) map[key].Count += 1; else map[key] = strategy.CreateCluster(key); // Check our limit count += 1; if (count > this.MaxObjectsToConsider) break; } // Now that we know exactly how many items are in each cluster, create a label for it foreach (ICluster cluster in map.Values) cluster.DisplayLabel = strategy.GetClusterDisplayLabel(cluster); return new List<ICluster>(map.Values); }
public void SetUp() { nullableDictionary = new NullableDictionary<string, string>(); }