Here are the examples of the csharp api System.Collections.Generic.IEnumerable.SelectMany(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2462 Examples
19
Source : CelesteNetUtils.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
private static Type[] _GetTypes()
=> _Getreplacedemblies().SelectMany(_GetTypes).ToArray();
19
Source : ModelClassGenerator.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static IEnumerable<MemberDeclarationSyntax> GenerateMapping(SqModelMeta meta)
{
return ExtractTableRefs(meta).SelectMany(tr => GenerateMapping(meta, tr));
}
19
Source : ModelClassGenerator.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static IEnumerable<MemberDeclarationSyntax> GenerateReaderClreplaced(SqModelMeta meta)
{
return ExtractTableRefs(meta, out var addName).SelectMany(tableRef => GenerateReaderClreplaced(meta, tableRef, addName));
}
19
Source : ModelClassGenerator.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static IEnumerable<MemberDeclarationSyntax> GenerateWriterClreplaced(SqModelMeta meta)
{
return ExtractTableRefs(meta, out var addName).SelectMany(tableRef => GenerateWriterClreplaced(meta, tableRef, addName));
}
19
Source : IPHelper.cs
with MIT License
from 1100100
with MIT License
from 1100100
public static IPAddress GetLocalInternetIp()
{
return NetworkInterface
.GetAllNetworkInterfaces()
.Select(p => p.GetIPProperties())
.SelectMany(p =>
p.UnicastAddresses
).FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address) && InternalIp(p.Address))?.Address;
}
19
Source : CosmosClientStreamWrapper.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
internal async Task<IEnumerable<string>> GetParreplacedionDoreplacedents(CancellationToken ct)
{
try
{
var queryRequestOption = new QueryRequestOptions
{
ParreplacedionKey = new ParreplacedionKey(_parreplacedionKeyStr)
};
var feedIterator = _container
.GereplacedemQueryStreamIterator(requestOptions: queryRequestOption);
var jsonItemList = new List<IEnumerable<string>>();
while (feedIterator.HasMoreResults)
{
using var response = await feedIterator.ReadNextAsync(cancellationToken: ct);
await using var cosmosItem = new CosmosItem<string>();
var jsonStrings = await cosmosItem.GetJsonStringsFromStream(response.Content, ct);
if (jsonStrings?.Any() ?? false)
{
jsonItemList.Add(jsonStrings);
}
}
return jsonItemList.SelectMany(d => d);
}
catch (Exception ex)
{
throw new CosmosClientException($"Unable to read parreplacedion: {_parreplacedionKeyStr}.", ex);
}
}
19
Source : CosmosClientStreamWrapper.cs
with MIT License
from 1iveowl
with MIT License
from 1iveowl
internal async Task<IEnumerable<T>> GetParreplacedionObjects<T>(CancellationToken ct)
{
try
{
var queryRequestOption = new QueryRequestOptions
{
ParreplacedionKey = new ParreplacedionKey(_parreplacedionKeyStr)
};
var feedIterator = _container
.GereplacedemQueryStreamIterator(requestOptions: queryRequestOption);
var jsonItemList = new List<IEnumerable<T>>();
while (feedIterator.HasMoreResults)
{
using var response = await feedIterator.ReadNextAsync(cancellationToken: ct);
await using var cosmosItem = new CosmosItem<T>();
var items = await cosmosItem.GereplacedemsFromStream(response.Content, ct);
if (items?.Any() ?? false)
{
jsonItemList.Add(items);
}
}
return jsonItemList.SelectMany(d => d);
}
catch (Exception ex)
{
throw new CosmosClientException($"Unable to read parreplacedion: {_parreplacedionKeyStr}.", ex);
}
}
19
Source : CommandPacket.cs
with MIT License
from 2881099
with MIT License
from 2881099
public CommandPacket InputIf(bool condition, params object[] args)
{
if (condition && args != null)
{
foreach (var item in args)
{
if (item is object[] objs) _input.AddRange(objs);
else if (item is string[] strs) _input.AddRange(strs.Select(a => (object)a));
else if (item is int[] ints) _input.AddRange(ints.Select(a => (object)a));
else if (item is long[] longs) _input.AddRange(longs.Select(a => (object)a));
else if (item is KeyValuePair<string, long>[] kvps1) _input.AddRange(kvps1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is KeyValuePair<string, string>[] kvps2) _input.AddRange(kvps2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is Dictionary<string, long> dict1) _input.AddRange(dict1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is Dictionary<string, string> dict2) _input.AddRange(dict2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else _input.Add(item);
}
}
return this;
}
19
Source : Connection.cs
with MIT License
from 2881099
with MIT License
from 2881099
public void ClientTracking(bool on_off, long? redirect, string[] prefix, bool bcast, bool optin, bool optout, bool noloop) => Call("CLIENT"
.SubCommand("TRACKING")
.InputIf(on_off, "ON")
.InputIf(!on_off, "OFF")
.InputIf(redirect != null, "REDIRECT", redirect)
.InputIf(prefix?.Any() == true, prefix?.Select(a => new[] { "PREFIX", a }).SelectMany(a => a).ToArray())
.InputIf(bcast, "BCAST")
.InputIf(optin, "OPTIN")
.InputIf(optout, "OPTOUT")
.InputIf(noloop, "NOLOOP"), rt => rt.ThrowOrNothing());
19
Source : PubSub.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal void UnSubscribe(bool punsub, string[] channels)
{
channels = channels?.Distinct().Select(a => punsub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
if (channels.Any() != true) return;
var ids = channels.Select(a => _registers.TryGetValue(a, out var tryval) ? tryval : null).Where(a => a != null).SelectMany(a => a.Keys).Distinct().ToArray();
Cancel(ids);
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 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
Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec
with GNU Affero General Public License v3.0
from 3CORESec
public static void Main(string[] args)
{
int ruleCount = 0;
int gradientMax = 0;
Parser.Default.ParseArguments<Options>(args)
.WithParsed(o =>
{
LoadConfig(o);
if (!o.Suricata)
{
LoadMismatchSearchMatrix(o);
foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
{
try
{
var dict = DeserializeYamlFile(ruleFilePath, o);
if (dict != null && dict.ContainsKey("tags"))
{
ruleCount++;
var tags = dict["tags"];
var categories = new List<string>();
string lastEntry = null;
foreach (string tag in tags)
{
//If its the technique id entry, then this adds the file name to the techniques map
if (tag.ToLower().StartsWith("attack.t"))
{
var techniqueId = tag.Replace("attack.", "").ToUpper();
if (!techniques.ContainsKey(techniqueId))
techniques[techniqueId] = new List<string>();
techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
if (techniques.Count > gradientMax)
gradientMax = techniques.Count;
//then if there are any categories so far, it checks for a mismatch for each one
if (categories.Count > 0 && o.Warning)
{
foreach (string category in categories)
if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
}
}
else
{
//if its the start of a new technique block, then clean categories and adds first category
if (lastEntry == null || lastEntry.StartsWith("attack.t"))
categories = new List<string>();
categories.Add(
tag.Replace("attack.", "")
.Replace("_", "-")
.ToLower());
}
lastEntry = tag;
}
}
}
catch (YamlException e)
{
Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
}
}
WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
PrintWarnings();
}
else
{
List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();
foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
{
res.Add(ParseRuleFile(ruleFilePath));
}
WriteSuricataFileResult(o,
res
.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key,
group => group.SelectMany(list => list).ToList()));
}
});
}
19
Source : Function.cs
with GNU Affero General Public License v3.0
from 3CORESec
with GNU Affero General Public License v3.0
from 3CORESec
private void initConfig()
{
_alerts = new List<ISender>();
config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
if (string.IsNullOrEmpty(config.SlackPath))
config.SlackPath = Environment.GetEnvironmentVariable("SLACKPATH");
if (string.IsNullOrEmpty(config.WebhookChannel))
config.WebhookChannel = Environment.GetEnvironmentVariable("WEBHOOKCHANNEL");
if (string.IsNullOrEmpty(config.WebHookToken))
config.WebHookToken = Environment.GetEnvironmentVariable("WEBHOOKTOKEN");
if (string.IsNullOrEmpty(config.PostUrl))
config.PostUrl = Environment.GetEnvironmentVariable("POSTURL");
var type = typeof(ISender);
var types = AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsreplacedignableFrom(p) && !p.IsInterface && !p.IsAbstract);
types.ToList().ForEach(type => {
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(Storage<SessionLog>), typeof(Config), typeof(IMemoryCache) });
ISender instance = ctor.Invoke(new object[] { _storage, config, memoryCache }) as ISender;
_alerts.Add(instance);
});
}
19
Source : SeatCollectionExtensions.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static IEnumerable<AdjacentSeats> OrderByMiddleOfTheRow(this IEnumerable<AdjacentSeats> adjacentSeats, int rowSize)
{
var sortedAdjacentSeatsGroups = new SortedList<int, List<AdjacentSeats>>();
foreach (var adjacentSeat in adjacentSeats)
{
var distanceFromRowCentroid = adjacentSeat.ComputeDistanceFromRowCentroid(rowSize);
if (!sortedAdjacentSeatsGroups.ContainsKey(distanceFromRowCentroid))
{
sortedAdjacentSeatsGroups.Add(distanceFromRowCentroid, new List<AdjacentSeats>());
}
sortedAdjacentSeatsGroups[distanceFromRowCentroid].Add(adjacentSeat);
}
return sortedAdjacentSeatsGroups.Values.SelectMany(_ => _);
}
19
Source : SuggestionsMade.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public bool MatchExpectations()
{
return ForCategory.SelectMany(s => s.Value).Any(x => x.MatchExpectation());
}
19
Source : CompilationProcessor.cs
with MIT License
from 71
with MIT License
from 71
public void RegisterAttributes(IreplacedemblySymbol replacedembly)
{
// Sort the attributes based on order and declaration
// Note: Since we're getting symbols here, the order is based
// on the order in which the files were read, and the order in code.
var attributes = replacedembly.GetAttributes();
// Find all used editors, and register 'em
var allEditors = new Dictionary<int, IList<CompilationEditor>>(attributes.Length);
int editorsCount = 0;
for (int i = 0; i < attributes.Length; i++)
{
AttributeData attr = attributes[i];
INamedTypeSymbol attrType = attr.AttributeClreplaced;
// Make sure the attribute inherits CometaryAttribute
for (;;)
{
attrType = attrType.BaseType;
if (attrType == null)
goto NextAttribute;
if (attrType.Name == nameof(CometaryAttribute))
break;
}
// We got here: we have a cometary attribute
IEnumerable<CompilationEditor> editors;
int order;
try
{
editors = InitializeAttribute(attr, out order);
}
catch (TargetInvocationException e)
{
initializationExceptions.Add((e.InnerException, attr));
continue;
}
catch (TypeInitializationException e)
{
initializationExceptions.Add((e.InnerException, attr));
continue;
}
catch (Exception e)
{
initializationExceptions.Add((e, attr));
continue;
}
if (!allEditors.TryGetValue(order, out var editorsOfSameOrder))
{
editorsOfSameOrder = new LightList<CompilationEditor>();
allEditors[order] = editorsOfSameOrder;
}
foreach (CompilationEditor editor in editors)
{
if (editor == null)
continue;
editorsOfSameOrder.Add(editor);
editorsCount++;
}
NextAttribute:;
}
Editors.Capacity = Editors.Count + editorsCount;
Editors.AddRange(allEditors.OrderBy(x => x.Key).SelectMany(x => x.Value));
}
19
Source : ExpressionTree.Linq.cs
with MIT License
from 71
with MIT License
from 71
public static IEnumerable<Expression> Children(this Expression expression, bool allChildren = false)
{
if (allChildren)
return new ExpressionEnumerator(expression);
switch (expression)
{
case BinaryExpression binary:
return new[] { binary.Left, binary.Right };
case BlockExpression block:
return block.Expressions.ToArray();
case ConditionalExpression conditional:
return new[] { conditional.Test, conditional.IfTrue, conditional.IfFalse };
case GotoExpression @goto:
return new[] { @goto.Value };
case IndexExpression index:
return MakeArray(index.Object, index.Arguments);
case InvocationExpression invocation:
return MakeArray(invocation.Expression, invocation.Arguments);
case LabelExpression label:
return new[] { label.DefaultValue };
case LambdaExpression lambda:
return lambda.Body.Children();
case ListInitExpression listInit:
return MakeArray(listInit.NewExpression, listInit.Initializers.SelectMany(x => x.Arguments));
case LoopExpression loop:
return new[] { loop.Body };
case MemberExpression member:
return new[] { member.Expression };
case MemberInitExpression memberInit:
return new[] { memberInit.NewExpression };
case MethodCallExpression call:
return MakeArray(call.Object, call.Arguments);
case NewArrayExpression newArray:
return newArray.Expressions.ToArray();
case NewExpression @new:
return @new.Arguments.ToArray();
case RuntimeVariablesExpression runtimeVar:
return runtimeVar.Variables.Cast<Expression>().ToArray();
case SwitchExpression @switch:
return MakeArray(@switch.SwitchValue, @switch.DefaultBody, @switch.Cases.SelectMany(x => x.TestValues.Prepend(x.Body)));
case TryExpression @try:
return MakeArray(@try.Body, @try.Fault, @try.Handlers.Select(x => x.Body), @try.Finally);
case TypeBinaryExpression typeBinary:
return new[] { typeBinary.Expression };
case UnaryExpression unary:
return new[] { unary.Operand };
default:
return new Expression[0];
}
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static bool CheckIsBanIP(string IP)
{
if ((DateTime.UtcNow - BlockipUpdate).TotalSeconds > 30)
{
var fileName = Loger.PathLog + "blockip.txt";
BlockipUpdate = DateTime.UtcNow;
if (!File.Exists(fileName)) Blockip = new HashSet<string>();
else
try
{
var listBlock = File.ReadAllLines(fileName, Encoding.UTF8);
if (listBlock.Any(b => b.Contains("/")))
{
listBlock = listBlock
.SelectMany(b =>
{
var bb = b.Trim();
var comment = "";
var ic = bb.IndexOf(" ");
if (ic > 0)
{
comment = bb.Substring(ic);
bb = bb.Substring(0, ic);
}
if (bb.Any(c => !char.IsDigit(c) && c != '.' && c != '/')) return new List<string>();
var ls = bb.LastIndexOf("/");
if (ls < 0) return new List<string>() { bb + comment };
var lp = bb.LastIndexOf(".");
if (lp <= 0) return new List<string>();
var ib = int.Parse(bb.Substring(lp + 1, ls - (lp + 1)));
var ie = int.Parse(bb.Substring(ls + 1));
var res = new List<string>();
var s = bb.Substring(0, lp + 1);
for (int i = ib; i <= ie; i++)
res.Add(s + i.ToString() + comment);
return res;
})
.ToArray();
File.WriteAllLines(fileName, listBlock, Encoding.Default);
}
Blockip = new HashSet<string>(listBlock
.Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b));
}
catch (Exception exp)
{
Loger.Log("CheckIsBanIP error " + exp.Message);
Blockip = new HashSet<string>();
return false;
}
}
return Blockip.Contains(IP.Trim());
}
19
Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static string[] GetFiles(MixedRealityToolkitModuleType module, string mrtkRelativeFolder)
{
if (!AreFoldersAvailable)
{
Debug.LogWarning("Failed to locate MixedRealityToolkit folders in the project.");
return null;
}
if (mrtkFolders.TryGetValue(module, out HashSet<string> modFolders))
{
return modFolders
.Select(t => Path.Combine(t, mrtkRelativeFolder))
.Where(Directory.Exists)
.SelectMany(t => Directory.GetFiles(t))
.Select(GetreplacedetDatabasePath)
.ToArray();
}
return null;
}
19
Source : SyncUsageHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private Type GetEncoderType()
{
var type = AppDomain.CurrentDomain
.Getreplacedemblies()
.SelectMany(replacedembly => replacedembly.GetTypes())
.FirstOrDefault(replacedemblyType => replacedemblyType.Name == _clreplaced &&
replacedemblyType.Namespace == _namespace);
return type;
}
19
Source : PropertyAttribute2nd.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string ToSentence(this PropertyAttribute2nd attribute2nd)
{
return new string(attribute2nd.ToString().Replace("Max", "Maximum").ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
}
19
Source : FactionBits.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string ToSentence(this FactionBits factionBits)
{
return new string(factionBits.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
}
19
Source : HookGroupType.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string ToSentence(this HookGroupType hookGroupType)
{
return new string(hookGroupType.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
}
19
Source : Skill.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string ToSentence(this Skill skill)
{
return new string(skill.ToString().ToCharArray().SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new char[] { ' ', c } : new char[] { c }).ToArray());
}
19
Source : Game.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
public void PlayAt(int row, int column)
{
var emptyCellsCount = _board.SelectMany(s=>s).Count(s => s == N);
var player = X;
if (emptyCellsCount % 2 == 0)
player = O;
_board[row][column] = player;
}
19
Source : PrimaryDacFinder.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private ITypeSymbol ApplyRule(PrimaryDacRuleBase rule)
{
IEnumerable<ITypeSymbol> dacCandidates = null;
IEnumerable<ISymbol> viewCandidates = null;
switch (rule.RuleKind)
{
case PrimaryDacRuleKind.Graph:
dacCandidates = (rule as GraphRuleBase)?.GetCandidatesFromGraphRule(this);
break;
case PrimaryDacRuleKind.View:
var viewWithTypeCandidates = GetViewCandidatesFromViewRule(rule as ViewRuleBase);
viewCandidates = viewWithTypeCandidates?.Select(view => view.Symbol);
dacCandidates = viewWithTypeCandidates?.Select(view => view.Type.GetDacFromView(PxContext));
break;
case PrimaryDacRuleKind.Dac:
var dacWithViewCandidates = GetCandidatesFromDacRule(rule as DacRuleBase);
dacCandidates = dacWithViewCandidates?.Select(group => group.Key);
viewCandidates = dacWithViewCandidates?.SelectMany(group => group);
break;
case PrimaryDacRuleKind.Action:
dacCandidates = GetCandidatesFromActionRule(rule as ActionRuleBase);
break;
}
if (dacCandidates.IsNullOrEmpty())
return null;
var dacCandidatesList = dacCandidates.Where(dac => dac != null).Distinct().ToList();
ITypeSymbol primaryDac = null;
if (rule.IsAbsolute && dacCandidatesList.Count == 1)
primaryDac = dacCandidatesList[0];
viewCandidates = viewCandidates ?? dacCandidatesList.SelectMany(dac => _dacWithViewsLookup[dac]);
ScoreRuleForViewCandidates(viewCandidates, rule);
return primaryDac;
}
19
Source : ITypeSymbolExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
{
type.ThrowOnNull(nameof(type));
if (type is ITypeParameterSymbol typeParameter)
{
IEnumerable<ITypeSymbol> constraintTypes = typeParameter.GetAllConstraintTypes(includeInterfaces: false)
.SelectMany(GetBaseTypesImplementation)
.Distinct();
return typeParameter.ToEnumerable()
.Concat(constraintTypes);
}
else
{
return type.GetBaseTypesAndThisImplementation();
}
}
19
Source : ITypeSymbolExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
{
type.ThrowOnNull(nameof(type));
if (type is ITypeParameterSymbol typeParameter)
{
return typeParameter.GetAllConstraintTypes(includeInterfaces: false)
.SelectMany(GetBaseTypesImplementation)
.Distinct();
}
return type.GetBaseTypesImplementation();
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterTransientDependency()
{
var types = replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
RegisterRpcServer(types);
RegisterSubscriber(types);
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterRpcServer(List<Type> types)
{
types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(RpcServerAttribute))).ToList();
//去重复
var dicMethod = new Dictionary<int, MethodInfo>();
methodInfos.ForEach(m =>
{
dicMethod.TryAdd(m.MetadataToken, m);
});
RpcServerMethodList = dicMethod.Select(d => d.Value).ToList();
var first = RpcServerMethodList.Select(d => d.GetCustomAttribute<RpcServerAttribute>().GetFormatKey()).GroupBy(d => d)
.ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
.FirstOrDefault();
if (first.Value > 1)
throw new ArgumentException($"RpcServr Key 重复:{first.Key}");
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterSubscriber(List<Type> types)
{
types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(SubscriberAttribute))).ToList();
//去重复
var dicMethod = new Dictionary<int, MethodInfo>();
methodInfos.ForEach(m =>
{
dicMethod.TryAdd(m.MetadataToken, m);
});
SubscriberMethodList = dicMethod.Select(d => d.Value).ToList();
var first = SubscriberMethodList.Select(d => d.GetCustomAttribute<SubscriberAttribute>().GetFormatKey()).GroupBy(d => d)
.ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
.FirstOrDefault();
if (first.Value > 1)
throw new ArgumentException($"Subscriber Key 重复:{first.Key}");
}
19
Source : TypeFinder.cs
with MIT License
from ad313
with MIT License
from ad313
public List<Type> FindAllInterface(List<replacedembly> replacedemblies = null)
{
replacedemblies ??= Getreplacedemblies();
if (replacedemblies == null || !replacedemblies.Any())
return new List<Type>();
return replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsInterface)).ToList();
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterTransientDependency()
{
//虚函数
var virtualClreplaced = replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced && t.GetInterfaces().Length == 0)).ToList();
var virtualMethods = virtualClreplaced.SelectMany(d => d.GetMethods()).Where(d =>
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopPublisherAttribute)) ||
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopSubscriberAttribute))).ToList();
var methods = TypeFinder.FindAllInterface(replacedemblies).SelectMany(d => d.GetMethods()).ToList();
methods.AddRange(virtualMethods);
var publishers = methods.SelectMany(d => d.GetCustomAttributes<AopPublisherAttribute>()).ToList();
var check = publishers.Select(d => d.Channel).GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).Where(d => d.Value > 1).ToList();
if (check.Any())
{
throw new Exception($"[AopCache AopPublisherAttribute] [Key 重复:{string.Join("、", check.Select(d => d.Key))}]");
}
//开启发布
if (publishers.Any())
{
AopPublisherAttribute.Enable = true;
}
var existsList = methods.Where(d =>
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopPublisherAttribute)) &&
d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(AopCacheAttribute))).ToList();
if (existsList.Any())
{
throw new Exception($"[AopCache AopPublisherAttribute] [不能与 AopCacheAttribute 一起使用 :{string.Join("、", existsList.Select(d => $"{d.DeclaringType?.FullName}.{d.Name}"))}]");
}
var subscribers = methods.SelectMany(d => d.GetCustomAttributes<AopSubscriberAttribute>()).ToList();
if (subscribers.Any())
{
AopSubscriberAttribute.ChannelList = subscribers.Select(d => d.Channel).Distinct().ToList();
AopSubscriberAttribute.MethodList = methods.Where(d =>
d.CustomAttributes != null &&
d.CustomAttributes.Any(c => c.AttributeType.Name == nameof(AopSubscriberAttribute))).ToList();
foreach (var subscriber in subscribers)
{
if (string.IsNullOrWhiteSpace(subscriber.Map))
continue;
//特殊处理冒号,兼容冒号
subscriber.Map = subscriber.Map.Replace(":", ".");
var key = subscriber.GetMapDictionaryKey();
if (AopSubscriberAttribute.MapDictionary.ContainsKey(key))
continue;
var mapDic = subscriber.Map.Split(',')
.Where(d => d.IndexOf('=') > -1
&& !string.IsNullOrWhiteSpace(d.Split('=')[0])
&& !string.IsNullOrWhiteSpace(d.Split('=')[1]))
.ToDictionary(d => d.Split('=')[0].Trim(), d => d.Split('=')[1].Trim().TrimStart('{').TrimEnd('}'));
AopSubscriberAttribute.MapDictionary.TryAdd(key, mapDic);
}
}
}
19
Source : Grammar.cs
with MIT License
from adamant
with MIT License
from adamant
public IEnumerable<GrammarRule> AncestorRules(GrammarRule rule)
{
var parents = ParentRules(rule).ToList();
return parents.Concat(parents.SelectMany(AncestorRules)).Distinct();
}
19
Source : EnumerableExtensions.cs
with MIT License
from adamant
with MIT License
from adamant
[DebuggerStepThrough]
public static IEnumerable<T> SelectMany<T>(this IEnumerable<IEnumerable<T>> source)
{
return source.SelectMany(items => items);
}
19
Source : TypeExtensions.cs
with MIT License
from adamant
with MIT License
from adamant
public static IEnumerable<Type> GetAllSubtypes(this Type type)
{
return AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(a => a.GetTypes())
.Where(t => type.IsreplacedignableFrom(t) && t != type)
.ToArray();
}
19
Source : SetVersionInfoTask.cs
with MIT License
from adamecr
with MIT License
from adamecr
private static void SetProjectPropertyNode(XContainer projectNode, string nodeName, string nodeValue)
{
var propertyNode = projectNode
.Elements("PropertyGroup")
.SelectMany(it => it.Elements(nodeName))
.SingleOrDefault();
// If no node exists, create it.
if (propertyNode == null)
{
var propertyGroupNode = GetOrCreateElement(projectNode, "PropertyGroup");
propertyNode = GetOrCreateElement(propertyGroupNode, nodeName);
}
propertyNode.SetValue(nodeValue);
}
19
Source : MessageHandlerContainer.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
public void Register(Action<MessageHandlerMetadata>? configureMessageHandlerMetadata, params replacedembly[] replacedemblies)
{
var messageHandlerTypes = replacedemblies.SelectMany(a => a.GetTypes())
.Where(t => t.IsClreplaced && !t.IsAbstract)
.SelectMany(t => t.GetInterfaces())
.Where(i => typeof(IMessageHandler) == i)
.ToList();
foreach (Type messageHandlerType in messageHandlerTypes)
{
Register(messageHandlerType, configureMessageHandlerMetadata);
}
}
19
Source : DependencyInjectionMessageHandlerContainer.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
public void Register(Action<MessageHandlerMetadata>? configureMessageHandlerMetadata, params replacedembly[] replacedemblies)
{
var messageHandlerTypes = replacedemblies.SelectMany(a => a.GetTypes())
.Where(t => t.IsClreplaced && !t.IsAbstract && t.GetInterfaces().Contains(typeof(IMessageHandler)))
.ToList();
foreach (Type messageHandlerType in messageHandlerTypes)
{
Register(messageHandlerType, configureMessageHandlerMetadata);
}
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<Enreplacedy> GetRelatedEnreplacediesRecursive(Enreplacedy enreplacedy)
{
if (enreplacedy == null) yield break;
yield return enreplacedy;
foreach (
var related in
enreplacedy.RelatedEnreplacedies.SelectMany(relationship => relationship.Value.Enreplacedies)
.SelectMany(GetRelatedEnreplacediesRecursive))
{
yield return related;
}
}
19
Source : EntityDefinition.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private ICollection<FetchAttribute> GetFetchAttributes()
{
// merge the column sets
return ColumnSets.SelectMany(set => set.ColumnSet).Select(set => new FetchAttribute { Name = set }).ToArray();
}
19
Source : CertificateExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<X509Certificate2> FindCertificatesByThumbprint(this IEnumerable<string> thumbprints, bool findByTimeValid = true, bool validOnly = false)
{
var certificates = thumbprints
.Where(thumbprint => !string.IsNullOrWhiteSpace(thumbprint))
.SelectMany(thumbprint => thumbprint.FindCertificatesByThumbprint(findByTimeValid, validOnly).OfType<X509Certificate2>());
return certificates;
}
19
Source : OrganizationServiceCacheServiceBehavior.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
serviceDescription.ThrowOnNull("serviceDescription");
serviceHostBase.ThrowOnNull("serviceHostBase");
var sb = serviceDescription.Behaviors.Find<ServiceBehaviorAttribute>();
foreach (var ed in serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>().SelectMany(cd => cd.Endpoints))
{
if (sb != null && sb.InstanceContextMode == InstanceContextMode.Single)
{
ed.DispatchRuntime.SingletonInstanceContext = new InstanceContext(serviceHostBase);
}
ed.DispatchRuntime.InstanceProvider = new OrganizationServiceCacheServiceInstanceProvider(_cache);
}
}
19
Source : EntityDefinition.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public Fetch CreateFetch()
{
var columnSet = ColumnSets.SelectMany(set => set.ColumnSet).ToArray();
var fetch = new Fetch
{
Enreplacedy = new FetchEnreplacedy(LogicalName)
{
Attributes = columnSet.Select(column => new FetchAttribute(column)).ToList()
},
SkipCache = true
};
if (ActiveStateCode != null)
{
fetch.AddFilter(new Filter
{
Conditions = new List<Condition>
{
new Condition("statecode", ConditionOperator.Equal, ActiveStateCode.Value)
}
});
}
return fetch;
}
19
Source : EntityListPackageRepositoryDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : CrmChangeTrackingManager.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : ForumAccessPermissionProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected override bool Tryreplacedert(OrganizationServiceContext context, Enreplacedy forum, CrmEnreplacedyRight right, CrmEnreplacedyCacheDependencyTrace dependencies, ContentMap map)
{
forum.replacedertEnreplacedyName("adx_communityforum");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on forum '{1}' ({2}).", right, forum.GetAttributeValue<string>("adx_name"), forum.Id));
this.AddDependencies(dependencies, forum, new[] { "adx_webrole", "adx_communityforumaccesspermission" });
if (!Roles.Enabled)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change.");
// If roles are not enabled on the site, grant Read, deny Change.
return (right == CrmEnreplacedyRight.Read);
}
var userRoles = this.GetUserRoles();
// Get all rules applicable to the forum, grouping equivalent rules. (Rules that
// target the same forum and confer the same right are equivalent.)
var ruleGroupings = from rule in this.GetRulesApplicableToForum(forum, dependencies, map)
let forumReference = rule.GetAttributeValue<EnreplacedyReference>("adx_forumid")
let rightOption = rule.GetAttributeValue<OptionSetValue>("adx_right")
where forumReference != null && rightOption != null
group rule by new { ForumID = forumReference.Id, Right = ParseRightOption(rightOption.Value) } into ruleGrouping
select ruleGrouping;
var websiteReference = forum.GetAttributeValue<EnreplacedyReference>("adx_websiteid");
// Order the rule groupings so that all GrantChange rules will be evaluated first.
ruleGroupings = ruleGroupings.OrderByDescending(grouping => grouping.Key.Right, new RightOptionComparer());
foreach (var ruleGrouping in ruleGroupings)
{
// Collect the names of all the roles that apply to this rule grouping
var ruleGroupingRoles = ruleGrouping.SelectMany(rule => GetRolesForGrouping(map, rule, websiteReference));
// Determine if the user belongs to any of the roles that apply to this rule grouping
var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role));
// If the user belongs to one of the roles...
if (userIsInAnyRoleForThisRule)
{
// ...and the rule is GrantChange...
if (ruleGrouping.Key.Right == RightOption.GrantChange)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.ForumID));
// ...the user has all rights.
return true;
}
}
// If the user does not belong to any of the roles, the rule restricts read, and the desired right
// is read...
else if (ruleGrouping.Key.Right == RightOption.RestrictRead && right == CrmEnreplacedyRight.Read)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on forum ({0}). Permission denied.", ruleGrouping.Key.ForumID));
// ...the user has no right.
return false;
}
}
// If none of the above rules apply, replacedert on parent webpage.
var parentWebPage = forum.GetAttributeValue<EnreplacedyReference>("adx_parentpageid");
WebPageNode parentPageNode;
map.TryGetValue(parentWebPage, out parentPageNode);
// If there is no parent web page, grant Read by default, and deny Change.
if (parentWebPage == null || parentPageNode == null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. Allowing Read, but not Change.");
return (right == CrmEnreplacedyRight.Read);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. replacederting right on parent web page.");
return this._webPageAccessControlProvider.Tryreplacedert(context, parentPageNode.ToEnreplacedy(), right, dependencies);
}
19
Source : Saml2ConfigurationManager.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static async Task<WsFederationConfiguration> GetConfigurationAsync(string address, IDoreplacedentRetriever retriever, CancellationToken cancel)
{
var doreplacedent = await retriever.GetDoreplacedentAsync(address, cancel);
var configuration = new WsFederationConfiguration();
using (var sr = new StringReader(doreplacedent))
using (var xr = XmlReader.Create(sr, _settings))
{
var serializer = new MetadataSerializer { CertificateValidationMode = X509CertificateValidationMode.None };
var enreplacedyDescriptor = serializer.ReadMetadata(xr) as EnreplacedyDescriptor;
if (enreplacedyDescriptor != null)
{
configuration.Issuer = enreplacedyDescriptor.EnreplacedyId.Id;
var idpssod = enreplacedyDescriptor.RoleDescriptors.OfType<IdenreplacedyProviderSingleSignOnDescriptor>().FirstOrDefault();
if (idpssod != null)
{
var redirectBinding = idpssod.SingleSignOnServices.FirstOrDefault(ssos => ssos.Binding == ProtocolBindings.HttpRedirect);
if (redirectBinding != null)
{
configuration.TokenEndpoint = redirectBinding.Location.OriginalString;
}
var keys = idpssod.Keys
.Where(key => key.KeyInfo != null && (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified))
.SelectMany(key => key.KeyInfo.OfType<X509RawDataKeyIdentifierClause>())
.Select(clause => new X509SecurityKey(new X509Certificate2(clause.GetX509RawData())));
foreach (var key in keys)
{
configuration.SigningKeys.Add(key);
}
}
}
}
return configuration;
}
19
Source : CacheDependencyCalculator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IEnumerable<string> GetDependencies(IEnumerable<Enreplacedy> enreplacedies, bool isSingle)
{
return enreplacedies.SelectMany(e => this.GetDependencies(e, isSingle));
}
19
Source : CacheDependencyCalculator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IEnumerable<string> GetDependencies(IEnumerable<EnreplacedyReference> enreplacedies, bool isSingle)
{
return enreplacedies.SelectMany(e => this.GetDependencies(e, isSingle));
}
See More Examples