Here are the examples of the csharp api System.Collections.Generic.IEnumerable.ToDictionary(System.Func, System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2404 Examples
19
View Source File : ServiceExtensions.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static TService SetMeta<TService>(this TService service, params (string key, string value)[] meta) where TService : IService
{
return service.SetMeta(meta.ToDictionary(key => key.key, value => value.value));
}
19
View Source File : DynamicProxy.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append([email protected]"{(proxyMethodName == "Before" ? [email protected]"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
[email protected]"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? [email protected]"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append([email protected]"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return [email protected]"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? [email protected]"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : [email protected]"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? [email protected]"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append([email protected]"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append([email protected]"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append([email protected]"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append([email protected]"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append([email protected]"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append([email protected]"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append([email protected]"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append([email protected]"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => [email protected]"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append([email protected]"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => [email protected]"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = [email protected]"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
View Source File : KeysTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Del()
{
var keys = Enumerable.Range(0, 10).Select(a => Guid.NewGuid().ToString()).ToArray();
cli.MSet(keys.ToDictionary(a => a, a => (object)a));
replacedert.Equal(10, cli.Del(keys));
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static void Main(string[] args)
{
int ruleCount = 0;
int gradientMax = 0;
Parser.Default.ParseArguments<Options>(args)
.WithParsed(o =>
{
LoadConfig(o);
if (!o.Suricata)
{
LoadMismatchSearchMatrix(o);
foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
{
try
{
var dict = DeserializeYamlFile(ruleFilePath, o);
if (dict != null && dict.ContainsKey("tags"))
{
ruleCount++;
var tags = dict["tags"];
var categories = new List<string>();
string lastEntry = null;
foreach (string tag in tags)
{
//If its the technique id entry, then this adds the file name to the techniques map
if (tag.ToLower().StartsWith("attack.t"))
{
var techniqueId = tag.Replace("attack.", "").ToUpper();
if (!techniques.ContainsKey(techniqueId))
techniques[techniqueId] = new List<string>();
techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
if (techniques.Count > gradientMax)
gradientMax = techniques.Count;
//then if there are any categories so far, it checks for a mismatch for each one
if (categories.Count > 0 && o.Warning)
{
foreach (string category in categories)
if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
}
}
else
{
//if its the start of a new technique block, then clean categories and adds first category
if (lastEntry == null || lastEntry.StartsWith("attack.t"))
categories = new List<string>();
categories.Add(
tag.Replace("attack.", "")
.Replace("_", "-")
.ToLower());
}
lastEntry = tag;
}
}
}
catch (YamlException e)
{
Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
}
}
WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
PrintWarnings();
}
else
{
List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();
foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
{
res.Add(ParseRuleFile(ruleFilePath));
}
WriteSuricataFileResult(o,
res
.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key,
group => group.SelectMany(list => list).ToList()));
}
});
}
19
View Source File : SlnWriter.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
protected void Validate(IEnumerable<ISection> sections)
{
var coh = GetSlnHandlers(sections)
.Where(s => s.CoHandlers != null && s.CoHandlers.Count > 0)
.ToDictionary(key => key.GetType(), value => value.CoHandlers);
foreach(var h in Handlers)
{
if(coh.ContainsKey(h.Key))
{
if(coh[h.Key].Except(Handlers.Keys).Count() != coh[h.Key].Count) {
throw new CoHandlerRuleException(
$"Only parent handler is allowed '{h.Key}' <- {String.Join(", ", coh[h.Key].Select(c => c.Name))}"
);
}
continue;
}
if(coh.Where(v => v.Value.Contains(h.Key))
.Select(v => v.Key)
.Except(Handlers.Keys).Count() > 0)
{
throw new CoHandlerRuleException($"Define parent handler instead of '{h.Key}'.");
}
}
}
19
View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
protected IXProject XProjectByFile(string file, IConfPlatform cfg, bool tryLoad, IDictionary<string, string> props)
{
var found = Projects?.FirstOrDefault(p =>
Eq(p.Projecreplacedem.projectConfig, cfg) && (p.ProjectFullPath == file)
);
if(found != null || !tryLoad || string.IsNullOrWhiteSpace(file)) {
return found;
}
return AddOrGet(GetOrLoadProject
(
GetProjecreplacedem(file, props),
DefProperties(cfg, slnProperties.ToDictionary(k => k.Key, v => v.Value).AddOrUpdate(props))
));
}
19
View Source File : Dialog_Exchenge.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public void DoWindowAddThingList(Rect inRect)
{
if (!ShowAddThingList) return;
if (AddThingGrid == null)
{
//инициализация
AddThingGrid = new GridBox<TransferableOneWay>();
Transferables = GameUtils.DistinctThings(AllThings);
var dicMaxCount = Transferables.ToDictionary(t => t, t => t.MaxCount);
AddThingGrid.DataSource = Transferables;
AddThingGrid.LineHeight = 24f;
AddThingGrid.Tooltip = null;
AddThingGrid.OnDrawLine = (int line, TransferableOneWay item, Rect rectLine) =>
{
try
{
if (!item.HasAnyThing) return;
float currentWidth = rectLine.width;
//ввод кол-во и кнопки < >
currentWidth -= 60f + rectLine.height * 2f;
Rect rect3 = new Rect(rectLine.width - 60f - rectLine.height, 0f, 60f, rectLine.height);
int num2 = GenUI.CurrentAdjustmentMultiplier(); //зажали кнопку для прибавления по 10/100
if (item.CanAdjustBy(-1 * num2).Accepted)
{
Rect rect4 = new Rect(rect3.x - rectLine.height, 0f, rectLine.height, rectLine.height).ContractedBy(1f);
if (Widgets.ButtonText(rect4, "<", true, false, true))
{
item.AdjustBy(-1 * num2);
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
}
}
int countToTransfer = item.CountToTransfer;
string editBuffer = item.EditBuffer;
Widgets.TextFieldNumeric<int>(rect3.ContractedBy(2f), ref countToTransfer, ref editBuffer, 0f, (float)dicMaxCount[item]);
item.AdjustTo(countToTransfer);
item.EditBuffer = editBuffer;
if (item.CanAdjustBy(1 * num2).Accepted)
{
Rect rect4 = new Rect(rect3.xMax, 0f, rectLine.height, rectLine.height).ContractedBy(1f);
if (Widgets.ButtonText(rect4, ">", true, false, true))
{
item.AdjustBy(1 * num2);
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
}
}
//кол-во
rect3 = new Rect(currentWidth - 60f, 0f, 60f, rectLine.height);
Text.WordWrap = false;
Text.Anchor = TextAnchor.MiddleRight;
Widgets.Label(rect3, dicMaxCount[item].ToString());
currentWidth -= 60f;
//цена
rect3 = new Rect(currentWidth - 60f, 0f, 80f, rectLine.height);
Text.Anchor = TextAnchor.MiddleLeft;
Widgets.Label(rect3, item.AnyThing.MarketValue.ToStringMoney());
Text.WordWrap = true;
currentWidth -= 60f;
//Иконка i и описание
GameUtils.DravLineThing(new Rect(0f, 0f, currentWidth, rectLine.height), item.AnyThing, Color.white);
}
catch (Exception e)
{
Log.Error(e.ToString());
}
};
}
//заголовок
Rect rect = new Rect(0f, 0f, inRect.width, 24);
inRect.yMin += rect.height;
Text.Font = GameFont.Tiny; // высота Tiny 18
Text.Anchor = TextAnchor.UpperCenter;
Widgets.Label(rect, "OCity_Dialog_Exchenge_Select_For_Sale".Translate(PlaceCurrent.Name));
//кнопка "Выбрать"
rect.xMin += inRect.width - 150f;
Text.Anchor = TextAnchor.MiddleCenter;
if (Widgets.ButtonText(rect.ContractedBy(1f), "OCity_Dialog_Exchenge_Choose".Translate(), true, false, true))
{
SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
AddThingListApply();
return;
}
Text.Font = GameFont.Tiny;
Text.Anchor = TextAnchor.MiddleLeft;
AddThingGrid.Area = inRect;
AddThingGrid.Drow();
}
19
View Source File : GameUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private static List<TransferableOneWay> ChechToTradeDo(IEnumerable<ThingTrade> targets, IEnumerable<Thing> allThings, ref int rate, bool setRect)
{
bool result = true;
var selects = new List<TransferableOneWay>();
var source = allThings.ToDictionary(i => i, i => i.stackCount);
//сортируем вещи сначала более плохие
var sourceKeys = source.Keys
.Select(t =>
{
QualityCategory qq;
QualityUtility.TryGetQuality(t, out qq);
return new { thing = t, q = qq };
})
.OrderBy(t => t.thing.def.defName + "#" + ((int)t.q).ToString() + (10000 - t.thing.HitPoints).ToString() + t.thing.stackCount.ToString().PadLeft(6))
.Select(t => t.thing)
.ToList();
foreach (var target in targets)
{
if (target.Count == 0)
{
target.NotTrade = false;
continue;
}
if (setRect && target.Count > 100 && rate > 1000000) rate = 1000000; //от переполнения
var select = new TransferableOneWay();
//Log.Message(target.DefName);
foreach (var thing in sourceKeys)
{
if (target.Count * rate <= select.CountToTransfer) break;
if (source[thing] == 0) continue;
if (target.MatchesThing(thing))
{
//нам подходит выбираем нужное кол-во
select.things.Add(thing);
var count = target.Count * rate - select.CountToTransfer > source[thing]
? source[thing]
: target.Count * rate - select.CountToTransfer;
select.ForceTo(select.CountToTransfer + count);
source[thing] -= count;
//Log.Message(target.DefName + " == " + thing.def.defName + " o:" + source[thing].ToString() + " g:" + select.CountToTransfer.ToString() + " rate:" + rate.ToString());
}
//else Log.Message(target.DefName + " != " + thing.def.defName + " " + select.CountToTransfer.ToString());
}
if (setRect && target.Count > select.CountToTransfer
|| !setRect && target.Count * rate > select.CountToTransfer)
{
result = false;
target.NotTrade = true;
//Log.Message("NotTrade " + target.Count.ToString() + " > " + select.CountToTransfer.ToString());
}
else
{
if (setRect && target.Count * rate > select.CountToTransfer)
{
rate = select.CountToTransfer / target.Count;
//Log.Message(" rate:" + rate.ToString());
}
selects.Add(select);
target.NotTrade = false;
}
}
return result ? selects : null;
}
19
View Source File : DynamoDBItem.cs
License : MIT License
Project Creator : abelperezok
License : MIT License
Project Creator : abelperezok
public DynamoDBItem MergeData(DynamoDBItem data)
{
var dataDict = data.ToDictionary();
var merged = _data.Union(dataDict).ToDictionary(k => k.Key, v => v.Value);
return new DynamoDBItem(merged);
}
19
View Source File : SerializationUtil.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static Dictionary<string, ExampleUsage> Deserialize(XDoreplacedent doc)
{
using (var reader = doc.Root.CreateReader())
{
var serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute { ElementName = "items" });
return ((Item[])serializer.Deserialize(reader)).ToDictionary(x => x.ExampleName, x => x.ExampleUsage);
}
}
19
View Source File : AudioDeviceSource.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void RefreshDevices()
{
if (!_dispatcher.CheckAccess())
{
_dispatcher.BeginInvoke((Action)RefreshDevices);
return;
}
DefaultDevice = GetDefaultDevice();
var deviceMap = Devices.ToDictionary(d => d.ID, d => d);
var presentDevices = new HashSet<string>();
foreach (var d in _enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active))
{
presentDevices.Add(d.ID);
if(deviceMap.TryGetValue(d.ID, out var device))
{
device.Update(d);
}
else
{
Devices.Add(new AudioDeviceInfo(d));
}
d.Dispose();
}
for (int i = Devices.Count - 1; i >=0; i--)
{
if (!presentDevices.Contains(Devices[i].ID))
{
Devices.RemoveAt(i);
}
}
DevicesChanged?.Invoke(this, EventArgs.Empty);
}
19
View Source File : SystemInfo.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
private static IReadOnlyDictionary<string, string> GetManagementInfo(string query, Regex regex)
{
try
{
var result = new ManagementObjectSearcher(new ObjectQuery(query));
var infoString = string.Empty;
using (var collection = result.Get())
{
foreach (var item in collection)
{
var managementObject = item as ManagementObject;
infoString = managementObject?.GetText(TextFormat.Mof);
if (!string.IsNullOrEmpty(infoString)) break;
}
}
if (string.IsNullOrEmpty(infoString)) return null;
return regex.Matches(infoString).OfType<Match>()
.Where(item => item.Success)
.ToDictionary(item => item.Groups[1].Value, item => item.Groups[2].Value);
}
catch (Exception e)
{
Logger.Error("An unexpected exception occured while getting management info. ", e);
return null;
}
}
19
View Source File : LandblockInstanceWriter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void CreateSQLINSERTStatement(IList<LandblockInstance> input, StreamWriter writer)
{
var instanceWcids = input.ToDictionary(i => i.Guid, i => i.WeenieClreplacedId);
input = input.OrderBy(r => r.Guid).ToList();
foreach (var value in input)
{
if (value != input[0])
writer.WriteLine();
writer.WriteLine("INSERT INTO `landblock_instance` (`guid`, `weenie_Clreplaced_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)");
string label = null;
if (WeenieNames != null)
WeenieNames.TryGetValue(value.WeenieClreplacedId, out label);
var output = "VALUES (" +
$"0x{value.Guid.ToString("X8")}, " +
$"{value.WeenieClreplacedId.ToString().PadLeft(5)}, " +
$"0x{value.ObjCellId:X8}, " +
$"{TrimNegativeZero(value.OriginX):0.######}, " +
$"{TrimNegativeZero(value.OriginY):0.######}, " +
$"{TrimNegativeZero(value.OriginZ):0.######}, " +
$"{TrimNegativeZero(value.AnglesW):0.######}, " +
$"{TrimNegativeZero(value.AnglesX):0.######}, " +
$"{TrimNegativeZero(value.AnglesY):0.######}, " +
$"{TrimNegativeZero(value.AnglesZ):0.######}, " +
$"{value.IsLinkChild.ToString().PadLeft(5)}, " +
$"'{value.LastModified:yyyy-MM-dd HH:mm:ss}'" +
$"); /* {label} */" +
Environment.NewLine + $"/* @teleloc 0x{value.ObjCellId:X8} [{TrimNegativeZero(value.OriginX):F6} {TrimNegativeZero(value.OriginY):F6} {TrimNegativeZero(value.OriginZ):F6}] {TrimNegativeZero(value.AnglesW):F6} {TrimNegativeZero(value.AnglesX):F6} {TrimNegativeZero(value.AnglesY):F6} {TrimNegativeZero(value.AnglesZ):F6} */";
output = FixNullFields(output);
writer.WriteLine(output);
if (value.LandblockInstanceLink != null && value.LandblockInstanceLink.Count > 0)
{
writer.WriteLine();
CreateSQLINSERTStatement(value.LandblockInstanceLink.OrderBy(r => r.ChildGuid).ToList(), instanceWcids, writer);
}
}
}
19
View Source File : CharacterOption.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static uint GetCharacterOptions1Flag(this ReadOnlyDictionary<CharacterOption, bool> options)
{
return GetCharacterOptions1Flag(options.ToDictionary(k => k.Key, v => v.Value));
}
19
View Source File : CharacterOption.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static uint GetCharacterOptions2Flag(this ReadOnlyDictionary<CharacterOption, bool> options)
{
return GetCharacterOptions2Flag(options.ToDictionary(k => k.Key, v => v.Value));
}
19
View Source File : PropertiesAllegianceExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static Dictionary<uint, PropertiesAllegiance> GetApprovedVreplacedals(this IDictionary<uint, PropertiesAllegiance> value, ReaderWriterLockSlim rwLock)
{
rwLock.EnterReadLock();
try
{
if (value == null)
return new Dictionary<uint, PropertiesAllegiance>();
return value.Where(i => i.Value.ApprovedVreplacedal).ToDictionary(i => i.Key, i => i.Value);
}
finally
{
rwLock.ExitReadLock();
}
}
19
View Source File : PropertiesAllegianceExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static Dictionary<uint, PropertiesAllegiance> GetBanList(this IDictionary<uint, PropertiesAllegiance> value, ReaderWriterLockSlim rwLock)
{
if (value == null)
return new Dictionary<uint, PropertiesAllegiance>();
rwLock.EnterReadLock();
try
{
return value.Where(i => i.Value.Banned).ToDictionary(i => i.Key, i => i.Value);
}
finally
{
rwLock.ExitReadLock();
}
}
19
View Source File : LootSwap.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static Dictionary<string, Type> GetTypes(string prefix)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var types = replacedembly.GetTypes();
return types.Where(i => i.FullName.StartsWith(prefix)).ToDictionary(i => i.FullName.Substring(i.FullName.LastIndexOf('.') + 1), i => i);
}
19
View Source File : PropertyManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static ReadOnlyDictionary<A, V> DictOf<A, V>(params (A, V)[] pairs)
{
return new ReadOnlyDictionary<A, V>(pairs.ToDictionary
(
tup => tup.Item1,
tup => tup.Item2
));
}
19
View Source File : Allegiance.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void BuildOfficers()
{
Officers = Members.Where(i => i.Value.Player.AllegianceOfficerRank != null).ToDictionary(i => i.Key, i => i.Value);
}
19
View Source File : Player_Death.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void PrunePermissions()
{
LootPermission = LootPermission.Where(p => p.Value >= DateTime.UtcNow).ToDictionary(p => p.Key, p => p.Value);
}
19
View Source File : DacKeyDeclarationAnalyzerBase.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private Dictionary<INamedTypeSymbol, List<ITypeSymbol>> GetUsedDacFieldsByKey(DacSemanticModel dac, List<INamedTypeSymbol> keys) =>
keys.Select(key => (Key: key, KeyFields: GetOrderedDacFieldsUsedByKey(dac, key)))
.ToDictionary(keyWithFields => keyWithFields.Key,
keyWithFields => keyWithFields.KeyFields);
19
View Source File : EventHost.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private async Task sample_publish_queue()
{
var key = "sample_publish_queue";
_eventBusProvider.SubscribeQueue<int>(key, async func =>
{
var data = await func(1000);
foreach (var v in data)
{
queue.Enqueue(v);
Console.WriteLine($"--------------------------------------{v}-----------------1");
}
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 11");
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<int>(key, async func =>
{
var data = await func(1000);
foreach (var v in data)
{
queue.Enqueue(v);
Console.WriteLine($"--------------------------------------{v}-----------------2");
}
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 12");
await Task.CompletedTask;
});
Enumerable.Range(0, 1000).AsParallel().ForAll(i =>
{
//Console.WriteLine($"{i}");
_eventBusProvider.PublishQueueAsync(key, new List<int>() { i }).GetAwaiter().GetResult();
});
//await _eventBusProvider.PublishQueueAsync(key, new List<int>());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 200).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 200).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 200).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 200).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(800, 200).ToList());
}
19
View Source File : EventHost.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private async Task sample_publish_queue_all3_big()
{
var key = "sample_publish_queue_all3";
var key2 = "sample_publish_queue_all4";
var index1 = 0;
var index2 = 0;
var index3 = 0;
var queue = new ConcurrentQueue<int>();
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 11");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 12");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 13");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------21");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 21");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------22");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 22");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------23");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 23");
//index1 = 0;
await Task.CompletedTask;
});
await Task.Delay(2000);
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1000, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await Task.Delay(20000);
}
19
View Source File : EventHost3.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private async Task sample_publish_queue_all2()
{
var key = "bbbbbbb";
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 11");
//index1 = 0;
await Task.CompletedTask;
});
//await Task.Delay(2000);
await _eventBusProvider.PublishQueueAsync(key, new List<TestClreplacedModel>());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
}
19
View Source File : EventHost.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private async Task sample_publish_queue_all2()
{
var key = "sample_publish_queue_all3";
//var queue = new ConcurrentQueue<int>();
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 11");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 12");
//index1 = 0;
await Task.CompletedTask;
});
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 13");
//index1 = 0;
await Task.CompletedTask;
});
//await Task.Delay(2000);
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
}
19
View Source File : EventHost.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private async Task sample_publish_queue_all3()
{
var key = "sample_publish_queue_all4";
//var queue = new ConcurrentQueue<int>();
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 11");
//index1 = 0;
await Task.CompletedTask;
});
//_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
// async data =>
// {
// foreach (var v in data)
// {
// queue.Enqueue(v.Index);
// Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
// }
// await Task.CompletedTask;
// }, completed: async () =>
// {
// Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 12");
// //index1 = 0;
// await Task.CompletedTask;
// });
//_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
// async data =>
// {
// foreach (var v in data)
// {
// queue.Enqueue(v.Index);
// Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
// }
// await Task.CompletedTask;
// }, completed: async () =>
// {
// Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 13");
// //index1 = 0;
// await Task.CompletedTask;
// });
//await Task.Delay(2000);
await _eventBusProvider.PublishQueueAsync(key, new List<TestClreplacedModel>());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1000, 1).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1000, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
}
19
View Source File : DictionaryExtensions.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public static FixedDictionary<TKey, TValue> ToFixedDictionary<TSource, TKey, TValue>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TValue> valueSelector)
where TKey : notnull
{
return new FixedDictionary<TKey, TValue>(source.ToDictionary(keySelector, valueSelector));
}
19
View Source File : EventHost2.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private async Task sample_publish_queue_all2()
{
var key = "aaaaaaa";
_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
async data =>
{
foreach (var v in data)
{
queue.Enqueue(v.Index);
Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
}
await Task.CompletedTask;
}, completed: async () =>
{
Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()} 11");
//index1 = 0;
await Task.CompletedTask;
});
//await Task.Delay(2000);
await _eventBusProvider.PublishQueueAsync(key, new List<TestClreplacedModel>());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
//await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
}
19
View Source File : DictionaryExtensions.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public static FixedDictionary<TKey, TValue> ToFixedDictionary<TKey, TValue>(
this IEnumerable<(TKey Key, TValue Value)> source)
where TKey : notnull
{
return new FixedDictionary<TKey, TValue>(source.ToDictionary(s => s.Key, s => s.Value));
}
19
View Source File : CountDictionary.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public Dictionary<BigInteger, BigInteger> ToDictionary()
{
return this.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
19
View Source File : SqliteSyncProvider.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
public async Task<SyncChangeSet> GetChangesAsync(Guid otherStoreId, SyncFilterParameter[] syncFilterParameters, SyncDirection syncDirection, CancellationToken cancellationToken = default)
{
syncFilterParameters = syncFilterParameters ?? new SyncFilterParameter[] { };
var fromAnchor = (await GetLastLocalAnchorForStoreAsync(otherStoreId, cancellationToken));
//if fromVersion is 0 means that client needs actually to initialize its local datastore
//await InitializeStoreAsync();
var now = DateTime.Now;
_logger?.Info($"[{_storeId}] Begin GetChanges(from={otherStoreId}, syncDirection={syncDirection}, fromVersion={fromAnchor})");
using (var c = new SqliteConnection(Configuration.ConnectionString))
{
await c.OpenAsync(cancellationToken);
using (var cmd = new SqliteCommand())
{
var items = new List<SqliteSyncItem>();
using (var tr = c.BeginTransaction())
{
cmd.Connection = c;
cmd.Transaction = tr;
try
{
cmd.CommandText = "SELECT MAX(ID) FROM __CORE_SYNC_CT";
cmd.Parameters.Clear();
var version = await cmd.ExecuteLongScalarAsync(cancellationToken);
cmd.CommandText = "SELECT MIN(ID) FROM __CORE_SYNC_CT";
cmd.Parameters.Clear();
var minVersion = await cmd.ExecuteLongScalarAsync(cancellationToken);
if (!fromAnchor.IsNull() && fromAnchor.Version < minVersion - 1)
throw new InvalidOperationException($"Unable to get changes, version of data requested ({fromAnchor}) is too old (min valid version {minVersion})");
foreach (var table in Configuration.Tables.Cast<SqliteSyncTable>().Where(_ => _.Columns.Any()))
{
if (table.SyncDirection != SyncDirection.UploadAndDownload &&
table.SyncDirection != syncDirection)
continue;
//var snapshoreplacedems = new HashSet<object>();
if (fromAnchor.IsNull() && !table.SkipInitialSnapshot)
{
cmd.CommandText = table.InitialSnapshotQuery;
cmd.Parameters.Clear();
foreach (var syncFilterParameter in syncFilterParameters)
{
cmd.Parameters.AddWithValue(syncFilterParameter.Name, syncFilterParameter.Value);
}
using (var r = await cmd.ExecuteReaderAsync(cancellationToken))
{
while (await r.ReadAsync(cancellationToken))
{
var values = Enumerable.Range(0, r.FieldCount).ToDictionary(_ => r.GetName(_), _ => GetValueFromRecord(table, r.GetName(_), _, r));
items.Add(new SqliteSyncItem(table, ChangeType.Insert, values));
//snapshoreplacedems.Add(values[table.PrimaryColumnName]);
_logger?.Trace($"[{_storeId}] Initial snapshot {items.Last()}");
}
}
}
if (!fromAnchor.IsNull())
{
cmd.CommandText = table.IncrementalAddOrUpdatesQuery;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@version", fromAnchor.Version);
cmd.Parameters.AddWithValue("@sourceId", otherStoreId.ToString());
foreach (var syncFilterParameter in syncFilterParameters)
{
cmd.Parameters.AddWithValue(syncFilterParameter.Name, syncFilterParameter.Value);
}
using (var r = await cmd.ExecuteReaderAsync(cancellationToken))
{
while (await r.ReadAsync(cancellationToken))
{
var values = Enumerable.Range(0, r.FieldCount).ToDictionary(_ => r.GetName(_), _ => GetValueFromRecord(table, r.GetName(_), _, r));
//if (snapshoreplacedems.Contains(values[table.PrimaryColumnName]))
// continue;
items.Add(new SqliteSyncItem(table, DetectChangeType(values),
values.Where(_ => _.Key != "__OP").ToDictionary(_ => _.Key, _ => _.Value == DBNull.Value ? null : _.Value)));
_logger?.Trace($"[{_storeId}] Incremental add or update {items.Last()}");
}
}
cmd.CommandText = table.IncrementalDeletesQuery;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@version", fromAnchor.Version);
cmd.Parameters.AddWithValue("@sourceId", otherStoreId.ToString());
using (var r = await cmd.ExecuteReaderAsync(cancellationToken))
{
while (await r.ReadAsync(cancellationToken))
{
var values = Enumerable.Range(0, r.FieldCount).ToDictionary(_ => r.GetName(_), _ => GetValueFromRecord(table, r.GetName(_), _, r));
items.Add(new SqliteSyncItem(table, ChangeType.Delete, values));
_logger?.Trace($"[{_storeId}] Incremental delete {items.Last()}");
}
}
}
}
tr.Commit();
var resChangeSet = new SyncChangeSet(new SyncAnchor(_storeId, version), await GetLastRemoteAnchorForStoreAsync(otherStoreId, cancellationToken), items);
_logger?.Info($"[{_storeId}] Completed GetChanges(to={version}, {items.Count} items) in {(DateTime.Now - now).TotalMilliseconds}ms");
return resChangeSet;
}
catch (Exception)
{
tr.Rollback();
throw;
}
}
}
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : AdisonCavani
License : GNU General Public License v3.0
Project Creator : AdisonCavani
Dictionary<string, string> DirectoriesDictionary(string directoryPath, string repoPath)
{
var dirsArray = Directory.GetDirectories(directoryPath);
return dirsArray.ToDictionary(key => key, value => value.Substring(value.IndexOf(@"customize\") + 10));
}
19
View Source File : AuthorizeNetHelper.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static Dictionary<string, string> ToDictionary(NameValueCollection source)
{
return source.Cast<string>().Select(s => new { Key = s, Value = source[s] }).ToDictionary(p => p.Key, p => p.Value);
}
19
View Source File : MetadataHelper.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static Dictionary<string, AttributeTypeCode?> BuildAttributeTypeCodeDictionary(OrganizationServiceContext serviceContext, string enreplacedyLogicalName)
{
var enreplacedyMetadata = GetEnreplacedyMetadata(serviceContext, enreplacedyLogicalName);
if (enreplacedyMetadata == null)
{
return null;
}
var attributes = enreplacedyMetadata.Attributes;
var attributeDictionary = attributes.Where(attribute => attribute.AttributeType != null).ToDictionary(attribute => attribute.LogicalName, attribute => attribute.AttributeType != null ? attribute.AttributeType.Value : (AttributeTypeCode?)null);
return attributeDictionary;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, int> FetchCounts(this OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string countAttributeLogicalName, string linkEnreplacedyLogicalName, string linkFromAttributeLogicalName, string linkToAttributeLogicalName, IEnumerable<Guid> linkEnreplacediesIds, Action<Action<string, string, string>> addFilterConditions = null)
{
if (!linkEnreplacediesIds.Any())
{
return new Dictionary<Guid, int>();
}
var ids = linkEnreplacediesIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy>
<attribute aggregate=""countcolumn"" alias=""count"" />
<filter/>
<link-enreplacedy>
<attribute alias=""id"" groupby=""true"" />
<filter type=""or"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
enreplacedy.SetAttributeValue("name", enreplacedyLogicalName);
enreplacedy.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName);
var filter = enreplacedy.Descendants("filter").First();
filter.SetAttributeValue("type", "and");
if (addFilterConditions != null)
{
addFilterConditions(filter.AddFetchXmlFilterCondition);
}
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var linkEnreplacedyAttribute = linkEnreplacedy.Descendants("attribute").First();
linkEnreplacedyAttribute.SetAttributeValue("name", linkFromAttributeLogicalName);
var linkEnreplacedyFilter = linkEnreplacedy.Descendants("filter").First();
linkEnreplacedyFilter.AddFetchXmlFilterInCondition(linkFromAttributeLogicalName, ids.Select(id => id.ToString()));
var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
var results = ids.ToDictionary(id => id, id => 0);
foreach (var result in response.EnreplacedyCollection.Enreplacedies)
{
var id = (Guid)result.GetAttributeValue<AliasedValue>("id").Value;
var count = (int)result.GetAttributeValue<AliasedValue>("count").Value;
results[id] = count;
}
return results;
}
19
View Source File : SolutionDefinition.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static SolutionDefinition Union(SolutionDefinition first, SolutionDefinition second)
{
if (first == null && second == null) return null;
if (first == null) return second;
if (second == null) return first;
var solutions = first.Solutions.Union(second.Solutions).ToArray();
var enreplacedies = Union(first.Enreplacedies, second.Enreplacedies, first.Solutions).ToDictionary(e => e.LogicalName, e => e);
var relationships = Union(first.ManyRelationships, second.ManyRelationships, first.Solutions).ToDictionary(r => r.SchemaName, r => r);
return new SolutionDefinition(solutions, enreplacedies, relationships);
}
19
View Source File : NotificationUpdateManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal Dictionary<string, string> GetEnreplacediesWithTimeStamps(bool isSearchIndexInvalidation)
{
// Return a dictionary of type [enreplacedy - timestamp]
Dictionary<string, string> preppedEnreplacedyList = this.ProcessingTable.Keys
.Select(key => new KeyValuePair<string, string>(key, this.GetEnreplacedyVersionNumber(key, isSearchIndexInvalidation)))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
return preppedEnreplacedyList;
}
19
View Source File : NotificationUpdateManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal Dictionary<string, EnreplacedyRecordMessage> ProcessingEnreplacediesTable()
{
return new Dictionary<string, EnreplacedyRecordMessage>(this.ProcessingTable.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
}
19
View Source File : AttributeCounterStrategy.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IDictionary<Guid, ForumCounts> GetForumCounts(OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> forums)
{
if (forums == null) throw new ArgumentNullException("forums");
return forums.ToDictionary(e => e.Id, e => GetForumCounts(serviceContext, e));
}
19
View Source File : AttributeCounterStrategy.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IDictionary<Guid, int> GetForumThreadPostCounts(OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> forumThreads)
{
if (forumThreads == null) throw new ArgumentNullException("forumThreads");
return forumThreads.ToDictionary(e => e.Id, e => GetForumThreadPostCount(serviceContext, e));
}
19
View Source File : AttributeCounterStrategy.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IDictionary<Guid, int> GetForumThreadPostCounts(OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> forumThreads)
{
if (forumThreads == null) throw new ArgumentNullException("forumThreads");
var fromAttributes = forumThreads.Select(e => new Tuple<Enreplacedy, int?>(e, GetForumThreadPostCountFromAttribute(e))).ToArray();
var fallbackEnreplacedies = fromAttributes.Where(e => e.Item2 == null).Select(e => e.Item1).ToArray();
var counts = fromAttributes.ToDictionary(e => e.Item1.Id, e => e.Item2.GetValueOrDefault());
foreach (var fetchCounts in _fetchCounterStrategy.GetForumThreadPostCounts(serviceContext, fallbackEnreplacedies))
{
counts[fetchCounts.Key] = fetchCounts.Value;
}
return counts;
}
19
View Source File : CrmJsonConverter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static void Serialize<TKey, TValue>(JsonWriter writer, DataCollection<TKey, TValue> value, JsonSerializer serializer)
{
if (value != null)
{
if (typeof(TKey) == typeof(Relationship))
{
// serialize complex keys as lists instead
var surrogate = new JsonList<KeyValuePair<TKey, TValue>> { Value = value.ToList() };
serializer.Serialize(writer, surrogate);
}
else
{
var surrogate = value.ToDictionary(pair => pair.Key, pair => pair.Value);
serializer.Serialize(writer, surrogate);
}
}
}
19
View Source File : ExtendedAttributeSearchResultInfo.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IDictionary<string, string> GetAttributes(Enreplacedy enreplacedy, IDictionary<string, EnreplacedyMetadata> metadataCache)
{
if (AttributeLayoutXml == null || enreplacedy == null)
{
return CreateBaseAttributesDictionary();
}
var attributeLookup = Metadata.Attributes.ToDictionary(a => a.LogicalName, a => a);
var attributes = CreateBaseAttributesDictionary();
var names = from cell in AttributeLayoutXml.XPathSelectElements("//cell")
select cell.Attribute("name")
into nameAttibute where nameAttibute != null
select nameAttibute.Value
into name where !string.IsNullOrEmpty(name)
select name;
foreach (var name in names)
{
AttributeMetadata attributeMetadata;
if (!attributeLookup.TryGetValue(name, out attributeMetadata))
{
continue;
}
var resultAttribute = GetSearchResultAttribute(Context, enreplacedy, attributeMetadata, metadataCache);
if (resultAttribute == null)
{
continue;
}
attributes[resultAttribute.Value.Key] = resultAttribute.Value.Value;
}
return attributes;
}
19
View Source File : ConnectionStringExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<string, string> ToDictionary(this string connectionString)
{
var builder = new DbConnectionStringBuilder { ConnectionString = connectionString };
var connection = builder.Cast<KeyValuePair<string, object>>().ToDictionary(pair => pair.Key, pair => pair.Value.ToString());
return new Dictionary<string, string>(connection, StringComparer.OrdinalIgnoreCase);
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, int> FetchCounts(this OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string countAttributeLogicalName, string linkEnreplacedyLogicalName, string linkFromAttributeLogicalName, string linkToAttributeLogicalName, IEnumerable<Guid> linkEnreplacediesIds, Action<Action<string, string, string>> addFilterConditions, Action<Action<string, string, string>> addOrFilterConditions = null, Action<Action<string, string>> addBinaryFilterConditions = null)
{
var ids = linkEnreplacediesIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy>
<attribute aggregate=""countcolumn"" alias=""count"" />
<filter type=""and"" />
<link-enreplacedy>
<attribute alias=""id"" groupby=""true"" />
<filter type=""or"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
enreplacedy.SetAttributeValue("name", enreplacedyLogicalName);
enreplacedy.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName);
var filter = enreplacedy.Descendants("filter").First();
addFilterConditions(filter.AddFetchXmlFilterCondition);
if (addBinaryFilterConditions != null)
{
addBinaryFilterConditions(filter.AddFetchXmlFilterCondition);
}
if (addOrFilterConditions != null)
{
var orFilter = new XElement("filter");
orFilter.SetAttributeValue("type", "or");
addOrFilterConditions(orFilter.AddFetchXmlFilterCondition);
filter.AddAfterSelf(orFilter);
}
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var linkEnreplacedyAttribute = linkEnreplacedy.Descendants("attribute").First();
linkEnreplacedyAttribute.SetAttributeValue("name", linkFromAttributeLogicalName);
var linkEnreplacedyFilter = linkEnreplacedy.Descendants("filter").First();
foreach (var id in ids)
{
linkEnreplacedyFilter.AddFetchXmlFilterCondition(linkFromAttributeLogicalName, "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
var results = ids.ToDictionary(id => id, id => 0);
foreach (var result in response.Enreplacedies)
{
var id = result.GetAttributeAliasedValue<Guid>("id");
var count = result.GetAttributeAliasedValue<int>("count");
results[id] = count;
}
return results;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, int> FetchCounts(this OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string countAttributeLogicalName, string linkEnreplacedyLogicalName, string linkFromAttributeLogicalName, string linkToAttributeLogicalName, IEnumerable<Guid> linkEnreplacediesIds, Action<Action<string, string, string>> addFilterConditions, Action<Action<string, string, string>> addOrFilterConditions = null)
{
var ids = linkEnreplacediesIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy>
<attribute aggregate=""countcolumn"" alias=""count"" />
<filter type=""and"" />
<link-enreplacedy>
<attribute alias=""id"" groupby=""true"" />
<filter type=""or"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
enreplacedy.SetAttributeValue("name", enreplacedyLogicalName);
enreplacedy.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName);
var filter = enreplacedy.Descendants("filter").First();
addFilterConditions(filter.AddFetchXmlFilterCondition);
if (addOrFilterConditions != null)
{
var orFilter = new XElement("filter");
orFilter.SetAttributeValue("type", "or");
addOrFilterConditions(orFilter.AddFetchXmlFilterCondition);
filter.AddAfterSelf(orFilter);
}
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var linkEnreplacedyAttribute = linkEnreplacedy.Descendants("attribute").First();
linkEnreplacedyAttribute.SetAttributeValue("name", linkFromAttributeLogicalName);
var linkEnreplacedyFilter = linkEnreplacedy.Descendants("filter").First();
foreach (var id in ids)
{
linkEnreplacedyFilter.AddFetchXmlFilterCondition(linkFromAttributeLogicalName, "eq", id.ToString());
}
var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
var results = ids.ToDictionary(id => id, id => 0);
foreach (var result in response.EnreplacedyCollection.Enreplacedies)
{
var id = result.GetAttributeAliasedValue<Guid>("id");
var count = result.GetAttributeAliasedValue<int>("count");
results[id] = count;
}
return results;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, int> FetchCounts(
this OrganizationServiceContext serviceContext,
string enreplacedyLogicalName,
string countAttributeLogicalName,
string linkEnreplacedyLogicalName,
string linkFromAttributeLogicalName,
string linkToAttributeLogicalName, IEnumerable<Guid> linkEnreplacediesIds,
Action<Action<string, string, string>> addFilterConditions,
Action<Action<string, string, string>> addOrFilterConditions = null)
{
var ids = linkEnreplacediesIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy>
<attribute aggregate=""countcolumn"" alias=""count"" />
<filter type=""and"" />
<link-enreplacedy>
<attribute alias=""id"" groupby=""true"" />
<filter type=""or"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
enreplacedy.SetAttributeValue("name", enreplacedyLogicalName);
enreplacedy.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName);
var filter = enreplacedy.Descendants("filter").First();
addFilterConditions(filter.AddFetchXmlFilterCondition);
if (addOrFilterConditions != null)
{
var orFilter = new XElement("filter");
orFilter.SetAttributeValue("type", "or");
addOrFilterConditions(orFilter.AddFetchXmlFilterCondition);
filter.AddAfterSelf(orFilter);
}
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
linkEnreplacedy.SetAttributeValue("name", linkEnreplacedyLogicalName);
linkEnreplacedy.SetAttributeValue("from", linkFromAttributeLogicalName);
linkEnreplacedy.SetAttributeValue("to", linkToAttributeLogicalName);
var linkEnreplacedyAttribute = linkEnreplacedy.Descendants("attribute").First();
linkEnreplacedyAttribute.SetAttributeValue("name", linkFromAttributeLogicalName);
var linkEnreplacedyFilter = linkEnreplacedy.Descendants("filter").First();
foreach (var id in ids)
{
linkEnreplacedyFilter.AddFetchXmlFilterCondition(linkFromAttributeLogicalName, "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()), RequestFlag.AllowStaleData);
var results = ids.ToDictionary(id => id, id => 0);
foreach (var result in response.Enreplacedies)
{
var id = result.GetAttributeAliasedValue<Guid>("id");
var count = result.GetAttributeAliasedValue<int>("count");
results[id] = count;
}
return results;
}
19
View Source File : EntityDrop.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private Hash GetFormattedValues()
{
return Hash.FromDictionary(Enreplacedy.FormattedValues.ToDictionary(item => item.Key, item => item.Value as object));
}
19
View Source File : SiteMarkerRoute.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private RouteBase GetRoute(ApplicationPath siteMarkerApplicationPath, Func<KeyValuePair<string, object>, bool> constraintFilter)
{
if (constraintFilter == null) throw new ArgumentNullException("constraintFilter");
if (siteMarkerApplicationPath == null
|| siteMarkerApplicationPath.AppRelativePath == null
|| siteMarkerApplicationPath.AbsolutePath == null)
{
return null;
}
// Trim the "~/" from the start of the app-relative path to get a virtual path.
var siteMarkerVirtualPath = siteMarkerApplicationPath.AppRelativePath.Substring(2);
if (!(string.IsNullOrEmpty(siteMarkerVirtualPath) || siteMarkerVirtualPath.EndsWith("/")))
{
return null;
}
// Add the site marker absolute path to the route values (by way of the defaults). This is done for the
// benefit of the PortalContext system, which looks for this path value to determine the current portal
// context enreplacedy.
var defaults = Defaults == null ? new RouteValueDictionary() : new RouteValueDictionary(Defaults);
defaults["path"] = siteMarkerApplicationPath.AbsolutePath;
var constraints = Constraints == null
? null
: new RouteValueDictionary(Constraints.Where(constraintFilter).ToDictionary(e => e.Key, e => e.Value));
return new Route("{0}{1}".FormatWith(siteMarkerVirtualPath, Url), defaults, constraints, DataTokens, RouteHandler);
}
See More Examples