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 : Logger.cs
with Apache License 2.0
from adamralph

private static void Message(string message)
        {
            if (message.Contains('\r', StringComparison.OrdinalIgnoreCase) || message.Contains('\n', StringComparison.OrdinalIgnoreCase))
            {
                var lines = message.Replace("\r\n", "\n", StringComparison.OrdinalIgnoreCase).Split('\r', '\n');
                message = string.Join($"{Environment.NewLine}MinVer: ", lines);
            }

            Console.Error.WriteLine($"MinVer: {message}");
        }

19 Source : BaseStrictDiffVisitor.cs
with MIT License
from adrianoc

internal bool ValidateGenericParameters(IMemberDefinition sourceMember, IMemberDefinition targetMember, Collection<GenericParameter> source, Collection<GenericParameter> target, string sourceFileName, string targetFileName)
        {
            if (source.Count != target.Count)
            {
                output.WriteLine($"[{sourceFileName}] Mismatch in generic parameters.\n\t{ToString(source)} : {sourceFileName}\n\t{ToString(target)}: {targetFileName}");
                return false;
            }

            var ret = true;
            var i = 0;
            foreach (var sourceParam in source)
            {
                var targetParam = target[i++];
                if (sourceParam.Name != targetParam.Name)
                {
                    output.WriteLine($"TypeParameter names differs {sourceParam.Name} / {targetParam.Name} in {sourceMember} / {targetMember}");
                    ret = false;
                }

                if (sourceParam.IsContravariant != targetParam.IsContravariant)
                {
                    output.WriteLine($"Difference in contra-variance for '{sourceParam.Name}' :\n\tSource ({sourceFileName}): {sourceParam.IsContravariant}\n\tTarget ({targetFileName}): {targetParam.IsContravariant}");
                    ret = false;
                }
                
                if (sourceParam.IsCovariant != targetParam.IsCovariant)
                {
                    output.WriteLine($"Difference in co-variance for '{sourceParam.Name}' :\n\tSource ({sourceFileName}): {sourceParam.IsCovariant}\n\tTarget ({targetFileName}): {targetParam.IsCovariant}");
                    ret = false;
                }

                if (sourceParam.HasReferenceTypeConstraint != targetParam.HasReferenceTypeConstraint)
                {
                    output.WriteLine($"Difference in 'clreplaced' constraint for '{sourceParam.Name}' :\n\tSource ({sourceFileName}): {sourceParam.HasReferenceTypeConstraint}\n\tTarget ({targetFileName}): {targetParam.HasReferenceTypeConstraint}");
                    ret = false;
                }
                
                if (sourceParam.HasDefaultConstructorConstraint != targetParam.HasDefaultConstructorConstraint)
                {
                    output.WriteLine($"Difference in 'new()' constraint for '{sourceParam.Name}' :\n\tSource ({sourceFileName}): {sourceParam.HasDefaultConstructorConstraint}\n\tTarget ({targetFileName}): {targetParam.HasDefaultConstructorConstraint}");
                    ret = false;
                }

                if (sourceParam.HasNotNullableValueTypeConstraint ^ targetParam.HasNotNullableValueTypeConstraint)
                {
                    output.WriteLine($"Difference in 'struct' constraint for '{sourceParam.Name}' :\n\tSource ({sourceFileName}): {sourceParam.HasReferenceTypeConstraint}\n\tTarget ({targetFileName}): {targetParam.HasNotNullableValueTypeConstraint}");
                    ret = false;
                }
                
                
                if (sourceParam.Constraints.Count != targetParam.Constraints.Count)
                {
                    output.WriteLine($"# of constrains differs for type parameter '{sourceParam.Name}' :\n\tSource ({sourceFileName}): {sourceParam.Constraints.Count}\n\t{string.Join(',', sourceParam.Constraints.Select(c => c.ConstraintType))}\n\tTarget ({targetFileName}): {targetParam.Constraints.Count}\n\t{string.Join(',', targetParam.Constraints.Select(c => c.ConstraintType))}");
                    ret = false;
                    continue;
                }

                var sortedTargetConstraintTypes = targetParam.Constraints.OrderBy(c => c.ConstraintType.FullName).ToArray();
                var constraintIndex = 0;
                foreach (var sourceConstraint in sourceParam.Constraints.OrderBy(c => c.ConstraintType.FullName))
                {
                    var targetConstraint = sortedTargetConstraintTypes[constraintIndex++];
                    if (sourceConstraint.ConstraintType.FullName != targetConstraint.ConstraintType.FullName)
                    {
                        output.WriteLine($"Generic constraint types ({sourceConstraint.ConstraintType.FullName} / {targetConstraint.ConstraintType.FullName}) differ on generic type parameter '{sourceParam.Name}'");
                        return false;
                    }
                }
            }
            
            return ret;
        
            string ToString(IEnumerable<GenericParameter> genericParameters)
            {
                if (!genericParameters.Any())
                    return "None";
                
                return string.Join(',', genericParameters.Select(gp => gp.Name));
            }
        }

19 Source : StrictEventDiffVisitor.cs
with MIT License
from adrianoc

public EventDefinition VisitEvent(EventDefinition sourceEvent, TypeDefinition target)
        {
            var @event = target.Events.SingleOrDefault(evt => evt.FullName == sourceEvent.FullName);
            if (@event == null)
            {
                _output.WriteLine($"Event '{sourceEvent.FullName}' not found in type '{target.FullName}'");
            }
            return @event;
        }

19 Source : StrictPropertyDiffVisitor.cs
with MIT License
from adrianoc

public PropertyDefinition VisitProperty(PropertyDefinition sourceProperty, TypeDefinition target)
        {
            var property = target.Properties.SingleOrDefault(prop => prop.FullName == sourceProperty.FullName);
            if (property == null)
            {
                _output.WriteLine($"Property '{sourceProperty.FullName}' not found in type '{target.FullName}'");
            }
            return property;
        }

19 Source : StrictEventDiffVisitor.cs
with MIT License
from adrianoc

public bool VisitType(EventDefinition source, EventDefinition target)
        {
            var ret = source.EventType.FullName == target.EventType.FullName;
            if (!ret)
                _output.WriteLine($"Types of event '{source.Name}' differs. Expected '{source.EventType.FullName}' but got '{target.EventType.FullName}'");
                
            return ret;
        }

19 Source : StrictPropertyDiffVisitor.cs
with MIT License
from adrianoc

public bool VisitAccessors(PropertyDefinition source, PropertyDefinition target)
        {
            bool ret = true;
            if (source.GetMethod?.FullName != target.GetMethod?.FullName)
            {
                _output.WriteLine($"GetMethod differs: Expected '{source.GetMethod}' but got '{target.GetMethod}'");
            }
            
            if (source.SetMethod?.FullName != target.SetMethod?.FullName)
            {
                _output.WriteLine($"SetMethod differs: Expected '{source.SetMethod}' but got '{target.SetMethod}'");
            }

            return ret;
        }

19 Source : FileLogger.cs
with MIT License
from adrianmteo

internal override void WriteMessage(string message)
        {
            ReaderWriterLockSlim currentLock = _allLocks[Path];

            try
            {
                currentLock.EnterWriteLock();

                using (StreamWriter writer = File.AppendText(Path))
                {
                    writer.WriteLine(message);
                    writer.Flush();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while writing log to file: {1}", ex.Message);
            }
            finally
            {
                currentLock.ExitWriteLock();
            }
        }

19 Source : StrictPropertyDiffVisitor.cs
with MIT License
from adrianoc

public bool VisitAttributes(PropertyDefinition source, PropertyDefinition target)
        {
            var ret = source.Attributes == target.Attributes;
            if (!ret)
                _output.WriteLine($"Attributes of event '{source.Name}' differs. Expected '{source.Attributes}' but got '{target.Attributes}'");
            
            return ret;
        }

19 Source : AssetManager.cs
with MIT License
from Adsito

public static void replacedetDump()
	{
		using (StreamWriter streamWriter = new StreamWriter(replacedetDumpPath, false))
			foreach (var item in BundleLookup.Keys)
				streamWriter.WriteLine(item + " : " + ToID(item));
	}

19 Source : StrictEventDiffVisitor.cs
with MIT License
from adrianoc

public bool VisitAccessors(EventDefinition source, EventDefinition target)
        {
            var ret = source.Attributes == target.Attributes;
            if (!ret)
                _output.WriteLine($"Attributes of event '{source.Name}' differs. Expected '{source.Attributes}' but got '{target.Attributes}'");
            
            return ret;
        }

19 Source : StrictPropertyDiffVisitor.cs
with MIT License
from adrianoc

public bool VisitType(PropertyDefinition source, PropertyDefinition target)
        {
            var ret = source.PropertyType.FullName == target.PropertyType.FullName;
            if (!ret)
                _output.WriteLine($"Types of property '{source.Name}' differs. Expected '{source.PropertyType.FullName}' but got '{target.PropertyType.FullName}'");
                
            return ret;
        }

19 Source : Utils.cs
with MIT License
from adrianoc

internal static bool CheckCustomAttributes(TextWriter output, IMemberDefinition source, IMemberDefinition target)
        {
            if (source.HasCustomAttributes != target.HasCustomAttributes)
            {
                // if all attrs in the expected replacedembly are in the ignore list we handle as if it had no attrs at all.
                if (source.HasCustomAttributes && source.CustomAttributes.All(ca => compilerEmmitedAttributesToIgnore.Contains(ca.Constructor.DeclaringType.FullName)))
                    return true;

                var sourceFileName = (source is TypeDefinition sourceDef ? sourceDef : source.DeclaringType).Module.FileName;
                var targetFileName = (target is TypeDefinition targetDef ? targetDef : source.DeclaringType).Module.FileName;
                output.WriteLine($"'{source.FullName}'{(!source.HasCustomAttributes ? "don't" : "")} have custom attributes in {sourceFileName} while '{targetFileName}' {(target.HasCustomAttributes ? "does" : "doesn't")} have.");
                return false;
            }

            if (!source.HasCustomAttributes)
            {
                return true;
            }

            foreach (var customAttribute in source.CustomAttributes)
            {
                var found = target.CustomAttributes.Any(candidate => CustomAttributeMatches(candidate, customAttribute));
                if (!found && !compilerEmmitedAttributesToIgnore.Contains(customAttribute.Constructor.DeclaringType.FullName))
                {
                    output.WriteLine($"Custom attribute {customAttribute.Constructor.FullName} not found in {target.FullName}");
                    return false;
                }
            }

            return true;
        }

19 Source : Formatter.cs
with MIT License
from adrianoc

private static void WriteVariables(TextWriter writer, MethodBody body)
        {
            var variables = body.Variables;

            writer.Write('\t');
            writer.Write(".locals {0}(", body.InitLocals ? "init " : string.Empty);

            for (var i = 0; i < variables.Count; i++)
            {
                if (i > 0)
                {
                    writer.Write(", ");
                }

                var variable = variables[i];

                writer.Write("{0} {1}", variable.VariableType, variable);
            }

            writer.WriteLine(")");
        }

19 Source : File.cs
with GNU General Public License v3.0
from aelariane

public virtual void WriteLine(string line)
        {
            if (!info.Exists)
            {
                return;
            }

            if (AlwaysOpen)
            {
                textWriter.WriteLine(line);
                return;
            }
            using (textWriter = info.AppendText())
            {
                textWriter.WriteLine(line);
            }
        }

19 Source : Client.cs
with MIT License
from Aerion

private void DebugWriteLine(string str)
        {
            _debugWriter?.WriteLine(str);
        }

19 Source : Program.cs
with MIT License
from Aerion

public void Dump(TextWriter tw)
            {
                tw.WriteLine($"{nameof(Verbose)}: {Verbose}");
                tw.WriteLine($"{nameof(UserToken)}: {UserToken}");
                tw.WriteLine($"{nameof(Links)}: {string.Join(" ", Links)}");
            }

19 Source : Program.cs
with MIT License
from Aerion

private static async Task<T> RetryOnFailure<T>(Func<Task<T>> task)
        {
            try
            {
                return await task();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Error.WriteLine($"Caught exception - retrying once: {ex}");
                Console.ResetColor();
                return await task();
            }
        }

19 Source : ExportDialog.cs
with GNU General Public License v2.0
from afrantzis

private void UpdatePatternFile(ListStore ls)
	{
		StreamWriter writer;

		try {
			FileStream fs = GetPatternFile(FileMode.Create, FileAccess.Write);
			writer = new StreamWriter(fs);
		}
		catch (Exception e) {
			System.Console.WriteLine(e.Message);
			return;
		}

		foreach (object[] row in ls)
		writer.WriteLine(row[0] as string);

		writer.Flush();
		writer.BaseStream.Close();
	}

19 Source : ErrorHandler.cs
with MIT License
from AgathokakologicalBit

public static void LogErrorInfo(State state)
        {
            Console.Error.WriteLine(
                $"Error #LC{state.ErrorCode.ToString("D3")}:\n{state.ErrorMessage}\n"
            );
        }

19 Source : ErrorHandler.cs
with MIT License
from AgathokakologicalBit

public static void LogErrorPosition(Token token)
        {
            Console.Error.WriteLine(
                $"Line: {token.Line}\nPosition: {token.Position}\n"
            );
        }

19 Source : ErrorHandler.cs
with MIT License
from AgathokakologicalBit

public static void LogErrorTokensPart(State state, int index, int leftBound, int rightBound)
        {
            var reader = state.Tokens.Skip(index - leftBound);
            var tokensToPrint = reader.Take(leftBound + rightBound + 1);

            Console.Error.WriteLine(
                String.Join(
                    " ",
                    tokensToPrint.Select(t => t.Value)
                )
            );

            var codePointerString = new String(
                '^',
                state.Tokens[index].Length
            );
            var shift = tokensToPrint.Take(leftBound).Select(t => t.Value.Length).Sum() + leftBound;
            var underline = new String(' ', shift) + codePointerString;
            Console.Error.WriteLine(underline);
        }

19 Source : Program.cs
with MIT License
from AgathokakologicalBit

static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            if (args.Length == 0)
            {
                Console.WriteLine("Target file is required");
                return;
            }

            if (!File.Exists(args[0]))
            {
                Console.Error.WriteLine(
                     "Error #LC001:\n" +
                    $"File {args[0]} does not exists:\n" +
                    $"  {Path.GetFullPath(args[0])}"
                );
                return;
            }

            var code = File.ReadAllText(args[0]);
            var tokenizer = new Tokenizer(code, new TokenizerOptions
            {
                SkipWhitespace = true
            });

            var watch = Stopwatch.StartNew();
            var tokens = tokenizer.Tokenize();
            watch.Stop();
            Console.WriteLine("\n===---        STATS        ---===");

            Console.WriteLine($" [T] Tokens count: {tokens.Length}");
            Console.WriteLine($" [T] Ellapsed time: {watch.Elapsed.TotalSeconds}s");

            watch.Start();
            var ast = Parser.Parse(tokens);
            var interpreter = new Interpreter(ast?.Code?.Context);
            interpreter.AddModule(new LanguageModule());
            ast = Optimizer.Optimize(ast);
            watch.Stop();

            Console.WriteLine($"\n [P] Ellapsed time: {watch.Elapsed.TotalSeconds}s");

            if (ast == null)
            {
                Console.Error.WriteLine("Error occurred during compilation process");
                return;
            }

            Console.WriteLine("\n\n===---  INTERPRETATION   ---===");


            try
            {
                watch.Start();
                interpreter.Run(ast);
                watch.Stop();
                Console.WriteLine($"\n [E] Ellapsed time: {watch.Elapsed.TotalSeconds}s");

                Console.WriteLine("\n\n===---   RUN MAIN   ---===");

                watch.Start();
                interpreter.Run("main", new StringNode("", false));
                watch.Stop();
                Console.WriteLine($"\n [E] Ellapsed time: {watch.Elapsed.TotalSeconds}s");
            }
            catch (Exception e)
            {
                Console.WriteLine("===---   ERROR OCCURED   ---===");
                Console.WriteLine(e.Message);
            }
        }

19 Source : GuiderImpl.cs
with MIT License
from agalasso

public void WriteLine(string s)
        {
            sw.WriteLine(s);
        }

19 Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu

private static DiskInfo LinuxFolderDiskInfo(string path)
        {
            DiskInfo disk = new DiskInfo();
            if (string.IsNullOrEmpty(path))
            {
                return disk;
            }
            if (!path.StartsWith("/"))
            {
                path = $"/{path}";
            }

            Process p = new Process();
            p.StartInfo.FileName = "sh";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine($"cd {path}");
            p.StandardInput.WriteLine($"df -k {path} | awk '{{print $2,$3,$4,$5}}'");
            p.StandardInput.WriteLine("exit");

            string strResult = p.StandardOutput.ReadToEnd();

            string[] arr = strResult.Split('\n');
            if (arr.Length == 0)
            {
                return disk;
            }
            string[] resultArray = arr[1].TrimStart().TrimEnd().Split(' ');
            if (resultArray == null || resultArray.Length == 0)
            {
                return disk;
            }

            disk.TotalSize = Convert.ToInt32(resultArray[0]) / (1024 * 1024);
            disk.UsedSize = Convert.ToInt32(resultArray[1]) / (1024 * 1024);
            disk.AvailableSize = Convert.ToInt32(resultArray[2]) / (1024 * 1024);
            disk.Use = disk.UsedSize / disk.TotalSize;

            return disk;
        }

19 Source : TxtRecorder.cs
with Mozilla Public License 2.0
from agebullhu

private void WriteFile(string log, string type)
        {
            var writer = GetWriter(type);
            if (writer == null)
                return;
            try
            {
                writer.Size += log.Length;
                writer.Stream.WriteLine(log);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString(), $"TextRecorder.WriteFile->{type}");
                writer.Stream.Dispose();
                writer.Stream.Close();
                ResetFile(type, writer);
            }
        }

19 Source : WSSocket.cs
with Mozilla Public License 2.0
from agebullhu

public bool Bind(string address)
        {
            _actor.SendMoreFrame(BindCommand).SendFrame(address);

            byte[] bytes = _actor.ReceiveFrameBytes();
            int errorCode = BitConverter.ToInt32(bytes, 0);

            if (errorCode != 0)
            {
                Console.Error.WriteLine($"Bind {address} Failed");
                return false;
            }
            return true;
        }

19 Source : Tester.cs
with Mozilla Public License 2.0
from agebullhu

static void TestFrame(string replacedle, ZeroOperatorStateType state, params byte[][] frames)
        {
            Console.Error.Write(replacedle);
            Console.ForegroundColor = ConsoleColor.Red;
            TestFrameInner(replacedle, state, frames);
            Console.Error.WriteLine();
            Console.Error.WriteLine("**----**");
            Console.ResetColor();
        }

19 Source : Tester.cs
with Mozilla Public License 2.0
from agebullhu

static void TestFrameInner(string replacedle, ZeroOperatorStateType state, byte[][] frames)
        {
            using (var socket = ZSocket.CreateClientSocket(address, ZSocketType.DEALER))
            {
                socket.SetOption(ZSocketOption.RCVTIMEO, 30000);
                if (!socket.SendTo(frames))
                {
                    Console.Error.Write(" : Send Error");
                    return;
                }
                var result = socket.Receive();
                if (!result.InteractiveSuccess)
                    Console.Error.WriteLine(" : Receive Error");
                if (result.State == state)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.Write($"(success) : {state}");
                }
                else
                    Console.Error.Write($"(bad) : {result.State}");
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void SaveSettings()
        {
            if (saveSettings && !currentlyReading)
            {
                try
                {
                    StreamWriter sw = null;

                    try
                    {
                        if (!Directory.Exists(settingsPath)) 
                            Directory.CreateDirectory(settingsPath);

                        using (sw = new StreamWriter(settingsFile))
                        {
                            sw.WriteLine("ToolVersion=" + c_toolVer);
                            sw.WriteLine("Beep=" + chkBeep.Checked);
                            sw.WriteLine("FoV=" + fFoV);
                            sw.WriteLine("FoVOffset=" + pFoV.ToString("x"));
                            sw.WriteLine("UpdateNotify=" + chkUpdate.Checked);
                            sw.WriteLine("DisableHotkeys=" + chkHotkeys.Checked);
                            sw.WriteLine("HotkeyIncrease=" + (int)catchKeys[0]);
                            sw.WriteLine("HotkeyDecrease=" + (int)catchKeys[1]);
                            sw.WriteLine("HotkeyReset=" + (int)catchKeys[2]);
                        }
                    }
                    catch
                    {
                        if (sw != null)
                            sw.Close();

                        File.Delete(settingsFile);
                        throw;
                    }

                    SaveGameMode();
                }
                catch
                {
                    saveSettings = false;
                }
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

private void SaveData()
        {
            if (saveSettings && !currentlyReading)
            {
                try
                {
                    StreamWriter sw = null;
                    try
                    {
                        if (!Directory.Exists(settingsPath)) Directory.CreateDirectory(settingsPath);
                        sw = new StreamWriter(Path.Combine(settingsPath, settingsFile));
                        sw.WriteLine("ToolVersion=" + c_toolVer);
                        sw.WriteLine("Beep=" + chkBeep.Checked.ToString().ToLower());
                        sw.WriteLine("FoV=" + ((int)fFoV).ToString());
                        sw.WriteLine("FoVOffset=" + pFoV.ToString("x"));
                        sw.WriteLine("UpdatePopup=" + chkUpdate.Checked.ToString().ToLower());
                        sw.WriteLine("DisableHotkeys=" + chkHotkeys.Checked.ToString().ToLower());
                        sw.WriteLine("HotkeyIncrease=" + (int)catchKeys[0]);
                        sw.WriteLine("HotkeyDecrease=" + (int)catchKeys[1]);
                        sw.WriteLine("HotkeyReset=" + (int)catchKeys[2]);
                    }
                    catch
                    {
                        //MessageBox.Show("catch");
                        if (sw != null) sw.Close();
                        File.Delete(settingsFile);
                        saveSettings = false;
                    }
                    finally
                    {
                        if (sw != null) sw.Close();
                    }
                }
                catch
                {
                    saveSettings = false;
                }
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void SaveSettings()
        {
            if (saveSettings && !currentlyReading)
            {
                try
                {
                    StreamWriter sw = null;

                    try
                    {
                        if (!Directory.Exists(settingsPath)) 
                            Directory.CreateDirectory(settingsPath);

                        using (sw = new StreamWriter(settingsFile))
                        {
                            sw.WriteLine("ToolVersion=" + c_toolVer);
                            sw.WriteLine("Beep=" + chkBeep.Checked);
                            sw.WriteLine("FoV=" + fFoV);
                            sw.WriteLine("FoVOffset=" + pFoV.ToString("x"));
                            sw.WriteLine("UpdatePopup=" + chkUpdate.Checked);
                            sw.WriteLine("DisableHotkeys=" + chkHotkeys.Checked);
                            sw.WriteLine("HotkeyIncrease=" + (int)catchKeys[0]);
                            sw.WriteLine("HotkeyDecrease=" + (int)catchKeys[1]);
                            sw.WriteLine("HotkeyReset=" + (int)catchKeys[2]);
                        }
                    }
                    catch
                    {
                        if (sw != null)
                            sw.Close();

                        File.Delete(settingsFile);
                        throw;
                    }
                }
                catch
                {
                    saveSettings = false;
                }
            }
        }

19 Source : StudiomdlExport.cs
with GNU General Public License v3.0
from ahmed605

public void Export(ModelNode node, string filename)
        {
            _selectedNodes = new Dictionary<object, bool>();
            PrepareSelectedNodes(node, false);

            try
            {
                using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                {
                    using (var sw = new StreamWriter(fs))
                    {
                        sw.WriteLine("version 1");
                        sw.WriteLine("nodes");

                        Skeleton skeleton = FindSkeleton(node);
                        if (skeleton != null)
                        {
                            ExportNodes(sw, skeleton.RootBone, null);
                        }
                        else
                        {
                            sw.WriteLine("0 \"root\" -1");
                        }
                        sw.WriteLine("end");

                        sw.WriteLine("skeleton");
                        sw.WriteLine("time 0");
                        if (skeleton != null)
                        {
                            ExportSkeleton(sw, skeleton.RootBone);
                        }
                        else
                        {
                            sw.WriteLine("0   0.0 0.0 0.0   0.0 0.0 0.0");
                        }
                        sw.WriteLine("end");

                        sw.WriteLine("triangles");
                        ExportModelNode(sw, node);
                        sw.WriteLine("end");
                    }
                }
            }
            finally
            {
                _selectedNodes = null;
            }
        }

19 Source : DecompileCFOutput.cs
with GNU General Public License v3.0
from ahmed605

private void WriteInstruction(TextWriter writer, HLInstruction instruction, string indent)
        {
            writer.Write(string.Format("{0}{1:x}: ", indent, instruction.Instruction.Offset));
            if (instruction.BranchFunction != null)
            {
                writer.WriteLine(string.Format("{0}()", instruction.BranchFunction.Name));
            }
            else if (instruction.ExitFunction)
            {
                writer.WriteLine("return");
            }
            else if (instruction.Instruction is InstructionNative)
            {
                writer.WriteLine(string.Format("{0}(in={1}, out={2})", instruction.Instruction.Operands[2],
                                               instruction.Instruction.Operands[0], instruction.Instruction.Operands[1]));
            }
            else
            {
                writer.WriteLine(string.Format("{0}", instruction.Instruction.GetInstructionText()));
            }
        }

19 Source : DecompileCFOutput.cs
with GNU General Public License v3.0
from ahmed605

private void ProcessCodePath(TextWriter writer, CodePath path, string indent)
        {
            HLInstruction instruction = path.GetFirstInstruction();

            while (instruction != null)
            {
                if (instruction.IsConditionalBranch)
                {
                    writer.WriteLine(string.Format("{0}if ({1})", indent,
                                                   instruction.DefaultConditional ? "true" : "false"));
                    writer.WriteLine(indent + "{");
                    ProcessCodePath(writer, instruction.BranchCodesPaths[instruction.DefaultConditional],
                                    indent + "    ");
                    writer.WriteLine(indent + "}");

                    if (instruction.BranchCodesPaths.ContainsKey(!instruction.DefaultConditional))
                    {
                        CodePath elsePath = instruction.BranchCodesPaths[!instruction.DefaultConditional];

                        if (elsePath.StartInstruction != null)
                        {
                            writer.WriteLine(indent + "else");
                            writer.WriteLine(indent + "{");
                            ProcessCodePath(writer, elsePath,
                                            indent + "    ");
                            writer.WriteLine(indent + "}");
                        }
                    }
                }
                else if (instruction.IsSwitchBranch)
                {
                    // Do switch cases ever fall through?? I'm replaceduming they don't here!

                    writer.WriteLine(indent + "switch");
                    writer.WriteLine(indent + "{");

                    // Keep track of code paths are have already outputted to keep
                    // track of offsets that lead to the same codepath
                    var swDonePaths = new List<CodePath>();

                    foreach (var item in instruction.BranchCodesPaths)
                    {
                        if (swDonePaths.Contains(item.Value))
                        {
                            continue;
                        }

                        foreach (var item2 in instruction.BranchCodesPaths)
                        {
                            // O(n^2) loop here, there's probably a better way to optimize it

                            if (item2.Value == item.Value)
                            {
                                if (item2.Key.GetType() == typeof (int))
                                {
                                    writer.WriteLine(string.Format("{0}    case {1}:", indent, item2.Key));
                                }
                                else
                                {
                                    writer.WriteLine(string.Format("{0}    default:", indent, item2.Key));
                                }
                            }
                        }

                        writer.WriteLine(indent + "    {");
                        ProcessCodePath(writer, item.Value, indent + "        ");
                        if (item.Value.EndInstruction == null || !item.Value.EndInstruction.ExitFunction)
                        {
                            writer.WriteLine(indent + "        break");
                        }
                        writer.WriteLine(indent + "    }");

                        swDonePaths.Add(item.Value);
                    }

                    writer.WriteLine(indent + "}");
                }
                else if (instruction.LoopCodePath != null)
                {
                    // First of a loop instruction (hopefully, someday, this will be extracted out by the Programreplacedyzer)
                    // Can we ever break out of a loop? I replacedume we can't here!

                    writer.WriteLine(indent + "while");
                    writer.WriteLine(indent + "(");
                    instruction = WriteLoopConditional(writer, instruction, indent + "    ");
                    writer.WriteLine(indent + ")");
                    writer.WriteLine(indent + "{");
                    ProcessCodePath(writer, instruction.BranchCodesPaths[true], indent + "    ");
                    writer.WriteLine(indent + "}");
                }
                else
                {
                    WriteInstruction(writer, instruction, indent);
                }

                instruction = instruction.GetNextInstruction();
            }
        }

19 Source : DecompileFullOutput.cs
with GNU General Public License v3.0
from ahmed605

public void Process(File file, TextWriter writer)
        {
            var decoder = new Decoder(file);
            var program = new ScriptProgram(decoder);
            var replacedyzer = new ControlFlowreplacedyzer(program);
            replacedyzer.replacedyze();

            var stackreplacedyzer = new StackUsereplacedyzer(program);
            stackreplacedyzer.replacedyze();

            foreach (Function function in program.Functions)
            {
                var sb = new StringBuilder();
                for (int i = 0; i < function.ParameterCount; i++)
                {
                    if (i != 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append("var");
                    sb.Append(i);
                }

                writer.WriteLine(string.Format("{0} {1}({2})", function.ReturnCount > 0 ? "function" : "void",
                                               function.Name, sb));
                writer.WriteLine("{");

                if (function.VariableCount > 2)
                {
                    writer.Write("   auto ");
                    for (int i = 2; i < function.VariableCount; i++)
                    {
                        if (i != 2)
                        {
                            writer.Write(", ");
                        }
                        writer.Write("var" + (i + function.ParameterCount));
                    }
                    writer.WriteLine(";");
                }

                if (function.TemporaryCount > 0)
                {
                    writer.Write("   auto ");
                    for (int i = 0; i < function.TemporaryCount; i++)
                    {
                        if (i != 0)
                        {
                            writer.Write(", ");
                        }
                        writer.Write("temp" + i);
                    }
                    writer.WriteLine(";");
                }

                if (function.TemporaryCount > 0 || function.VariableCount > 2)
                {
                    writer.WriteLine();
                }

                ProcessCodePath(writer, function.MainCodePath, "   ");

                writer.WriteLine("}");
                writer.WriteLine();
            }
        }

19 Source : DecompileScruffHeaderOutput.cs
with GNU General Public License v3.0
from ahmed605

public void Process(File file, TextWriter writer)
        {
            writer.WriteLine(string.Format("ScriptFlags = 0x{0:x}", file.Header.ScriptFlags));
            writer.WriteLine( string.Format("GlobalsSignature = 0x{0:x}", file.Header.GlobalsSignature) );
            writer.WriteLine();

            if (file.Header.GlobalVarCount > 0)
            {
                writer.WriteLine(string.Format("GlobalsCount = {0}", file.Header.GlobalVarCount));
                writer.WriteLine();
                uint[] globals = file.GlobalVars;
                for(int i=0; i<globals.Length; i++)
                {
                    writer.WriteLine(string.Format("G[{0}] = {1}", i, globals[i]));
                }
                writer.WriteLine();
            }

            writer.WriteLine(string.Format("LocalsCount = {0}", file.Header.LocalVarCount));
            writer.WriteLine();
            uint[] locals = file.LocalVars;
            for (int i = 0; i < locals.Length; i++)
            {
                writer.WriteLine(string.Format("L[{0}] = {1}", i, locals[i]));
            }
            writer.WriteLine();
        }

19 Source : DecompileFullOutput.cs
with GNU General Public License v3.0
from ahmed605

private void ProcessCodePath(TextWriter writer, CodePath path, string indent)
        {
            HLInstruction instruction = path.GetFirstInstruction();

            while (instruction != null)
            {
                Annotate(writer, indent, instruction);

                if (instruction.UnconditionalBranch)
                {
                    // Not used
                }
                else if (instruction.IsConditionalBranch)
                {
                    if (_nextIfIsAnElseIf)
                    {
                        writer.Write(string.Format("{0}else if", indent));
                        _nextIfIsAnElseIf = false;
                    }
                    else
                    {
                        writer.Write(string.Format("{0}if", indent));
                    }
                    writer.WriteLine(string.Format(" ({0})", instruction.ProcessedStackValue));
                    writer.WriteLine(indent + "{");
                    ProcessCodePath(writer, instruction.BranchCodesPaths[instruction.DefaultConditional],
                                    indent + "    ");
                    writer.WriteLine(indent + "}");

                    if (instruction.BranchCodesPaths.ContainsKey(!instruction.DefaultConditional))
                    {
                        CodePath elsePath = instruction.BranchCodesPaths[!instruction.DefaultConditional];
                        if (elsePath.StartInstruction != null)
                        {
                            if (IsCodePathAnIfPath(elsePath))
                            {
                                _nextIfIsAnElseIf = true;
                                ProcessCodePath(writer, elsePath, indent);
                            }
                            else
                            {
                                writer.WriteLine(indent + "else");
                                writer.WriteLine(indent + "{");
                                ProcessCodePath(writer, elsePath, indent + "    ");
                                writer.WriteLine(indent + "}");
                            }
                        }
                    }
                }
                else if (instruction.IsSwitchBranch)
                {
                    // Do switch cases ever fall through?? I'm replaceduming they don't here!

                    writer.WriteLine(indent + string.Format("switch ({0})", instruction.ProcessedStackValue));
                    writer.WriteLine(indent + "{");

                    // Keep track of code paths are have already outputted to keep
                    // track of offsets that lead to the same codepath
                    var swDonePaths = new List<CodePath>();

                    foreach (var item in instruction.BranchCodesPaths)
                    {
                        if (swDonePaths.Contains(item.Value))
                        {
                            continue;
                        }

                        foreach (var item2 in instruction.BranchCodesPaths)
                        {
                            // O(n^2) loop here, there's probably a better way to optimize it

                            if (item2.Value == item.Value)
                            {
                                if (item2.Key.GetType() == typeof (int))
                                {
                                    writer.WriteLine(string.Format("{0}    case {1}:", indent, LiteralFormatter.FormatInteger((int)item2.Key)));
                                }
                                else
                                {
                                    writer.WriteLine(string.Format("{0}    default:", indent));
                                }
                            }
                        }

                        writer.WriteLine(indent + "    {");
                        ProcessCodePath(writer, item.Value, indent + "        ");
                        if (item.Value.EndInstruction == null || !item.Value.EndInstruction.ExitFunction)
                        {
                            writer.WriteLine(indent + "        break;");
                        }
                        writer.WriteLine(indent + "    }");

                        swDonePaths.Add(item.Value);
                    }

                    writer.WriteLine(indent + "}");
                }
                else if (instruction.LoopCodePath != null)
                {
                    // First of a loop instruction (hopefully, someday, this will be extracted out by the Programreplacedyzer)
                    // Can we ever break out of a loop? I replacedume we can't here!

                    while (!instruction.IsConditionalBranch)
                    {
                        instruction = instruction.NextInstruction;
                        Annotate(writer, indent, instruction);
                    }

                    writer.WriteLine(indent + string.Format("while ({0})", instruction.ProcessedStackValue));
                    writer.WriteLine(indent + "{");
                    ProcessCodePath(writer, instruction.BranchCodesPaths[true], indent + "    ");
                    writer.WriteLine(indent + "}");
                }
                else
                {
                    WriteInstruction(writer, instruction, indent);
                }

                instruction = instruction.NextInstruction;
            }
        }

19 Source : DecompileScruffOutput.cs
with GNU General Public License v3.0
from ahmed605

public void Process(File file, TextWriter writer)
        {
            var decoder = new Decoder(file);
            var program = new ScriptProgram(decoder);
            var replacedyzer = new ControlFlowreplacedyzer(program);
            replacedyzer.replacedyze();

            foreach (Function function in program.Functions)
            {
                writer.WriteLine(string.Format(".function {0} (params={1}, vars={2}, return={3})",
                                               function.Name, function.ParameterCount, function.VariableCount, function.ReturnCount));

                ProcessCodePath(writer, function.MainCodePath, "   ");

                writer.WriteLine(".endfunction");
                writer.WriteLine();
            }
        }

19 Source : DecompileScruffOutput.cs
with GNU General Public License v3.0
from ahmed605

private void WriteInstruction(TextWriter writer, HLInstruction instruction, string indent)
        {
            //writer.Write(string.Format("{0}{1:x}: ", indent, instruction.Instruction.Offset));
            
            if (instruction.BranchFunction != null)
            {
                writer.Write(indent);
                writer.WriteLine(string.Format(".call {0}", instruction.BranchFunction.Name));
            }
            else if (instruction.ExitFunction)
            {

                Function parentFunction = instruction.ParentCodePath.ParentFunction;
                if (instruction.ExitFunction && instruction == parentFunction.MainCodePath.EndInstruction)
                {
                    // Don't write the default return unless we're somewhere in the middle!
                }
                else
                {
                    writer.Write(indent);
                    writer.WriteLine(".return");
                }
            }
            else if (instruction.Instruction is InstructionNative)
            {
                writer.Write(indent);
                writer.WriteLine(string.Format(".native {1} // in={2}, out={3}", instruction.Instruction.OpCode,
                                               instruction.Instruction.Operands[2], instruction.Instruction.Operands[0],
                                               instruction.Instruction.Operands[1]));
            }
            else if (instruction.UnconditionalBranch || instruction.Instruction.OpCode == OpCode.Jump)
            {
                //writer.WriteLine();
            }
            else
            {
                writer.Write(indent);
                writer.WriteLine(string.Format("{0}", instruction.Instruction.GetInstructionText()));
            }
        }

19 Source : DecompileScruffOutput.cs
with GNU General Public License v3.0
from ahmed605

private void ProcessCodePath(TextWriter writer, CodePath path, string indent)
        {
            HLInstruction instruction = path.GetFirstInstruction();

            while (instruction != null)
            {
                if (instruction.IsConditionalBranch)
                {
                    writer.WriteLine(string.Format("{0}.if{1}", indent, instruction.DefaultConditional ? "true" : "false"));
                    ProcessCodePath(writer, instruction.BranchCodesPaths[instruction.DefaultConditional],
                                    indent + "    ");

                    if (instruction.BranchCodesPaths.ContainsKey(!instruction.DefaultConditional))
                    {
                        CodePath elsePath = instruction.BranchCodesPaths[!instruction.DefaultConditional];

                        if (elsePath.StartInstruction != null)
                        {
                            writer.WriteLine(indent + ".else");
                            ProcessCodePath(writer, elsePath,
                                            indent + "    ");
                        }
                    }

                    writer.WriteLine(indent + ".endif");
                }
                else if (instruction.IsSwitchBranch)
                {
                    // Do switch cases ever fall through?? I'm replaceduming they don't here!

                    writer.WriteLine(indent + ".switch");

                    // Keep track of code paths are have already outputted to keep
                    // track of offsets that lead to the same codepath
                    var swDonePaths = new List<CodePath>();

                    foreach (var item in instruction.BranchCodesPaths)
                    {
                        if (swDonePaths.Contains(item.Value))
                        {
                            continue;
                        }

                        foreach (var item2 in instruction.BranchCodesPaths)
                        {
                            // O(n^2) loop here, there's probably a better way to optimize it

                            if (item2.Value == item.Value)
                            {
                                if (item2.Key.GetType() == typeof (int))
                                {
                                    writer.WriteLine(string.Format("{0}    .case {1}", indent, item2.Key));
                                }
                                else
                                {
                                    writer.WriteLine(string.Format("{0}    .default", indent, item2.Key));
                                }
                            }
                        }

                        ProcessCodePath(writer, item.Value, indent + "        ");
                        if (item.Value.EndInstruction == null || !item.Value.EndInstruction.ExitFunction)
                        {
                            writer.WriteLine(indent + "        .break");
                        }

                        swDonePaths.Add(item.Value);
                    }

                    writer.WriteLine(indent + ".endswitch");
                }
                else if (instruction.LoopCodePath != null)
                {
                    // First of a loop instruction (hopefully, someday, this will be extracted out by the Programreplacedyzer)
                    // Can we ever break out of a loop? I replacedume we can't here!

                    writer.WriteLine(indent + ".while");
                    instruction = WriteLoopConditional(writer, instruction, indent + "    ");
                    writer.WriteLine(indent + ".do");
                    ProcessCodePath(writer, instruction.BranchCodesPaths[true], indent + "    ");
                    writer.WriteLine(indent + ".endwhile");
                }
                else
                {
                    WriteInstruction(writer, instruction, indent);
                }

                instruction = instruction.GetNextInstruction();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ahmed605

static int Main(string[] args)
        {
            string gtaPath = KeyUtil.FindGTADirectory();
            while (gtaPath == null)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLine("Could not find GTAIV directory. Please install GTAIV or copy EFLC.exe\n" +
                                    "to the same path as Scruff.");
                return 1;
            }

            byte[] key = KeyUtil.FindKey(gtaPath);
            if (key == null)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLine("Your EFLC.exe seems to be modified or is a newer version than this tool\n" +
                                        "supports. If it is a newer version, please check for an update of Scruff.\n" +
                                        "Scruff can not run without a supported EFLC.exe file.");
                return 1;
            }

            KeyStore.SetKeyLoader(() => key);


            CodeFormatOptions[] formats = 
                {
                    new CodeFormatOptions("d", CodeFormat.ScruffDecompile, "Default Scruff disreplacedembly format"),
                    new CodeFormatOptions("h", CodeFormat.ScruffHeader, "Default Scruff header/local varibles/etc format"),
                    new CodeFormatOptions("hl", CodeFormat.FullDecompile, "High level C-like format"),
                    new CodeFormatOptions("hla", CodeFormat.FullDecompileAnnotate, "High level C-like format (annotated)"),
                    new CodeFormatOptions("ll", CodeFormat.Disreplacedemble, "Low level raw replacedembly format"),
                    new CodeFormatOptions("cp", CodeFormat.CodePath, "Code path for the control-flow-replacedyzer (for debugging)"),
                };

            CodeFormat customFormat = CodeFormat.ScruffDecompile;
            bool defaultMode = true;
            string filename = null;
            string outputFilename = null;

            if (args.Length > 0)
            {
                var argsQueue = new Queue<string>(args);

                while (argsQueue.Count > 0)
                {
                    var arg = argsQueue.Dequeue();
                    if (arg.StartsWith("-"))
                    {
                        if (arg == "-o")
                        {
                            defaultMode = false;
                            outputFilename = argsQueue.Dequeue();
                        }
                        else
                        {
                            foreach (var format in formats)
                            {
                                if (arg == "-" + format.Param)
                                {
                                    defaultMode = false;
                                    customFormat = format.Format;
                                    break;
                                }
                            }                            
                        }
                    }
                    else
                    {
                        if (argsQueue.Count > 0)
                        {
                            break;
                        }
                        filename = arg;
                    }
                }
            }

            if (filename == null)
            {
                var formatParams = new StringBuilder();
                foreach (var format in formats)
                {
                    if (formatParams.Length > 0)
                    {
                        formatParams.Append("|");
                    }
                    formatParams.Append("-");
                    formatParams.Append(format.Param);
                }

                Console.Error.WriteLine("Scruff - A RAGE Script File Decompiler/Disreplacedembler");
                Console.Error.WriteLine("v" + Version + " -- (c) 2008-2009, Aru <oneforaru at gmail dot com>");
                Console.Error.WriteLine();
                Console.Error.WriteLine(string.Format("Usage: scruff [{0}] [-o filename.sca] filename.sco", formatParams));
                Console.Error.WriteLine();
                Console.Error.WriteLine("By default, will generate filename.sca (-d) and filename.sch (-h)");
                Console.Error.WriteLine("If output file is specified, only filename.sca will be generated.");
                Console.Error.WriteLine("If format specified without output filename, will dump to console (stdout).");
                Console.Error.WriteLine();
                Console.Error.WriteLine("For custom options, use:");
                Console.Error.WriteLine("    -{0,-5} {1}", "o", "Saves the result to a specified file.");
                foreach (var format in formats)
                {
                    Console.Error.WriteLine("    -{0,-5} {1}", format.Param, format.Description);
                }
                Console.Error.WriteLine();
                /*
                Console.Error.WriteLine("Press any key to exit");
                Console.ReadKey();
                 */
                return 1;
            }

            var file = new ScriptFile();

            try
            {
                file.Open(filename);
            }
            catch
            {
                Console.Error.WriteLine("Invalid input file -- not a valid script.");
                /*
                Console.ReadKey();
                 */
                return 1;
            }

            if (defaultMode)
            {
                using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sca")))
                {
                    var sw = new StreamWriter(fs);
                    OutputCode(file, CodeFormat.ScruffDecompile, sw);
                    sw.Flush();
                }

                using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sch")))
                {
                    var sw = new StreamWriter(fs);
                    OutputCode(file, CodeFormat.ScruffHeader, sw);
                    sw.Flush();
                }
            }
            else
            {
                if (outputFilename != null)
                {
                    using(var fs = File.OpenWrite(outputFilename))
                    {
                        var sw = new StreamWriter(fs);
                        OutputCode(file, customFormat, sw);
                        sw.Flush();
                    }
                }
                else
                {
                    OutputCode(file, customFormat, Console.Out);                    
                }

            }

#if DEBUG
            Console.ReadLine();
#endif

            return 0;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from ahmed605

private static void OutputCode(ScriptFile file, CodeFormat format, TextWriter writer)
        {
            writer.WriteLine("// Generated by Scruff v" + Version + ", (c) 2008, aru.");
            writer.WriteLine("// This disreplacedembly/decompilation is licensed for research purposes only.");
            writer.WriteLine();

            file.GetCode(format, writer);
        }

19 Source : DecompileFullOutput.cs
with GNU General Public License v3.0
from ahmed605

private void WriteInstruction(TextWriter writer, HLInstruction instruction, string indent)
        {
            if (instruction.ProcessedStackValue != null)
            {
                if (instruction.ProcessedStackValue is ProcessedStackValueGroup)
                {
                    var group = instruction.ProcessedStackValue as ProcessedStackValueGroup;
                    foreach (StackValue value in group.Values)
                    {
                        writer.WriteLine(string.Format("{0}{1};", indent, value));
                    }
                }
                else
                {
                    Function parentFunction = instruction.ParentCodePath.ParentFunction;
                    if (parentFunction.ReturnCount == 0 && 
                        instruction.ExitFunction && 
                        instruction == parentFunction.MainCodePath.EndInstruction)
                    {
                        // Don't write the default return unless there's a return value!
                        //writer.WriteLine(string.Format("{0}// {1};", indent, instruction.ProcessedStackValue));
                    }
                    else
                    {
                        writer.WriteLine(string.Format("{0}{1};", indent, instruction.ProcessedStackValue));
                    }
                }
            }
        }

19 Source : DecompileFullOutput.cs
with GNU General Public License v3.0
from ahmed605

private void Annotate(TextWriter writer, string indent, HLInstruction instruction)
        {
            if (_annotate)
            {
                writer.WriteLine(string.Format("{0}// {1}", indent, instruction.Instruction));
            }
        }

19 Source : VariablesOutput.cs
with GNU General Public License v3.0
from ahmed605

public void Process(File file, TextWriter writer)
        {
            writer.WriteLine( string.Format("GlobalsSignature = 0x{0:x};", file.Header.GlobalsSignature) );
            writer.WriteLine();

            if (file.Header.GlobalVarCount > 0)
            {
                writer.WriteLine(string.Format("GlobalsCount = {0};", file.Header.GlobalVarCount));
                writer.WriteLine();
                uint[] globals = file.GlobalVars;
                for(int i=0; i<globals.Length; i++)
                {
                    writer.WriteLine(string.Format("G[{0}] = {1};", i, globals[i]));
                }
                writer.WriteLine();
            }

            writer.WriteLine(string.Format("LocalsCount = {0};", file.Header.LocalVarCount));
            writer.WriteLine();
            uint[] locals = file.LocalVars;
            for (int i = 0; i < locals.Length; i++)
            {
                writer.WriteLine(string.Format("L[{0}] = {1};", i, locals[i]));
            }
            writer.WriteLine();
        }

19 Source : HyperTextExport.cs
with GNU General Public License v3.0
from ahmed605

private static void ExportNode(HtmlNode node, TextWriter writer, string indent)
        {
            bool emptyNode = node.ChildNodes.Count == 0;
            bool dataNode = node.Data != null;

            if (dataNode)
            {
                string value = node.Data.Value;
                value = value.Replace("&", "&");
                value = value.Replace("<", "<");
                value = value.Replace(">", ">");
                writer.Write("{0}", value);
            }
            else
            {
                string tagName = GetTagName(node.Tag);
                string attributes = GetAttributes(node);

                if (emptyNode && node.Tag != HtmlTag.Style)
                {
                    //writer.WriteLine("{0}<{1} {2}/>", indent, tagName, attributes);
                    writer.Write("<{0} {1}/>", tagName, attributes);
                }
                else if (node.Tag == HtmlTag.Style)
                {
                    writer.WriteLine("{0}<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">", indent);
                    writer.WriteLine("{0}<style>", indent);
                    writer.WriteLine(indent + "   body { font-family: Arial; }");
                    writer.WriteLine(indent + "   a:link { text-decoration: none; }");
                    writer.WriteLine("{0}</style>", indent);
                }
                else
                {
                    //writer.WriteLine("{0}<{1}{2}>", indent, tagName, attributes);
                    writer.Write("<{0}{1}>", tagName, attributes);
                    foreach (var childNode in node.ChildNodes)
                    {
                        ExportNode(childNode, writer, indent + "   ");
                    }
                    //writer.WriteLine("{0}</{1}>", indent, tagName);
                    writer.Write("</{0}>", tagName);
                }
            }

        }

19 Source : StudiomdlExport.cs
with GNU General Public License v3.0
from ahmed605

private void ExportModel(TextWriter sw, Model model, Drawable drawable)
        {
            foreach (var geometry in model.Geometries)
            {
                foreach (var mesh in geometry.Meshes)
                {
                    if (_selectedNodes[mesh])
                    {

                        Vertex[] vertices = mesh.DecodeVertexData();
                        ushort[] indices = mesh.DecodeIndexData();
                        string materialName = "material_" + mesh.MaterialIndex + "_" +
                                              drawable.Materials[mesh.MaterialIndex].ShaderName;

                        for (int i = 0; i < mesh.FaceCount; i++)
                        {
                            Vertex v1 = vertices[indices[i*3 + 0]];
                            Vertex v2 = vertices[indices[i*3 + 1]];
                            Vertex v3 = vertices[indices[i*3 + 2]];

                            sw.WriteLine(materialName);
                            ExportVertex(sw, mesh, v1);
                            ExportVertex(sw, mesh, v2);
                            ExportVertex(sw, mesh, v3);
                        }
                    }
                }
            }
        }

19 Source : CodePathOutput.cs
with GNU General Public License v3.0
from ahmed605

public void Process(File file, TextWriter writer)
        {
            var decoder = new Decoder(file);
            var program = new ScriptProgram(decoder);
            var replacedyzer = new ControlFlowreplacedyzer(program);
            replacedyzer.replacedyze();

            // Dump the code paths
            foreach (Function function in program.Functions)
            {
                writer.WriteLine("function " + function.Name);
                foreach (CodePath path in function.CodePaths)
                {
                    writer.WriteLine("    " + path.Name + ":");
                    writer.WriteLine(string.Format("        0x{0:x} --> 0x{1:x}", path.StartOffset, path.EndOffset));
                    if (path.ParentCodePath != null)
                    {
                        writer.WriteLine("        parent: {0}, exit: 0x{1:x}, reentry: 0x{2:x}",
                                         path.ParentCodePath.Name, path.ParentExitInstruction.Instruction.Offset,
                                         path.ParentEntryTargetInstruction.Instruction.Offset);
                    }
                }
                writer.WriteLine();
            }
        }

19 Source : DecompileCFOutput.cs
with GNU General Public License v3.0
from ahmed605

public void Process(File file, TextWriter writer)
        {
            var decoder = new Decoder(file);
            var program = new ScriptProgram(decoder);
            var replacedyzer = new ControlFlowreplacedyzer(program);
            replacedyzer.replacedyze();

            foreach (Function function in program.Functions)
            {
                writer.WriteLine(string.Format("{0} {1}(params={2}, vars={3})",
                                               function.ReturnCount > 0 ? "function" : "void", function.Name,
                                               function.ParameterCount, function.VariableCount));
                writer.WriteLine("{");

                ProcessCodePath(writer, function.MainCodePath, "   ");

                writer.WriteLine("}");
                writer.WriteLine();
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from ahopper

void exportIconPack<P>(string replacedle, IDictionary<P, string> pack, bool invert = false) where P : Enum
        {
            //TODO use proper xml writer
            using (var file = File.CreateText($"..\\..\\..\\Avalonia.IconPacks\\Icons\\{replacedle}.xaml"))
            {
                file.WriteLine("<Styles xmlns=\"https://github.com/avaloniaui\"");
                file.WriteLine("    xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" >");
                file.WriteLine("    <Style>");
                file.WriteLine("        <Style.Resources>");

                var icons = Enum.GetValues(typeof(P));

                foreach (var icon in icons)
                {
                    var name = icon.ToString();
                    
                    var data = pack[(P)icon];
                    if (invert)
                    {
                        data = invertPath(data);
                    }
                    if (!String.IsNullOrEmpty(data))
                    {
                        file.WriteLine($"            <GeometryDrawing x:Key=\"{replacedle}.{name}\" Brush=\"#FF000000\" Geometry=\"{data}\"/>");
                    }
                }
                file.WriteLine("        </Style.Resources>");
                file.WriteLine("    </Style>");
                file.WriteLine("</Styles>");
            }
        }

See More Examples