protected static CsFile CreateFile() { var file = new CsFile(); file.AddImportNamespace("System"); return(file); }
public static void Run(string basePath) { var gen = new KeysGenerator(); var a = typeof(KeysGeneratorRunner).Assembly; void AddString(string n, string p = "Value") { gen.Add(new KeysGeneratorDef(n, a, WrappedTypes.String, p)); } AddString(nameof(XValueTypeName), nameof(XValueTypeName.ValueTypeName)); AddString(nameof(XUnitTypeName), nameof(XUnitTypeName.TypeName)); AddString(nameof(XUnitContainerTypeName), nameof(XUnitContainerTypeName.TypeName)); var file = new CsFile(); file.AddImportNamespace("System"); IAutoCodeGeneratorContext ctx = new AutoCodeGenerator.SimpleAutoCodeGeneratorContext(file, type => { var c = file.GetOrCreateClass(type); c.IsPartial = true; return(c); }); gen.AssemblyStart(a, ctx); gen.AssemblyEnd(a, ctx); var filename = Path.Combine(basePath, "Keys.auto.cs"); file.SaveIfDifferent(filename); }
public void CommentedOutLogging() { CsFile csFile = GetCsFile("LoggingCommentedOut.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(0, _vulnerabilities.Count); }
public void LoggingAsValue() { CsFile csFile = GetCsFile("LoggingInfoAsValue.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(0, _vulnerabilities.Count); }
private NdArrayLevel2Generator(CsFile csFile, int dimension, string wrappedType) { _dimension = dimension; _wrappedType = wrappedType; _class = csFile.GetOrCreateClass("Lang.Python.Numpy", $"NdArray{dimension}D{wrappedType.FirstUpper()}"); _class.BaseClass = $"NdArray{dimension}D<{wrappedType}>"; }
public void CbcEncryption() { CsFile csFile = GetCsFile("CbcCipherMode.cs.test"); _analyzer.Analyze(csFile); Assert.AreEqual(0, _vulnerabilities.Count()); }
public static CsClass Generate(CsFile f, int dimension) { var a = new NdArrayLevel1Generator(f, dimension); a.Add_Constructor(); a.Add_Map(); return(a._class); }
public void WebViewJavaScriptEnabledAsVariableName() { CsFile csFile = GetCsFile("WebViewJavaScriptEnabledAsVariableName.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(0, _vulnerabilities.Count()); }
public void LoggingInfoWithFullyQualifiedName() { CsFile csFile = GetCsFile("LoggingInfoFQ.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); }
public void NonExistingFile() { CsFile csFile = GetCsFile("NonExistingFile.cs"); CompilationUnitSyntax unit = csFile.GetUnit(); Assert.AreEqual("", unit.ToFullString()); Assert.AreEqual(0, unit.DescendantNodes().Count()); }
public static void CreateBamProjectPackage() { string projectOrSolutionPath = GetArgument("projectOrSolution", "Please specify the path to the solution or project file"); FileInfo file = new FileInfo(projectOrSolutionPath); bool isSolution = file.Extension.Equals(".sln"); bool isProject = file.Extension.Equals(".csproj"); if (!isSolution && !isProject) { OutLineFormat("Specified file format not supported: {0}", file.Extension, ConsoleColor.Red); return; } List <string> projectFilePaths = new List <string>(); if (isProject) { projectFilePaths.Add(file.FullName); } if (isSolution) { projectFilePaths.AddRange(file.GetProjectFilePaths()); } BamProject bamProject = CreateBamProject(projectFilePaths); BamProject bamPackage = new BamProject(); string bamPackageFilePath = ".\\BamPackage.zip"; if (File.Exists(bamPackageFilePath)) { File.Move(bamPackageFilePath, bamPackageFilePath.GetNextFileName()); } string bamPackageDir = ".\\BamPackage\\"; if (Directory.Exists(bamPackageDir)) { Directory.Move(bamPackageDir, bamPackageDir.GetNextDirectoryName()); } Directory.CreateDirectory(bamPackageDir); DirectoryInfo dir = new DirectoryInfo(bamPackageDir); List <CsFile> targetCsFiles = new List <CsFile>(); foreach (CsFile csFile in bamProject.CsFiles) { CsFile targetCsFile = csFile.CopyTo(dir.FullName); DirectoryInfo rootDir = new DirectoryInfo(csFile.Root); targetCsFile.Root = Path.Combine(bamPackageDir, rootDir.Name); targetCsFiles.Add(targetCsFile); } bamPackage.CsFiles = targetCsFiles.ToArray(); bamPackage.AssemblyReferences = bamProject.AssemblyReferences; bamPackage.ToJsonFile(Path.Combine(dir.FullName, "BamProject.json")); string outputPath = new FileInfo(bamPackageFilePath).FullName; ZipFile.CreateFromDirectory(dir.FullName, outputPath); OutLineFormat("Package file written: {0}", outputPath); }
public void ModifyTest() { CsFile csFile = new CsFile(@"D:\Research\projects\GUI-Testing-Automation\Solution Utilities\SampleInput\FirstFolder\MainWindow.xaml.cs"); CsFileModifier csFileModifier = new CsFileModifier(); //csFileModifier.Modify(csFile, new List<string>() { "SecondWindow"}); Assert.IsTrue(true); }
public CsFile GetActualCsFile() { if (File.Exists(ActualCsFile)) { File.Delete(ActualCsFile); } File.Copy(SampleCsFile, ActualCsFile); return(CsFile.Get(ActualCsFile)); }
public void ProcessTest() { CsFileAnalyzer csFileAnalyzer = new CsFileAnalyzer(); CsFile csFile = new CsFile(@"..\..\..\Solution Utilities\WindowsFormsApp1\Program1.cs"); csFileAnalyzer.CsFile = csFile; csFileAnalyzer.Process(); Assert.AreEqual(csFile.Classes[0].Name, "MainWindow"); Assert.AreEqual(csFile.Classes[0].BaseOnClass[0], "Window"); }
protected virtual void PrepareFile(CsFile file) { if (file.Namespaces.Any()) { return; } file.AddImportNamespace("System"); file.AddImportNamespace("System.Globalization"); file.AddImportNamespace("System.Collections.Generic"); file.AddImportNamespace("JetBrains.Annotations"); }
public static void AddGeneratorName(CsFile file, string name) { if (string.IsNullOrEmpty(file.BeginContent)) { file.BeginContent = "// generator: " + name; } else { file.BeginContent += ", " + name; } }
protected void Save(CsFile file, CsClass cl, params string[] subDirs) { var a = new List <string> { BasePath.FullName }; a.AddRange(subDirs); a.Add(cl.GetShortName()); var fileName = Path.Combine(a.ToArray()); file.SaveIfDifferent(fileName); }
public static CsClass Generate(CsFile f, int dimension, string wrappedType) { var a = new NdArrayLevel2Generator(f, dimension, wrappedType); a.Add_Constructor(); a.Add_Mean(); if (wrappedType == "double" || wrappedType == "int") { a.Add_Map(wrappedType, "double"); } if (wrappedType == "int") { a.Add_Direct_Cast("double"); } return(a._class); }
public void HardcodedHttpUrlAsConst() { CsFile csFile = GetCsFile("HardcodedHttpUrlVariants.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("HardcodedHttpUrl", vulnerability.Code); Assert.AreEqual("Hardcoded HTTP URL found", vulnerability.Title); Assert.AreEqual("HTTP traffic may not be encrypted, which opens the door to man-in-the-middle attacks. HTTP URL: http://www.example.com.", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "HardcodedHttpUrl", "HardcodedHttpUrlVariants.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.HardcodedHttpUrlVariants", vulnerability.FullyQualifiedName); Assert.AreEqual(10, vulnerability.LineNumber); }
public void WorldReadable() { CsFile csFile = GetCsFile("WorldReadable.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("WorldReadable", vulnerability.Code); Assert.AreEqual("WorldReadable file found", vulnerability.Title); Assert.AreEqual("A WorldReadable file may expose sensitive data to other apps.", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "WorldReadable", "WorldReadable.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.WorldReadable", vulnerability.FullyQualifiedName); Assert.AreEqual(16, vulnerability.LineNumber); }
public void ExternalStorageVariants() { CsFile csFile = GetCsFile("ExternalStorageVariants.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(2, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("ExternalStorage", vulnerability.Code); Assert.AreEqual("External storage is used", vulnerability.Title); Assert.AreEqual("Files on external storage can be accessed by any app. Check this method: GetExternalFilesDir(...).", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "ExternalStorage", "ExternalStorageVariants.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.ExternalStorageVariants", vulnerability.FullyQualifiedName); Assert.AreEqual(15, vulnerability.LineNumber); }
public void SslCertificate() { CsFile csFile = GetCsFile("CertificateValidation.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("CertificateValidation", vulnerability.Code); Assert.AreEqual("Certificate validation overwritten", vulnerability.Title); Assert.AreEqual("Certificate validation callback is overwritten. This may open the door to man-in-the-middle attacks.", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "CertificateValidation", "CertificateValidation.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.CertificateValidation", vulnerability.FullyQualifiedName); Assert.AreEqual(17, vulnerability.LineNumber); }
public void CheckPermissionVariants() { CsFile csFile = GetCsFile("CheckPermissionVariants.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(2, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("CheckPermission", vulnerability.Code); Assert.AreEqual("Permissions may not be enforced", vulnerability.Title); Assert.AreEqual("Permissions may not be enforced when using this method in an exported component: CheckCallingOrSelfPermission(...).", vulnerability.Description); var expectedPath = Path.Combine("TestFiles", "CheckPermission", "CheckPermissionVariants.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.CheckPermissionVariants", vulnerability.FullyQualifiedName); Assert.AreEqual(18, vulnerability.LineNumber); }
public void PhoneNumberAccess() { CsFile csFile = GetCsFile("PhoneNumberAccess.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("PhoneNumberAccess", vulnerability.Code); Assert.AreEqual("Access to phone number", vulnerability.Title); Assert.AreEqual("Be careful accessing the phone number of your user. This is personally identifying information (PII).", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "PhoneNumberAccess", "PhoneNumberAccess.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.UniqueIdentifiers", vulnerability.FullyQualifiedName); Assert.AreEqual(18, vulnerability.LineNumber); }
public override void Analyze(CsFile csFile) { var assignments = csFile.GetUnit().DescendantNodes().OfType <AssignmentExpressionSyntax>(); var vulnerabilities = assignments .Where(IsEcbCipherMode) .Select(assignment => new Vulnerability { Code = "EcbCipherMode", Title = "Unsafe cipher mode used", Description = $"You may leak information by using the ECB cipher mode. Encrypting the same block of bits using this mode returns the same output.", FilePath = csFile.FilePath, FullyQualifiedName = QualifiedNameResolver.Resolve(assignment), LineNumber = assignment.Right.GetLocation().GetLineSpan().StartLinePosition.Line + 1 }).ToList(); vulnerabilities.ForEach(OnVulnerabilityDiscovered); }
public void JavaScriptInterface() { CsFile csFile = GetCsFile("JavaScriptInterface.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("JavascriptInterface", vulnerability.Code); Assert.AreEqual("JavascriptInterface is added to a WebView", vulnerability.Title); Assert.AreEqual("Adding a JavascriptInterface to a WebView might allow remote code execution attacks.", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "JavaScriptInterface", "JavaScriptInterface.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.JavaScriptInterface", vulnerability.FullyQualifiedName); Assert.AreEqual(16, vulnerability.LineNumber); }
public void Logging() { CsFile csFile = GetCsFile("Logging.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(7, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("Logging", vulnerability.Code); Assert.AreEqual("Logging was found", vulnerability.Title); Assert.AreEqual("Logging was found in the app: Log.Verbose(...). Other apps may read the logs.", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "Logging", "Logging.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.Logging", vulnerability.FullyQualifiedName); Assert.AreEqual(17, vulnerability.LineNumber); }
public void WebViewJavaScriptEnabled() { CsFile csFile = GetCsFile("WebViewJavaScriptEnabled.cs"); _analyzer.Analyze(csFile); Assert.AreEqual(1, _vulnerabilities.Count); Vulnerability vulnerability = _vulnerabilities[0]; Assert.AreEqual("JavaScriptEnabled", vulnerability.Code); Assert.AreEqual("JavaScript enabled in WebView", vulnerability.Title); Assert.AreEqual("Enabling JavaScript in a WebView opens the door to XSS attacks.", vulnerability.Description); string expectedPath = Path.Combine("TestFiles", "JavaScriptEnabled", "WebViewJavaScriptEnabled.cs"); Assert.AreEqual(expectedPath, vulnerability.FilePath); Assert.AreEqual("BankingApp.TestFiles.WebViewJavaScriptEnabled", vulnerability.FullyQualifiedName); Assert.AreEqual(17, vulnerability.LineNumber); }
public override void Analyze(CsFile csFile) { var accessExpressions = csFile.GetUnit().DescendantNodes().OfType <MemberAccessExpressionSyntax>(); var vulnerabilities = accessExpressions .Where(IsLogMethod) .Select(expression => new Vulnerability { Code = "Logging", Title = "Logging was found", Description = $"Logging was found in the app: Log.{GetMethodName(expression)}(...). Other apps may read the logs.", FilePath = csFile.FilePath, FullyQualifiedName = QualifiedNameResolver.Resolve(expression), LineNumber = expression.GetLocation().GetLineSpan().StartLinePosition.Line + 1 }).ToList(); vulnerabilities.ForEach(OnVulnerabilityDiscovered); }
public override void Analyze(CsFile csFile) { var accessExpressions = csFile.GetUnit().DescendantNodes().OfType <MemberAccessExpressionSyntax>(); var vulnerabilities = accessExpressions .Where(expression => expression.ToString() == WorldReadableMode) .Select(expression => new Vulnerability { Code = "WorldReadable", Title = "WorldReadable file found", Description = $"A WorldReadable file may expose sensitive data to other apps.", FilePath = csFile.FilePath, FullyQualifiedName = QualifiedNameResolver.Resolve(expression), LineNumber = expression.GetLocation().GetLineSpan().StartLinePosition.Line + 1 }).ToList(); vulnerabilities.ForEach(OnVulnerabilityDiscovered); }
/// <summary> /// generiert den Code vom schnelleren Dictionary-Ersatz /// </summary> /// <param name="projectName">Name/Namespace des Projektes</param> /// <returns>fertig zusammengestellte Cs-Datei</returns> public static CsFile GenDictionaryFastCrc(string projectName) { var csDictFast = new CsFile(); #region # // --- using *.* --- csDictFast.Write(); csDictFast.Write(); csDictFast.Write("#region # using *.*"); csDictFast.Write(); csDictFast.Write("using System;"); csDictFast.Write("using System.Runtime.CompilerServices;"); csDictFast.Write(); csDictFast.Write("// ReSharper disable UnusedMember.Global"); csDictFast.Write(); csDictFast.Write("#endregion"); csDictFast.Write(); csDictFast.Write(); #endregion csDictFast.Write("namespace " + projectName, ns => { ns.Write("sealed class DictionaryFastCrc<TValue> where TValue : struct", cl => { cl.Write("private int[] buckets = new int[1];"); cl.Write("private ulong bucketsMask;"); cl.Write("private Entry[] entries = new Entry[1];"); cl.Write("private int count;"); cl.Write("private int freeList;"); cl.Write("private int freeCount;"); cl.Write("internal int Count { get { return count - freeCount; } }"); cl.Write("public TValue this[ulong key]", th => { th.Write("get", g => { g.Write("int entry = FindEntry(key);"); g.Write("if (entry >= 0) return entries[entry].value;"); g.Write("throw new Exception(\"key not found\");"); }); th.Write("set { Insert(key, value, false); }"); }); cl.Write(); cl.Write("internal DictionaryFastCrc(int capacity = 1) { Initialize(Math.Max(1, capacity)); }"); cl.Write(); cl.Write("internal void Add(ulong key, TValue value) { Insert(key, value, true); }"); cl.Write(); cl.Write("public void Clear()", f => { f.Write("if (count <= 0) return;"); f.Write("Array.Clear(buckets, 0, buckets.Length);"); f.Write("Array.Clear(entries, 0, count);"); f.Write("freeList = -1;"); f.Write("count = 0;"); f.Write("freeCount = 0;"); }); cl.Write(); cl.Write("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); cl.Write("internal bool ContainsKey(ulong key)", f => { f.Write("for (int index = buckets[key & bucketsMask]; index != 0; index = entries[index].next) if (entries[index].key == key) return true;"); f.Write("return false;"); }); cl.Write(); cl.Write("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); cl.Write("private int FindEntry(ulong key)", f => { f.Write("for (int index = buckets[key & bucketsMask]; index != 0; index = entries[index].next) if (entries[index].key == key) return index;"); f.Write("return -1;"); }); cl.Write(); cl.Write("static int GetDouble(int min)", f => { f.Write("int dub = 1;"); f.Write("while (dub < min) dub *= 2;"); f.Write("return dub;"); }); cl.Write(); cl.Write("private void Initialize(int capacity)", f => { f.Write("int prime = GetDouble(capacity);"); f.Write("buckets = new int[prime];"); f.Write("bucketsMask = (ulong)(buckets.Length - 1);"); f.Write("entries = new Entry[prime];"); f.Write("freeList = -1;"); }); cl.Write(); cl.Write("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); cl.Write("private void Insert(ulong key, TValue value, bool add)", f => { f.Write("var index1 = key & bucketsMask;"); f.Write("int num2 = 0;"); f.Write("for (int index2 = buckets[index1]; index2 != 0; index2 = entries[index2].next)", fr => { fr.Write("if (entries[index2].key == key)", i => { i.Write("if (add) throw new ArgumentException();"); i.Write("entries[index2].value = value;"); i.Write("return;"); }); fr.Write("++num2;"); }); f.Write("int index3;"); f.Write("if (freeCount > 0)", i => { i.Write("index3 = freeList;"); i.Write("freeList = entries[index3].next;"); i.Write("--freeCount;"); }); f.Write("else", e => { e.Write("if (count == entries.Length)", i => { i.Write("Resize(GetDouble(count + 1));"); i.Write("index1 = key & bucketsMask;"); }); e.Write("index3 = count;"); e.Write("++count;"); }); f.Write("entries[index3].next = buckets[index1];"); f.Write("entries[index3].key = key;"); f.Write("entries[index3].value = value;"); f.Write("buckets[index1] = index3;"); f.Write("if (num2 <= 100) return;"); f.Write("Resize(entries.Length);"); }); cl.Write(); cl.Write("private static unsafe void ResizeConvert(int* numArray, Entry[] entryArray, int limit)", f => { f.Write("ulong mask = (ulong)entryArray.Length - 1;"); f.Write("if (limit > entryArray.Length) throw new IndexOutOfRangeException();"); f.Write("for (int i = 0; i < limit; i++)", fr => { fr.Write("var index2 = entryArray[i].key & mask;"); fr.Write("entryArray[i].next = numArray[index2];"); fr.Write("numArray[index2] = i;"); }); }); cl.Write(); cl.Write("private unsafe void Resize(int newSize)", f => { f.Write("var numArray = new int[newSize];"); f.Write("var entryArray = new Entry[newSize];"); f.Write("Array.Copy(entries, 0, entryArray, 0, count);"); f.Write("fixed (int* numArrayP = numArray)", fr => { fr.Write("ResizeConvert(numArrayP, entryArray, count);"); }); f.Write("buckets = numArray;"); f.Write("bucketsMask = (ulong)(buckets.Length - 1);"); f.Write("entries = entryArray;"); }); cl.Write(); cl.Write("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); cl.Write("public bool TryGetValue(ulong key, out TValue value)", f => { f.Write("int entry = FindEntry(key);"); f.Write("if (entry >= 0)", i => { i.Write("value = entries[entry].value;"); i.Write("return true;"); }); f.Write("value = default(TValue);"); f.Write("return false;"); }); cl.Write(); cl.Write("private struct Entry", f => { f.Write("public ulong key;"); f.Write("public int next;"); f.Write("public TValue value;"); }); }); }); return csDictFast; }
/// <summary> /// generiert die allgemeinen SokoTools /// </summary> /// <param name="projectName">Name/Namespace des Projektes</param> /// <returns>fertig zusammengestellte Cs-Datei</returns> public static CsFile GenSokoTools(string projectName) { var csSokoTools = new CsFile(); #region # // --- using *.* --- csSokoTools.Write(); csSokoTools.Write(); csSokoTools.Write("#region # using *.*"); csSokoTools.Write(); csSokoTools.Write("using System.Text;"); csSokoTools.Write("using System.Linq;"); csSokoTools.Write("using System.Collections.Generic;"); csSokoTools.Write("using System.Runtime.CompilerServices;"); csSokoTools.Write(); csSokoTools.Write("#endregion"); csSokoTools.Write(); csSokoTools.Write(); #endregion csSokoTools.Write("namespace " + projectName, ns => { ns.Write("static class SokoTools", cl => { #region # // --- IEnumerable<int[]> FieldBoxesVariants(int fieldCount, int boxesCount) --- cl.Write("public static IEnumerable<int[]> FieldBoxesVariants(int fieldCount, int boxesCount)", m => { m.Write("int dif = fieldCount - boxesCount;"); m.Write("int end = boxesCount - 1;"); m.Write(); m.Write("var boxesVariant = new int[boxesCount];"); m.Write(); m.Write("for (int box = 0; ; )", f => { f.Write("while (box < end) boxesVariant[box + 1] = boxesVariant[box++] + 1;"); f.Write("yield return boxesVariant;"); f.Write("while (boxesVariant[box]++ == box + dif) if (--box < 0) yield break;"); }); }); cl.Write(); #endregion #region # // --- Crc64-Tools --- cl.Write("public const ulong CrcStart = 0xcbf29ce484222325u;"); cl.Write("const ulong CrcMul = 0x100000001b3;"); cl.Write(); cl.Write("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); cl.Write("public static ulong CrcCompute(ulong crc64, int value)", crcf => { cl.Write("return (crc64 ^ (uint)value) * CrcMul;"); }); cl.Write(); cl.Write("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); cl.Write("public static ulong CrcCompute(ulong crc64, ushort[] buffer, int ofs, int len)", crcf => { crcf.Write("crc64 ^= buffer[ofs];"); crcf.Write("for (int i = 1; i < len; i++) crc64 = crc64 * CrcMul ^ buffer[i + ofs];"); crcf.Write("return crc64 * CrcMul;"); }); cl.Write(); #endregion #region # // --- TxtView() --- cl.Write("public static string TxtView(char[] fieldData, int fieldWidth, ushort[] fieldTargets, int playerPos)", tx => { tx.Write("var output = new StringBuilder();"); tx.Write("for (int i = 0; i < fieldData.Length - 1; i++)", f => { f.Write("bool target = fieldTargets.Any(x => x == i);"); f.Write("bool player = playerPos == i;"); f.Write("switch (fieldData[i])", sw => { sw.Write("case ' ': output.Append(target ? (player ? '+' : '.') : (player ? '@' : ' ')); break;"); sw.Write("case '#': output.Append('#'); break;"); sw.Write("default: output.Append(target ? '*' : '$'); break;"); }); f.Write("if (i % fieldWidth == fieldWidth - 1) output.AppendLine();"); }); tx.Write("output.Append(fieldData[fieldData.Length - 2]).AppendLine().AppendLine();"); tx.Write("return output.ToString();"); }); #endregion }); }); return csSokoTools; }