System.IO.TextWriter.WriteLine(string)

Here are the examples of the csharp api System.IO.TextWriter.WriteLine(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5861 Examples 7

19 Source : Program.cs
with MIT License
from 0x0ade

private static void LogHeader(TextWriter w) {
            w.WriteLine("CelesteNet.Server");
            w.WriteLine($"Server v.{typeof(CelesteNetServer).replacedembly.GetName().Version}");
            w.WriteLine($"Shared v.{typeof(Logger).replacedembly.GetName().Version}");
            w.WriteLine();
        }

19 Source : Logger.cs
with MIT License
from 0x0ade

public static void Log(LogLevel level, string tag, string str) {
            if (level < Level)
                return;

            TextWriter w = Writer;
            w.Write("(");
            w.Write(DateTime.Now);
            w.Write(LogCelesteNetTag ? ") [CelesteNet] [" : ") [");
            w.Write(level.ToString());
            w.Write("] [");
            w.Write(tag);
            w.Write("] ");
            w.WriteLine(str);
        }

19 Source : Logger.cs
with MIT License
from 0x0ade

public static void LogDetailed(string tag, string str) {
            Log(LogLevel.VVV, tag, str);
            Writer.WriteLine(new StackTrace(1, true).ToString());
        }

19 Source : Logger.cs
with MIT License
from 0x0ade

[MethodImpl(MethodImplOptions.NoInlining)]
        public static void LogDetailed(LogLevel level, string tag, string str) {
            Log(level, tag, str);
            Writer.WriteLine(new StackTrace(1, true).ToString());
        }

19 Source : Logger.cs
with MIT License
from 0x0ade

public static void LogDetailedException(/*this*/ Exception? e, string? tag = null) {
            if (e == null)
                return;

            TextWriter w = Writer;

            if (tag == null) {
                w.WriteLine("--------------------------------");
                w.WriteLine("Detailed exception log:");
            }
            for (Exception? e_ = e; e_ != null; e_ = e_.InnerException) {
                w.WriteLine("--------------------------------");
                w.WriteLine(e_.GetType().FullName + ": " + e_.Message + "\n" + e_.StackTrace);

                switch (e_) {
                    case ReflectionTypeLoadException rtle:
                        if (rtle.Types != null)
                            for (int i = 0; i < rtle.Types.Length; i++)
                                w.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + rtle.Types[i]);
                        if (rtle.LoaderExceptions != null)
                            for (int i = 0; i < rtle.LoaderExceptions.Length; i++)
                                LogDetailedException(rtle.LoaderExceptions[i], tag + (tag == null ? "" : ", ") + "rtle:" + i);
                        break;

                    case TypeLoadException tle:
                        w.WriteLine("TypeLoadException.TypeName: " + tle.TypeName);
                        break;

                    case BadImageFormatException bife:
                        w.WriteLine("BadImageFormatException.FileName: " + bife.FileName);
                        break;
                }
            }
        }

19 Source : patch_Program.cs
with MIT License
from 0x0ade

public static void WriteToLog(string s) {
            Console.Error.WriteLine(s);
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static void Main(string[] args) {
            string inputDir;
            if (args.Length != 1 || !Directory.Exists(inputDir = args[0])) {
                Console.Error.WriteLine("Usage: inputdir");
                return;
            }

            foreach (string path in Directory.GetFiles(inputDir)) {
                Console.WriteLine($"Stripping: {path}");
                Strip(path);
            }
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static void Main(string[] args) {
            // Required for the relative extra paths to work properly.
            if (!File.Exists("MonoMod.RuntimeDetour.dll"))
                Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            string inputDir, outputDir;
            if (args.Length != 2 ||
                !Directory.Exists(inputDir = args[0]) ||
                !Directory.Exists(outputDir = args[1])) {
                Console.Error.WriteLine("Usage: inputdir outputdir");
                return;
            }

            // Check that the files exist.
            if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
                return;
            if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
                return;

            // Strip or copy.
            foreach (string path in Directory.GetFiles(inputDir)) {
                if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
                    Console.WriteLine($"Copying: {path}");
                    File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
                    continue;
                }

                Console.WriteLine($"Stripping: {path}");
                Stripper.Strip(path);
            }

            // Generate hooks.
            string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
            string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
            GenHooks(inputXNA, hooksXNA);
            GenHooks(inputFNA, hooksFNA);

            // Merge generated .dlls and MonoMod into one .dll per environment.
            string[] extrasMod = {
                "TerrariaHooks.dll",
                "MonoMod.exe",
                "MonoMod.RuntimeDetour.dll",
                "MonoMod.Utils.dll"
            };
            Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
            File.Delete(hooksXNA);
            Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
            File.Delete(hooksFNA);
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static bool VerifyFile(out string path, params string[] paths) {
            path = Path.Combine(paths);
            if (!File.Exists(path) && !Directory.Exists(path)) {
                Console.Error.WriteLine($"Missing: {path}");
                return false;
            }
            return true;
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static void Repack(string input, string[] extras, string output, string name = null) {
            Console.Error.WriteLine($"Repacking: {input} -> {output}");
            if (name == null)
                name = Path.GetFileName(output);

            string outputTmp = Path.Combine(Path.GetDirectoryName(output), name);
            if (File.Exists(outputTmp))
                File.Delete(outputTmp);

            List<string> args = new List<string>();
            args.Add($"/out:{outputTmp}");
            args.Add(input);
            foreach (string dep in extras)
                if (!string.IsNullOrWhiteSpace(dep))
                    args.Add(dep.Trim());

            RepackOptions options = new RepackOptions(args);
            ILRepack repack = new ILRepack(options);
            repack.Repack();

            if (output != outputTmp) {
                if (File.Exists(output))
                    File.Delete(output);
                File.Move(outputTmp, output);
            }
        }

19 Source : Program.cs
with zlib License
from 0x0ade

public static void Main(string[] args) {
            XnaToFnaUtil xtf = new XnaToFnaUtil();

            Console.WriteLine($"XnaToFna {XnaToFnaUtil.Version}");
            Console.WriteLine($"using MonoMod {MonoModder.Version}");

            bool showHelp = false;
            bool showVersion = false;
            bool relinkOnly = false;

            OptionSet options = new OptionSet {
                { "h|help", "Show this message and exit.", v => showHelp = v != null },
                { "v|version", "Show the version and exit.", v => showVersion = v != null },
                { "profile=", "Choose between multiple base profiles:\ndefault, minimal, forms", v => {
                    switch (v.ToLowerInvariant()) {
                        case "default":
                            xtf.HookCompat = true;
                            xtf.HookHacks = true;
                            xtf.HookEntryPoint = false;
                            xtf.HookLocks = false;
                            xtf.FixOldMonoXML = false;
                            xtf.HookBinaryFormatter = true;
                            xtf.HookReflection = true;
                            break;

                        case "minimal":
                            xtf.HookCompat = false;
                            xtf.HookHacks = false;
                            xtf.HookEntryPoint = false;
                            xtf.HookLocks = false;
                            xtf.FixOldMonoXML = false;
                            xtf.HookBinaryFormatter = false;
                            xtf.HookReflection = false;
                            break;

                        case "forms":
                            xtf.HookCompat = true;
                            xtf.HookHacks = false;
                            xtf.HookEntryPoint = true;
                            xtf.HookLocks = false;
                            xtf.FixOldMonoXML = false;
                            xtf.HookBinaryFormatter = false;
                            xtf.HookReflection = false;
                            break;
                    }
                } },

                { "relinkonly=", "Only read and write the replacedemblies listed.", (bool v) => relinkOnly = v },

                { "hook-compat=", "Toggle Forms and P/Invoke compatibility hooks.", (bool v) => xtf.HookCompat = v },
                { "hook-hacks=", "Toggle some hack hooks, f.e.\nXNATOFNA_DISPLAY_FULLSCREEN", (bool v) => xtf.HookEntryPoint = v },
                { "hook-locks=", "Toggle if locks should be \"destroyed\" or not.", (bool v) => xtf.HookLocks = v },
                { "hook-oldmonoxml=", "Toggle basic XML serialization fixes.\nPlease try updating mono first!", (bool v) => xtf.FixOldMonoXML = v },
                { "hook-binaryformatter=", "Toggle BinaryFormatter-related fixes.", (bool v) => xtf.HookBinaryFormatter = v },
                { "hook-reflection=", "Toggle reflection-related fixes.", (bool v) => xtf.HookBinaryFormatter = v },
                { "hook-patharg=", "Hook the given method to receive fixed paths.\nCan be used multiple times.", v => xtf.FixPathsFor.Add(v) },

                { "ilplatform=", "Choose the target IL platform:\nkeep, x86, x64, anycpu, x86pref", v => xtf.PreferredPlatform = ParseEnum(v, ILPlatform.Keep) },
                { "mixeddeps=", "Choose the action performed to mixed dependencies:\nkeep, stub, remove", v => xtf.MixedDeps = ParseEnum(v, MixedDepAction.Keep) },
                { "removepublickeytoken=", "Remove the public key token of a dependency.\nCan be used multiple times.", v => xtf.DestroyPublicKeyTokens.Add(v) },
            };

            void WriteHelp(TextWriter writer) {
                writer.WriteLine("Usage: <mono> XnaToFna.exe [options] <--> FileOrDir <FileOrDir> <...>");
                options.WriteOptionDescriptions(writer);
            }

            List<string> extra;
            try {
                extra = options.Parse(args);
            } catch (OptionException e) {
                Console.Error.Write("Command parse error: ");
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine();
                WriteHelp(Console.Error);
                return;
            }

            if (showVersion) {
                return;
            }

            if (showHelp) {
                WriteHelp(Console.Out);
                return;
            }

            foreach (string arg in extra)
                xtf.ScanPath(arg);

            if (!relinkOnly && !Debugger.IsAttached) // Otherwise catches XnaToFna.vshost.exe
                xtf.ScanPath(Directory.GetCurrentDirectory());

            xtf.OrderModules();

            xtf.RelinkAll();

            xtf.Log("[Main] Done!");

            if (Debugger.IsAttached) // Keep window open when running in IDE
                Console.ReadKey();
        }

19 Source : ILogger.cs
with MIT License
from 0x1000000

public void LogNormal(string message)
        {
            if (this.IsNormalOrHigher)
            {
                this._out.WriteLine(message);
            }
        }

19 Source : ILogger.cs
with MIT License
from 0x1000000

public void LogDetailed(string message)
        {
            if (this.IsDetailed)
            {
                this._out.WriteLine(message);
            }
        }

19 Source : Program.cs
with MIT License
from 0x1000000

private static int Run<TOpts>(TOpts opts, Func<TOpts,Task> task)
        {
            try
            {
                task(opts).Wait();
                return 0;
            }
            catch (SqExpressCodeGenException e)
            {
                Console.WriteLine(e.Message);
                return 1;
            }
            catch (AggregateException e) when (e.InnerException is SqExpressCodeGenException sqExpressCodeGenException)
            {
                Console.Error.WriteLine(sqExpressCodeGenException.Message);
                return 1;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Unhandled Exception: ");
                Console.Error.WriteLine(e);
                return 1;
            }
        }

19 Source : ILogger.cs
with MIT License
from 0x1000000

public void LogMinimal(string message)
        {
            if (this.IsMinimalOrHigher)
            {
                this._out.WriteLine(message);
            }
        }

19 Source : Program.cs
with MIT License
from 0x1000000

public static int Main(string[] args)
        {
            try
            {
                var parser = new Parser(with =>
                {
                    with.CaseInsensitiveEnumValues = true;
                    with.CaseSensitive = false;
                    with.AutoHelp = true;
                    with.AutoVersion = true;
                    with.HelpWriter = Console.Error;
                });

                return parser.ParseArguments<GenTablesOptions, GenModelsOptions>(args)
                    .MapResult(
                        (GenTablesOptions opts) => Run(opts, RunGenTablesOptions),
                        (GenModelsOptions opts) => Run(opts, RunGenModelsOptions),
                        errs => 1);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Command line parser exception: ");
                Console.Error.WriteLine(e);
                return 1;
            }
        }

19 Source : Disassembler.cs
with MIT License
from 0xd4d

public void Disreplacedemble(Formatter formatter, TextWriter output, DisasmInfo method) {
			formatterOutput.writer = output;
			targets.Clear();
			sortedTargets.Clear();

			bool uppercaseHex = formatter.Options.UppercaseHex;

			output.Write(commentPrefix);
			output.WriteLine("================================================================================");
			output.Write(commentPrefix);
			output.WriteLine(method.MethodFullName);
			uint codeSize = 0;
			foreach (var info in method.Code)
				codeSize += (uint)info.Code.Length;
			var codeSizeHexText = codeSize.ToString(uppercaseHex ? "X" : "x");
			output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes");
			var instrCount = method.Instructions.Count;
			var instrCountHexText = instrCount.ToString(uppercaseHex ? "X" : "x");
			output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions");

			void Add(ulong address, TargetKind kind) {
				if (!targets.TryGetValue(address, out var addrInfo))
					targets[address] = new AddressInfo(kind);
				else if (addrInfo.Kind < kind)
					addrInfo.Kind = kind;
			}
			if (method.Instructions.Count > 0)
				Add(method.Instructions[0].IP, TargetKind.Unknown);
			foreach (ref var instr in method.Instructions) {
				switch (instr.FlowControl) {
				case FlowControl.Next:
				case FlowControl.Interrupt:
					break;

				case FlowControl.UnconditionalBranch:
					Add(instr.NextIP, TargetKind.Unknown);
					if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
						Add(instr.NearBranchTarget, TargetKind.Branch);
					break;

				case FlowControl.ConditionalBranch:
				case FlowControl.XbeginXabortXend:
					if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
						Add(instr.NearBranchTarget, TargetKind.Branch);
					break;

				case FlowControl.Call:
					if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
						Add(instr.NearBranchTarget, TargetKind.Call);
					break;

				case FlowControl.IndirectBranch:
					Add(instr.NextIP, TargetKind.Unknown);
					// Unknown target
					break;

				case FlowControl.IndirectCall:
					// Unknown target
					break;

				case FlowControl.Return:
				case FlowControl.Exception:
					Add(instr.NextIP, TargetKind.Unknown);
					break;

				default:
					Debug.Fail($"Unknown flow control: {instr.FlowControl}");
					break;
				}

				var baseReg = instr.MemoryBase;
				if (baseReg == Register.RIP || baseReg == Register.EIP) {
					int opCount = instr.OpCount;
					for (int i = 0; i < opCount; i++) {
						if (instr.GetOpKind(i) == OpKind.Memory) {
							if (method.Contains(instr.IPRelativeMemoryAddress))
								Add(instr.IPRelativeMemoryAddress, TargetKind.Branch);
							break;
						}
					}
				}
				else if (instr.MemoryDisplSize >= 2) {
					ulong displ;
					switch (instr.MemoryDisplSize) {
					case 2:
					case 4: displ = instr.MemoryDisplacement; break;
					case 8: displ = (ulong)(int)instr.MemoryDisplacement; break;
					default:
						Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}");
						goto case 8;
					}
					if (method.Contains(displ))
						Add(displ, TargetKind.Branch);
				}
			}
			foreach (var map in method.ILMap) {
				if (targets.TryGetValue(map.nativeStartAddress, out var info)) {
					if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown)
						info.Kind = TargetKind.BlockStart;
				}
				else
					targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown));
				if (info.ILOffset < 0)
					info.ILOffset = map.ilOffset;
			}

			int labelIndex = 0, methodIndex = 0;
			string GetLabel(int index) => LABEL_PREFIX + index.ToString();
			string GetFunc(int index) => FUNC_PREFIX + index.ToString();
			foreach (var kv in targets) {
				if (method.Contains(kv.Key))
					sortedTargets.Add(kv);
			}
			sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key));
			foreach (var kv in sortedTargets) {
				var address = kv.Key;
				var info = kv.Value;

				switch (info.Kind) {
				case TargetKind.Unknown:
					info.Name = null;
					break;

				case TargetKind.Data:
					info.Name = GetLabel(labelIndex++);
					break;

				case TargetKind.BlockStart:
				case TargetKind.Branch:
					info.Name = GetLabel(labelIndex++);
					break;

				case TargetKind.Call:
					info.Name = GetFunc(methodIndex++);
					break;

				default:
					throw new InvalidOperationException();
				}
			}

			foreach (ref var instr in method.Instructions) {
				ulong ip = instr.IP;
				if (targets.TryGetValue(ip, out var lblInfo)) {
					output.WriteLine();
					if (!(lblInfo.Name is null)) {
						output.Write(lblInfo.Name);
						output.Write(':');
						output.WriteLine();
					}
					if (lblInfo.ILOffset >= 0) {
						if (ShowSourceCode) {
							foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) {
								output.Write(commentPrefix);
								var line = info.Line;
								int column = commentPrefix.Length;
								WriteWithTabs(output, line, 0, line.Length, '\0', ref column);
								output.WriteLine();
								if (info.Partial) {
									output.Write(commentPrefix);
									column = commentPrefix.Length;
									WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column);
									output.WriteLine(new string('^', info.Span.Length));
								}
							}
						}
					}
				}

				if (ShowAddresses) {
					var address = FormatAddress(bitness, ip, uppercaseHex);
					output.Write(address);
					output.Write(" ");
				}
				else
					output.Write(formatter.Options.TabSize > 0 ? "\t\t" : "        ");

				if (ShowHexBytes) {
					if (!method.TryGetCode(ip, out var nativeCode))
						throw new InvalidOperationException();
					var codeBytes = nativeCode.Code;
					int index = (int)(ip - nativeCode.IP);
					int instrLen = instr.Length;
					for (int i = 0; i < instrLen; i++) {
						byte b = codeBytes[index + i];
						output.Write(b.ToString(uppercaseHex ? "X2" : "x2"));
					}
					int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen;
					for (int i = 0; i < missingBytes; i++)
						output.Write("  ");
					output.Write(" ");
				}

				formatter.Format(instr, formatterOutput);
				output.WriteLine();
			}
		}

19 Source : Log.cs
with MIT License
from 13xforever

private static void LogInternal(Exception e, string message, LogLevel level, ConsoleColor foregroundColor, ConsoleColor? backgroundColor = null)
        {
            try
            {
#if DEBUG
                const LogLevel minLevel = LogLevel.TRACE;
#else
                const LogLevel minLevel = LogLevel.DEBUG;
#endif
                if (level >= minLevel && message != null)
                {
                    Console.ForegroundColor = foregroundColor;
                    if (backgroundColor is ConsoleColor bg)
                        Console.BackgroundColor = bg;
                    Console.WriteLine(DateTime.Now.ToString("hh:mm:ss ") + message);
                    Console.ResetColor();
                }
                if (FileLog != null)
                {
                    if (message != null)
                        FileLog.WriteLine($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}\t{(long)Timer.Elapsed.TotalMilliseconds}\t{level}\t{message}");
                    if (e != null)
                        FileLog.WriteLine(e.ToString());
                    FileLog.Flush();
                }
            }
            catch { }
        }

19 Source : DotNetToJScript.cs
with MIT License
from 1y0n

static void WriteColor(string str, ConsoleColor color)
        {
            ConsoleColor old_color = Console.ForegroundColor;
            Console.ForegroundColor = color;
            try
            {
                Console.Error.WriteLine(str);
            }
            finally
            {
                Console.ForegroundColor = old_color;
            }
        }

19 Source : Common.cs
with MIT License
from 1y0n

public static string Execute_Cmd(string cmd)
        {
            string output = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;

            //获取cmd窗口的输出信息
            output = p.StandardOutput.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
            return output;
        }

19 Source : VMFAdapter.cs
with MIT License
from 1upD

public void Export(NailsMap map)
        {
            try
            {

            log.Info(string.Format("Exporting Nails map data to VMF file: {0}", this._filename));

            // Make a deep copy of the stored VMF to add instances to
            VMF output_vmf = new VMFParser.VMF(this._vmf.ToVMFStrings());
            int i = 0;

            foreach(NailsCube cube in map.NailsCubes)
            {
                int x_pos = cube.X * this._horizontal_scale;
                int y_pos = cube.Y * this._horizontal_scale;
                int z_pos = cube.Z * this._vertical_scale;

                var faces = cube.GetFaces();

                if (faces.Contains(NailsCubeFace.Floor))
                {
                    instanceData instance = this.MakeInstance("floor", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Front))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Left))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 90, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Back))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 180, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Right))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 270, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Ceiling))
                {
                    instanceData instance = this.MakeInstance("ceiling", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }
            }


            using (StreamWriter sw = new StreamWriter(new FileStream(this._filename, FileMode.Create)))
            {
                var vmfStrings = output_vmf.ToVMFStrings();
                foreach (string line in vmfStrings)
                {
                    sw.WriteLine(line);
                }
            }

            log.Info(string.Format("Wrote to VMF file: {0}", this._filename));

            } catch (Exception e)
            {
                log.Error("VMFAdapter.Export(): Caught exception: ", e);
                log.Info(string.Format("Failed to write to VMF file: {0}", this._filename));
            }


        }

19 Source : Command.cs
with Apache License 2.0
from 214175590

public static CmdResult run(String cmd)
        {
            CmdResult result = new CmdResult();
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;
            //p.StandardInput.WriteLine("exit");
            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

            //获取cmd窗口的输出信息
            result.result = p.StandardOutput.ReadToEnd();
            result.error = p.StandardError.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();

            return result;
        }

19 Source : ConsoleApp.cs
with MIT License
from 2881099

public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
			if (bat == null || bat.Any() == false) return ("", "", "");
            if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
			var proc = new System.Diagnostics.Process();
			proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
				CreateNoWindow = true,
				FileName = "cmd.exe",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				RedirectStandardOutput = true,
				WorkingDirectory = cddir
			};
			proc.Start();
			foreach (var cmd in bat)
				proc.StandardInput.WriteLine(cmd);
			proc.StandardInput.WriteLine("exit");
			var outStr = proc.StandardOutput.ReadToEnd();
			var errStr = proc.StandardError.ReadToEnd();
			proc.Close();
			var idx = outStr.IndexOf($">{bat[0]}");
			if (idx != -1) {
				idx = outStr.IndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Substring(idx + 1);
			}
			idx = outStr.LastIndexOf(">exit");
			if (idx != -1) {
				idx = outStr.LastIndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Remove(idx);
			}
			outStr = outStr.Trim();
			if (outStr == "") outStr = null;
			if (errStr == "") errStr = null;
			return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
		}

19 Source : Utils.cs
with GNU General Public License v3.0
from 2dust

public static void SaveLog(string strreplacedle, Exception ex)
        {
            try
            {
                string path = Path.Combine(StartupPath(), "guiLogs");
                string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!File.Exists(FilePath))
                {
                    FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
                    FsCreate.Close();
                    FsCreate.Dispose();
                }
                FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
                StreamWriter SwWrite = new StreamWriter(FsWrite);

                string strContent = ex.ToString();

                SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
                SwWrite.Write(strContent);
                SwWrite.WriteLine(Environment.NewLine);
                SwWrite.WriteLine(" ");
                SwWrite.Flush();
                SwWrite.Close();
            }
            catch { }
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void Main(string[] args)
        {

            int ruleCount = 0;
            int gradientMax = 0;
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(o =>
                {
                    LoadConfig(o);
                    if (!o.Suricata)
                    {
                        LoadMismatchSearchMatrix(o);
                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
                        {
                            try
                            {
                                var dict = DeserializeYamlFile(ruleFilePath, o);
                                if (dict != null && dict.ContainsKey("tags"))
                                {
                                    ruleCount++;
                                    var tags = dict["tags"];
                                    var categories = new List<string>();
                                    string lastEntry = null;
                                    foreach (string tag in tags)
                                    {
                                        //If its the technique id entry, then this adds the file name to the techniques map
                                        if (tag.ToLower().StartsWith("attack.t"))
                                        {
                                            var techniqueId = tag.Replace("attack.", "").ToUpper();
                                            if (!techniques.ContainsKey(techniqueId))
                                                techniques[techniqueId] = new List<string>();
                                            techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
                                            if (techniques.Count > gradientMax)
                                                gradientMax = techniques.Count;
                                            //then if there are any categories so far, it checks for a mismatch for each one
                                            if (categories.Count > 0 && o.Warning)
                                            {
                                                foreach (string category in categories)
                                                    if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
                                                        mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
                                            }
                                        }
                                        else
                                        {
                                            //if its the start of a new technique block, then clean categories and adds first category
                                            if (lastEntry == null || lastEntry.StartsWith("attack.t"))
                                                categories = new List<string>();
                                            categories.Add(
                                                tag.Replace("attack.", "")
                                                .Replace("_", "-")
                                                .ToLower());
                                        }
                                        lastEntry = tag;
                                    }
                                }
                            }
                            catch (YamlException e)
                            {
                                Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
                            }
                        }

                        WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
                        PrintWarnings();
                    }
                    else
                    {

                        List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();

                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
                        {
                            res.Add(ParseRuleFile(ruleFilePath));
                        }

                        WriteSuricataFileResult(o,
                            res
                                .SelectMany(dict => dict)
                                .ToLookup(pair => pair.Key, pair => pair.Value)
                                .ToDictionary(group => group.Key,
                                              group => group.SelectMany(list => list).ToList()));
                    }

                });
        }

19 Source : SlnWriter.cs
with MIT License
from 3F

protected virtual void Write(string raw)
        {
            stream.WriteLine(raw);
        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void RecordLog(string message)
        {
            if (Log != null)
            {
                try
                {
                    Log.WriteLine(message);
                }
                catch { throw; }
            }
        }

19 Source : Program.cs
with MIT License
from 5argon

static void Gen1(int tag, int scd)
        {
            if (tag == 0 && scd == 0) return;

            for (int whereable = 0; whereable <= tag; whereable++)
            {
                //Every time there is an scd, gen a no filter, and filtered (1,2) version.
                for (int ft = 0; ft < scd + 1; ft++)
                {
                    List<string> componentTypes = new List<string>();
                    List<string> whereableTypes = new List<string>();
                    List<string> whereableUsings = new List<string>();
                    List<string> whereableWhere = new List<string>();
                    List<string> scds = new List<string>();
                    List<string> args = new List<string>();
                    List<string> argsForward = new List<string>();
                    List<string> argsFilter = new List<string>();
                    for (int i = 0; i < tag; i++)
                    {
                        componentTypes.Add($"CD{i + 1}");
                        if (i < whereable)
                        {
                            whereableTypes.Add($"CD{i + 1}");
                            whereableUsings.Add($"using(var cd{i + 1}Cda = eq.ToComponentDataArray<CD{i + 1}>(Allocator.TempJob))");
                            whereableWhere.Add($"cd{i + 1}Cda[i]");
                        }
                    }
                    if (whereable != 0)
                    {
                        args.Add($"Func<{string.Join(",", whereableTypes)}, bool> where");
                        argsForward.Add("where");
                    }
                    for (int i = 0; i < scd; i++)
                    {
                        componentTypes.Add($"SCD{i + 1}");
                        if (i >= ft)
                        {
                            scds.Add($"filter{i + 1}");
                            args.Add($"SCD{i + 1} filter{i + 1}");
                            argsForward.Add($"filter{i + 1}");
                        }
                        else
                        {
                            args.Add($"bool nf{(scd > 1 ? (i + 1).ToString() : string.Empty)}");
                            argsForward.Add($"nf{(scd > 1 ? (i + 1).ToString() : string.Empty)}");
                        }
                    }
                    string typeHor = string.Join(",", componentTypes);
                    string argsString = scd > 0 || whereable > 0 ? string.Join(",", args) : string.Empty;
                    string wheres = string.Join("\n", componentTypes.Select(x =>
                    {
                        if (x.Contains("SCD"))
                        {
                            return $"where {x} : struct, ISharedComponentData";
                        }
                        else
                        {
                            return $"where {x} : struct, IComponentData";
                        }
                    }));
                    string typeVert = string.Join(",\n", componentTypes.Select(x => $"ComponentType.ReadOnly<{x}>()"));
                    string filters = scd > 0 && ft != scd ?
                    $"eq.SetSharedComponentFilter({string.Join(",", scds)});"
                    : string.Empty;

                    if (whereable == 0)
                    {
                        if (tag != 0)
                        {
                            Do(gsGetSingleton);
                        }
                        else
                        {
                            Do(gsGetSingletonScdFirst);
                        }

                        if (tag != 0)
                        {
                            Do(gsGet);
                        }
                    }

                    Do(gsGetSingletonEnreplacedy);
                    Do(gsEnreplacedyCount);
                    Do(gsEnreplacedies);

                    void Do(string tem)
                    {
                        sw.WriteLine(tem
                            .Replace("<<MAIN>>", componentTypes[0])
                            .Replace("<<NOFILTER>>", string.Empty)
                            .Replace("<<TYPEHOR>>", typeHor)
                            .Replace("<<ARGS>>", argsString)
                            .Replace("<<ARGSFORWARD>>", string.Join(",",argsForward))
                            .Replace("<<WHERE>>", wheres)
                            .Replace("<<TYPEVERT>>", typeVert)
                            .Replace("<<FILTER>>", filters)
                            .Replace("<<WHEREABLES>>", whereable == 0 ? string.Empty : whereableCheck.Replace("<<WHEREABLEUSINGS>>", string.Join("\n", whereableUsings)).Replace("<<WHEREABLEWHERE>>", string.Join(",", whereableWhere)))
                        );
                    }
                }
            }
        }

19 Source : DebugProgramTemplate.cs
with MIT License
from 71

public static int Main(string[] args)
    {
        try
        {
            Diagnosticreplacedyzer replacedyzer = new Cometaryreplacedyzer();
            CSharpParseOptions parseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "DEBUGGING" });

            if (IsWrittenToDisk && ShouldBreakAtStart)
                Debugger.Break();

            CompilationWithreplacedyzers compilation = CSharpCompilation.Create(
                replacedemblyName + "+Debugging",
                Files.Split(';').Select(x => CSharpSyntaxTree.ParseText(File.ReadAllText(x), parseOptions)),
                References.Split(';').Select(x => MetadataReference.CreateFromFile(x))
            ).Withreplacedyzers(ImmutableArray.Create(replacedyzer));

            ExecuteAsync(compilation).Wait();

            return 0;
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e.Message);
            Console.Error.WriteLine();
            Console.Error.WriteLine(e.StackTrace);

            Console.ReadKey();

            return 1;
        }
    }

19 Source : Program.cs
with MIT License
from 71

public static int Main(string[] args)
        {
            string ns = null;
            string dir = Directory.GetCurrentDirectory();
            string output = Path.Combine(Directory.GetCurrentDirectory(), OUTPUT_FILENAME);
            bool makePublic = false;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "--public":
                    case "-p":
                        makePublic = true;
                        break;
                    case "--namespace":
                    case "-n":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No namespace given.");
                            return 1;
                        }

                        ns = args[++i];
                        break;
                    case "--directory":
                    case "-d":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No directory given.");
                            return 1;
                        }

                        dir = args[++i];
                        break;
                    case "--output":
                    case "-o":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No directory given.");
                            return 1;
                        }

                        output = args[++i];
                        break;
                    default:
                        Console.Error.WriteLine($"Unknown argument: '{args[i]}'.");
                        return 1;
                }
            }

            string methodRedirectionPath = Path.Combine(dir, "Redirection.Method.cs");
            string helpersPath = Path.Combine(dir, "Helpers.cs");

            if (!File.Exists(methodRedirectionPath) || !File.Exists(helpersPath))
            {
                Console.Error.WriteLine("Invalid directory given.");
                return 1;
            }

            try
            {
                // Read files
                string methodRedirectionContent = File.ReadAllText(methodRedirectionPath);
                string helpersContent = File.ReadAllText(helpersPath);

                // Parse content to trees, and get their root / clreplacedes / usings
                SyntaxTree methodRedirectionTree = SyntaxFactory.ParseSyntaxTree(methodRedirectionContent, path: methodRedirectionPath);
                SyntaxTree helpersTree = SyntaxFactory.ParseSyntaxTree(helpersContent, path: helpersPath);

                CompilationUnitSyntax methodRedirection = methodRedirectionTree.GetCompilationUnitRoot();
                CompilationUnitSyntax helpers = helpersTree.GetCompilationUnitRoot();

                UsingDirectiveSyntax[] usings = methodRedirection.Usings.Select(x => x.Name.ToString())
                    .Concat(helpers.Usings.Select(x => x.Name.ToString()))
                    .Distinct()
                    .OrderBy(x => x)
                    .Select(x => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(x)))
                    .ToArray();

                ClreplacedDeclarationSyntax methodRedirectionClreplaced = methodRedirection.DescendantNodes()
                                                                                 .OfType<ClreplacedDeclarationSyntax>()
                                                                                 .First();
                ClreplacedDeclarationSyntax helpersClreplaced = helpers.DescendantNodes()
                                                             .OfType<ClreplacedDeclarationSyntax>()
                                                             .First();

                // Set visibility of main clreplaced
                if (!makePublic)
                {
                    var modifiers = methodRedirectionClreplaced.Modifiers;
                    var publicModifier = modifiers.First(x => x.Kind() == SyntaxKind.PublicKeyword);

                    methodRedirectionClreplaced = methodRedirectionClreplaced.WithModifiers(
                        modifiers.Replace(publicModifier, SyntaxFactory.Token(SyntaxKind.InternalKeyword))
                    );
                }

                // Set visibility of helpers clreplaced
                helpersClreplaced = helpersClreplaced.WithModifiers(
                    helpersClreplaced.Modifiers.Replace(
                        helpersClreplaced.Modifiers.First(x => x.Kind() == SyntaxKind.InternalKeyword),
                        SyntaxFactory.Token(SyntaxKind.PrivateKeyword)
                    )
                );

                // Change helpers clreplaced extension methods to normal methods
                var extMethods = helpersClreplaced.DescendantNodes()
                                             .OfType<MethodDeclarationSyntax>()
                                             .Where(x => x.ParameterList.DescendantTokens().Any(tok => tok.Kind() == SyntaxKind.ThisKeyword));
                var extMethodsNames = extMethods.Select(x => x.Identifier.Text);

                helpersClreplaced = helpersClreplaced.ReplaceNodes(
                    helpersClreplaced.DescendantNodes().OfType<ParameterSyntax>().Where(x => x.Modifiers.Any(SyntaxKind.ThisKeyword)),
                    (x,_) => x.WithModifiers(x.Modifiers.Remove(x.Modifiers.First(y => y.Kind() == SyntaxKind.ThisKeyword)))
                );

                // Disable overrides
                var members = methodRedirectionClreplaced.Members;

                for (int i = 0; i < members.Count; i++)
                {
                    var member = members[i];

                    if (!(member is MethodDeclarationSyntax method))
                    {
                        if (member is ConstructorDeclarationSyntax ctor)
                            members = members.Replace(ctor, ctor.WithIdentifier(SyntaxFactory.Identifier("Redirection")));

                        continue;
                    }

                    var overrideModifier = method.Modifiers.FirstOrDefault(x => x.Kind() == SyntaxKind.OverrideKeyword);

                    if (overrideModifier == default(SyntaxToken))
                        continue;

                    method = method.WithModifiers(
                        method.Modifiers.Remove(overrideModifier)
                    );

                    members = members.Replace(member, method);
                }

                // Add missing field
                var field = SyntaxFactory.FieldDeclaration(
                    SyntaxFactory.VariableDeclaration(
                        SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
                        SyntaxFactory.SeparatedList(new[] {
                            SyntaxFactory.VariableDeclarator("isRedirecting")
                        })
                    )
                );

                const string DOCS = @"
    /// <summary>
    ///   Provides the ability to redirect calls from one method to another.
    /// </summary>
";

                var disposableType = SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(nameof(IDisposable)));

                methodRedirectionClreplaced = methodRedirectionClreplaced.WithMembers(members)
                    // Add docs
                    .WithLeadingTrivia(SyntaxFactory.Comment(DOCS))
                    // Rename to 'Redirection'
                    .WithIdentifier(SyntaxFactory.Identifier("Redirection"))
                    // Disable inheritance, but implement IDisposable
                    .WithBaseList(SyntaxFactory.BaseList().AddTypes(disposableType))
                    // Embed helpers, missing field
                    .AddMembers(field, helpersClreplaced);

                // Generate namespace (or member, if no namespace is specified)
                MemberDeclarationSyntax @namespace = ns == null
                    ? (MemberDeclarationSyntax)methodRedirectionClreplaced
                    : SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns)).AddMembers(methodRedirectionClreplaced);

                var extCalls = @namespace.DescendantNodes()
                                         .OfType<InvocationExpressionSyntax>()
                                         .Where(x => x.Expression is MemberAccessExpressionSyntax access && extMethodsNames.Contains(access.Name.Identifier.Text));
                var helpersAccess = SyntaxFactory.IdentifierName("Helpers");

                @namespace = @namespace.ReplaceNodes(
                    extCalls,
                    (x, _) => SyntaxFactory.InvocationExpression(((MemberAccessExpressionSyntax)x.Expression).WithExpression(helpersAccess)).WithArgumentList(x.ArgumentList.WithArguments(x.ArgumentList.Arguments.Insert(0, SyntaxFactory.Argument(((MemberAccessExpressionSyntax)x.Expression).Expression)))));

                // Generate syntax root
                CompilationUnitSyntax root = SyntaxFactory.CompilationUnit()
                                                          .AddUsings(usings)
                                                          .AddMembers(@namespace);

                // Print root to file
                using (FileStream fs = File.OpenWrite(output))
                using (TextWriter writer = new StreamWriter(fs))
                {
                    fs.SetLength(0);

                    Formatter.Format(root, new AdhocWorkspace()).WriteTo(writer);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error encountered:");
                Console.Error.WriteLine(e.Message);
                return 1;
            }

            return 0;
        }

19 Source : KissManga.cs
with GNU General Public License v3.0
from 9vult

public override void UpdateDLChapters(String[] chapterNums)
        {
            using (StreamWriter file = new StreamWriter(Path.Combine(mangaRoot.FullName, "cdl.txt")))
            {
                foreach (String num in chapterNums)
                {
                    file.WriteLine(num);
                }
            }
        }

19 Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin

public void InitializeCommunicator()
    {
        Application.logMessageReceived += HandleLog;
        logPath = Path.GetFullPath(".") + "/unity-environment.log";
        logWriter = new StreamWriter(logPath, false);
        logWriter.WriteLine(System.DateTime.Now.ToString());
        logWriter.WriteLine(" ");
        logWriter.Close();
        messageHolder = new byte[messageLength];

        // Create a TCP/IP  socket.  
        sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sender.Connect("localhost", comPort);

        AcademyParameters accParamerters = new AcademyParameters();
        accParamerters.brainParameters = new List<BrainParameters>();
        accParamerters.brainNames = new List<string>();
        accParamerters.externalBrainNames = new List<string>();
        accParamerters.apiNumber = api;
        accParamerters.logPath = logPath;
        foreach (Brain b in brains)
        {
            accParamerters.brainParameters.Add(b.brainParameters);
            accParamerters.brainNames.Add(b.gameObject.name);
            if (b.brainType == BrainType.External)
            {
                accParamerters.externalBrainNames.Add(b.gameObject.name);
            }
        }
        accParamerters.AcademyName = academy.gameObject.name;
        accParamerters.resetParameters = academy.resetParameters;

        SendParameters(accParamerters);
    }

19 Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin

void HandleLog(string logString, string stackTrace, LogType type)
	{
        logWriter = new StreamWriter(logPath, true);
        logWriter.WriteLine(type.ToString());
        logWriter.WriteLine(logString);
        logWriter.WriteLine(stackTrace);
        logWriter.Close();
	}

19 Source : Logger.cs
with MIT License
from aabiryukov

public void Write(LogVerbosity logType, string message)
        {
            if ((int)logType >= (int)Level)
                TextWriter.WriteLine($"{DateTime.Now:hh:mm:ss:fff} | {logType} | {message}");
        }

19 Source : DellFanCmd.cs
with GNU General Public License v3.0
from AaronKelley

public static int ProcessCommand(string[] args)
        {
            int returnCode = 0;

            try
            {
                if (args.Length != 1)
                {
                    Usage();
                }
                else
                {
                    // Behavior variables.
                    bool disableEcFanControl = false;
                    bool enableEcFanControl = false;
                    bool setFansToMax = false;
                    bool useAlternateCommand = false;
                    bool setFanLevel = false;
                    bool getFanRpm = false;
                    bool runTest = false;
                    BzhFanIndex fanSelection = BzhFanIndex.Fan1;
                    BzhFanLevel fanLevel = BzhFanLevel.Level0;

                    // Figure out what was requested.
                    if (args[0] == "ec-disable")
                    {
                        disableEcFanControl = true;
                        setFansToMax = true;
                    }
                    else if (args[0] == "ec-disable-nofanchg")
                    {
                        disableEcFanControl = true;
                    }
                    else if (args[0] == "ec-enable")
                    {
                        enableEcFanControl = true;
                    }
                    else if (args[0] == "ec-disable-alt")
                    {
                        disableEcFanControl = true;
                        setFansToMax = true;
                        useAlternateCommand = true;
                    }
                    else if (args[0] == "ec-disable-alt-nofanchg")
                    {
                        disableEcFanControl = true;
                        useAlternateCommand = true;
                    }
                    else if (args[0] == "ec-enable-alt")
                    {
                        enableEcFanControl = true;
                        useAlternateCommand = true;
                    }
                    else if (args[0] == "fan1-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan1;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan1-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan1;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan1-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan1;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan2-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan2;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan2-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan2;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan2-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan2;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan3-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan3;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan3-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan3;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan3-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan3;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan4-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan4;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan4-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan4;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan4-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan4;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan5-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan5;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan5-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan5;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan5-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan5;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan6-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan6;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan6-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan6;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan6-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan6;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan7-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan7;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan7-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan7;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan7-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan7;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "rpm-fan1")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan1;
                    }
                    else if (args[0] == "rpm-fan2")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan2;
                    }
                    else if (args[0] == "rpm-fan3")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan3;
                    }
                    else if (args[0] == "rpm-fan4")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan4;
                    }
                    else if (args[0] == "rpm-fan5")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan5;
                    }
                    else if (args[0] == "rpm-fan6")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan6;
                    }
                    else if (args[0] == "rpm-fan7")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan7;
                    }
                    else if (args[0] == "test")
                    {
                        runTest = true;
                    }
                    else if (args[0] == "test-alt")
                    {
                        runTest = true;
                        useAlternateCommand = true;
                    }
                    else
                    {
                        Usage();
                        return -3;
                    }

                    // Execute request.

                    // Load driver first.
                    if (LoadDriver())
                    {
                        if (disableEcFanControl)
                        {
                            // Disable EC fan control.
                            Console.WriteLine("Attempting to disable EC control of the fan...");

                            bool success = DellSmbiosBzh.DisableAutomaticFanControl(useAlternateCommand);

                            if (!success)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" ...Success.");

                            if (setFansToMax)
                            {
                                // Crank the fans up, for safety.
                                Console.WriteLine("Setting fan 1 speed to maximum...");
                                success = DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level2);
                                if (!success)
                                {
                                    Console.Error.WriteLine("Failed.");
                                }

                                Console.WriteLine("Setting fan 2 speed to maximum...");
                                success = DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level2);
                                if (!success)
                                {
                                    Console.Error.WriteLine("Failed.  (Maybe your system just has one fan?)");
                                }
                            }
                            else
                            {
                                Console.WriteLine("WARNING: CPU and GPU are not designed to run under load without active cooling.");
                                Console.WriteLine("Make sure that you have alternate fan speed control measures in place.");
                            }
                        }
                        else if (enableEcFanControl)
                        {
                            // Enable EC fan control.
                            Console.WriteLine("Attempting to enable EC control of the fan...");

                            bool success = DellSmbiosBzh.EnableAutomaticFanControl(useAlternateCommand);

                            if (!success)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" ...Success.");
                        }
                        else if (setFanLevel)
                        {
                            // Set the fan to a specific level.
                            Console.WriteLine("Attempting to set the fan level...");
                            bool success = DellSmbiosBzh.SetFanLevel(fanSelection, fanLevel);

                            if (!success)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" ...Success.");
                        }
                        else if (getFanRpm)
                        {
                            // Query the fan RPM.
                            Console.WriteLine("Attempting to query the fan RPM...");
                            uint? result = DellSmbiosBzh.GetFanRpm(fanSelection);

                            if (result == null)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" Result: {0}", result);
                            if (result < int.MaxValue)
                            {
                                returnCode = int.Parse(result.ToString());
                            }
                            else
                            {
                                Console.WriteLine(" (Likely error)");
                                returnCode = -1;
                            }
                        }
                        else if (runTest)
                        {
                            // Test all of the fan levels and report RPMs.

                            uint? rpmIdleFan1;
                            uint? rpmLevel0Fan1;
                            uint? rpmLevel1Fan1;
                            uint? rpmLevel2Fan1;

                            uint? rpmIdleFan2 = null;
                            uint? rpmLevel0Fan2 = null;
                            uint? rpmLevel1Fan2 = null;
                            uint? rpmLevel2Fan2 = null;

                            int sleepInterval = 7500;
                            bool fan2Present = true;

                            // Disable EC fan control.
                            Console.WriteLine("Disabling EC fan control...");
                            DellSmbiosBzh.DisableAutomaticFanControl(useAlternateCommand);

                            // Query current idle fan levels.
                            rpmIdleFan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);
                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level0);

                            rpmIdleFan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);
                            bool success = DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level0);

                            if (!success)
                            {
                                // No fan 2?
                                fan2Present = false;
                                Console.WriteLine("Looks like fan 2 is not present, system only has one fan?");
                            }

                            // Measure fan 1.
                            Console.WriteLine("Measuring: Fan 1, level 0...");
                            Thread.Sleep(sleepInterval);
                            rpmLevel0Fan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);

                            Console.WriteLine("Measuring: Fan 1, level 1..."); 
                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level1);
                            Thread.Sleep(sleepInterval);
                            rpmLevel1Fan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);

                            Console.WriteLine("Measuring: Fan 1, level 2..."); 
                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level2);
                            Thread.Sleep(sleepInterval);
                            rpmLevel2Fan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);

                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level0);

                            if (fan2Present)
                            {
                                // Measure fan 2.
                                Console.WriteLine("Measuring: Fan 2, level 0...");
                                rpmLevel0Fan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);

                                Console.WriteLine("Measuring: Fan 2, level 1..."); 
                                DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level1);
                                Thread.Sleep(sleepInterval);
                                rpmLevel1Fan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);

                                Console.WriteLine("Measuring: Fan 2, level 2..."); 
                                DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level2);
                                Thread.Sleep(sleepInterval);
                                rpmLevel2Fan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);
                            }

                            // Enable EC fan control.
                            Console.WriteLine("Enabling EC fan control...");
                            DellSmbiosBzh.EnableAutomaticFanControl(useAlternateCommand);

                            Console.WriteLine("Test procedure is finished.");
                            Console.WriteLine();
                            Console.WriteLine();

                            // Output results.
                            Console.WriteLine("Fan 1 initial speed: {0}", rpmIdleFan1);
                            if (fan2Present)
                            {
                                Console.WriteLine("Fan 2 initial speed: {0}", rpmIdleFan2);
                            }
                            Console.WriteLine();

                            Console.WriteLine("Fan 1 level 0 speed: {0}", rpmLevel0Fan1);
                            Console.WriteLine("Fan 1 level 1 speed: {0}", rpmLevel1Fan1);
                            Console.WriteLine("Fan 1 level 2 speed: {0}", rpmLevel2Fan1);
                            Console.WriteLine();

                            if (fan2Present)
                            {
                                Console.WriteLine("Fan 2 level 0 speed: {0}", rpmLevel0Fan2);
                                Console.WriteLine("Fan 2 level 1 speed: {0}", rpmLevel1Fan2);
                                Console.WriteLine("Fan 2 level 2 speed: {0}", rpmLevel2Fan2);
                                Console.WriteLine();
                            }
                        }

                        // Unload driver.
                        UnloadDriver();
                    }
                }
            }
            catch (DllNotFoundException)
            {
                Console.Error.WriteLine("Unable to load DellSmbiosBzh.dll");
                Console.Error.WriteLine("Make sure that the file is present.  If it is, install the required Visual C++ redistributable:");
                Console.Error.WriteLine("https://aka.ms/vs/16/release/vc_redist.x64.exe");
                returnCode = -1;
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("Error: {0}", exception.Message);
                Console.Error.WriteLine(exception.StackTrace);
                returnCode = -1;
                UnloadDriver();
            }

            return returnCode;
        }

19 Source : SetThermalSetting.cs
with GNU General Public License v3.0
from AaronKelley

public static int ExecuteSetThermalSetting(string[] args)
        {
            if (args.Length != 2)
            {
                DellFanCmd.Usage();
                return -1;
            }

            ThermalSetting newSetting, currentSetting;

            // Determine the requested setting from the command line parameter.
            switch (args[1].ToLower())
            {
                case "optimized":
                    newSetting = ThermalSetting.Optimized;
                    break;
                case "cool":
                    newSetting = ThermalSetting.Cool;
                    break;
                case "quiet":
                    newSetting = ThermalSetting.Quiet;
                    break;
                case "performance":
                    newSetting = ThermalSetting.Performance;
                    break;
                default:
                    DellFanCmd.Usage();
                    return -1;
            }

            // Check the current setting.
            currentSetting = DellSmbiosSmi.GetThermalSetting();
            Console.WriteLine("Thermal setting, before change: {0}", currentSetting);

            // Apply the new setting.
            if (!DellSmbiosSmi.SetThermalSetting(newSetting))
            {
                Console.Error.WriteLine("Failed to apply the new thermal setting.");
                return -1;
            }

            // Check the new setting.
            currentSetting = DellSmbiosSmi.GetThermalSetting();
            Console.WriteLine("Thermal setting, after change:  {0}", currentSetting);

            if (currentSetting == ThermalSetting.Error)
            {
                return -1;
            }

            return 0;
        }

19 Source : DellFanCmd.cs
with GNU General Public License v3.0
from AaronKelley

public static bool LoadDriver()
        {
            Console.WriteLine("Loading SMM I/O driver...");
            bool result = DellSmbiosBzh.Initialize();
            if (!result)
            {
                Console.Error.WriteLine("Failed.");
                Console.Error.WriteLine();
                Console.Error.WriteLine("Please make sure that bzh_dell_smm_io_x64.sys is present in the working directory,");
                Console.Error.WriteLine("and that measures needed to allow the signature to be verified have been performed.");
                Console.Error.WriteLine("Also, make sure that you are running the program \"as administrator\".");
                Console.Error.WriteLine();

                Console.WriteLine("Attempting driver cleanup after failed driver load, errors may follow.");
                UnloadDriver();

                return false;
            }

            Console.WriteLine(" ...Success.");
            return true;
        }

19 Source : LogManager.cs
with MIT License
from Abc-Arbitrage

private void WriteThread()
        {
            try
            {
                WriteToAppenders();
            }
            catch (Exception ex)
            {
                try
                {
                    Console.Error.WriteLine("Fatal error in ZeroLog." + nameof(WriteThread) + ":");
                    Console.Error.WriteLine(ex);

                    Shutdown();
                }
                catch
                {
                    // Don't kill the process
                }
            }
        }

19 Source : LeapMotionConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd

[MenuItem("Mixed Reality Toolkit/Utilities/Leap Motion/Configure CSC File for Leap Motion")]
        static void UpdateCSC()
        {
            // The csc file will always be in the root of replacedets
            string cscFilePath = Path.Combine(Application.dataPath, "csc.rsp");

            // Each line of the csc file
            List<string> cscFileLines = new List<string>();

            // List of the warning numbers after "-nowarn: " in the csc file
            List<string> warningNumbers = new List<string>();

            // List of new warning numbers to add to the csc file
            List<string> warningNumbersToAdd = new List<string>()
            {
                "618",
                "649"
            };

            using (StreamReader streamReader = new StreamReader(cscFilePath))
            {
                while (streamReader.Peek() > -1)
                {
                    string cscFileLine = streamReader.ReadLine();

                    if (cscFileLine.Contains("-nowarn"))
                    {
                        string[] currentWarningNumbers = cscFileLine.Split(',', ':');
                        warningNumbers = currentWarningNumbers.ToList();

                        // Remove "nowarn" from the warningNumbers list
                        warningNumbers.Remove("-nowarn");

                        foreach (string warningNumberToAdd in warningNumbersToAdd)
                        {
                            // Add the new warning numbers if they are not already in the file
                            if (!warningNumbers.Contains(warningNumberToAdd))
                            {
                                warningNumbers.Add(warningNumberToAdd);
                            }
                        }

                        cscFileLines.Add(string.Join(",", warningNumbers));
                    }
                    else
                    {
                        cscFileLines.Add(cscFileLine);
                    }
                }
            }

            using (StreamWriter streamWriter = new StreamWriter(cscFilePath))
            {
                foreach (string cscLine in cscFileLines)
                {
                    if (cscLine.StartsWith("1701"))
                    {
                        string warningNumbersJoined = string.Join(",", warningNumbers);
                        streamWriter.WriteLine(string.Concat("-nowarn:", warningNumbersJoined));
                    }
                    else
                    {
                        streamWriter.WriteLine(cscLine);
                    } 
                }
            }

            Debug.Log($"Saving {cscFilePath}");
        }

19 Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd

internal static void EnsureMSBuildForUnity()
        {
            PackageManifest manifest = null;

            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return;
            }

            // Read the package manifest into a list of strings (for easy finding of entries)
            // and then deserialize.
            List<string> manifestFileLines = new List<string>();
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        manifestFileLines.Add(line);
                    }

                    // Go back to the start of the file.
                    manifestStream.Seek(0, 0);

                    // Deserialize the scoped registries portion of the package manifest.
                    manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
                }
            }

            if (manifest == null)
            {
                Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
                return;
            }

            // Ensure that pre-existing scoped registries are retained.
            List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
            if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
            {
                scopedRegistries.AddRange(manifest.scopedRegistries);
            }

            // Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
            bool needToAddRegistry = true;
            foreach (ScopedRegistry registry in scopedRegistries)
            {
                if (registry.url == MSBuildRegistryUrl)
                {
                    needToAddRegistry = false;
                }
            }

            // If no entry was found, add one.
            if (needToAddRegistry)
            {
                ScopedRegistry registry = new ScopedRegistry();
                registry.name = MSBuildRegistryName;
                registry.url = MSBuildRegistryUrl;
                registry.scopes = MSBuildRegistryScopes;

                scopedRegistries.Add(registry);
            }

            // Update the manifest's scoped registries, as the collection may have been modified.
            manifest.scopedRegistries = scopedRegistries.ToArray();

            int dependenciesStartIndex = -1;
            int scopedRegistriesStartIndex = -1;
            int scopedRegistriesEndIndex = -1;
            int packageLine = -1;

            // Presume that we need to add the MSBuild for Unity package. If this value is false,
            // we will check to see if the currently configured version meets or exceeds the
            // minimum requirements.
            bool needToAddPackage = true;

            // Attempt to find the MSBuild for Unity package entry in the dependencies collection
            // This loop also identifies the dependencies collection line and the start / end of a
            // pre-existing scoped registries collections
            for (int i = 0; i < manifestFileLines.Count; i++)
            {
                if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
                {
                    scopedRegistriesStartIndex = i;
                }
                if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
                {
                    scopedRegistriesEndIndex = i;
                }
                if (manifestFileLines[i].Contains("\"dependencies\": {"))
                {
                    dependenciesStartIndex = i;
                }
                if (manifestFileLines[i].Contains(MSBuildPackageName))
                {
                    packageLine = i;
                    needToAddPackage = false;
                }
            }

            // If no package was found add it to the dependencies collection.
            if (needToAddPackage)
            {
                // Add the package to the collection (pad the entry with four spaces)
                manifestFileLines.Insert(dependenciesStartIndex + 1, $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
            }
            else
            {
                // Replace the line that currently exists
                manifestFileLines[packageLine] = $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
            }

            // Update the manifest file.
            // First, serialize the scoped registry collection.
            string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);

            // Ensure that the file is truncated to ensure it is always valid after writing.
            using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(outFile))
                {
                    bool scopedRegistriesWritten = false;

                    // Write each line of the manifest back to the file.
                    for (int i = 0; i < manifestFileLines.Count; i++)
                    {
                        if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
                        {
                            // Skip these lines, they will be replaced.
                            continue;
                        }

                        if (!scopedRegistriesWritten && (i > 0))
                        {
                            // Trim the leading '{' and '\n' from the serialized scoped registries
                            serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
                            // Trim, the trailing '\n' and '}'
                            serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
                            // Append a trailing ',' to close the scopedRegistries node
                            serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
                            writer.WriteLine(serializedRegistriesJson);

                            scopedRegistriesWritten = true;
                        }

                        writer.WriteLine(manifestFileLines[i]);
                    }
                }
            }
        }

19 Source : Program.cs
with MIT License
from abock

static int Main(string[] args)
    {
        var decode = false;
        var wrap = 76;
        var showHelp = false;
        var showVersion = false;

        var options = new OptionSet
        {
            { "usage: ecoji [OPTIONS]... [FILE]" },
            { "" },
            { "Encode or decode data as Unicode emojis. 😻🍹" },
            { "" },
            { "Options:" },
            {
                "d|decode",
                "Decode data.",
                v => decode = v != null
            },
            {
                "w|wrap=",
                "Wrap encoded lines after {COLS} characters (default 76). " +
                    "Use 0 to disable line wrapping.",
                (int v) => wrap = v
            },
            {
                "h|help",
                "Print this message.",
                v => showHelp = v != null
            },
            {
                "v|version",
                "Print version information.",
                v => showVersion = v != null
            }
        };

        void ShowHelp()
            => options.WriteOptionDescriptions(Console.Out);

        void ShowVersion()
        {
            Console.WriteLine($"Ecoji (.NET Core) version {version}");
            Console.WriteLine($"  Copyright   : {copyright}");
            Console.WriteLine($"  License     : MIT");
            Console.WriteLine($"  Source code : https://github.com/abock/dotnet-ecoji");
            Console.WriteLine();
            Console.WriteLine($"Based on Ecoji by Keith Turner:");
            Console.WriteLine($"  https://github.com/keith-turner/ecoji");
        }

        try
        {
            var positional = options.Parse(args);

            if (showHelp)
            {
                ShowHelp();
                return ExitShowHelp;
            }

            if (showVersion)
            {
                ShowVersion();
                return ExitShowVersion;
            }

            Stream inputStream;

            if (positional is null ||
                positional.Count == 0 ||
                positional[0] == "-")
                inputStream = Console.OpenStandardInput();
            else if (positional.Count == 1)
                inputStream = new FileStream(
                    positional[0],
                    FileMode.Open,
                    FileAccess.Read);
            else
                throw new Exception("more than one file was provided");

            try
            {
                using(inputStream)
                {
                    if (decode)
                    {
                        using var stdout = Console.OpenStandardOutput();
                        Ecoji.Decode(inputStream, stdout);
                    }
                    else
                    {
                        Ecoji.Encode(inputStream, Console.Out, wrap);
                    }
                }
            }
            catch (Exception e)
            {
                WriteError($"pipe or encoding/decoding error: {e}");
                return ExitDataError;
            }

            return ExitSuccess;
        }
        catch (Exception e)
        {
            WriteError(e.Message);
            ShowHelp();
            return ExitArgumentsError;
        }
        
        static void WriteError(string error)
        {
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Error.WriteLine($"error: {error}");
            Console.Error.WriteLine();
            Console.ResetColor();
        }
    }

19 Source : Program.cs
with MIT License
from abock

static async Task<int> Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.Error.WriteLine("usage: ecoji-gen OUTPUT_FILE");
            return 1;
        }

        using var writer = new StreamWriter(args[0]);
        await GenerateAsync(writer);
        return 0;
    }

19 Source : Program.cs
with MIT License
from abock

static async Task GenerateAsync(
        TextWriter writer,
        CancellationToken cancellationToken = default)
    {
        var emojis = await ParseAsync(cancellationToken);

        var padding41 = emojis[256]; emojis.RemoveAt(256);
        var padding42 = emojis[512]; emojis.RemoveAt(512);
        var padding43 = emojis[768]; emojis.RemoveAt(768);

        writer.WriteLine($"// AUTOGENERATED DO NOT EDIT! {DateTime.Now:o}"); 
        writer.WriteLine();
        writer.WriteLine("using System.Collections.Generic;");
        writer.WriteLine();
        writer.WriteLine("public static partial clreplaced Ecoji");
        writer.WriteLine("{");
        writer.WriteLine("    // This should sort before everything.");
        writer.WriteLine("    // This is output when 3 or less input bytes are present.");
        writer.WriteLine("    static readonly int padding = 0x2615;");
        writer.WriteLine();
        writer.WriteLine("    // The following paddings are used when only 4 of 5 input bytes are present.");
        writer.WriteLine();
        writer.WriteLine("    // This should sort between padding and emojis[0]");
        writer.WriteLine("    static readonly int padding40 = 0x269C;");
        writer.WriteLine();
        writer.WriteLine("    // This should sort between emojis[255] and emojis[256]");
        writer.WriteLine($"    static readonly int padding41 = 0x{padding41.Rune:X};");
        writer.WriteLine();
        writer.WriteLine("    // This should sort between emojis[511] and emojis[512]");
        writer.WriteLine($"    static readonly int padding42 = 0x{padding42.Rune:X};");
        writer.WriteLine();
        writer.WriteLine("    // This should sort between emojis[767] and emojis[768]");
        writer.WriteLine($"    static readonly int padding43 = 0x{padding43.Rune:X};");
        writer.WriteLine();

        writer.WriteLine("    static readonly int[] emojis = new int[]");
        writer.WriteLine("    {");
        for (int i = 0; i < 1024; i++)
            writer.WriteLine($"        0x{emojis[i].Rune:X}, // {emojis[i].Emoji}");
        writer.WriteLine("    };");

        writer.WriteLine();
        writer.WriteLine("    static readonly Dictionary<int, int> revEmojis = new Dictionary<int, int>");
        writer.WriteLine("    {");
        for (int i = 0; i < 1024; i++)
            writer.WriteLine($"        [0x{emojis[i].Rune:X}] = {i}, // {emojis[i].Emoji}");
        writer.WriteLine("    };");
        writer.WriteLine("}");
    }

19 Source : ExportExampleHelper.cs
with MIT License
from ABTSoftware

private static void ExportExampleToSolution(ref string lastGroup, Example current)
        {
            string projectName = ProjectWriter.WriteProject(
                current, ExportPath + @"\", TryAutomaticallyFindreplacedemblies(), false);

            if (!File.Exists(ScriptPath))
            {
                using (var fs = File.CreateText(ScriptPath))
                {
                    // Write the header
                    fs.WriteLine("REM Compile and run all exported SciChart examples for testing");
                    fs.WriteLine("@echo OFF");                    
                    fs.WriteLine("");
                    fs.Close();
                }                
            }

            if (lastGroup != null && current.Group != lastGroup)
            {
                using (var fs = File.AppendText(ScriptPath))
                {
                    fs.WriteLine("@echo Finished Example Group " + lastGroup + ". Press any key to continue...");
                    fs.WriteLine("pause(0)");
                    fs.WriteLine("");
                }
            }
            lastGroup = current.Group;

            using (var fs = File.AppendText(ScriptPath))
            {
                fs.WriteLine("@echo Building " + projectName);
                fs.WriteLine(@"IF NOT EXIST ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin"" @echo VisualStudio folder not exists with the following path: ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin"" ");
                fs.WriteLine(@"call ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe"" /p:Configuration=""Debug"" ""{0}/{0}.csproj"" /p:WarningLevel=0", projectName);
                fs.WriteLine("if ERRORLEVEL 1 (");
                fs.WriteLine("   @echo - Example {0} Failed to compile >> errorlog.txt", projectName);
                fs.WriteLine(") else (");
                fs.WriteLine(@"   start """" ""{0}/bin/Debug/{0}.exe""", projectName);
                fs.WriteLine(")");
                fs.WriteLine("");
            }
        }

19 Source : MainViewModel.cs
with MIT License
from ABTSoftware

public static void WriteLog(string entry, string fileName)
        {
            string strPath = fileName;
            System.IO.StreamWriter sw;
            if (System.IO.File.Exists(strPath))
                sw = System.IO.File.AppendText(strPath);
            else
                sw = System.IO.File.CreateText(strPath);
            if (sw != null)
            {
                sw.WriteLine(entry + "[" + DateTime.Now.ToLongTimeString() + "]");
                sw.Close();
            }

        }

19 Source : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CreateSQLDELETEStatement(Biota input, StreamWriter writer)
        {
            writer.WriteLine($"DELETE FROM `biota` WHERE `id` = {input.Id};");
        }

19 Source : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CreateSQLINSERTStatement(Biota input, StreamWriter writer)
        {
            writer.WriteLine("INSERT INTO `biota` (`id`, `weenie_Clreplaced_Id`, `weenie_Type`, `populated_Collection_Flags`)");

            // Default to all flags if none are set
            var output = $"VALUES ({input.Id}, {input.WeenieClreplacedId}, {input.WeenieType}, {(input.PopulatedCollectionFlags != 0 ? input.PopulatedCollectionFlags : 4294967295)}) /* {Enum.GetName(typeof(WeenieType), input.WeenieType)} */;";

            output = FixNullFields(output);

            writer.WriteLine(output);

            if (input.BiotaPropertiesInt != null && input.BiotaPropertiesInt.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesInt.OrderBy(r => r.Type).ToList(), writer);
            }
            if (input.BiotaPropertiesInt64 != null && input.BiotaPropertiesInt64.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesInt64.OrderBy(r => r.Type).ToList(), writer);
            }
            if (input.BiotaPropertiesBool != null && input.BiotaPropertiesBool.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesBool.OrderBy(r => r.Type).ToList(), writer);
            }
            if (input.BiotaPropertiesFloat != null && input.BiotaPropertiesFloat.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesFloat.OrderBy(r => r.Type).ToList(), writer);
            }
            if (input.BiotaPropertiesString != null && input.BiotaPropertiesString.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesString.OrderBy(r => r.Type).ToList(), writer);
            }
            if (input.BiotaPropertiesDID != null && input.BiotaPropertiesDID.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesDID.OrderBy(r => r.Type).ToList(), writer);
            }

            if (input.BiotaPropertiesPosition != null && input.BiotaPropertiesPosition.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesPosition.OrderBy(r => r.PositionType).ToList(), writer);
            }

            if (input.BiotaPropertiesIID != null && input.BiotaPropertiesIID.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesIID.OrderBy(r => r.Type).ToList(), writer);
            }

            if (input.BiotaPropertiesAttribute != null && input.BiotaPropertiesAttribute.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesAttribute.OrderBy(r => r.Type).ToList(), writer);
            }
            if (input.BiotaPropertiesAttribute2nd != null && input.BiotaPropertiesAttribute2nd.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesAttribute2nd.OrderBy(r => r.Type).ToList(), writer);
            }

            if (input.BiotaPropertiesSkill != null && input.BiotaPropertiesSkill.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesSkill.OrderBy(r => r.Type).ToList(), writer);
            }

            if (input.BiotaPropertiesBodyPart != null && input.BiotaPropertiesBodyPart.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesBodyPart.OrderBy(r => r.Key).ToList(), writer);
            }

            if (input.BiotaPropertiesSpellBook != null && input.BiotaPropertiesSpellBook.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesSpellBook.OrderBy(r => r.Spell).ToList(), writer);
            }

            if (input.BiotaPropertiesEventFilter != null && input.BiotaPropertiesEventFilter.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesEventFilter.OrderBy(r => r.Event).ToList(), writer);
            }

            if (input.BiotaPropertiesEmote != null && input.BiotaPropertiesEmote.Count > 0)
            {
                //writer.WriteLine(); // This is not needed because CreateSQLINSERTStatement will take care of it for us on each Recipe.
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesEmote.OrderBy(r => r.Category).ToList(), writer);
            }

            if (input.BiotaPropertiesCreateList != null && input.BiotaPropertiesCreateList.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesCreateList.OrderBy(r => r.DestinationType).ToList(), writer);
            }

            if (input.BiotaPropertiesBook != null)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesBook, writer);
            }
            if (input.BiotaPropertiesBookPageData != null && input.BiotaPropertiesBookPageData.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesBookPageData.OrderBy(r => r.PageId).ToList(), writer);
            }

            if (input.BiotaPropertiesGenerator != null && input.BiotaPropertiesGenerator.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesGenerator.ToList(), writer);
            }

            if (input.BiotaPropertiesPalette != null && input.BiotaPropertiesPalette.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesPalette.OrderBy(r => r.SubPaletteId).ToList(), writer);
            }
            if (input.BiotaPropertiesTextureMap != null && input.BiotaPropertiesTextureMap.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesTextureMap.OrderBy(r => r.Index).ToList(), writer);
            }
            if (input.BiotaPropertiesAnimPart != null && input.BiotaPropertiesAnimPart.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesAnimPart.OrderBy(r => r.Index).ToList(), writer);
            }

            if (input.BiotaPropertiesEnchantmentRegistry != null && input.BiotaPropertiesEnchantmentRegistry.Count > 0)
            {
                writer.WriteLine();
                CreateSQLINSERTStatement(input.Id, input.BiotaPropertiesEnchantmentRegistry.ToList(), writer);
            }
        }

19 Source : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CreateSQLINSERTStatement(uint id, IList<BiotaPropertiesInt64> input, StreamWriter writer)
        {
            writer.WriteLine("INSERT INTO `biota_properties_int64` (`object_Id`, `type`, `value`)");

            var lineGenerator = new Func<int, string>(i => $"{id}, {input[i].Type.ToString().PadLeft(3)}, {input[i].Value.ToString().PadLeft(12)}) /* {Enum.GetName(typeof(PropertyInt64), input[i].Type)} */");

            ValuesWriter(input.Count, lineGenerator, writer);
        }

19 Source : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CreateSQLINSERTStatement(uint id, IList<BiotaPropertiesFloat> input, StreamWriter writer)
        {
            writer.WriteLine("INSERT INTO `biota_properties_float` (`object_Id`, `type`, `value`)");

            var lineGenerator = new Func<int, string>(i => $"{id}, {input[i].Type.ToString().PadLeft(3)}, {input[i].Value.ToString(CultureInfo.InvariantCulture).PadLeft(7)}) /* {Enum.GetName(typeof(PropertyFloat), input[i].Type)} */");

            ValuesWriter(input.Count, lineGenerator, writer);
        }

19 Source : BiotaSQLWriter.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CreateSQLINSERTStatement(uint id, IList<BiotaPropertiesPosition> input, StreamWriter writer)
        {
            writer.WriteLine("INSERT INTO `biota_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)");

            var lineGenerator = new Func<int, string>(i => $"{id}, {(uint)input[i].PositionType}, {input[i].ObjCellId}, {input[i].OriginX}, {input[i].OriginY}, {input[i].OriginZ}, {input[i].AnglesW}, {input[i].AnglesX}, {input[i].AnglesY}, {input[i].AnglesZ}) /* {Enum.GetName(typeof(PositionType), input[i].PositionType)} */" + Environment.NewLine + $"/* @teleloc 0x{input[i].ObjCellId:X8} [{input[i].OriginX:F6} {input[i].OriginY:F6} {input[i].OriginZ:F6}] {input[i].AnglesW:F6} {input[i].AnglesX:F6} {input[i].AnglesY:F6} {input[i].AnglesZ:F6} */");

            ValuesWriter(input.Count, lineGenerator, writer);
        }

See More Examples