Here are the examples of the csharp api System.Collections.Generic.IEnumerable.GroupBy(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1555 Examples
19
View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052
License : MIT License
Project Creator : 188867052
public static string GenerateRoutes(IEnumerable<RouteInfo> infos)
{
StringBuilder sb = new StringBuilder();
var group = infos.GroupBy(o => o.Namespace);
sb.AppendLine($"using {typeof(object).Namespace};");
sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");
sb.AppendLine();
for (int i = 0; i < group.Count(); i++)
{
sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
}
return sb.ToString();
}
19
View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052
License : MIT License
Project Creator : 188867052
private static StringBuilder GenerateNamespace(IGrouping<string, RouteInfo> namespaceGroup, bool isLast)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"namespace {GetConvertedNamespace(namespaceGroup.Key)}");
sb.AppendLine("{");
var group = namespaceGroup.GroupBy(o => o.ControllerName);
for (int i = 0; i < group.Count(); i++)
{
sb.Append(GenerateClreplaced(group.ElementAt(i), i == (group.Count() - 1)));
}
sb.AppendLine("}");
if (!isLast)
{
sb.AppendLine();
}
return sb;
}
19
View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052
License : MIT License
Project Creator : 188867052
private static string RenameOverloadedAction(IGrouping<string, RouteInfo> group, int index)
{
var currenreplacedem = group.ElementAt(index);
var sameActionNameGroup = group.GroupBy(o => o.ActionName);
foreach (var item in sameActionNameGroup)
{
if (item.Count() > 1)
{
for (int i = 1; i < item.Count(); i++)
{
var element = item.ElementAt(i);
if (element == currenreplacedem)
{
return element.ActionName + i;
}
}
}
}
return currenreplacedem.ActionName;
}
19
View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052
License : MIT License
Project Creator : 188867052
public static string GenerateRoutes(IList<RouteInfo> infos)
{
StringBuilder sb = new StringBuilder();
var group = infos.GroupBy(o => o.Namespace);
sb.AppendLine($"using {typeof(object).Namespace};");
sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");
sb.AppendLine($"using {typeof(Task).Namespace};");
sb.AppendLine($"using {typeof(HttpClientAsync).Namespace};");
sb.AppendLine();
for (int i = 0; i < group.Count(); i++)
{
sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
}
return sb.ToString();
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static Dictionary<string, PropertyInfo> GetPropertiesDictIgnoreCase(this Type that) => that == null ? null : _dicGetPropertiesDictIgnoreCase.GetOrAdd(that, tp =>
{
var props = that.GetProperties().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, PropertyInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var prop in props)
{
if (dict.TryGetValue(prop.Name, out var existsProp))
{
if (existsProp.DeclaringType != prop) dict[prop.Name] = prop;
continue;
}
dict.Add(prop.Name, prop);
}
return dict;
});
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp =>
{
var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var field in fields)
{
if (dict.ContainsKey(field.Name)) dict[field.Name] = field;
else dict.Add(field.Name, field);
}
return dict;
});
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($@"{(proxyMethodName == "Before" ? $@"
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" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
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($@"
{(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 $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__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 ? $@"
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($@"
{(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($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{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($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{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($@"
}}");
}
#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 => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(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 => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"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 : GodotOnReadySourceGenerator.cs
License : MIT License
Project Creator : 31
License : MIT License
Project Creator : 31
public void Execute(GeneratorExecutionContext context)
{
// If this isn't working, run 'dotnet build-server shutdown' first.
if (Environment
.GetEnvironmentVariable($"Debug{nameof(GodotOnReadySourceGenerator)}") == "true")
{
Debugger.Launch();
}
var receiver = context.SyntaxReceiver as OnReadyReceiver ?? throw new Exception();
INamedTypeSymbol GetSymbolByName(string fullName) =>
context.Compilation.GetTypeByMetadataName(fullName)
?? throw new Exception($"Can't find {fullName}");
var onReadyGetSymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyGetAttribute");
var onReadySymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyAttribute");
var generateDataSelectorEnumSymbol =
GetSymbolByName("GodotOnReady.Attributes.GenerateDataSelectorEnumAttribute");
var resourceSymbol = GetSymbolByName("Godot.Resource");
var nodeSymbol = GetSymbolByName("Godot.Node");
List<PartialClreplacedAddition> additions = new();
var clreplacedSymbols = receiver.AllClreplacedes
.Select(clreplacedDecl =>
{
INamedTypeSymbol? clreplacedSymbol = context.Compilation
.GetSemanticModel(clreplacedDecl.SyntaxTree)
.GetDeclaredSymbol(clreplacedDecl);
if (clreplacedSymbol is null)
{
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"GORSG0001",
"Inspection",
$"Unable to find declared symbol for {clreplacedDecl}. Skipping.",
"GORSG.Parsing",
DiagnosticSeverity.Warning,
true
),
clreplacedDecl.GetLocation()
)
);
}
return clreplacedSymbol;
})
.Distinct(SymbolEqualityComparer.Default)
.OfType<INamedTypeSymbol>();
foreach (var clreplacedSymbol in clreplacedSymbols)
{
foreach (var attribute in clreplacedSymbol.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, generateDataSelectorEnumSymbol)))
{
var fields = clreplacedSymbol.GetMembers()
.OfType<IFieldSymbol>()
.Where(f => f.IsReadOnly && f.IsStatic)
.ToArray();
additions.Add(new DataSelectorEnumAddition(
fields,
new AttributeSite(clreplacedSymbol, attribute)));
}
var members = Enumerable
.Concat(
clreplacedSymbol.GetMembers().OfType<IPropertySymbol>().Select(MemberSymbol.Create),
clreplacedSymbol.GetMembers().OfType<IFieldSymbol>().Select(MemberSymbol.Create))
.ToArray();
foreach (var member in members)
{
foreach (var attribute in member.Symbol
.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, onReadyGetSymbol)))
{
var site = new MemberAttributeSite(
member,
new AttributeSite(clreplacedSymbol, attribute));
if (site.AttributeSite.Attribute.NamedArguments.Any(
a => a.Key == "Property" && a.Value.Value is string { Length: > 0 }))
{
additions.Add(new OnReadyGetNodePropertyAddition(site));
}
else if (member.Type.IsOfBaseType(nodeSymbol))
{
additions.Add(new OnReadyGetNodeAddition(site));
}
else if (member.Type.IsOfBaseType(resourceSymbol))
{
additions.Add(new OnReadyGetResourceAddition(site));
}
else
{
string issue =
$"The type '{member.Type}' of '{member.Symbol}' is not supported." +
" Expected a Resource or Node subclreplaced.";
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"GORSG0002",
"Inspection",
issue,
"GORSG.Parsing",
DiagnosticSeverity.Error,
true
),
member.Symbol.Locations.FirstOrDefault()
)
);
}
}
}
foreach (var methodSymbol in clreplacedSymbol.GetMembers().OfType<IMethodSymbol>())
{
foreach (var attribute in methodSymbol
.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, onReadySymbol)))
{
additions.Add(new OnReadyAddition(methodSymbol, attribute, clreplacedSymbol));
}
}
}
foreach (var clreplacedAdditionGroup in additions.GroupBy(a => a.Clreplaced))
{
SourceStringBuilder source = CreateInitializedSourceBuilder();
if (clreplacedAdditionGroup.Key is not { } clreplacedSymbol) continue;
source.NamespaceBlockBraceIfExists(clreplacedSymbol.GetSymbolNamespaceName(), () =>
{
source.Line("public partial clreplaced ", clreplacedAdditionGroup.Key.Name);
source.BlockBrace(() =>
{
foreach (var addition in clreplacedAdditionGroup)
{
addition.DeclarationWriter?.Invoke(source);
}
if (clreplacedAdditionGroup.Any(a => a.ConstructorStatementWriter is not null))
{
source.Line();
source.Line("public ", clreplacedAdditionGroup.Key.Name, "()");
source.BlockBrace(() =>
{
foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
{
addition.ConstructorStatementWriter?.Invoke(source);
}
source.Line("Constructor();");
});
source.Line("partial void Constructor();");
}
if (clreplacedAdditionGroup.Any(a => a.OnReadyStatementWriter is not null))
{
source.Line();
source.Line("public override void _Ready()");
source.BlockBrace(() =>
{
source.Line("base._Ready();");
// OrderBy is a stable sort.
// Sort by Order, then by discovery order (implicitly).
foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
{
addition.OnReadyStatementWriter?.Invoke(source);
}
});
}
});
foreach (var addition in clreplacedAdditionGroup)
{
addition.OutsideClreplacedStatementWriter?.Invoke(source);
}
});
string escapedNamespace =
clreplacedAdditionGroup.Key.GetSymbolNamespaceName()?.Replace(".", "_") ?? "";
context.AddSource(
$"Partial_{escapedNamespace}_{clreplacedAdditionGroup.Key.Name}",
source.ToString());
}
}
19
View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
protected IEnumerable<ProjecreplacedemCfg> GetUniqPrjCfgs(IEnumerable<ProjecreplacedemCfg> pItems)
{
// each sln cfg may refer to the same prj cfg more than once
return pItems.GroupBy(p => new{ p.project.pGuid, p.projectConfig }).Select(g => g.First());
}
19
View Source File : HelpersTests.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
[Fact]
public void TestUninitializedMethods()
{
bool IsValidMethod(MethodInfo method)
{
if (method.IsAbstract)
return false;
if (!method.IsStatic && method.DeclaringType.GetTypeInfo().IsAbstract)
return false;
return !method.ContainsGenericParameters;
}
// We're testing LINQ expressions here, cuz there are (instance / static) and (public / non-public) methods,
// properties, and most methods are independant. Last time I checked, running this step checks
// 193 different methods.
foreach (var method in typeof(Expression).GetMethods(BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic)
.Where(IsValidMethod)
.GroupBy(x => x.Name)
.Select(Enumerable.First))
{
// Find non-jitted start
IntPtr start = method.GetRuntimeMethodHandle().GetMethodStart();
// Compile method (should work on this platform)
Helpers.TryPrepareMethod(method, method.GetRuntimeMethodHandle()).ShouldBeTrue();
// Find freshly jitted start
IntPtr newStart = method.GetRuntimeMethodHandle().GetMethodStart();
// start != newStart => it wasn't jitted before: Fixup should be good
start.HasBeenCompiled().ShouldBe(start == newStart);
// In any case, the new method shouldn't be a fixup
newStart.HasBeenCompiled().ShouldBeTrue();
}
}
19
View Source File : RpcService.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal void CleanupRegistration()
{
foreach (var controller in Controllers)
{
var gps = controller.Value.GroupBy(m => m.MethodName).Where(gp => gp.Count() > 1);
var hiddenMethods = new List<RpcMethod>();
foreach (var gp in gps)
{
hiddenMethods.AddRange(gp.Where(m => m.Method.DeclaringType != controller.Key));
}
foreach (var m in hiddenMethods)
{
controller.Value.Remove(m);
}
}
}
19
View Source File : WorkFlowInvoker.cs
License : Apache License 2.0
Project Creator : AbpApp
License : Apache License 2.0
Project Creator : AbpApp
private async Task<IEnumerable<WorkflowExecutionContext>> ResumeManyAsync(
IEnumerable<(WorkflowInstance, ActivityInstance)> workflowInstances,
Variables input,
CancellationToken cancellationToken)
{
var executionContexts = new List<WorkflowExecutionContext>();
var workflowInstanceGroups = workflowInstances.GroupBy(x => x.Item1);
foreach (var workflowInstanceGroup in workflowInstanceGroups)
{
var workflowInstance = workflowInstanceGroup.Key;
var workflowDefinition = await _workflowRegistry.GetWorkflowDefinitionAsync(
workflowInstance.DefinitionId,
VersionOptions.SpecificVersion(workflowInstance.Version),
cancellationToken
);
var workflow = _workflowFactory.CreateWorkflow(workflowDefinition, input, workflowInstance);
foreach (var activity in workflowInstanceGroup)
{
var executionContext = await ExecuteAsync(
workflow,
true,
new[] { activity.Item2.Id },
cancellationToken
);
executionContexts.Add(executionContext);
}
}
return executionContexts;
}
19
View Source File : GroupingByCategory.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public ObservableCollection<TileViewModel> GroupingPredicate(IDictionary<Guid, Example> examples)
{
var groups = examples
.OrderBy(example => example.Value.replacedle)
.GroupBy(example => example.Value.Group)
.OrderBy(group => group.Key);
var result = new ObservableCollection<TileViewModel>();
foreach (IGrouping<string, KeyValuePair<Guid, Example>> pairs in groups)
{
result.Add(new TileViewModel
{
TileDataContext = new EverythingGroupViewModel { GroupingName = pairs.Key }
});
foreach (var example in pairs.Select(x => x.Value))
{
result.Add(new TileViewModel{TileDataContext = example});
}
}
return result;
}
19
View Source File : GroupingByName.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public ObservableCollection<TileViewModel> GroupingPredicate(IDictionary<Guid, Example> examples)
{
var groups = examples
.Select(example => new {Letter = example.Value.replacedle.FirstOrDefault(), Example = example.Value})
.OrderBy(arg => arg.Example.replacedle)
.GroupBy(arg => arg.Letter);
var result = new ObservableCollection<TileViewModel>();
foreach (var pairs in groups)
{
result.Add(new TileViewModel
{
TileDataContext = new EverythingGroupViewModel { GroupingName = pairs.Key.ToString() }
});
foreach (var example in pairs)
{
result.Add(new TileViewModel { TileDataContext = example.Example });
}
}
return result;
}
19
View Source File : SurfaceMeshSelectionModifier.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public override void OnModifierMouseUp(ModifierMouseArgs e)
{
base.OnModifierMouseUp(e);
ClearAll();
if (!IsDragging || Viewport3D == null || Viewport3D.RootEnreplacedy == null) return;
var endPoint = e.MousePoint;
var distanceDragged = PointUtil.Distance(StartPoint, endPoint);
var isAreaSelection = distanceDragged > MinDragSensitivity;
IList<EnreplacedyVertexId> hitEnreplacedyVertexIds;
if (isAreaSelection)
{
// Drag select
hitEnreplacedyVertexIds = Viewport3D.PickScene(new Rect(StartPoint, e.MousePoint));
}
else
{
// Point select
var vertexId = Viewport3D.PickScene(e.MousePoint);
hitEnreplacedyVertexIds = vertexId.HasValue ? new[] { vertexId.Value } : new EnreplacedyVertexId[0];
}
if (!hitEnreplacedyVertexIds.IsNullOrEmpty())
{
var hitEnreplacedyGroups = hitEnreplacedyVertexIds
.GroupBy(x => x.EnreplacedyId)
.ToDictionary(x => x.Key, x => x.Select(i => new VertexId { Id = i.VertexId }).ToList());
var xSize = BoundedPaletteProvider.XSize - 1;
//Visit enreplacedies to perform selection or deselection
Viewport3D.RootEnreplacedy.VisitEnreplacedies(enreplacedy =>
{
var enreplacedyId = enreplacedy.EnreplacedyId;
var hitVertexIds = new List<VertexId>();
if (hitEnreplacedyGroups.ContainsKey(enreplacedyId))
{
hitVertexIds = hitEnreplacedyGroups[enreplacedyId];
}
if (hitVertexIds.Any())
{
if (!_selectedVertices.ContainsKey(enreplacedyId))
_selectedVertices.Add(enreplacedyId, new HashSet<ulong>());
var selectedVertices = _selectedVertices[enreplacedyId];
hitVertexIds.ForEach(x => selectedVertices.Add(x.Id));
BoundedPaletteProvider.SelectedIndexes.Clear();
foreach (var hitEnreplacedyVertexId in hitEnreplacedyVertexIds)
{
var id = Convert.ToInt32(hitEnreplacedyVertexId.VertexId) - 1;
var vertexIndexInfo = new SurfaceMeshVertexInfo();
if (id < xSize)
{
vertexIndexInfo.XIndex = id;
}
else
{
vertexIndexInfo.ZIndex = id / xSize;
vertexIndexInfo.XIndex = id - (vertexIndexInfo.ZIndex * xSize);
}
BoundedPaletteProvider.SelectedIndexes.Add(vertexIndexInfo);
}
}
else
{
_selectedVertices.Remove(enreplacedyId);
BoundedPaletteProvider.SelectedIndexes.Clear();
}
});
}
IsDragging = false;
ReleaseMouseCapture();
BoundedPaletteProvider.DataSeries.IsDirty = true;
BoundedPaletteProvider.DataSeries.OnDataSeriesChanged(DataSeriesUpdate.SelectionChanged,
DataSeriesAction.None);
}
19
View Source File : Player_Spells.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 CreateSentinelBuffPlayers(IEnumerable<Player> players, bool self = false, ulong maxLevel = 8)
{
if (!(Session.AccessLevel >= AccessLevel.Sentinel)) return;
var SelfOrOther = self ? "Self" : "Other";
// ensure level 8s are installed
var maxSpellLevel = Math.Clamp(maxLevel, 1, 8);
if (maxSpellLevel == 8 && DatabaseManager.World.GetCachedSpell((uint)SpellId.ArmorOther8) == null)
maxSpellLevel = 7;
var tySpell = typeof(SpellId);
List<BuffMessage> buffMessages = new List<BuffMessage>();
// prepare messages
List<string> buffsNotImplementedYet = new List<string>();
foreach (var spell in Buffs)
{
var spellNamPrefix = spell;
bool isBane = false;
if (spellNamPrefix.StartsWith("@"))
{
isBane = true;
spellNamPrefix = spellNamPrefix.Substring(1);
}
string fullSpellEnumName = spellNamPrefix + ((isBane) ? string.Empty : SelfOrOther) + maxSpellLevel;
string fullSpellEnumNameAlt = spellNamPrefix + ((isBane) ? string.Empty : ((SelfOrOther == "Self") ? "Other" : "Self")) + maxSpellLevel;
uint spellID = (uint)Enum.Parse(tySpell, fullSpellEnumName);
var buffMsg = BuildBuffMessage(spellID);
if (buffMsg == null)
{
spellID = (uint)Enum.Parse(tySpell, fullSpellEnumNameAlt);
buffMsg = BuildBuffMessage(spellID);
}
if (buffMsg != null)
{
buffMsg.Bane = isBane;
buffMessages.Add(buffMsg);
}
else
{
buffsNotImplementedYet.Add(fullSpellEnumName);
}
}
// buff each player
players.ToList().ForEach(targetPlayer =>
{
if (buffMessages.Any(k => !k.Bane))
{
// bake player into the messages
buffMessages.Where(k => !k.Bane).ToList().ForEach(k => k.SetTargetPlayer(targetPlayer));
// update client-side enchantments
targetPlayer.Session.Network.EnqueueSend(buffMessages.Where(k => !k.Bane).Select(k => k.SessionMessage).ToArray());
// run client-side effect scripts, omitting duplicates
targetPlayer.EnqueueBroadcast(buffMessages.Where(k => !k.Bane).ToList().GroupBy(m => m.Spell.TargetEffect).Select(a => a.First().LandblockMessage).ToArray());
// update server-side enchantments
var buffsForPlayer = buffMessages.Where(k => !k.Bane).ToList().Select(k => k.Enchantment);
var lifeBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.LifeMagic).ToList();
var critterBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.CreatureEnchantment).ToList();
var itemBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.ItemEnchantment).ToList();
lifeBuffsForPlayer.ForEach(spl =>
{
CreateEnchantmentSilent(spl.Spell, targetPlayer);
});
critterBuffsForPlayer.ForEach(spl =>
{
CreateEnchantmentSilent(spl.Spell, targetPlayer);
});
itemBuffsForPlayer.ForEach(spl =>
{
CreateEnchantmentSilent(spl.Spell, targetPlayer);
});
}
if (buffMessages.Any(k => k.Bane))
{
// Impen/bane
var items = targetPlayer.EquippedObjects.Values.ToList();
var itembuffs = buffMessages.Where(k => k.Bane).ToList();
foreach (var itemBuff in itembuffs)
{
foreach (var item in items)
{
if ((item.WeenieType == WeenieType.Clothing || item.IsShield) && item.IsEnchantable)
CreateEnchantmentSilent(itemBuff.Spell, item);
}
}
}
});
}
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 : 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 : 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 : 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 : EntityListPackageRepositoryDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public PackageRepository SelectRepository(string category = null, string filter = null, string search = null)
{
replacedertEnreplacedyListAccess();
var serviceContext = Dependencies.GetServiceContext();
Enreplacedy packageRepository;
if (!TryGetPackageRepository(serviceContext, PackageRepository, out packageRepository))
{
throw new InvalidOperationException("Unable to retrieve the package repository ({0}:{1}).".FormatWith(PackageRepository.LogicalName, PackageRepository.Id));
}
Enreplacedy enreplacedyList;
if (!TryGetEnreplacedyList(serviceContext, EnreplacedyList, out enreplacedyList))
{
throw new InvalidOperationException("Unable to retrieve the enreplacedy list ({0}:{1}).".FormatWith(EnreplacedyList.LogicalName, EnreplacedyList.Id));
}
Enreplacedy view;
if (!TryGetView(serviceContext, enreplacedyList, View, out view))
{
throw new InvalidOperationException("Unable to retrieve view ({0}:{1}).".FormatWith(View.LogicalName, View.Id));
}
var fetchXml = view.GetAttributeValue<string>("fetchxml");
if (string.IsNullOrEmpty(fetchXml))
{
throw new InvalidOperationException("Unable to retrieve the view FetchXML ({0}:{1}).".FormatWith(View.LogicalName, View.Id));
}
var fetch = Fetch.Parse(fetchXml);
var searchableAttributes = fetch.Enreplacedy.Attributes.Select(a => a.Name).ToArray();
fetch.Enreplacedy.Attributes = FetchAttribute.All;
var settings = new EnreplacedyListSettings(enreplacedyList);
AddPackageCategoryJoin(fetch.Enreplacedy);
AddPackageComponentJoin(fetch.Enreplacedy);
AddPackageDependencyJoin(fetch.Enreplacedy);
AddPackageImageJoin(fetch.Enreplacedy);
AddPackagePublisherJoin(fetch.Enreplacedy);
AddPackageVersionJoin(fetch.Enreplacedy);
// Refactor the query to reduce links, but just do an in-memory category filter for now.
//AddPackageCategoryFilter(fetch.Enreplacedy, category);
AddSelectableFilterToFetchEnreplacedy(fetch.Enreplacedy, settings, filter);
AddWebsiteFilterToFetchEnreplacedy(fetch.Enreplacedy, settings);
AddSearchFilterToFetchEnreplacedy(fetch.Enreplacedy, settings, search, searchableAttributes);
var enreplacedyGroupings = FetchEnreplacedies(serviceContext, fetch).GroupBy(e => e.Id);
var packages = GetPackages(enreplacedyGroupings, GetPackageUrl(settings)).ToArray();
var categoryComparer = new PackageCategoryComparer();
var repositoryCategories = packages.SelectMany(e => e.Categories).Distinct(categoryComparer).OrderBy(e => e.Name);
// Do in-memory category filter.
if (!string.IsNullOrWhiteSpace(category))
{
var filterCategory = new PackageCategory(category);
packages = packages
.Where(e => e.Categories.Any(c => categoryComparer.Equals(c, filterCategory)))
.ToArray();
}
return new PackageRepository
{
replacedle = packageRepository.GetAttributeValue<string>("adx_name"),
Categories = repositoryCategories,
Packages = packages,
Description = packageRepository.GetAttributeValue<string>("adx_description"),
RequiredInstallerVersion = packageRepository.GetAttributeValue<string>("adx_requiredinstallerversion")
};
}
19
View Source File : CrmChangeTrackingManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private IEnumerable<IChangedItem> GetChangesRelatedToWebsite(Dictionary<string, RetrieveEnreplacedyChangesResponse> responseCollection, CrmDbContext context, Guid websiteId)
{
var changedItemList = new List<IChangedItem>();
var groupedChanges = responseCollection
.SelectMany(kvp => kvp.Value.EnreplacedyChanges.Changes)
.GroupBy(change => this.GetEnreplacedyIdFromChangeItem(change));
foreach (var itemGroup in groupedChanges)
{
try
{
if (this.ChangesBelongsToWebsite(itemGroup, context, websiteId))
{
changedItemList.AddRange(itemGroup);
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application,
$"Changes regarding enreplacedy (id: {itemGroup.Key.ToString()}) don't belong to website {websiteId.ToString()}");
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericErrorException(ex);
}
}
return changedItemList;
}
19
View Source File : PortalCacheInvalidatorThread.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private List<string> PostRequest(IEnumerable<PluginMessage> messages, bool isMetadataChangeMessage, bool isSearchIndexInvalidation = false)
{
List<string> enreplacediesWithSuccessfulInvalidation = new List<string>();
try
{
var batchedMessages = messages
.Where(mesg => mesg != null)
.GroupBy(mesg => mesg.Target == null ? string.Empty : mesg.Target.LogicalName);
foreach (var batchedmessage in batchedMessages)
{
List<OrganizationServiceCachePluginMessage> batchedPluginMessage = new List<OrganizationServiceCachePluginMessage>();
var searchInvalidationDatum = new Dictionary<Guid, SearchIndexBuildRequest.SearchIndexInvalidationData>();
foreach (var changedItem in batchedmessage)
{
if (changedItem != null)
{
if (changedItem.Target != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Posting Request for message with Enreplacedy: {0} and ChangeType: {1}", changedItem.Target.LogicalName, changedItem.MessageName));
}
var restartMessage = new ApplicationRestartPortalBusMessage();
// Conversion to OrganizationServiceCachePluginMessage type
var message = new OrganizationServiceCachePluginMessage();
message.MessageName = changedItem.MessageName;
message.RelatedEnreplacedies = changedItem.RelatedEnreplacedies;
message.Relationship = changedItem.Relationship;
message.Target = changedItem.Target;
if (restartMessage.Validate(changedItem))
{
// The restart messages should be processed only once when the message is received from Cache subscription.
if (!isSearchIndexInvalidation)
{
// restart the web application
var task = restartMessage.InvokeAsync(new OwinContext()).WithCurrentCulture();
task.GetAwaiter().GetResult();
SearchIndexBuildRequest.ProcessMessage(message);
}
}
else
{
if (!isSearchIndexInvalidation && FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching) && message.Target != null && message.Target.Id != Guid.Empty)
{
// Get relevant info for search index invalidation from content map before cache invalidation
// MUST OCCUR BEFORE CACHE INVALIDATION
if (!searchInvalidationDatum.ContainsKey(message.Target.Id))
{
searchInvalidationDatum.Add(message.Target.Id, GetSearchIndexInvalidationData(message));
}
}
batchedPluginMessage.Add(message);
}
}
else
{
//logging
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("ChangedItem Record is Null "));
}
}
if (batchedPluginMessage.Count > 0)
{
if (isMetadataChangeMessage)
{
// Invalidate both search index as well as cache
try
{
InvalidateSearchIndex(batchedPluginMessage, searchInvalidationDatum);
}
catch (Exception e)
{
// Even if exception occurs, we still need to invalidate cache, hence cathing exception here and logging error.
ADXTrace.Instance.TraceError(TraceCategory.Exception, e.ToString());
}
InvalidateCache(batchedPluginMessage);
}
else if (isSearchIndexInvalidation)
{
InvalidateSearchIndex(batchedPluginMessage, searchInvalidationDatum);
}
else
{
// Invalidate cache
InvalidateCache(batchedPluginMessage);
}
}
enreplacediesWithSuccessfulInvalidation.Add(batchedmessage.Key);
}
return enreplacediesWithSuccessfulInvalidation;
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
return enreplacediesWithSuccessfulInvalidation;
}
}
19
View Source File : EntityListVideoDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public Video SelectVideo()
{
var serviceContext = Dependencies.GetServiceContext();
var fetch = new Fetch
{
Version = "1.0",
MappingType = MappingType.Logical,
Enreplacedy = new FetchEnreplacedy
{
Name = Video.LogicalName,
Attributes = new[]
{
new FetchAttribute("adx_replacedle"),
new FetchAttribute("adx_copy"),
new FetchAttribute("adx_displaydate"),
new FetchAttribute("adx_mediaembed"),
new FetchAttribute("adx_mediaurl"),
},
Filters = new[]
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new[]
{
new Condition("adx_videoid", ConditionOperator.Equal, Video.Id),
new Condition("statecode", ConditionOperator.Equal, 0),
}
}
},
Links = new[]
{
new Link
{
Name = "adx_video_tag",
FromAttribute = "adx_videoid",
ToAttribute = "adx_videoid",
Type = JoinOperator.LeftOuter,
Links = new[]
{
new Link
{
Alias = "tag",
Name = "adx_tag",
FromAttribute = "adx_tagid",
ToAttribute = "adx_tagid",
Type = JoinOperator.LeftOuter,
Attributes = new[]
{
new FetchAttribute("adx_name"),
},
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0)
}
}
}
}
}
},
},
},
};
var enreplacedyGrouping = FetchEnreplacedies(serviceContext, fetch)
.GroupBy(e => e.Id)
.FirstOrDefault();
if (enreplacedyGrouping == null)
{
return null;
}
var enreplacedy = enreplacedyGrouping.FirstOrDefault();
if (enreplacedy == null)
{
return null;
}
var tags = enreplacedyGrouping.Select(e => e.GetAttributeAliasedValue<string>("adx_name", "tag")).OrderBy(tag => tag).ToList();
return new Video
{
replacedle = enreplacedy.GetAttributeValue<string>("adx_replacedle"),
Copy = enreplacedy.GetAttributeValue<string>("adx_copy"),
DisplayDate = enreplacedy.GetAttributeValue<DateTime?>("adx_displaydate"),
MediaEmbed = enreplacedy.GetAttributeValue<string>("adx_mediaembed"),
MediaUrl = enreplacedy.GetAttributeValue<string>("adx_mediaurl"),
Tags = tags,
};
}
19
View Source File : PackageDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public Package SelectPackage()
{
var serviceContext = Dependencies.GetServiceContext();
var website = Dependencies.GetWebsite();
var fetch = new Fetch
{
Version = "1.0",
MappingType = MappingType.Logical,
Enreplacedy = new FetchEnreplacedy
{
Name = Package.LogicalName,
Attributes = FetchAttribute.All,
Filters = new[]
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new[]
{
new Condition("adx_packageid", ConditionOperator.Equal, Package.Id),
new Condition("statecode", ConditionOperator.Equal, 0),
}
}
},
Links = new Collection<Link>()
}
};
AddPackageCategoryJoin(fetch.Enreplacedy);
AddPackageComponentJoin(fetch.Enreplacedy);
AddPackageDependencyJoin(fetch.Enreplacedy);
AddPackageImageJoin(fetch.Enreplacedy);
AddPackagePublisherJoin(fetch.Enreplacedy);
AddPackageVersionJoin(fetch.Enreplacedy);
var enreplacedyGrouping = FetchEnreplacedies(serviceContext, fetch)
.GroupBy(e => e.Id)
.FirstOrDefault();
if (enreplacedyGrouping == null)
{
return null;
}
var enreplacedy = enreplacedyGrouping.FirstOrDefault();
if (enreplacedy == null)
{
return null;
}
var versions = GetPackageVersions(enreplacedyGrouping, website.Id)
.OrderByDescending(e => e.ReleaseDate)
.ToArray();
var currentVersion = versions.FirstOrDefault();
if (currentVersion == null)
{
return null;
}
PackageImage icon;
var images = GetPackageImages(enreplacedyGrouping, website.Id, enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_iconid"), out icon)
.OrderBy(e => e.Name)
.ToArray();
var packageRepository = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_packagerepository");
return new Package
{
Categories = GetPackageCategories(enreplacedyGrouping).ToArray(),
Components = GetPackageComponents(enreplacedyGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
ContentUrl = currentVersion.Url,
Dependencies = GetPackageDependencies(enreplacedyGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
Description = enreplacedy.GetAttributeValue<string>("adx_description"),
DisplayName = enreplacedy.GetAttributeValue<string>("adx_name"),
HideFromPackageListing = enreplacedy.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
Icon = icon,
Images = images,
OverwriteWarning = enreplacedy.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
PublisherName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "publisher"),
ReleaseDate = currentVersion.ReleaseDate,
RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
Summary = enreplacedy.GetAttributeValue<string>("adx_summary"),
Type = GetPackageType(enreplacedy.GetAttributeValue<OptionSetValue>("adx_type")),
UniqueName = enreplacedy.GetAttributeValue<string>("adx_uniquename"),
Uri = GetPackageUri(packageRepository, website.Id, enreplacedy.GetAttributeValue<string>("adx_uniquename")),
Url = null,
Version = currentVersion.Version,
Versions = versions
};
}
19
View Source File : MarketingDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private IEnumerable<IMarketingList> GetMarketingLists(string emailAddress)
{
var context = Dependencies.GetServiceContext();
var website = Dependencies.GetWebsite();
const string fetchXml =
@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""true"" >
<enreplacedy name=""list"" >
<attribute name=""listid"" />
<attribute name=""listname"" />
<attribute name=""purpose"" />
<order attribute=""listname"" />
<filter type=""and"" >
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
</filter>
<link-enreplacedy name=""adx_website_list"" from=""listid"" to=""listid"" visible=""false"" intersect=""true"" >
<link-enreplacedy name=""adx_website"" from=""adx_websiteid"" to=""adx_websiteid"" alias=""af"" >
<filter type=""and"" >
<condition attribute=""adx_websiteid"" operator=""eq"" value=""{1}"" />
</filter>
</link-enreplacedy>
</link-enreplacedy>
<link-enreplacedy name=""listmember"" from=""listid"" to=""listid"" visible=""false"" intersect=""true"" link-type=""outer"" >
<link-enreplacedy name=""contact"" from=""contactid"" to=""enreplacedyid"" alias=""c"" link-type=""outer"" >
<attribute name=""contactid"" />
<filter type=""and"" >
<filter type=""or"" >
<condition attribute=""emailaddress1"" operator=""eq"" value=""{0}"" />
<condition attribute=""emailaddress2"" operator=""eq"" value=""{0}"" />
<condition attribute=""emailaddress3"" operator=""eq"" value=""{0}"" />
</filter>
</filter>
</link-enreplacedy>
</link-enreplacedy>
<link-enreplacedy name=""listmember"" from=""listid"" to=""listid"" visible=""false"" intersect=""true"" link-type=""outer"" >
<link-enreplacedy name=""lead"" from=""leadid"" to=""enreplacedyid"" alias=""l"" link-type=""outer"" >
<attribute name=""leadid"" />
<filter type=""and"" >
<filter type=""or"" >
<condition attribute=""emailaddress1"" operator=""eq"" value=""{0}"" />
<condition attribute=""emailaddress2"" operator=""eq"" value=""{0}"" />
<condition attribute=""emailaddress3"" operator=""eq"" value=""{0}"" />
</filter>
</filter>
</link-enreplacedy>
</link-enreplacedy>
<link-enreplacedy name=""listmember"" from=""listid"" to=""listid"" visible=""false"" intersect=""true"" link-type=""outer"" >
<link-enreplacedy name=""account"" from=""accountid"" to=""enreplacedyid"" alias=""a"" link-type=""outer"" >
<attribute name=""accountid"" />
<filter type=""and"" >
<filter type=""or"" >
<condition attribute=""emailaddress1"" operator=""eq"" value=""{0}"" />
<condition attribute=""emailaddress2"" operator=""eq"" value=""{0}"" />
<condition attribute=""emailaddress3"" operator=""eq"" value=""{0}"" />
</filter>
</filter>
</link-enreplacedy>
</link-enreplacedy>
<filter operator=""and"">
<filter type=""or"">
<condition enreplacedyname=""c"" attribute=""contactid"" operator=""not-null"" />
<condition enreplacedyname=""l"" attribute=""leadid"" operator=""not-null"" />
<condition enreplacedyname=""a"" attribute=""accountid"" operator=""not-null"" />
</filter>
</filter>
</enreplacedy>
</fetch>";
var lists = (RetrieveMultipleResponse)context.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.FormatWith(emailAddress, website.Id.ToString("B")))
});
var groups = lists.EnreplacedyCollection.Enreplacedies.GroupBy(l => l.GetAttributeValue<Guid>("listid"));
var marketingLists = groups.Select(group => new MarketingList(group));
return marketingLists;
}
19
View Source File : CrmEntityIndexSearcher.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected ICrmEnreplacedySearchResultPage GetUserSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int initialOffset, int resultLimit, ICrmEnreplacedySearchResultFactory resultFactory, int pageNumber, int pageSize, ICollection<ICrmEnreplacedySearchResult> results)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("(searchLimit={0},rawOffset={1},resultLimit={2})", searchLimit, initialOffset, resultLimit));
RawSearchResultSet rawSearchResults = GetRawSearchResults(query, searchLimit, initialOffset);
if (initialOffset >= rawSearchResults.TotalHits)
{
return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
}
var stopwatch = new Stopwatch();
stopwatch.Start();
var groupedNotes = new List<IGrouping<EnreplacedyReference, ICrmEnreplacedySearchResult>>();
var displayNotes = IsAnnotationSearchEnabled();
if (displayNotes && !string.IsNullOrEmpty(query.QueryTerm))
{
var rawNotes = this.GetRelatedAnnotations(rawSearchResults, query);
var notes =
rawNotes.Select(doreplacedent => resultFactory.GetResult(doreplacedent, 1, results.Count + 1)).ToList();
//Grouping Notes by related Knowledge Articles
groupedNotes =
notes.Where(note => note.EnreplacedyLogicalName == "annotation")
.GroupBy(note => note.Enreplacedy.GetAttributeValue<EnreplacedyReference>("objectid"))
.ToList();
}
var offsetForNexreplacederation = initialOffset;
foreach (var scoreDoc in rawSearchResults.Results)
{
offsetForNexreplacederation++;
var result = resultFactory.GetResult(_searcher.Doc(scoreDoc.Doc), scoreDoc.Score, results.Count + 1);
// Not a valid user result, filter out
if (result == null)
{
continue;
}
if (result.EnreplacedyLogicalName == "knowledgearticle" && displayNotes)
{
var relatedNotes = groupedNotes.Where(a => a.Key.Id == result.EnreplacedyID).SelectMany(i => i).Take(3).ToList();
if (relatedNotes.Any(note => note.Fragment == result.Fragment))
{
result.Fragment = GetKnowledgeArticleDescription(result);
}
result.Enreplacedy["relatedNotes"] = relatedNotes;
}
results.Add(result);
if (results.Count >= resultLimit)
{
stopwatch.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
}
}
stopwatch.Stop();
// We asked for more hits than we got back from Lucene, and we still didn't gather enough valid
// results. That's all we're going to get, so the number of results we got is the number of hits.
if (searchLimit >= rawSearchResults.TotalHits)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GenerateResultPage(results, results.Count, pageNumber, pageSize, rawSearchResults);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GetUserSearchResults(query, searchLimit * ExtendedSearchLimitMultiple, offsetForNexreplacederation, resultLimit, resultFactory, pageNumber, pageSize, results);
}
19
View Source File : EnumerableFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IEnumerable GroupBy(IEnumerable input, string key)
{
return input.Cast<object>().GroupBy(e => Get(e, key)).Select(group => new Hash
{
{ "key", @group.Key },
{ "items", @group.AsEnumerable() }
});
}
19
View Source File : TokenContract_Fee_Calculate_Coefficient.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private void replacedertPieceUpperBoundsIsInOrder(
IReadOnlyCollection<CalculateFeePieceCoefficients> calculateFeePieceCoefficientsList)
{
// No same piece upper bound.
replacedert(!calculateFeePieceCoefficientsList.GroupBy(i => i.Value[0]).Any(g => g.Count() > 1),
"Piece upper bounds contains same elements.");
var pieceUpperBounds = calculateFeePieceCoefficientsList.Select(l => l.Value[0]).ToList();
var orderedEnumerable = pieceUpperBounds.OrderBy(i => i).ToList();
for (var i = 0; i < calculateFeePieceCoefficientsList.Count; i++)
{
replacedert(pieceUpperBounds[i] == orderedEnumerable[i], "Piece upper bounds not in order.");
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski
License : GNU General Public License v3.0
Project Creator : agolaszewski
public static void ExtendedList()
{
ConsoleColor result = Question.ExtendedList("Pick",
_complexClreplacedList
.GroupBy(x => x.Name[0])
.Select(x => x.First())
.ToDictionary(key => (ConsoleKey)((int)key.Name[0]), item => item.Color))
.WithConfirmation()
.WithDefaultValue(ConsoleColor.Black)
.WithValidation(answer => answer == ConsoleColor.Black, "Pick black")
.Prompt();
Menu();
}
19
View Source File : frmScheduleDetail.cs
License : MIT License
Project Creator : ahm3tcelik
License : MIT License
Project Creator : ahm3tcelik
private void LoadExercises()
{
List<dynamic> dyamicExercises = exerciseService.GetAllWithPartBySchedule(schedule.ScheduleID);
exercises.Clear();
foreach (dynamic e in dyamicExercises)
{
Exercise exercise = new Exercise
{
ExerciseID = e.ExerciseID,
ExerciseName = e.ExerciseName,
ExerciseSet = e.ExerciseSet,
ExerciseRep = e.ExerciseRep,
ExerciseDay = e.ExerciseDay,
ExerciseDesc = e.ExerciseDesc,
PartID = e.PartID,
Part = new Part { PartID = e.PartID, PartName = e.PartName },
ScheduleID = e.ScheduleID
};
exercises.Add(exercise);
}
var groupExercises = exercises.GroupBy(e => e.ExerciseDay).Select(group => group.ToList()).ToList();
foreach(var exercisesPerDay in groupExercises)
{
exerciseUserControl exerciseUserControl = new exerciseUserControl(exercisesPerDay);
flpSchedules.Controls.Add(exerciseUserControl);
}
}
19
View Source File : CatalogEntry.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
public static DependencyGroup[] ToDependencyGroups(List<LiGet.Enreplacedies.PackageDependency> dependencies,
string catalogUri, Func<string, Uri> getRegistrationUrl)
{
if(dependencies == null || !dependencies.Any())
return new DependencyGroup[0];
var groups = new List<DependencyGroup>();
var frameworkDeps = dependencies.Where(d => d.IsFrameworkDependency()).Select(d => d.TargetFramework).Distinct();
foreach(var frameworkDep in frameworkDeps) {
var g = new DependencyGroup() {
CatalogUrl = catalogUri + $"#dependencygroup/.{frameworkDep}",
TargetFramework = frameworkDep
};
groups.Add(g);
}
// empty string key implies no target framework
Dictionary<string, List<PackageDependency>> dependenciesByFramework = new Dictionary<string, List<PackageDependency>>();
foreach (var packageDependency in dependencies.Where(d => !d.IsFrameworkDependency()))
{
var dep = new PackageDependency() {
Id = packageDependency.Id,
Range = packageDependency.VersionRange
};
string framework = packageDependency.TargetFramework == null ? "" : packageDependency.TargetFramework;
List<PackageDependency> deps = new List<PackageDependency>();
if (!dependenciesByFramework.TryGetValue(framework, out deps)) {
deps = new List<PackageDependency>();
dependenciesByFramework.Add(framework, deps);
}
deps.Add(dep);
}
var perFrameworkDeps =
dependenciesByFramework.GroupBy(d => d.Key)
.Select(grouppedDeps =>
{
var framework = string.IsNullOrEmpty(grouppedDeps.Key) ? null : grouppedDeps.Key;
string catalogForGroup = catalogUri + "#dependencygroup";
if(framework != null)
catalogForGroup = catalogUri + $"#dependencygroup/.{framework}";
var g = new DependencyGroup() {
CatalogUrl = catalogForGroup,
TargetFramework = framework,
Dependencies = grouppedDeps.SelectMany(d => d.Value)
.Select(d => new PackageDependency() {
CatalogUrl = catalogUri + $"#dependencygroup/.{grouppedDeps.Key}/{d.Id}",
Id = d.Id,
Range = d.Range,
Registration = getRegistrationUrl(d.Id).AbsoluteUri
}).ToArray()
};
return g;
});
return groups.Concat(perFrameworkDeps).ToArray();
}
19
View Source File : HeroesResponsiveCollectionView.xaml.cs
License : MIT License
Project Creator : aimore
License : MIT License
Project Creator : aimore
public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize)
{
return source
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / chunkSize)
.Select(x => x.Select(v => v.Value).ToList())
.ToList();
}
19
View Source File : CustomScanner.cs
License : Apache License 2.0
Project Creator : airbus-cert
License : Apache License 2.0
Project Creator : airbus-cert
private bool TestAllVariablesUnique(ExternalVariables externalVariables, out string duplicatesListString)
{
duplicatesListString = "";
List<string> allKeys = externalVariables.StringVariables.Keys.ToList();
allKeys.AddRange(externalVariables.IntVariables.Keys.ToList());
allKeys.AddRange(externalVariables.FloatVariables.Keys.ToList());
allKeys.AddRange(externalVariables.BoolVariables.Keys.ToList());
var duplicates = allKeys.GroupBy(_ => _).Where(_ => _.Count() > 1).ToList();
if (duplicates.Count == 0) return true;
for (var i = 0; i < duplicates.Count; i++)
{
duplicatesListString += $"{duplicates[i].Key}";
if (i < (duplicates.Count - 1))
duplicatesListString += ", ";
}
return false;
}
19
View Source File : APIDocGeneratorMiddleware.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task Invoke(HttpContext context)
{
if (_isAPIAction == null || _judgeAuthorized == null)
{
throw new ArgumentNullException();
}
if (context.Request.Path.ToString().Trim().Trim('/').ToLower() != _docAddress)
{
await _next.Invoke(context);
return;
}
switch (_format)
{
case DocFormat.Json:
context.Response.ContentType = "application/json";
break;
case DocFormat.Markdown:
context.Response.ContentType = "text/markdown";
break;
default:
throw new InvalidDataException($"Invalid format: '{_format}'!");
}
context.Response.StatusCode = 200;
var actionsMatches = new List<API>();
var possibleControllers = replacedembly
.GetEntryreplacedembly()
?.GetTypes()
.Where(type => typeof(ControllerBase).IsreplacedignableFrom(type))
.ToList();
foreach (var controller in possibleControllers ?? new List<Type>())
{
if (!IsController(controller))
{
continue;
}
var controllerRoute = controller.GetCustomAttributes(typeof(RouteAttribute), true)
.Select(t => t as RouteAttribute)
.Select(t => t?.Template)
.FirstOrDefault();
foreach (var method in controller.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
{
if (!IsAction(method) || !_isAPIAction(method, controller))
{
continue;
}
var args = GenerateArguments(method);
var possibleResponses = GetPossibleResponses(method);
var api = new API
{
ControllerName = controller.Name,
ActionName = method.Name,
IsPost = method.CustomAttributes.Any(t => t.AttributeType == typeof(HttpPostAttribute)),
Routes = method.GetCustomAttributes(typeof(RouteAttribute), true)
.Select(t => t as RouteAttribute)
.Select(t => t?.Template)
.Select(t => $"{controllerRoute}/{t}")
.ToList(),
Arguments = args,
AuthRequired = _judgeAuthorized(method, controller),
PossibleResponses = possibleResponses
};
if (!api.Routes.Any())
{
api.Routes.Add($"{api.ControllerName.TrimController()}/{api.ActionName}");
}
actionsMatches.Add(api);
}
}
var generatedJsonDoc = JsonConvert.SerializeObject(actionsMatches);
if (_format == DocFormat.Json)
{
await context.Response.WriteAsync(generatedJsonDoc);
}
else if (_format == DocFormat.Markdown)
{
var generator = new MarkDownDocGenerator();
var groupedControllers = actionsMatches.GroupBy(t => t.ControllerName);
string finalMarkDown = string.Empty;
foreach (var controllerDoc in groupedControllers)
{
finalMarkDown += generator.GenerateMarkDownForAPI(controllerDoc, $"{context.Request.Scheme}://{context.Request.Host}") + "\r\n--------\r\n";
}
await context.Response.WriteAsync(finalMarkDown);
}
}
19
View Source File : DBEntryUnitAircraftData.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal void Merge(DBEntryUnitAircraftData aircraftData)
{
Liveries = Liveries.Union(aircraftData.Liveries).ToList();
PayloadTasks = PayloadTasks
.Union(aircraftData.PayloadTasks)
.GroupBy(g => g.Key)
.ToDictionary(pair => pair.Key, pair => pair.Last().Value);
}
19
View Source File : MissionGeneratorBriefing.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal void GenerateMissionBriefingDescription(DCSMission mission, MissionTemplate template, List<UnitFamily> objectiveTargetUnitFamilies)
{
// Try to get the provided custom mission description.
string briefingDescription = (template.BriefingMissionDescription ?? "").Replace("\r\n", "\n").Replace("\n", " ").Trim();
// No custom description found, generate one from the most frequent objective task/target combination.
if (string.IsNullOrEmpty(briefingDescription))
{
if (template.Objectives.Count == 0)
briefingDescription = "";
else
{
List<string> descriptionsList = new List<string>();
for (int i = 0; i < template.Objectives.Count; i++)
{
DBEntryBriefingDescription descriptionDB =
Database.Instance.GetEntry<DBEntryBriefingDescription>(
Database.Instance.GetEntry<DBEntryObjectiveTask>(template.Objectives[i].Task).BriefingDescription);
descriptionsList.Add(descriptionDB.DescriptionText[(int)objectiveTargetUnitFamilies[i]]);
}
briefingDescription = descriptionsList.GroupBy(i => i).OrderByDescending(grp => grp.Count()).Select(grp => grp.Key).First();
briefingDescription = GeneratorTools.ParseRandomString(briefingDescription);
}
}
mission.Briefing.Description = briefingDescription;
mission.SetValue("BRIEFINGDESCRIPTION", briefingDescription);
}
19
View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
targetMembers.AddRange(GetFields(type, bindingAttr));
targetMembers.AddRange(GetProperties(type, bindingAttr));
// for some reason .NET returns multiple members when overriding a generic member on a base clreplaced
// http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl
// filter members to only return the override on the topmost clreplaced
// update: I think this is fixed in .NET 3.5 SP1 - leave this in for now...
List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count);
foreach (var groupedMember in targetMembers.GroupBy(m => m.Name))
{
int count = groupedMember.Count();
IList<MemberInfo> members = groupedMember.ToList();
if (count == 1)
{
distinctMembers.Add(members.First());
}
else
{
IList<MemberInfo> resolvedMembers = new List<MemberInfo>();
foreach (MemberInfo memberInfo in members)
{
// this is a bit hacky
// if the hiding property is hiding a base property and it is virtual
// then this ensures the derived property gets used
if (resolvedMembers.Count == 0)
{
resolvedMembers.Add(memberInfo);
}
else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item")
{
resolvedMembers.Add(memberInfo);
}
}
distinctMembers.AddRange(resolvedMembers);
}
}
return distinctMembers;
}
19
View Source File : CharacterGenerator.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
protected virtual IEnumerable<CharacterModel> ConsolidateModels(IEnumerable<CharacterModel> models)
{
//models with the same name have the same mesh, just different properties on the HumanoidBodyVariant
//try and take the dlc models
foreach (var modelGroup in models.GroupBy(x => x.Name))
{
var model = modelGroup.OrderBy(GetModelSorting).FirstOrDefault();
yield return model;
}
}
19
View Source File : NpcPatcher.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public void CreatePatch(Patch patch, IList<ValuePair<Model>> npcs)
{
var modifiedNpcs = npcs.Where(x => x.Modified).ToList();
if (!modifiedNpcs.Any())
return;
var npcMap = new CharacterReferences()
.LoadMap(modifiedNpcs.Select(x => x.Default));
var modifications = new List<(ValuePair<Model> Npc, string File)>();
foreach (var npc in modifiedNpcs)
{
if (!npcMap.TryGetValue(npc.Default, out var files))
continue;
foreach (var file in files)
modifications.Add((npc, file));
}
foreach (var mods in modifications.GroupBy(x => x.File))
{
UpdateCharacterReference(patch, mods.Key, mods.Select(x => x.Npc));
}
var mapping = modifiedNpcs.Select(x => (x.Default.Id, x.Value.Id));
patch.AddObject(mapping, MapName);
}
19
View Source File : OutfitPatcher.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private void UpdateModelVariants(Patch patch, IEnumerable<OutfitDetail> outfits, bool modifiedOnly,
Func<OutfitDetail, HzdCore, HumanoidBodyVariant, bool> updateVariant)
{
foreach (var group in outfits.Where(x => !modifiedOnly || x.Modified).GroupBy(x => x.Model.Source))
{
var core = patch.AddFile(group.Key);
var changes = new List<(BaseGGUUID SourceId, BaseGGUUID NewId,
HumanoidBodyVariant Data, Action collapse)>();
var variants = core.GetTypesById<HumanoidBodyVariant>();
foreach (var outfit in group)
{
var variant = variants[outfit.VariantId];
//copy the variant
var newVariant = CopyVariant(variant, out var isOriginal);
if (updateVariant(outfit, core, newVariant))
{
void collapseVariant()
{
//okay to collapse armor variants into original
if (isOriginal && outfit.IsCharacter) return;
core.Binary.RemoveObject(variant);
newVariant.ObjectUUID = variant.ObjectUUID;
outfit.VariantId = variant.ObjectUUID;
if (isOriginal)
newVariant.Name.Value = variant.Name.Value;
}
var change = changes.FirstOrDefault(x => HzdUtils.EqualsIgnoreId(x.Data, newVariant));
if (change.NewId != null)
{
changes.Add((change.SourceId, change.NewId, null, () =>
{
//okay to collapse armor variants into original
if (isOriginal && outfit.IsCharacter) return;
outfit.VariantId = variant.ObjectUUID;
}));
outfit.VariantId = change.NewId;
continue;
}
changes.Add((variant.ObjectUUID, newVariant.ObjectUUID, newVariant, collapseVariant));
outfit.VariantId = newVariant.ObjectUUID;
core.Binary.AddObject(newVariant);
}
}
//only 1 new variant copy, collapse changes into original
foreach (var changeGroup in changes.GroupBy(x => x.SourceId)
.Where(g => g.Count(x => x.Data != null) == 1))
{
foreach (var change in changeGroup)
change.collapse();
}
if (changes.Any())
{
core.Save();
}
}
}
19
View Source File : OutfitPatcher.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private void UpdateModelVariants(Patch patch, IEnumerable<OutfitDetail> outfits, bool modifiedOnly,
Func<OutfitDetail, HzdCore, HumanoidBodyVariant, bool> updateVariant)
{
foreach (var group in outfits.Where(x => !modifiedOnly || x.Modified).GroupBy(x => x.Model.Source))
{
var core = patch.AddFile(group.Key);
var changes = new List<(BaseGGUUID SourceId, BaseGGUUID NewId,
HumanoidBodyVariant Data, Action collapse)>();
var variants = core.GetTypesById<HumanoidBodyVariant>();
foreach (var outfit in group)
{
var variant = variants[outfit.VariantId];
//copy the variant
var newVariant = CopyVariant(variant, out var isOriginal);
if (updateVariant(outfit, core, newVariant))
{
void collapseVariant()
{
//okay to collapse armor variants into original
if (isOriginal && outfit.IsCharacter) return;
core.Binary.RemoveObject(variant);
newVariant.ObjectUUID = variant.ObjectUUID;
outfit.VariantId = variant.ObjectUUID;
if (isOriginal)
newVariant.Name.Value = variant.Name.Value;
}
var change = changes.FirstOrDefault(x => HzdUtils.EqualsIgnoreId(x.Data, newVariant));
if (change.NewId != null)
{
changes.Add((change.SourceId, change.NewId, null, () =>
{
//okay to collapse armor variants into original
if (isOriginal && outfit.IsCharacter) return;
outfit.VariantId = variant.ObjectUUID;
}));
outfit.VariantId = change.NewId;
continue;
}
changes.Add((variant.ObjectUUID, newVariant.ObjectUUID, newVariant, collapseVariant));
outfit.VariantId = newVariant.ObjectUUID;
core.Binary.AddObject(newVariant);
}
}
//only 1 new variant copy, collapse changes into original
foreach (var changeGroup in changes.GroupBy(x => x.SourceId)
.Where(g => g.Count(x => x.Data != null) == 1))
{
foreach (var change in changeGroup)
change.collapse();
}
if (changes.Any())
{
core.Save();
}
}
}
19
View Source File : OutfitPatcher.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private void UpdateOutfitRefs(Patch patch, List<OutfitDetail> outfits)
{
var maps = outfits.Where(x => x.Modified).GroupBy(x => x.Outfit.SourceFile);
foreach (var map in maps)
{
//extract original outfit files to temp
var core = patch.AddFile(map.Key);
//update references from based on new maps
var refs = core.GetTypesById<NodeGraphHumanoidBodyVariantUUIDRefVariableOverride>();
foreach (var outfit in map)
{
if (refs.TryGetValue(outfit.Outfit.RefId, out var variantRef))
variantRef.Object.GUID.replacedignFromOther(outfit.VariantId);
}
core.Save();
}
}
19
View Source File : ElasticSearchStorage.cs
License : MIT License
Project Creator : akpaevj
License : MIT License
Project Creator : akpaevj
private List<(string IndexName, List<EventLogItem> Enreplacedies)> GetGroupedData(List<EventLogItem> enreplacedies)
{
var data = new List<(string IndexName, List<EventLogItem> Enreplacedies)>();
switch (_separation)
{
case "H":
var groups = enreplacedies.GroupBy(c => c.DateTime.ToString("yyyyMMddhh")).OrderBy(c => c.Key);
foreach (var item in groups)
data.Add(($"{_eventLogItemsIndex}-{item.Key}", item.ToList()));
break;
case "D":
groups = enreplacedies.GroupBy(c => c.DateTime.ToString("yyyyMMdd")).OrderBy(c => c.Key);
foreach (var item in groups)
data.Add(($"{_eventLogItemsIndex}-{item.Key}", item.ToList()));
break;
case "M":
groups = enreplacedies.GroupBy(c => c.DateTime.ToString("yyyyMM")).OrderBy(c => c.Key);
foreach (var item in groups)
data.Add(($"{_eventLogItemsIndex}-{item.Key}", item.ToList()));
break;
default:
data.Add(($"{_eventLogItemsIndex}-all", enreplacedies));
break;
}
return data;
}
19
View Source File : AssetDuplicateTreeModel.cs
License : MIT License
Project Creator : akof1314
License : MIT License
Project Creator : akof1314
public override void SetDataPaths(string refPathStr, string pathStr, string commonPathStr)
{
base.SetDataPaths(refPathStr, pathStr, commonPathStr);
var style = replacedetDanshariStyle.Get();
var resFileList = GetResFileList();
var fileList = GetFileMd5Infos(resFileList);
if (fileList == null || fileList.Count == 0)
{
return;
}
var rootInfo = new replacedetInfo(GetAutoId(), String.Empty, String.Empty);
var groups = fileList.GroupBy(info => info.md5).Where(g => g.Count() > 1);
foreach (var group in groups)
{
replacedetInfo dirInfo = new replacedetInfo(GetAutoId(), String.Empty, String.Format(style.duplicateGroup, group.Count()));
dirInfo.isExtra = true;
rootInfo.AddChild(dirInfo);
foreach (var member in group)
{
dirInfo.AddChild(GetreplacedetInfoByFileMd5Info(member));
}
}
if (rootInfo.hasChildren)
{
data = rootInfo;
}
EditorUtility.ClearProgressBar();
}
19
View Source File : Offence.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
internal static List<Offence> DeserializeOffences()
{
List<Offence> AllOffences = new List<Offence>();
if (Directory.Exists("Plugins/LSPDFR/LSPDFR+/Offences"))
{
foreach (string file in Directory.EnumerateFiles("Plugins/LSPDFR/LSPDFR+/Offences", "*.xml", SearchOption.TopDirectoryOnly))
{
try
{
using (var reader = new StreamReader(file))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Offence>),
new XmlRootAttribute("Offences"));
AllOffences.AddRange((List<Offence>)deserializer.Deserialize(reader));
}
}
catch (Exception e)
{
Game.LogTrivial(e.ToString());
Game.LogTrivial("LSPDFR+ - Error parsing XML from " + file);
}
}
}
else
{
}
if (AllOffences.Count == 0)
{
AllOffences.Add(new Offence());
Game.DisplayNotification("~r~~h~LSPDFR+ couldn't find a valid XML file with offences in Plugins/LSPDFR/LSPDFR+/Offences. Setting just the default offence.");
}
CategorizedTrafficOffences = AllOffences.GroupBy(x => x.offenceCategory).ToDictionary(x => x.Key, x => x.ToList());
return AllOffences;
}
19
View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
public virtual new bool RefreshPorts()
{
// If a port behavior was attached to one port, then
// the port count might have been updated by the node
// so we have to refresh the list of port views.
UpdatePortViewWithPorts(nodeTarget.inputPorts, inputPortViews);
UpdatePortViewWithPorts(nodeTarget.outputPorts, outputPortViews);
void UpdatePortViewWithPorts(NodePortContainer ports, List< PortView > portViews)
{
if (ports.Count == 0 && portViews.Count == 0) // Nothing to update
return;
// When there is no current portviews, we can't zip the list so we just add all
if (portViews.Count == 0)
SyncPortCounts(ports, new PortView[]{});
else if (ports.Count == 0) // Same when there is no ports
SyncPortCounts(new NodePort[]{}, portViews);
else if (portViews.Count != ports.Count)
SyncPortCounts(ports, portViews);
else
{
var p = ports.GroupBy(n => n.fieldName);
var pv = portViews.GroupBy(v => v.fieldName);
p.Zip(pv, (portPerFieldName, portViewPerFieldName) => {
IEnumerable< PortView > portViewsList = portViewPerFieldName;
if (portPerFieldName.Count() != portViewPerFieldName.Count())
portViewsList = SyncPortCounts(portPerFieldName, portViewPerFieldName);
SyncPortOrder(portPerFieldName, portViewsList);
// We don't care about the result, we just iterate over port and portView
return "";
}).ToList();
}
// Here we're sure that we have the same amount of port and portView
// so we can update the view with the new port data (if the name of a port have been changed for example)
for (int i = 0; i < portViews.Count; i++)
portViews[i].UpdatePortView(ports[i].portData);
}
return base.RefreshPorts();
}
19
View Source File : PrimaryKeyIndex.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
internal void ClearAndRenderValues(List<LightDataTableRow> rows, string key)
{
_savedIndexes.Clear();
if (string.IsNullOrEmpty(key)) return;
if (rows.Any())
_savedIndexes = rows.GroupBy(x => x[key]).Select(x => x.First()).ToList().FindAll(x => x[key] != null).ToDictionary(x => x[key], x => x);
}
See More Examples